]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp
Merge ^/head r317503 through r317807.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaDecl.cpp
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50
51 using namespace clang;
52 using namespace sema;
53
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62
63 namespace {
64
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowTemplates && getAsTypeTemplateDecl(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowTemplates;
90 };
91
92 } // end anonymous namespace
93
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125
126   default:
127     break;
128   }
129
130   return false;
131 }
132
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       if (auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169           BaseRD = BasePrimaryTemplate;
170         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171           if (const ClassTemplatePartialSpecializationDecl *PS =
172                   CTD->findPartialSpecialization(Base.getType()))
173             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174               BaseRD = PS;
175         }
176       }
177     }
178     if (BaseRD) {
179       for (NamedDecl *ND : BaseRD->lookup(&II)) {
180         if (!isa<TypeDecl>(ND))
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183       }
184       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186         case UnqualifiedTypeNameLookupResult::FoundNonType:
187           return UnqualifiedTypeNameLookupResult::FoundNonType;
188         case UnqualifiedTypeNameLookupResult::FoundType:
189           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190           break;
191         case UnqualifiedTypeNameLookupResult::NotFound:
192           break;
193         }
194       }
195     }
196   }
197
198   return FoundTypeDecl;
199 }
200
201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202                                                       const IdentifierInfo &II,
203                                                       SourceLocation NameLoc) {
204   // Lookup in the parent class template context, if any.
205   const CXXRecordDecl *RD = nullptr;
206   UnqualifiedTypeNameLookupResult FoundTypeDecl =
207       UnqualifiedTypeNameLookupResult::NotFound;
208   for (DeclContext *DC = S.CurContext;
209        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210        DC = DC->getParent()) {
211     // Look for type decls in dependent base classes that have known primary
212     // templates.
213     RD = dyn_cast<CXXRecordDecl>(DC);
214     if (RD && RD->getDescribedClassTemplate())
215       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216   }
217   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218     return nullptr;
219
220   // We found some types in dependent base classes.  Recover as if the user
221   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
222   // lookup during template instantiation.
223   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
224
225   ASTContext &Context = S.Context;
226   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227                                           cast<Type>(Context.getRecordType(RD)));
228   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
229
230   CXXScopeSpec SS;
231   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232
233   TypeLocBuilder Builder;
234   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235   DepTL.setNameLoc(NameLoc);
236   DepTL.setElaboratedKeywordLoc(SourceLocation());
237   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
239 }
240
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
243 ///
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250                              Scope *S, CXXScopeSpec *SS,
251                              bool isClassName, bool HasTrailingDot,
252                              ParsedType ObjectTypePtr,
253                              bool IsCtorOrDtorName,
254                              bool WantNontrivialTypeSourceInfo,
255                              bool IsClassTemplateDeductionContext,
256                              IdentifierInfo **CorrectedII) {
257   // FIXME: Consider allowing this outside C++1z mode as an extension.
258   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
259                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
260                               !isClassName && !HasTrailingDot;
261
262   // Determine where we will perform name lookup.
263   DeclContext *LookupCtx = nullptr;
264   if (ObjectTypePtr) {
265     QualType ObjectType = ObjectTypePtr.get();
266     if (ObjectType->isRecordType())
267       LookupCtx = computeDeclContext(ObjectType);
268   } else if (SS && SS->isNotEmpty()) {
269     LookupCtx = computeDeclContext(*SS, false);
270
271     if (!LookupCtx) {
272       if (isDependentScopeSpecifier(*SS)) {
273         // C++ [temp.res]p3:
274         //   A qualified-id that refers to a type and in which the
275         //   nested-name-specifier depends on a template-parameter (14.6.2)
276         //   shall be prefixed by the keyword typename to indicate that the
277         //   qualified-id denotes a type, forming an
278         //   elaborated-type-specifier (7.1.5.3).
279         //
280         // We therefore do not perform any name lookup if the result would
281         // refer to a member of an unknown specialization.
282         if (!isClassName && !IsCtorOrDtorName)
283           return nullptr;
284
285         // We know from the grammar that this name refers to a type,
286         // so build a dependent node to describe the type.
287         if (WantNontrivialTypeSourceInfo)
288           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
289
290         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
291         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
292                                        II, NameLoc);
293         return ParsedType::make(T);
294       }
295
296       return nullptr;
297     }
298
299     if (!LookupCtx->isDependentContext() &&
300         RequireCompleteDeclContext(*SS, LookupCtx))
301       return nullptr;
302   }
303
304   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
305   // lookup for class-names.
306   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
307                                       LookupOrdinaryName;
308   LookupResult Result(*this, &II, NameLoc, Kind);
309   if (LookupCtx) {
310     // Perform "qualified" name lookup into the declaration context we
311     // computed, which is either the type of the base of a member access
312     // expression or the declaration context associated with a prior
313     // nested-name-specifier.
314     LookupQualifiedName(Result, LookupCtx);
315
316     if (ObjectTypePtr && Result.empty()) {
317       // C++ [basic.lookup.classref]p3:
318       //   If the unqualified-id is ~type-name, the type-name is looked up
319       //   in the context of the entire postfix-expression. If the type T of
320       //   the object expression is of a class type C, the type-name is also
321       //   looked up in the scope of class C. At least one of the lookups shall
322       //   find a name that refers to (possibly cv-qualified) T.
323       LookupName(Result, S);
324     }
325   } else {
326     // Perform unqualified name lookup.
327     LookupName(Result, S);
328
329     // For unqualified lookup in a class template in MSVC mode, look into
330     // dependent base classes where the primary class template is known.
331     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
332       if (ParsedType TypeInBase =
333               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
334         return TypeInBase;
335     }
336   }
337
338   NamedDecl *IIDecl = nullptr;
339   switch (Result.getResultKind()) {
340   case LookupResult::NotFound:
341   case LookupResult::NotFoundInCurrentInstantiation:
342     if (CorrectedII) {
343       TypoCorrection Correction =
344           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
345                       llvm::make_unique<TypeNameValidatorCCC>(
346                           true, isClassName, AllowDeducedTemplate),
347                       CTK_ErrorRecovery);
348       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
349       TemplateTy Template;
350       bool MemberOfUnknownSpecialization;
351       UnqualifiedId TemplateName;
352       TemplateName.setIdentifier(NewII, NameLoc);
353       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
354       CXXScopeSpec NewSS, *NewSSPtr = SS;
355       if (SS && NNS) {
356         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
357         NewSSPtr = &NewSS;
358       }
359       if (Correction && (NNS || NewII != &II) &&
360           // Ignore a correction to a template type as the to-be-corrected
361           // identifier is not a template (typo correction for template names
362           // is handled elsewhere).
363           !(getLangOpts().CPlusPlus && NewSSPtr &&
364             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
365                            Template, MemberOfUnknownSpecialization))) {
366         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
367                                     isClassName, HasTrailingDot, ObjectTypePtr,
368                                     IsCtorOrDtorName,
369                                     WantNontrivialTypeSourceInfo,
370                                     IsClassTemplateDeductionContext);
371         if (Ty) {
372           diagnoseTypo(Correction,
373                        PDiag(diag::err_unknown_type_or_class_name_suggest)
374                          << Result.getLookupName() << isClassName);
375           if (SS && NNS)
376             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
377           *CorrectedII = NewII;
378           return Ty;
379         }
380       }
381     }
382     // If typo correction failed or was not performed, fall through
383   case LookupResult::FoundOverloaded:
384   case LookupResult::FoundUnresolvedValue:
385     Result.suppressDiagnostics();
386     return nullptr;
387
388   case LookupResult::Ambiguous:
389     // Recover from type-hiding ambiguities by hiding the type.  We'll
390     // do the lookup again when looking for an object, and we can
391     // diagnose the error then.  If we don't do this, then the error
392     // about hiding the type will be immediately followed by an error
393     // that only makes sense if the identifier was treated like a type.
394     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
395       Result.suppressDiagnostics();
396       return nullptr;
397     }
398
399     // Look to see if we have a type anywhere in the list of results.
400     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
401          Res != ResEnd; ++Res) {
402       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
403           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
404         if (!IIDecl ||
405             (*Res)->getLocation().getRawEncoding() <
406               IIDecl->getLocation().getRawEncoding())
407           IIDecl = *Res;
408       }
409     }
410
411     if (!IIDecl) {
412       // None of the entities we found is a type, so there is no way
413       // to even assume that the result is a type. In this case, don't
414       // complain about the ambiguity. The parser will either try to
415       // perform this lookup again (e.g., as an object name), which
416       // will produce the ambiguity, or will complain that it expected
417       // a type name.
418       Result.suppressDiagnostics();
419       return nullptr;
420     }
421
422     // We found a type within the ambiguous lookup; diagnose the
423     // ambiguity and then return that type. This might be the right
424     // answer, or it might not be, but it suppresses any attempt to
425     // perform the name lookup again.
426     break;
427
428   case LookupResult::Found:
429     IIDecl = Result.getFoundDecl();
430     break;
431   }
432
433   assert(IIDecl && "Didn't find decl");
434
435   QualType T;
436   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
437     // C++ [class.qual]p2: A lookup that would find the injected-class-name
438     // instead names the constructors of the class, except when naming a class.
439     // This is ill-formed when we're not actually forming a ctor or dtor name.
440     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
441     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
442     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
443         FoundRD->isInjectedClassName() &&
444         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
445       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
446           << &II << /*Type*/1;
447
448     DiagnoseUseOfDecl(IIDecl, NameLoc);
449
450     T = Context.getTypeDeclType(TD);
451     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
452   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
453     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
454     if (!HasTrailingDot)
455       T = Context.getObjCInterfaceType(IDecl);
456   } else if (AllowDeducedTemplate) {
457     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
458       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
459                                                        QualType(), false);
460   }
461
462   if (T.isNull()) {
463     // If it's not plausibly a type, suppress diagnostics.
464     Result.suppressDiagnostics();
465     return nullptr;
466   }
467
468   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
469   // constructor or destructor name (in such a case, the scope specifier
470   // will be attached to the enclosing Expr or Decl node).
471   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
472       !isa<ObjCInterfaceDecl>(IIDecl)) {
473     if (WantNontrivialTypeSourceInfo) {
474       // Construct a type with type-source information.
475       TypeLocBuilder Builder;
476       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
477
478       T = getElaboratedType(ETK_None, *SS, T);
479       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
480       ElabTL.setElaboratedKeywordLoc(SourceLocation());
481       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
482       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
483     } else {
484       T = getElaboratedType(ETK_None, *SS, T);
485     }
486   }
487
488   return ParsedType::make(T);
489 }
490
491 // Builds a fake NNS for the given decl context.
492 static NestedNameSpecifier *
493 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
494   for (;; DC = DC->getLookupParent()) {
495     DC = DC->getPrimaryContext();
496     auto *ND = dyn_cast<NamespaceDecl>(DC);
497     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
498       return NestedNameSpecifier::Create(Context, nullptr, ND);
499     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
500       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
501                                          RD->getTypeForDecl());
502     else if (isa<TranslationUnitDecl>(DC))
503       return NestedNameSpecifier::GlobalSpecifier(Context);
504   }
505   llvm_unreachable("something isn't in TU scope?");
506 }
507
508 /// Find the parent class with dependent bases of the innermost enclosing method
509 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
510 /// up allowing unqualified dependent type names at class-level, which MSVC
511 /// correctly rejects.
512 static const CXXRecordDecl *
513 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
514   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
515     DC = DC->getPrimaryContext();
516     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
517       if (MD->getParent()->hasAnyDependentBases())
518         return MD->getParent();
519   }
520   return nullptr;
521 }
522
523 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
524                                           SourceLocation NameLoc,
525                                           bool IsTemplateTypeArg) {
526   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
527
528   NestedNameSpecifier *NNS = nullptr;
529   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
530     // If we weren't able to parse a default template argument, delay lookup
531     // until instantiation time by making a non-dependent DependentTypeName. We
532     // pretend we saw a NestedNameSpecifier referring to the current scope, and
533     // lookup is retried.
534     // FIXME: This hurts our diagnostic quality, since we get errors like "no
535     // type named 'Foo' in 'current_namespace'" when the user didn't write any
536     // name specifiers.
537     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
538     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
539   } else if (const CXXRecordDecl *RD =
540                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
541     // Build a DependentNameType that will perform lookup into RD at
542     // instantiation time.
543     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
544                                       RD->getTypeForDecl());
545
546     // Diagnose that this identifier was undeclared, and retry the lookup during
547     // template instantiation.
548     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
549                                                                       << RD;
550   } else {
551     // This is not a situation that we should recover from.
552     return ParsedType();
553   }
554
555   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
556
557   // Build type location information.  We synthesized the qualifier, so we have
558   // to build a fake NestedNameSpecifierLoc.
559   NestedNameSpecifierLocBuilder NNSLocBuilder;
560   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
561   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
562
563   TypeLocBuilder Builder;
564   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
565   DepTL.setNameLoc(NameLoc);
566   DepTL.setElaboratedKeywordLoc(SourceLocation());
567   DepTL.setQualifierLoc(QualifierLoc);
568   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
569 }
570
571 /// isTagName() - This method is called *for error recovery purposes only*
572 /// to determine if the specified name is a valid tag name ("struct foo").  If
573 /// so, this returns the TST for the tag corresponding to it (TST_enum,
574 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
575 /// cases in C where the user forgot to specify the tag.
576 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
577   // Do a tag name lookup in this scope.
578   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
579   LookupName(R, S, false);
580   R.suppressDiagnostics();
581   if (R.getResultKind() == LookupResult::Found)
582     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
583       switch (TD->getTagKind()) {
584       case TTK_Struct: return DeclSpec::TST_struct;
585       case TTK_Interface: return DeclSpec::TST_interface;
586       case TTK_Union:  return DeclSpec::TST_union;
587       case TTK_Class:  return DeclSpec::TST_class;
588       case TTK_Enum:   return DeclSpec::TST_enum;
589       }
590     }
591
592   return DeclSpec::TST_unspecified;
593 }
594
595 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
596 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
597 /// then downgrade the missing typename error to a warning.
598 /// This is needed for MSVC compatibility; Example:
599 /// @code
600 /// template<class T> class A {
601 /// public:
602 ///   typedef int TYPE;
603 /// };
604 /// template<class T> class B : public A<T> {
605 /// public:
606 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
607 /// };
608 /// @endcode
609 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
610   if (CurContext->isRecord()) {
611     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
612       return true;
613
614     const Type *Ty = SS->getScopeRep()->getAsType();
615
616     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
617     for (const auto &Base : RD->bases())
618       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
619         return true;
620     return S->isFunctionPrototypeScope();
621   }
622   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
623 }
624
625 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
626                                    SourceLocation IILoc,
627                                    Scope *S,
628                                    CXXScopeSpec *SS,
629                                    ParsedType &SuggestedType,
630                                    bool AllowClassTemplates) {
631   // Don't report typename errors for editor placeholders.
632   if (II->isEditorPlaceholder())
633     return;
634   // We don't have anything to suggest (yet).
635   SuggestedType = nullptr;
636
637   // There may have been a typo in the name of the type. Look up typo
638   // results, in case we have something that we can suggest.
639   if (TypoCorrection Corrected =
640           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
641                       llvm::make_unique<TypeNameValidatorCCC>(
642                           false, false, AllowClassTemplates),
643                       CTK_ErrorRecovery)) {
644     if (Corrected.isKeyword()) {
645       // We corrected to a keyword.
646       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
647       II = Corrected.getCorrectionAsIdentifierInfo();
648     } else {
649       // We found a similarly-named type or interface; suggest that.
650       if (!SS || !SS->isSet()) {
651         diagnoseTypo(Corrected,
652                      PDiag(diag::err_unknown_typename_suggest) << II);
653       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
654         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
655         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
656                                 II->getName().equals(CorrectedStr);
657         diagnoseTypo(Corrected,
658                      PDiag(diag::err_unknown_nested_typename_suggest)
659                        << II << DC << DroppedSpecifier << SS->getRange());
660       } else {
661         llvm_unreachable("could not have corrected a typo here");
662       }
663
664       CXXScopeSpec tmpSS;
665       if (Corrected.getCorrectionSpecifier())
666         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
667                           SourceRange(IILoc));
668       // FIXME: Support class template argument deduction here.
669       SuggestedType =
670           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
671                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
672                       /*IsCtorOrDtorName=*/false,
673                       /*NonTrivialTypeSourceInfo=*/true);
674     }
675     return;
676   }
677
678   if (getLangOpts().CPlusPlus) {
679     // See if II is a class template that the user forgot to pass arguments to.
680     UnqualifiedId Name;
681     Name.setIdentifier(II, IILoc);
682     CXXScopeSpec EmptySS;
683     TemplateTy TemplateResult;
684     bool MemberOfUnknownSpecialization;
685     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
686                        Name, nullptr, true, TemplateResult,
687                        MemberOfUnknownSpecialization) == TNK_Type_template) {
688       TemplateName TplName = TemplateResult.get();
689       Diag(IILoc, diag::err_template_missing_args)
690         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
691       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
692         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
693           << TplDecl->getTemplateParameters()->getSourceRange();
694       }
695       return;
696     }
697   }
698
699   // FIXME: Should we move the logic that tries to recover from a missing tag
700   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
701
702   if (!SS || (!SS->isSet() && !SS->isInvalid()))
703     Diag(IILoc, diag::err_unknown_typename) << II;
704   else if (DeclContext *DC = computeDeclContext(*SS, false))
705     Diag(IILoc, diag::err_typename_nested_not_found)
706       << II << DC << SS->getRange();
707   else if (isDependentScopeSpecifier(*SS)) {
708     unsigned DiagID = diag::err_typename_missing;
709     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
710       DiagID = diag::ext_typename_missing;
711
712     Diag(SS->getRange().getBegin(), DiagID)
713       << SS->getScopeRep() << II->getName()
714       << SourceRange(SS->getRange().getBegin(), IILoc)
715       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
716     SuggestedType = ActOnTypenameType(S, SourceLocation(),
717                                       *SS, *II, IILoc).get();
718   } else {
719     assert(SS && SS->isInvalid() &&
720            "Invalid scope specifier has already been diagnosed");
721   }
722 }
723
724 /// \brief Determine whether the given result set contains either a type name
725 /// or
726 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
727   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
728                        NextToken.is(tok::less);
729
730   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
731     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
732       return true;
733
734     if (CheckTemplate && isa<TemplateDecl>(*I))
735       return true;
736   }
737
738   return false;
739 }
740
741 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
742                                     Scope *S, CXXScopeSpec &SS,
743                                     IdentifierInfo *&Name,
744                                     SourceLocation NameLoc) {
745   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
746   SemaRef.LookupParsedName(R, S, &SS);
747   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
748     StringRef FixItTagName;
749     switch (Tag->getTagKind()) {
750       case TTK_Class:
751         FixItTagName = "class ";
752         break;
753
754       case TTK_Enum:
755         FixItTagName = "enum ";
756         break;
757
758       case TTK_Struct:
759         FixItTagName = "struct ";
760         break;
761
762       case TTK_Interface:
763         FixItTagName = "__interface ";
764         break;
765
766       case TTK_Union:
767         FixItTagName = "union ";
768         break;
769     }
770
771     StringRef TagName = FixItTagName.drop_back();
772     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
773       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
774       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
775
776     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
777          I != IEnd; ++I)
778       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
779         << Name << TagName;
780
781     // Replace lookup results with just the tag decl.
782     Result.clear(Sema::LookupTagName);
783     SemaRef.LookupParsedName(Result, S, &SS);
784     return true;
785   }
786
787   return false;
788 }
789
790 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
791 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
792                                   QualType T, SourceLocation NameLoc) {
793   ASTContext &Context = S.Context;
794
795   TypeLocBuilder Builder;
796   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
797
798   T = S.getElaboratedType(ETK_None, SS, T);
799   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
800   ElabTL.setElaboratedKeywordLoc(SourceLocation());
801   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
802   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
803 }
804
805 Sema::NameClassification
806 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
807                    SourceLocation NameLoc, const Token &NextToken,
808                    bool IsAddressOfOperand,
809                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
810   DeclarationNameInfo NameInfo(Name, NameLoc);
811   ObjCMethodDecl *CurMethod = getCurMethodDecl();
812
813   if (NextToken.is(tok::coloncolon)) {
814     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
815     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
816   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
817              isCurrentClassName(*Name, S, &SS)) {
818     // Per [class.qual]p2, this names the constructors of SS, not the
819     // injected-class-name. We don't have a classification for that.
820     // There's not much point caching this result, since the parser
821     // will reject it later.
822     return NameClassification::Unknown();
823   }
824
825   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
826   LookupParsedName(Result, S, &SS, !CurMethod);
827
828   // For unqualified lookup in a class template in MSVC mode, look into
829   // dependent base classes where the primary class template is known.
830   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
831     if (ParsedType TypeInBase =
832             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
833       return TypeInBase;
834   }
835
836   // Perform lookup for Objective-C instance variables (including automatically
837   // synthesized instance variables), if we're in an Objective-C method.
838   // FIXME: This lookup really, really needs to be folded in to the normal
839   // unqualified lookup mechanism.
840   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
841     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
842     if (E.get() || E.isInvalid())
843       return E;
844   }
845
846   bool SecondTry = false;
847   bool IsFilteredTemplateName = false;
848
849 Corrected:
850   switch (Result.getResultKind()) {
851   case LookupResult::NotFound:
852     // If an unqualified-id is followed by a '(', then we have a function
853     // call.
854     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
855       // In C++, this is an ADL-only call.
856       // FIXME: Reference?
857       if (getLangOpts().CPlusPlus)
858         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
859
860       // C90 6.3.2.2:
861       //   If the expression that precedes the parenthesized argument list in a
862       //   function call consists solely of an identifier, and if no
863       //   declaration is visible for this identifier, the identifier is
864       //   implicitly declared exactly as if, in the innermost block containing
865       //   the function call, the declaration
866       //
867       //     extern int identifier ();
868       //
869       //   appeared.
870       //
871       // We also allow this in C99 as an extension.
872       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
873         Result.addDecl(D);
874         Result.resolveKind();
875         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
876       }
877     }
878
879     // In C, we first see whether there is a tag type by the same name, in
880     // which case it's likely that the user just forgot to write "enum",
881     // "struct", or "union".
882     if (!getLangOpts().CPlusPlus && !SecondTry &&
883         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
884       break;
885     }
886
887     // Perform typo correction to determine if there is another name that is
888     // close to this name.
889     if (!SecondTry && CCC) {
890       SecondTry = true;
891       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
892                                                  Result.getLookupKind(), S,
893                                                  &SS, std::move(CCC),
894                                                  CTK_ErrorRecovery)) {
895         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
896         unsigned QualifiedDiag = diag::err_no_member_suggest;
897
898         NamedDecl *FirstDecl = Corrected.getFoundDecl();
899         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
900         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
902           UnqualifiedDiag = diag::err_no_template_suggest;
903           QualifiedDiag = diag::err_no_member_template_suggest;
904         } else if (UnderlyingFirstDecl &&
905                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
906                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
907                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
908           UnqualifiedDiag = diag::err_unknown_typename_suggest;
909           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
910         }
911
912         if (SS.isEmpty()) {
913           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
914         } else {// FIXME: is this even reachable? Test it.
915           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
916           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
917                                   Name->getName().equals(CorrectedStr);
918           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
919                                     << Name << computeDeclContext(SS, false)
920                                     << DroppedSpecifier << SS.getRange());
921         }
922
923         // Update the name, so that the caller has the new name.
924         Name = Corrected.getCorrectionAsIdentifierInfo();
925
926         // Typo correction corrected to a keyword.
927         if (Corrected.isKeyword())
928           return Name;
929
930         // Also update the LookupResult...
931         // FIXME: This should probably go away at some point
932         Result.clear();
933         Result.setLookupName(Corrected.getCorrection());
934         if (FirstDecl)
935           Result.addDecl(FirstDecl);
936
937         // If we found an Objective-C instance variable, let
938         // LookupInObjCMethod build the appropriate expression to
939         // reference the ivar.
940         // FIXME: This is a gross hack.
941         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
942           Result.clear();
943           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
944           return E;
945         }
946
947         goto Corrected;
948       }
949     }
950
951     // We failed to correct; just fall through and let the parser deal with it.
952     Result.suppressDiagnostics();
953     return NameClassification::Unknown();
954
955   case LookupResult::NotFoundInCurrentInstantiation: {
956     // We performed name lookup into the current instantiation, and there were
957     // dependent bases, so we treat this result the same way as any other
958     // dependent nested-name-specifier.
959
960     // C++ [temp.res]p2:
961     //   A name used in a template declaration or definition and that is
962     //   dependent on a template-parameter is assumed not to name a type
963     //   unless the applicable name lookup finds a type name or the name is
964     //   qualified by the keyword typename.
965     //
966     // FIXME: If the next token is '<', we might want to ask the parser to
967     // perform some heroics to see if we actually have a
968     // template-argument-list, which would indicate a missing 'template'
969     // keyword here.
970     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
971                                       NameInfo, IsAddressOfOperand,
972                                       /*TemplateArgs=*/nullptr);
973   }
974
975   case LookupResult::Found:
976   case LookupResult::FoundOverloaded:
977   case LookupResult::FoundUnresolvedValue:
978     break;
979
980   case LookupResult::Ambiguous:
981     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
982         hasAnyAcceptableTemplateNames(Result)) {
983       // C++ [temp.local]p3:
984       //   A lookup that finds an injected-class-name (10.2) can result in an
985       //   ambiguity in certain cases (for example, if it is found in more than
986       //   one base class). If all of the injected-class-names that are found
987       //   refer to specializations of the same class template, and if the name
988       //   is followed by a template-argument-list, the reference refers to the
989       //   class template itself and not a specialization thereof, and is not
990       //   ambiguous.
991       //
992       // This filtering can make an ambiguous result into an unambiguous one,
993       // so try again after filtering out template names.
994       FilterAcceptableTemplateNames(Result);
995       if (!Result.isAmbiguous()) {
996         IsFilteredTemplateName = true;
997         break;
998       }
999     }
1000
1001     // Diagnose the ambiguity and return an error.
1002     return NameClassification::Error();
1003   }
1004
1005   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1006       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1007     // C++ [temp.names]p3:
1008     //   After name lookup (3.4) finds that a name is a template-name or that
1009     //   an operator-function-id or a literal- operator-id refers to a set of
1010     //   overloaded functions any member of which is a function template if
1011     //   this is followed by a <, the < is always taken as the delimiter of a
1012     //   template-argument-list and never as the less-than operator.
1013     if (!IsFilteredTemplateName)
1014       FilterAcceptableTemplateNames(Result);
1015
1016     if (!Result.empty()) {
1017       bool IsFunctionTemplate;
1018       bool IsVarTemplate;
1019       TemplateName Template;
1020       if (Result.end() - Result.begin() > 1) {
1021         IsFunctionTemplate = true;
1022         Template = Context.getOverloadedTemplateName(Result.begin(),
1023                                                      Result.end());
1024       } else {
1025         TemplateDecl *TD
1026           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1027         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1028         IsVarTemplate = isa<VarTemplateDecl>(TD);
1029
1030         if (SS.isSet() && !SS.isInvalid())
1031           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1032                                                     /*TemplateKeyword=*/false,
1033                                                       TD);
1034         else
1035           Template = TemplateName(TD);
1036       }
1037
1038       if (IsFunctionTemplate) {
1039         // Function templates always go through overload resolution, at which
1040         // point we'll perform the various checks (e.g., accessibility) we need
1041         // to based on which function we selected.
1042         Result.suppressDiagnostics();
1043
1044         return NameClassification::FunctionTemplate(Template);
1045       }
1046
1047       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1048                            : NameClassification::TypeTemplate(Template);
1049     }
1050   }
1051
1052   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1053   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1054     DiagnoseUseOfDecl(Type, NameLoc);
1055     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1056     QualType T = Context.getTypeDeclType(Type);
1057     if (SS.isNotEmpty())
1058       return buildNestedType(*this, SS, T, NameLoc);
1059     return ParsedType::make(T);
1060   }
1061
1062   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1063   if (!Class) {
1064     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1065     if (ObjCCompatibleAliasDecl *Alias =
1066             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1067       Class = Alias->getClassInterface();
1068   }
1069
1070   if (Class) {
1071     DiagnoseUseOfDecl(Class, NameLoc);
1072
1073     if (NextToken.is(tok::period)) {
1074       // Interface. <something> is parsed as a property reference expression.
1075       // Just return "unknown" as a fall-through for now.
1076       Result.suppressDiagnostics();
1077       return NameClassification::Unknown();
1078     }
1079
1080     QualType T = Context.getObjCInterfaceType(Class);
1081     return ParsedType::make(T);
1082   }
1083
1084   // We can have a type template here if we're classifying a template argument.
1085   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1086       !isa<VarTemplateDecl>(FirstDecl))
1087     return NameClassification::TypeTemplate(
1088         TemplateName(cast<TemplateDecl>(FirstDecl)));
1089
1090   // Check for a tag type hidden by a non-type decl in a few cases where it
1091   // seems likely a type is wanted instead of the non-type that was found.
1092   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1093   if ((NextToken.is(tok::identifier) ||
1094        (NextIsOp &&
1095         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1096       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1097     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1098     DiagnoseUseOfDecl(Type, NameLoc);
1099     QualType T = Context.getTypeDeclType(Type);
1100     if (SS.isNotEmpty())
1101       return buildNestedType(*this, SS, T, NameLoc);
1102     return ParsedType::make(T);
1103   }
1104
1105   if (FirstDecl->isCXXClassMember())
1106     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1107                                            nullptr, S);
1108
1109   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1110   return BuildDeclarationNameExpr(SS, Result, ADL);
1111 }
1112
1113 Sema::TemplateNameKindForDiagnostics
1114 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1115   auto *TD = Name.getAsTemplateDecl();
1116   if (!TD)
1117     return TemplateNameKindForDiagnostics::DependentTemplate;
1118   if (isa<ClassTemplateDecl>(TD))
1119     return TemplateNameKindForDiagnostics::ClassTemplate;
1120   if (isa<FunctionTemplateDecl>(TD))
1121     return TemplateNameKindForDiagnostics::FunctionTemplate;
1122   if (isa<VarTemplateDecl>(TD))
1123     return TemplateNameKindForDiagnostics::VarTemplate;
1124   if (isa<TypeAliasTemplateDecl>(TD))
1125     return TemplateNameKindForDiagnostics::AliasTemplate;
1126   if (isa<TemplateTemplateParmDecl>(TD))
1127     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1128   return TemplateNameKindForDiagnostics::DependentTemplate;
1129 }
1130
1131 // Determines the context to return to after temporarily entering a
1132 // context.  This depends in an unnecessarily complicated way on the
1133 // exact ordering of callbacks from the parser.
1134 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1135
1136   // Functions defined inline within classes aren't parsed until we've
1137   // finished parsing the top-level class, so the top-level class is
1138   // the context we'll need to return to.
1139   // A Lambda call operator whose parent is a class must not be treated
1140   // as an inline member function.  A Lambda can be used legally
1141   // either as an in-class member initializer or a default argument.  These
1142   // are parsed once the class has been marked complete and so the containing
1143   // context would be the nested class (when the lambda is defined in one);
1144   // If the class is not complete, then the lambda is being used in an
1145   // ill-formed fashion (such as to specify the width of a bit-field, or
1146   // in an array-bound) - in which case we still want to return the
1147   // lexically containing DC (which could be a nested class).
1148   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1149     DC = DC->getLexicalParent();
1150
1151     // A function not defined within a class will always return to its
1152     // lexical context.
1153     if (!isa<CXXRecordDecl>(DC))
1154       return DC;
1155
1156     // A C++ inline method/friend is parsed *after* the topmost class
1157     // it was declared in is fully parsed ("complete");  the topmost
1158     // class is the context we need to return to.
1159     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1160       DC = RD;
1161
1162     // Return the declaration context of the topmost class the inline method is
1163     // declared in.
1164     return DC;
1165   }
1166
1167   return DC->getLexicalParent();
1168 }
1169
1170 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1171   assert(getContainingDC(DC) == CurContext &&
1172       "The next DeclContext should be lexically contained in the current one.");
1173   CurContext = DC;
1174   S->setEntity(DC);
1175 }
1176
1177 void Sema::PopDeclContext() {
1178   assert(CurContext && "DeclContext imbalance!");
1179
1180   CurContext = getContainingDC(CurContext);
1181   assert(CurContext && "Popped translation unit!");
1182 }
1183
1184 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1185                                                                     Decl *D) {
1186   // Unlike PushDeclContext, the context to which we return is not necessarily
1187   // the containing DC of TD, because the new context will be some pre-existing
1188   // TagDecl definition instead of a fresh one.
1189   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1190   CurContext = cast<TagDecl>(D)->getDefinition();
1191   assert(CurContext && "skipping definition of undefined tag");
1192   // Start lookups from the parent of the current context; we don't want to look
1193   // into the pre-existing complete definition.
1194   S->setEntity(CurContext->getLookupParent());
1195   return Result;
1196 }
1197
1198 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1199   CurContext = static_cast<decltype(CurContext)>(Context);
1200 }
1201
1202 /// EnterDeclaratorContext - Used when we must lookup names in the context
1203 /// of a declarator's nested name specifier.
1204 ///
1205 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1206   // C++0x [basic.lookup.unqual]p13:
1207   //   A name used in the definition of a static data member of class
1208   //   X (after the qualified-id of the static member) is looked up as
1209   //   if the name was used in a member function of X.
1210   // C++0x [basic.lookup.unqual]p14:
1211   //   If a variable member of a namespace is defined outside of the
1212   //   scope of its namespace then any name used in the definition of
1213   //   the variable member (after the declarator-id) is looked up as
1214   //   if the definition of the variable member occurred in its
1215   //   namespace.
1216   // Both of these imply that we should push a scope whose context
1217   // is the semantic context of the declaration.  We can't use
1218   // PushDeclContext here because that context is not necessarily
1219   // lexically contained in the current context.  Fortunately,
1220   // the containing scope should have the appropriate information.
1221
1222   assert(!S->getEntity() && "scope already has entity");
1223
1224 #ifndef NDEBUG
1225   Scope *Ancestor = S->getParent();
1226   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1227   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1228 #endif
1229
1230   CurContext = DC;
1231   S->setEntity(DC);
1232 }
1233
1234 void Sema::ExitDeclaratorContext(Scope *S) {
1235   assert(S->getEntity() == CurContext && "Context imbalance!");
1236
1237   // Switch back to the lexical context.  The safety of this is
1238   // enforced by an assert in EnterDeclaratorContext.
1239   Scope *Ancestor = S->getParent();
1240   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1241   CurContext = Ancestor->getEntity();
1242
1243   // We don't need to do anything with the scope, which is going to
1244   // disappear.
1245 }
1246
1247 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1248   // We assume that the caller has already called
1249   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1250   FunctionDecl *FD = D->getAsFunction();
1251   if (!FD)
1252     return;
1253
1254   // Same implementation as PushDeclContext, but enters the context
1255   // from the lexical parent, rather than the top-level class.
1256   assert(CurContext == FD->getLexicalParent() &&
1257     "The next DeclContext should be lexically contained in the current one.");
1258   CurContext = FD;
1259   S->setEntity(CurContext);
1260
1261   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1262     ParmVarDecl *Param = FD->getParamDecl(P);
1263     // If the parameter has an identifier, then add it to the scope
1264     if (Param->getIdentifier()) {
1265       S->AddDecl(Param);
1266       IdResolver.AddDecl(Param);
1267     }
1268   }
1269 }
1270
1271 void Sema::ActOnExitFunctionContext() {
1272   // Same implementation as PopDeclContext, but returns to the lexical parent,
1273   // rather than the top-level class.
1274   assert(CurContext && "DeclContext imbalance!");
1275   CurContext = CurContext->getLexicalParent();
1276   assert(CurContext && "Popped translation unit!");
1277 }
1278
1279 /// \brief Determine whether we allow overloading of the function
1280 /// PrevDecl with another declaration.
1281 ///
1282 /// This routine determines whether overloading is possible, not
1283 /// whether some new function is actually an overload. It will return
1284 /// true in C++ (where we can always provide overloads) or, as an
1285 /// extension, in C when the previous function is already an
1286 /// overloaded function declaration or has the "overloadable"
1287 /// attribute.
1288 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1289                                        ASTContext &Context) {
1290   if (Context.getLangOpts().CPlusPlus)
1291     return true;
1292
1293   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1294     return true;
1295
1296   return (Previous.getResultKind() == LookupResult::Found
1297           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1298 }
1299
1300 /// Add this decl to the scope shadowed decl chains.
1301 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1302   // Move up the scope chain until we find the nearest enclosing
1303   // non-transparent context. The declaration will be introduced into this
1304   // scope.
1305   while (S->getEntity() && S->getEntity()->isTransparentContext())
1306     S = S->getParent();
1307
1308   // Add scoped declarations into their context, so that they can be
1309   // found later. Declarations without a context won't be inserted
1310   // into any context.
1311   if (AddToContext)
1312     CurContext->addDecl(D);
1313
1314   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1315   // are function-local declarations.
1316   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1317       !D->getDeclContext()->getRedeclContext()->Equals(
1318         D->getLexicalDeclContext()->getRedeclContext()) &&
1319       !D->getLexicalDeclContext()->isFunctionOrMethod())
1320     return;
1321
1322   // Template instantiations should also not be pushed into scope.
1323   if (isa<FunctionDecl>(D) &&
1324       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1325     return;
1326
1327   // If this replaces anything in the current scope,
1328   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1329                                IEnd = IdResolver.end();
1330   for (; I != IEnd; ++I) {
1331     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1332       S->RemoveDecl(*I);
1333       IdResolver.RemoveDecl(*I);
1334
1335       // Should only need to replace one decl.
1336       break;
1337     }
1338   }
1339
1340   S->AddDecl(D);
1341
1342   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1343     // Implicitly-generated labels may end up getting generated in an order that
1344     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1345     // the label at the appropriate place in the identifier chain.
1346     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1347       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1348       if (IDC == CurContext) {
1349         if (!S->isDeclScope(*I))
1350           continue;
1351       } else if (IDC->Encloses(CurContext))
1352         break;
1353     }
1354
1355     IdResolver.InsertDeclAfter(I, D);
1356   } else {
1357     IdResolver.AddDecl(D);
1358   }
1359 }
1360
1361 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1362   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1363     TUScope->AddDecl(D);
1364 }
1365
1366 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1367                          bool AllowInlineNamespace) {
1368   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1369 }
1370
1371 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1372   DeclContext *TargetDC = DC->getPrimaryContext();
1373   do {
1374     if (DeclContext *ScopeDC = S->getEntity())
1375       if (ScopeDC->getPrimaryContext() == TargetDC)
1376         return S;
1377   } while ((S = S->getParent()));
1378
1379   return nullptr;
1380 }
1381
1382 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1383                                             DeclContext*,
1384                                             ASTContext&);
1385
1386 /// Filters out lookup results that don't fall within the given scope
1387 /// as determined by isDeclInScope.
1388 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1389                                 bool ConsiderLinkage,
1390                                 bool AllowInlineNamespace) {
1391   LookupResult::Filter F = R.makeFilter();
1392   while (F.hasNext()) {
1393     NamedDecl *D = F.next();
1394
1395     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1396       continue;
1397
1398     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1399       continue;
1400
1401     F.erase();
1402   }
1403
1404   F.done();
1405 }
1406
1407 static bool isUsingDecl(NamedDecl *D) {
1408   return isa<UsingShadowDecl>(D) ||
1409          isa<UnresolvedUsingTypenameDecl>(D) ||
1410          isa<UnresolvedUsingValueDecl>(D);
1411 }
1412
1413 /// Removes using shadow declarations from the lookup results.
1414 static void RemoveUsingDecls(LookupResult &R) {
1415   LookupResult::Filter F = R.makeFilter();
1416   while (F.hasNext())
1417     if (isUsingDecl(F.next()))
1418       F.erase();
1419
1420   F.done();
1421 }
1422
1423 /// \brief Check for this common pattern:
1424 /// @code
1425 /// class S {
1426 ///   S(const S&); // DO NOT IMPLEMENT
1427 ///   void operator=(const S&); // DO NOT IMPLEMENT
1428 /// };
1429 /// @endcode
1430 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1431   // FIXME: Should check for private access too but access is set after we get
1432   // the decl here.
1433   if (D->doesThisDeclarationHaveABody())
1434     return false;
1435
1436   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1437     return CD->isCopyConstructor();
1438   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1439     return Method->isCopyAssignmentOperator();
1440   return false;
1441 }
1442
1443 // We need this to handle
1444 //
1445 // typedef struct {
1446 //   void *foo() { return 0; }
1447 // } A;
1448 //
1449 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1450 // for example. If 'A', foo will have external linkage. If we have '*A',
1451 // foo will have no linkage. Since we can't know until we get to the end
1452 // of the typedef, this function finds out if D might have non-external linkage.
1453 // Callers should verify at the end of the TU if it D has external linkage or
1454 // not.
1455 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1456   const DeclContext *DC = D->getDeclContext();
1457   while (!DC->isTranslationUnit()) {
1458     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1459       if (!RD->hasNameForLinkage())
1460         return true;
1461     }
1462     DC = DC->getParent();
1463   }
1464
1465   return !D->isExternallyVisible();
1466 }
1467
1468 // FIXME: This needs to be refactored; some other isInMainFile users want
1469 // these semantics.
1470 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1471   if (S.TUKind != TU_Complete)
1472     return false;
1473   return S.SourceMgr.isInMainFile(Loc);
1474 }
1475
1476 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1477   assert(D);
1478
1479   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1480     return false;
1481
1482   // Ignore all entities declared within templates, and out-of-line definitions
1483   // of members of class templates.
1484   if (D->getDeclContext()->isDependentContext() ||
1485       D->getLexicalDeclContext()->isDependentContext())
1486     return false;
1487
1488   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1489     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1490       return false;
1491
1492     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1493       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1494         return false;
1495     } else {
1496       // 'static inline' functions are defined in headers; don't warn.
1497       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1498         return false;
1499     }
1500
1501     if (FD->doesThisDeclarationHaveABody() &&
1502         Context.DeclMustBeEmitted(FD))
1503       return false;
1504   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1505     // Constants and utility variables are defined in headers with internal
1506     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1507     // like "inline".)
1508     if (!isMainFileLoc(*this, VD->getLocation()))
1509       return false;
1510
1511     if (Context.DeclMustBeEmitted(VD))
1512       return false;
1513
1514     if (VD->isStaticDataMember() &&
1515         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1516       return false;
1517
1518     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1519       return false;
1520   } else {
1521     return false;
1522   }
1523
1524   // Only warn for unused decls internal to the translation unit.
1525   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1526   // for inline functions defined in the main source file, for instance.
1527   return mightHaveNonExternalLinkage(D);
1528 }
1529
1530 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1531   if (!D)
1532     return;
1533
1534   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1535     const FunctionDecl *First = FD->getFirstDecl();
1536     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1537       return; // First should already be in the vector.
1538   }
1539
1540   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1541     const VarDecl *First = VD->getFirstDecl();
1542     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1543       return; // First should already be in the vector.
1544   }
1545
1546   if (ShouldWarnIfUnusedFileScopedDecl(D))
1547     UnusedFileScopedDecls.push_back(D);
1548 }
1549
1550 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1551   if (D->isInvalidDecl())
1552     return false;
1553
1554   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1555       D->hasAttr<ObjCPreciseLifetimeAttr>())
1556     return false;
1557
1558   if (isa<LabelDecl>(D))
1559     return true;
1560
1561   // Except for labels, we only care about unused decls that are local to
1562   // functions.
1563   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1564   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1565     // For dependent types, the diagnostic is deferred.
1566     WithinFunction =
1567         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1568   if (!WithinFunction)
1569     return false;
1570
1571   if (isa<TypedefNameDecl>(D))
1572     return true;
1573
1574   // White-list anything that isn't a local variable.
1575   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1576     return false;
1577
1578   // Types of valid local variables should be complete, so this should succeed.
1579   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1580
1581     // White-list anything with an __attribute__((unused)) type.
1582     const auto *Ty = VD->getType().getTypePtr();
1583
1584     // Only look at the outermost level of typedef.
1585     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1586       if (TT->getDecl()->hasAttr<UnusedAttr>())
1587         return false;
1588     }
1589
1590     // If we failed to complete the type for some reason, or if the type is
1591     // dependent, don't diagnose the variable.
1592     if (Ty->isIncompleteType() || Ty->isDependentType())
1593       return false;
1594
1595     // Look at the element type to ensure that the warning behaviour is
1596     // consistent for both scalars and arrays.
1597     Ty = Ty->getBaseElementTypeUnsafe();
1598
1599     if (const TagType *TT = Ty->getAs<TagType>()) {
1600       const TagDecl *Tag = TT->getDecl();
1601       if (Tag->hasAttr<UnusedAttr>())
1602         return false;
1603
1604       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1605         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1606           return false;
1607
1608         if (const Expr *Init = VD->getInit()) {
1609           if (const ExprWithCleanups *Cleanups =
1610                   dyn_cast<ExprWithCleanups>(Init))
1611             Init = Cleanups->getSubExpr();
1612           const CXXConstructExpr *Construct =
1613             dyn_cast<CXXConstructExpr>(Init);
1614           if (Construct && !Construct->isElidable()) {
1615             CXXConstructorDecl *CD = Construct->getConstructor();
1616             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1617               return false;
1618           }
1619         }
1620       }
1621     }
1622
1623     // TODO: __attribute__((unused)) templates?
1624   }
1625
1626   return true;
1627 }
1628
1629 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1630                                      FixItHint &Hint) {
1631   if (isa<LabelDecl>(D)) {
1632     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1633                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1634     if (AfterColon.isInvalid())
1635       return;
1636     Hint = FixItHint::CreateRemoval(CharSourceRange::
1637                                     getCharRange(D->getLocStart(), AfterColon));
1638   }
1639 }
1640
1641 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1642   if (D->getTypeForDecl()->isDependentType())
1643     return;
1644
1645   for (auto *TmpD : D->decls()) {
1646     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1647       DiagnoseUnusedDecl(T);
1648     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1649       DiagnoseUnusedNestedTypedefs(R);
1650   }
1651 }
1652
1653 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1654 /// unless they are marked attr(unused).
1655 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1656   if (!ShouldDiagnoseUnusedDecl(D))
1657     return;
1658
1659   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1660     // typedefs can be referenced later on, so the diagnostics are emitted
1661     // at end-of-translation-unit.
1662     UnusedLocalTypedefNameCandidates.insert(TD);
1663     return;
1664   }
1665
1666   FixItHint Hint;
1667   GenerateFixForUnusedDecl(D, Context, Hint);
1668
1669   unsigned DiagID;
1670   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1671     DiagID = diag::warn_unused_exception_param;
1672   else if (isa<LabelDecl>(D))
1673     DiagID = diag::warn_unused_label;
1674   else
1675     DiagID = diag::warn_unused_variable;
1676
1677   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1678 }
1679
1680 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1681   // Verify that we have no forward references left.  If so, there was a goto
1682   // or address of a label taken, but no definition of it.  Label fwd
1683   // definitions are indicated with a null substmt which is also not a resolved
1684   // MS inline assembly label name.
1685   bool Diagnose = false;
1686   if (L->isMSAsmLabel())
1687     Diagnose = !L->isResolvedMSAsmLabel();
1688   else
1689     Diagnose = L->getStmt() == nullptr;
1690   if (Diagnose)
1691     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1692 }
1693
1694 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1695   S->mergeNRVOIntoParent();
1696
1697   if (S->decl_empty()) return;
1698   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1699          "Scope shouldn't contain decls!");
1700
1701   for (auto *TmpD : S->decls()) {
1702     assert(TmpD && "This decl didn't get pushed??");
1703
1704     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1705     NamedDecl *D = cast<NamedDecl>(TmpD);
1706
1707     if (!D->getDeclName()) continue;
1708
1709     // Diagnose unused variables in this scope.
1710     if (!S->hasUnrecoverableErrorOccurred()) {
1711       DiagnoseUnusedDecl(D);
1712       if (const auto *RD = dyn_cast<RecordDecl>(D))
1713         DiagnoseUnusedNestedTypedefs(RD);
1714     }
1715
1716     // If this was a forward reference to a label, verify it was defined.
1717     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1718       CheckPoppedLabel(LD, *this);
1719
1720     // Remove this name from our lexical scope, and warn on it if we haven't
1721     // already.
1722     IdResolver.RemoveDecl(D);
1723     auto ShadowI = ShadowingDecls.find(D);
1724     if (ShadowI != ShadowingDecls.end()) {
1725       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1726         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1727             << D << FD << FD->getParent();
1728         Diag(FD->getLocation(), diag::note_previous_declaration);
1729       }
1730       ShadowingDecls.erase(ShadowI);
1731     }
1732   }
1733 }
1734
1735 /// \brief Look for an Objective-C class in the translation unit.
1736 ///
1737 /// \param Id The name of the Objective-C class we're looking for. If
1738 /// typo-correction fixes this name, the Id will be updated
1739 /// to the fixed name.
1740 ///
1741 /// \param IdLoc The location of the name in the translation unit.
1742 ///
1743 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1744 /// if there is no class with the given name.
1745 ///
1746 /// \returns The declaration of the named Objective-C class, or NULL if the
1747 /// class could not be found.
1748 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1749                                               SourceLocation IdLoc,
1750                                               bool DoTypoCorrection) {
1751   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1752   // creation from this context.
1753   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1754
1755   if (!IDecl && DoTypoCorrection) {
1756     // Perform typo correction at the given location, but only if we
1757     // find an Objective-C class name.
1758     if (TypoCorrection C = CorrectTypo(
1759             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1760             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1761             CTK_ErrorRecovery)) {
1762       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1763       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1764       Id = IDecl->getIdentifier();
1765     }
1766   }
1767   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1768   // This routine must always return a class definition, if any.
1769   if (Def && Def->getDefinition())
1770       Def = Def->getDefinition();
1771   return Def;
1772 }
1773
1774 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1775 /// from S, where a non-field would be declared. This routine copes
1776 /// with the difference between C and C++ scoping rules in structs and
1777 /// unions. For example, the following code is well-formed in C but
1778 /// ill-formed in C++:
1779 /// @code
1780 /// struct S6 {
1781 ///   enum { BAR } e;
1782 /// };
1783 ///
1784 /// void test_S6() {
1785 ///   struct S6 a;
1786 ///   a.e = BAR;
1787 /// }
1788 /// @endcode
1789 /// For the declaration of BAR, this routine will return a different
1790 /// scope. The scope S will be the scope of the unnamed enumeration
1791 /// within S6. In C++, this routine will return the scope associated
1792 /// with S6, because the enumeration's scope is a transparent
1793 /// context but structures can contain non-field names. In C, this
1794 /// routine will return the translation unit scope, since the
1795 /// enumeration's scope is a transparent context and structures cannot
1796 /// contain non-field names.
1797 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1798   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1799          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1800          (S->isClassScope() && !getLangOpts().CPlusPlus))
1801     S = S->getParent();
1802   return S;
1803 }
1804
1805 /// \brief Looks up the declaration of "struct objc_super" and
1806 /// saves it for later use in building builtin declaration of
1807 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1808 /// pre-existing declaration exists no action takes place.
1809 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1810                                         IdentifierInfo *II) {
1811   if (!II->isStr("objc_msgSendSuper"))
1812     return;
1813   ASTContext &Context = ThisSema.Context;
1814
1815   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1816                       SourceLocation(), Sema::LookupTagName);
1817   ThisSema.LookupName(Result, S);
1818   if (Result.getResultKind() == LookupResult::Found)
1819     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1820       Context.setObjCSuperType(Context.getTagDeclType(TD));
1821 }
1822
1823 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1824   switch (Error) {
1825   case ASTContext::GE_None:
1826     return "";
1827   case ASTContext::GE_Missing_stdio:
1828     return "stdio.h";
1829   case ASTContext::GE_Missing_setjmp:
1830     return "setjmp.h";
1831   case ASTContext::GE_Missing_ucontext:
1832     return "ucontext.h";
1833   }
1834   llvm_unreachable("unhandled error kind");
1835 }
1836
1837 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1838 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1839 /// if we're creating this built-in in anticipation of redeclaring the
1840 /// built-in.
1841 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1842                                      Scope *S, bool ForRedeclaration,
1843                                      SourceLocation Loc) {
1844   LookupPredefedObjCSuperType(*this, S, II);
1845
1846   ASTContext::GetBuiltinTypeError Error;
1847   QualType R = Context.GetBuiltinType(ID, Error);
1848   if (Error) {
1849     if (ForRedeclaration)
1850       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1851           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1852     return nullptr;
1853   }
1854
1855   if (!ForRedeclaration &&
1856       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1857        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1858     Diag(Loc, diag::ext_implicit_lib_function_decl)
1859         << Context.BuiltinInfo.getName(ID) << R;
1860     if (Context.BuiltinInfo.getHeaderName(ID) &&
1861         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1862       Diag(Loc, diag::note_include_header_or_declare)
1863           << Context.BuiltinInfo.getHeaderName(ID)
1864           << Context.BuiltinInfo.getName(ID);
1865   }
1866
1867   if (R.isNull())
1868     return nullptr;
1869
1870   DeclContext *Parent = Context.getTranslationUnitDecl();
1871   if (getLangOpts().CPlusPlus) {
1872     LinkageSpecDecl *CLinkageDecl =
1873         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1874                                 LinkageSpecDecl::lang_c, false);
1875     CLinkageDecl->setImplicit();
1876     Parent->addDecl(CLinkageDecl);
1877     Parent = CLinkageDecl;
1878   }
1879
1880   FunctionDecl *New = FunctionDecl::Create(Context,
1881                                            Parent,
1882                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1883                                            SC_Extern,
1884                                            false,
1885                                            R->isFunctionProtoType());
1886   New->setImplicit();
1887
1888   // Create Decl objects for each parameter, adding them to the
1889   // FunctionDecl.
1890   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1891     SmallVector<ParmVarDecl*, 16> Params;
1892     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1893       ParmVarDecl *parm =
1894           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1895                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1896                               SC_None, nullptr);
1897       parm->setScopeInfo(0, i);
1898       Params.push_back(parm);
1899     }
1900     New->setParams(Params);
1901   }
1902
1903   AddKnownFunctionAttributes(New);
1904   RegisterLocallyScopedExternCDecl(New, S);
1905
1906   // TUScope is the translation-unit scope to insert this function into.
1907   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1908   // relate Scopes to DeclContexts, and probably eliminate CurContext
1909   // entirely, but we're not there yet.
1910   DeclContext *SavedContext = CurContext;
1911   CurContext = Parent;
1912   PushOnScopeChains(New, TUScope);
1913   CurContext = SavedContext;
1914   return New;
1915 }
1916
1917 /// Typedef declarations don't have linkage, but they still denote the same
1918 /// entity if their types are the same.
1919 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1920 /// isSameEntity.
1921 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1922                                                      TypedefNameDecl *Decl,
1923                                                      LookupResult &Previous) {
1924   // This is only interesting when modules are enabled.
1925   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1926     return;
1927
1928   // Empty sets are uninteresting.
1929   if (Previous.empty())
1930     return;
1931
1932   LookupResult::Filter Filter = Previous.makeFilter();
1933   while (Filter.hasNext()) {
1934     NamedDecl *Old = Filter.next();
1935
1936     // Non-hidden declarations are never ignored.
1937     if (S.isVisible(Old))
1938       continue;
1939
1940     // Declarations of the same entity are not ignored, even if they have
1941     // different linkages.
1942     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1943       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1944                                 Decl->getUnderlyingType()))
1945         continue;
1946
1947       // If both declarations give a tag declaration a typedef name for linkage
1948       // purposes, then they declare the same entity.
1949       if (S.getLangOpts().CPlusPlus &&
1950           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1951           Decl->getAnonDeclWithTypedefName())
1952         continue;
1953     }
1954
1955     Filter.erase();
1956   }
1957
1958   Filter.done();
1959 }
1960
1961 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1962   QualType OldType;
1963   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1964     OldType = OldTypedef->getUnderlyingType();
1965   else
1966     OldType = Context.getTypeDeclType(Old);
1967   QualType NewType = New->getUnderlyingType();
1968
1969   if (NewType->isVariablyModifiedType()) {
1970     // Must not redefine a typedef with a variably-modified type.
1971     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1972     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1973       << Kind << NewType;
1974     if (Old->getLocation().isValid())
1975       Diag(Old->getLocation(), diag::note_previous_definition);
1976     New->setInvalidDecl();
1977     return true;
1978   }
1979
1980   if (OldType != NewType &&
1981       !OldType->isDependentType() &&
1982       !NewType->isDependentType() &&
1983       !Context.hasSameType(OldType, NewType)) {
1984     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1985     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1986       << Kind << NewType << OldType;
1987     if (Old->getLocation().isValid())
1988       Diag(Old->getLocation(), diag::note_previous_definition);
1989     New->setInvalidDecl();
1990     return true;
1991   }
1992   return false;
1993 }
1994
1995 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1996 /// same name and scope as a previous declaration 'Old'.  Figure out
1997 /// how to resolve this situation, merging decls or emitting
1998 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1999 ///
2000 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2001                                 LookupResult &OldDecls) {
2002   // If the new decl is known invalid already, don't bother doing any
2003   // merging checks.
2004   if (New->isInvalidDecl()) return;
2005
2006   // Allow multiple definitions for ObjC built-in typedefs.
2007   // FIXME: Verify the underlying types are equivalent!
2008   if (getLangOpts().ObjC1) {
2009     const IdentifierInfo *TypeID = New->getIdentifier();
2010     switch (TypeID->getLength()) {
2011     default: break;
2012     case 2:
2013       {
2014         if (!TypeID->isStr("id"))
2015           break;
2016         QualType T = New->getUnderlyingType();
2017         if (!T->isPointerType())
2018           break;
2019         if (!T->isVoidPointerType()) {
2020           QualType PT = T->getAs<PointerType>()->getPointeeType();
2021           if (!PT->isStructureType())
2022             break;
2023         }
2024         Context.setObjCIdRedefinitionType(T);
2025         // Install the built-in type for 'id', ignoring the current definition.
2026         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2027         return;
2028       }
2029     case 5:
2030       if (!TypeID->isStr("Class"))
2031         break;
2032       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2033       // Install the built-in type for 'Class', ignoring the current definition.
2034       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2035       return;
2036     case 3:
2037       if (!TypeID->isStr("SEL"))
2038         break;
2039       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2040       // Install the built-in type for 'SEL', ignoring the current definition.
2041       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2042       return;
2043     }
2044     // Fall through - the typedef name was not a builtin type.
2045   }
2046
2047   // Verify the old decl was also a type.
2048   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2049   if (!Old) {
2050     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2051       << New->getDeclName();
2052
2053     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2054     if (OldD->getLocation().isValid())
2055       Diag(OldD->getLocation(), diag::note_previous_definition);
2056
2057     return New->setInvalidDecl();
2058   }
2059
2060   // If the old declaration is invalid, just give up here.
2061   if (Old->isInvalidDecl())
2062     return New->setInvalidDecl();
2063
2064   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2065     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2066     auto *NewTag = New->getAnonDeclWithTypedefName();
2067     NamedDecl *Hidden = nullptr;
2068     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2069         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2070         !hasVisibleDefinition(OldTag, &Hidden)) {
2071       // There is a definition of this tag, but it is not visible. Use it
2072       // instead of our tag.
2073       New->setTypeForDecl(OldTD->getTypeForDecl());
2074       if (OldTD->isModed())
2075         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2076                                     OldTD->getUnderlyingType());
2077       else
2078         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2079
2080       // Make the old tag definition visible.
2081       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2082
2083       // If this was an unscoped enumeration, yank all of its enumerators
2084       // out of the scope.
2085       if (isa<EnumDecl>(NewTag)) {
2086         Scope *EnumScope = getNonFieldDeclScope(S);
2087         for (auto *D : NewTag->decls()) {
2088           auto *ED = cast<EnumConstantDecl>(D);
2089           assert(EnumScope->isDeclScope(ED));
2090           EnumScope->RemoveDecl(ED);
2091           IdResolver.RemoveDecl(ED);
2092           ED->getLexicalDeclContext()->removeDecl(ED);
2093         }
2094       }
2095     }
2096   }
2097
2098   // If the typedef types are not identical, reject them in all languages and
2099   // with any extensions enabled.
2100   if (isIncompatibleTypedef(Old, New))
2101     return;
2102
2103   // The types match.  Link up the redeclaration chain and merge attributes if
2104   // the old declaration was a typedef.
2105   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2106     New->setPreviousDecl(Typedef);
2107     mergeDeclAttributes(New, Old);
2108   }
2109
2110   if (getLangOpts().MicrosoftExt)
2111     return;
2112
2113   if (getLangOpts().CPlusPlus) {
2114     // C++ [dcl.typedef]p2:
2115     //   In a given non-class scope, a typedef specifier can be used to
2116     //   redefine the name of any type declared in that scope to refer
2117     //   to the type to which it already refers.
2118     if (!isa<CXXRecordDecl>(CurContext))
2119       return;
2120
2121     // C++0x [dcl.typedef]p4:
2122     //   In a given class scope, a typedef specifier can be used to redefine
2123     //   any class-name declared in that scope that is not also a typedef-name
2124     //   to refer to the type to which it already refers.
2125     //
2126     // This wording came in via DR424, which was a correction to the
2127     // wording in DR56, which accidentally banned code like:
2128     //
2129     //   struct S {
2130     //     typedef struct A { } A;
2131     //   };
2132     //
2133     // in the C++03 standard. We implement the C++0x semantics, which
2134     // allow the above but disallow
2135     //
2136     //   struct S {
2137     //     typedef int I;
2138     //     typedef int I;
2139     //   };
2140     //
2141     // since that was the intent of DR56.
2142     if (!isa<TypedefNameDecl>(Old))
2143       return;
2144
2145     Diag(New->getLocation(), diag::err_redefinition)
2146       << New->getDeclName();
2147     Diag(Old->getLocation(), diag::note_previous_definition);
2148     return New->setInvalidDecl();
2149   }
2150
2151   // Modules always permit redefinition of typedefs, as does C11.
2152   if (getLangOpts().Modules || getLangOpts().C11)
2153     return;
2154
2155   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2156   // is normally mapped to an error, but can be controlled with
2157   // -Wtypedef-redefinition.  If either the original or the redefinition is
2158   // in a system header, don't emit this for compatibility with GCC.
2159   if (getDiagnostics().getSuppressSystemWarnings() &&
2160       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2161       (Old->isImplicit() ||
2162        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2163        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2164     return;
2165
2166   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2167     << New->getDeclName();
2168   Diag(Old->getLocation(), diag::note_previous_definition);
2169 }
2170
2171 /// DeclhasAttr - returns true if decl Declaration already has the target
2172 /// attribute.
2173 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2174   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2175   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2176   for (const auto *i : D->attrs())
2177     if (i->getKind() == A->getKind()) {
2178       if (Ann) {
2179         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2180           return true;
2181         continue;
2182       }
2183       // FIXME: Don't hardcode this check
2184       if (OA && isa<OwnershipAttr>(i))
2185         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2186       return true;
2187     }
2188
2189   return false;
2190 }
2191
2192 static bool isAttributeTargetADefinition(Decl *D) {
2193   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2194     return VD->isThisDeclarationADefinition();
2195   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2196     return TD->isCompleteDefinition() || TD->isBeingDefined();
2197   return true;
2198 }
2199
2200 /// Merge alignment attributes from \p Old to \p New, taking into account the
2201 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2202 ///
2203 /// \return \c true if any attributes were added to \p New.
2204 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2205   // Look for alignas attributes on Old, and pick out whichever attribute
2206   // specifies the strictest alignment requirement.
2207   AlignedAttr *OldAlignasAttr = nullptr;
2208   AlignedAttr *OldStrictestAlignAttr = nullptr;
2209   unsigned OldAlign = 0;
2210   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2211     // FIXME: We have no way of representing inherited dependent alignments
2212     // in a case like:
2213     //   template<int A, int B> struct alignas(A) X;
2214     //   template<int A, int B> struct alignas(B) X {};
2215     // For now, we just ignore any alignas attributes which are not on the
2216     // definition in such a case.
2217     if (I->isAlignmentDependent())
2218       return false;
2219
2220     if (I->isAlignas())
2221       OldAlignasAttr = I;
2222
2223     unsigned Align = I->getAlignment(S.Context);
2224     if (Align > OldAlign) {
2225       OldAlign = Align;
2226       OldStrictestAlignAttr = I;
2227     }
2228   }
2229
2230   // Look for alignas attributes on New.
2231   AlignedAttr *NewAlignasAttr = nullptr;
2232   unsigned NewAlign = 0;
2233   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2234     if (I->isAlignmentDependent())
2235       return false;
2236
2237     if (I->isAlignas())
2238       NewAlignasAttr = I;
2239
2240     unsigned Align = I->getAlignment(S.Context);
2241     if (Align > NewAlign)
2242       NewAlign = Align;
2243   }
2244
2245   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2246     // Both declarations have 'alignas' attributes. We require them to match.
2247     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2248     // fall short. (If two declarations both have alignas, they must both match
2249     // every definition, and so must match each other if there is a definition.)
2250
2251     // If either declaration only contains 'alignas(0)' specifiers, then it
2252     // specifies the natural alignment for the type.
2253     if (OldAlign == 0 || NewAlign == 0) {
2254       QualType Ty;
2255       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2256         Ty = VD->getType();
2257       else
2258         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2259
2260       if (OldAlign == 0)
2261         OldAlign = S.Context.getTypeAlign(Ty);
2262       if (NewAlign == 0)
2263         NewAlign = S.Context.getTypeAlign(Ty);
2264     }
2265
2266     if (OldAlign != NewAlign) {
2267       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2268         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2269         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2270       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2271     }
2272   }
2273
2274   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2275     // C++11 [dcl.align]p6:
2276     //   if any declaration of an entity has an alignment-specifier,
2277     //   every defining declaration of that entity shall specify an
2278     //   equivalent alignment.
2279     // C11 6.7.5/7:
2280     //   If the definition of an object does not have an alignment
2281     //   specifier, any other declaration of that object shall also
2282     //   have no alignment specifier.
2283     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2284       << OldAlignasAttr;
2285     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2286       << OldAlignasAttr;
2287   }
2288
2289   bool AnyAdded = false;
2290
2291   // Ensure we have an attribute representing the strictest alignment.
2292   if (OldAlign > NewAlign) {
2293     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2294     Clone->setInherited(true);
2295     New->addAttr(Clone);
2296     AnyAdded = true;
2297   }
2298
2299   // Ensure we have an alignas attribute if the old declaration had one.
2300   if (OldAlignasAttr && !NewAlignasAttr &&
2301       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2302     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2303     Clone->setInherited(true);
2304     New->addAttr(Clone);
2305     AnyAdded = true;
2306   }
2307
2308   return AnyAdded;
2309 }
2310
2311 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2312                                const InheritableAttr *Attr,
2313                                Sema::AvailabilityMergeKind AMK) {
2314   // This function copies an attribute Attr from a previous declaration to the
2315   // new declaration D if the new declaration doesn't itself have that attribute
2316   // yet or if that attribute allows duplicates.
2317   // If you're adding a new attribute that requires logic different from
2318   // "use explicit attribute on decl if present, else use attribute from
2319   // previous decl", for example if the attribute needs to be consistent
2320   // between redeclarations, you need to call a custom merge function here.
2321   InheritableAttr *NewAttr = nullptr;
2322   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2323   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2324     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2325                                       AA->isImplicit(), AA->getIntroduced(),
2326                                       AA->getDeprecated(),
2327                                       AA->getObsoleted(), AA->getUnavailable(),
2328                                       AA->getMessage(), AA->getStrict(),
2329                                       AA->getReplacement(), AMK,
2330                                       AttrSpellingListIndex);
2331   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2332     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2333                                     AttrSpellingListIndex);
2334   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2335     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2336                                         AttrSpellingListIndex);
2337   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2338     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2339                                    AttrSpellingListIndex);
2340   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2341     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2342                                    AttrSpellingListIndex);
2343   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2344     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2345                                 FA->getFormatIdx(), FA->getFirstArg(),
2346                                 AttrSpellingListIndex);
2347   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2348     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2349                                  AttrSpellingListIndex);
2350   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2351     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2352                                        AttrSpellingListIndex,
2353                                        IA->getSemanticSpelling());
2354   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2355     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2356                                       &S.Context.Idents.get(AA->getSpelling()),
2357                                       AttrSpellingListIndex);
2358   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2359            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2360             isa<CUDAGlobalAttr>(Attr))) {
2361     // CUDA target attributes are part of function signature for
2362     // overloading purposes and must not be merged.
2363     return false;
2364   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2365     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2366   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2367     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2368   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2369     NewAttr = S.mergeInternalLinkageAttr(
2370         D, InternalLinkageA->getRange(),
2371         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2372         AttrSpellingListIndex);
2373   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2374     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2375                                 &S.Context.Idents.get(CommonA->getSpelling()),
2376                                 AttrSpellingListIndex);
2377   else if (isa<AlignedAttr>(Attr))
2378     // AlignedAttrs are handled separately, because we need to handle all
2379     // such attributes on a declaration at the same time.
2380     NewAttr = nullptr;
2381   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2382            (AMK == Sema::AMK_Override ||
2383             AMK == Sema::AMK_ProtocolImplementation))
2384     NewAttr = nullptr;
2385   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2386     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2387                               UA->getGuid());
2388   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2389     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2390
2391   if (NewAttr) {
2392     NewAttr->setInherited(true);
2393     D->addAttr(NewAttr);
2394     if (isa<MSInheritanceAttr>(NewAttr))
2395       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2396     return true;
2397   }
2398
2399   return false;
2400 }
2401
2402 static const Decl *getDefinition(const Decl *D) {
2403   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2404     return TD->getDefinition();
2405   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2406     const VarDecl *Def = VD->getDefinition();
2407     if (Def)
2408       return Def;
2409     return VD->getActingDefinition();
2410   }
2411   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2412     return FD->getDefinition();
2413   return nullptr;
2414 }
2415
2416 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2417   for (const auto *Attribute : D->attrs())
2418     if (Attribute->getKind() == Kind)
2419       return true;
2420   return false;
2421 }
2422
2423 /// checkNewAttributesAfterDef - If we already have a definition, check that
2424 /// there are no new attributes in this declaration.
2425 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2426   if (!New->hasAttrs())
2427     return;
2428
2429   const Decl *Def = getDefinition(Old);
2430   if (!Def || Def == New)
2431     return;
2432
2433   AttrVec &NewAttributes = New->getAttrs();
2434   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2435     const Attr *NewAttribute = NewAttributes[I];
2436
2437     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2438       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2439         Sema::SkipBodyInfo SkipBody;
2440         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2441
2442         // If we're skipping this definition, drop the "alias" attribute.
2443         if (SkipBody.ShouldSkip) {
2444           NewAttributes.erase(NewAttributes.begin() + I);
2445           --E;
2446           continue;
2447         }
2448       } else {
2449         VarDecl *VD = cast<VarDecl>(New);
2450         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2451                                 VarDecl::TentativeDefinition
2452                             ? diag::err_alias_after_tentative
2453                             : diag::err_redefinition;
2454         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2455         S.Diag(Def->getLocation(), diag::note_previous_definition);
2456         VD->setInvalidDecl();
2457       }
2458       ++I;
2459       continue;
2460     }
2461
2462     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2463       // Tentative definitions are only interesting for the alias check above.
2464       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2465         ++I;
2466         continue;
2467       }
2468     }
2469
2470     if (hasAttribute(Def, NewAttribute->getKind())) {
2471       ++I;
2472       continue; // regular attr merging will take care of validating this.
2473     }
2474
2475     if (isa<C11NoReturnAttr>(NewAttribute)) {
2476       // C's _Noreturn is allowed to be added to a function after it is defined.
2477       ++I;
2478       continue;
2479     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2480       if (AA->isAlignas()) {
2481         // C++11 [dcl.align]p6:
2482         //   if any declaration of an entity has an alignment-specifier,
2483         //   every defining declaration of that entity shall specify an
2484         //   equivalent alignment.
2485         // C11 6.7.5/7:
2486         //   If the definition of an object does not have an alignment
2487         //   specifier, any other declaration of that object shall also
2488         //   have no alignment specifier.
2489         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2490           << AA;
2491         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2492           << AA;
2493         NewAttributes.erase(NewAttributes.begin() + I);
2494         --E;
2495         continue;
2496       }
2497     }
2498
2499     S.Diag(NewAttribute->getLocation(),
2500            diag::warn_attribute_precede_definition);
2501     S.Diag(Def->getLocation(), diag::note_previous_definition);
2502     NewAttributes.erase(NewAttributes.begin() + I);
2503     --E;
2504   }
2505 }
2506
2507 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2508 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2509                                AvailabilityMergeKind AMK) {
2510   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2511     UsedAttr *NewAttr = OldAttr->clone(Context);
2512     NewAttr->setInherited(true);
2513     New->addAttr(NewAttr);
2514   }
2515
2516   if (!Old->hasAttrs() && !New->hasAttrs())
2517     return;
2518
2519   // Attributes declared post-definition are currently ignored.
2520   checkNewAttributesAfterDef(*this, New, Old);
2521
2522   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2523     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2524       if (OldA->getLabel() != NewA->getLabel()) {
2525         // This redeclaration changes __asm__ label.
2526         Diag(New->getLocation(), diag::err_different_asm_label);
2527         Diag(OldA->getLocation(), diag::note_previous_declaration);
2528       }
2529     } else if (Old->isUsed()) {
2530       // This redeclaration adds an __asm__ label to a declaration that has
2531       // already been ODR-used.
2532       Diag(New->getLocation(), diag::err_late_asm_label_name)
2533         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2534     }
2535   }
2536
2537   // Re-declaration cannot add abi_tag's.
2538   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2539     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2540       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2541         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2542                       NewTag) == OldAbiTagAttr->tags_end()) {
2543           Diag(NewAbiTagAttr->getLocation(),
2544                diag::err_new_abi_tag_on_redeclaration)
2545               << NewTag;
2546           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2547         }
2548       }
2549     } else {
2550       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2551       Diag(Old->getLocation(), diag::note_previous_declaration);
2552     }
2553   }
2554
2555   if (!Old->hasAttrs())
2556     return;
2557
2558   bool foundAny = New->hasAttrs();
2559
2560   // Ensure that any moving of objects within the allocated map is done before
2561   // we process them.
2562   if (!foundAny) New->setAttrs(AttrVec());
2563
2564   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2565     // Ignore deprecated/unavailable/availability attributes if requested.
2566     AvailabilityMergeKind LocalAMK = AMK_None;
2567     if (isa<DeprecatedAttr>(I) ||
2568         isa<UnavailableAttr>(I) ||
2569         isa<AvailabilityAttr>(I)) {
2570       switch (AMK) {
2571       case AMK_None:
2572         continue;
2573
2574       case AMK_Redeclaration:
2575       case AMK_Override:
2576       case AMK_ProtocolImplementation:
2577         LocalAMK = AMK;
2578         break;
2579       }
2580     }
2581
2582     // Already handled.
2583     if (isa<UsedAttr>(I))
2584       continue;
2585
2586     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2587       foundAny = true;
2588   }
2589
2590   if (mergeAlignedAttrs(*this, New, Old))
2591     foundAny = true;
2592
2593   if (!foundAny) New->dropAttrs();
2594 }
2595
2596 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2597 /// to the new one.
2598 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2599                                      const ParmVarDecl *oldDecl,
2600                                      Sema &S) {
2601   // C++11 [dcl.attr.depend]p2:
2602   //   The first declaration of a function shall specify the
2603   //   carries_dependency attribute for its declarator-id if any declaration
2604   //   of the function specifies the carries_dependency attribute.
2605   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2606   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2607     S.Diag(CDA->getLocation(),
2608            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2609     // Find the first declaration of the parameter.
2610     // FIXME: Should we build redeclaration chains for function parameters?
2611     const FunctionDecl *FirstFD =
2612       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2613     const ParmVarDecl *FirstVD =
2614       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2615     S.Diag(FirstVD->getLocation(),
2616            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2617   }
2618
2619   if (!oldDecl->hasAttrs())
2620     return;
2621
2622   bool foundAny = newDecl->hasAttrs();
2623
2624   // Ensure that any moving of objects within the allocated map is
2625   // done before we process them.
2626   if (!foundAny) newDecl->setAttrs(AttrVec());
2627
2628   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2629     if (!DeclHasAttr(newDecl, I)) {
2630       InheritableAttr *newAttr =
2631         cast<InheritableParamAttr>(I->clone(S.Context));
2632       newAttr->setInherited(true);
2633       newDecl->addAttr(newAttr);
2634       foundAny = true;
2635     }
2636   }
2637
2638   if (!foundAny) newDecl->dropAttrs();
2639 }
2640
2641 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2642                                 const ParmVarDecl *OldParam,
2643                                 Sema &S) {
2644   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2645     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2646       if (*Oldnullability != *Newnullability) {
2647         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2648           << DiagNullabilityKind(
2649                *Newnullability,
2650                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2651                 != 0))
2652           << DiagNullabilityKind(
2653                *Oldnullability,
2654                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2655                 != 0));
2656         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2657       }
2658     } else {
2659       QualType NewT = NewParam->getType();
2660       NewT = S.Context.getAttributedType(
2661                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2662                          NewT, NewT);
2663       NewParam->setType(NewT);
2664     }
2665   }
2666 }
2667
2668 namespace {
2669
2670 /// Used in MergeFunctionDecl to keep track of function parameters in
2671 /// C.
2672 struct GNUCompatibleParamWarning {
2673   ParmVarDecl *OldParm;
2674   ParmVarDecl *NewParm;
2675   QualType PromotedType;
2676 };
2677
2678 } // end anonymous namespace
2679
2680 /// getSpecialMember - get the special member enum for a method.
2681 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2682   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2683     if (Ctor->isDefaultConstructor())
2684       return Sema::CXXDefaultConstructor;
2685
2686     if (Ctor->isCopyConstructor())
2687       return Sema::CXXCopyConstructor;
2688
2689     if (Ctor->isMoveConstructor())
2690       return Sema::CXXMoveConstructor;
2691   } else if (isa<CXXDestructorDecl>(MD)) {
2692     return Sema::CXXDestructor;
2693   } else if (MD->isCopyAssignmentOperator()) {
2694     return Sema::CXXCopyAssignment;
2695   } else if (MD->isMoveAssignmentOperator()) {
2696     return Sema::CXXMoveAssignment;
2697   }
2698
2699   return Sema::CXXInvalid;
2700 }
2701
2702 // Determine whether the previous declaration was a definition, implicit
2703 // declaration, or a declaration.
2704 template <typename T>
2705 static std::pair<diag::kind, SourceLocation>
2706 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2707   diag::kind PrevDiag;
2708   SourceLocation OldLocation = Old->getLocation();
2709   if (Old->isThisDeclarationADefinition())
2710     PrevDiag = diag::note_previous_definition;
2711   else if (Old->isImplicit()) {
2712     PrevDiag = diag::note_previous_implicit_declaration;
2713     if (OldLocation.isInvalid())
2714       OldLocation = New->getLocation();
2715   } else
2716     PrevDiag = diag::note_previous_declaration;
2717   return std::make_pair(PrevDiag, OldLocation);
2718 }
2719
2720 /// canRedefineFunction - checks if a function can be redefined. Currently,
2721 /// only extern inline functions can be redefined, and even then only in
2722 /// GNU89 mode.
2723 static bool canRedefineFunction(const FunctionDecl *FD,
2724                                 const LangOptions& LangOpts) {
2725   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2726           !LangOpts.CPlusPlus &&
2727           FD->isInlineSpecified() &&
2728           FD->getStorageClass() == SC_Extern);
2729 }
2730
2731 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2732   const AttributedType *AT = T->getAs<AttributedType>();
2733   while (AT && !AT->isCallingConv())
2734     AT = AT->getModifiedType()->getAs<AttributedType>();
2735   return AT;
2736 }
2737
2738 template <typename T>
2739 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2740   const DeclContext *DC = Old->getDeclContext();
2741   if (DC->isRecord())
2742     return false;
2743
2744   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2745   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2746     return true;
2747   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2748     return true;
2749   return false;
2750 }
2751
2752 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2753 static bool isExternC(VarTemplateDecl *) { return false; }
2754
2755 /// \brief Check whether a redeclaration of an entity introduced by a
2756 /// using-declaration is valid, given that we know it's not an overload
2757 /// (nor a hidden tag declaration).
2758 template<typename ExpectedDecl>
2759 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2760                                    ExpectedDecl *New) {
2761   // C++11 [basic.scope.declarative]p4:
2762   //   Given a set of declarations in a single declarative region, each of
2763   //   which specifies the same unqualified name,
2764   //   -- they shall all refer to the same entity, or all refer to functions
2765   //      and function templates; or
2766   //   -- exactly one declaration shall declare a class name or enumeration
2767   //      name that is not a typedef name and the other declarations shall all
2768   //      refer to the same variable or enumerator, or all refer to functions
2769   //      and function templates; in this case the class name or enumeration
2770   //      name is hidden (3.3.10).
2771
2772   // C++11 [namespace.udecl]p14:
2773   //   If a function declaration in namespace scope or block scope has the
2774   //   same name and the same parameter-type-list as a function introduced
2775   //   by a using-declaration, and the declarations do not declare the same
2776   //   function, the program is ill-formed.
2777
2778   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2779   if (Old &&
2780       !Old->getDeclContext()->getRedeclContext()->Equals(
2781           New->getDeclContext()->getRedeclContext()) &&
2782       !(isExternC(Old) && isExternC(New)))
2783     Old = nullptr;
2784
2785   if (!Old) {
2786     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2787     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2788     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2789     return true;
2790   }
2791   return false;
2792 }
2793
2794 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2795                                             const FunctionDecl *B) {
2796   assert(A->getNumParams() == B->getNumParams());
2797
2798   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2799     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2800     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2801     if (AttrA == AttrB)
2802       return true;
2803     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2804   };
2805
2806   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2807 }
2808
2809 /// MergeFunctionDecl - We just parsed a function 'New' from
2810 /// declarator D which has the same name and scope as a previous
2811 /// declaration 'Old'.  Figure out how to resolve this situation,
2812 /// merging decls or emitting diagnostics as appropriate.
2813 ///
2814 /// In C++, New and Old must be declarations that are not
2815 /// overloaded. Use IsOverload to determine whether New and Old are
2816 /// overloaded, and to select the Old declaration that New should be
2817 /// merged with.
2818 ///
2819 /// Returns true if there was an error, false otherwise.
2820 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2821                              Scope *S, bool MergeTypeWithOld) {
2822   // Verify the old decl was also a function.
2823   FunctionDecl *Old = OldD->getAsFunction();
2824   if (!Old) {
2825     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2826       if (New->getFriendObjectKind()) {
2827         Diag(New->getLocation(), diag::err_using_decl_friend);
2828         Diag(Shadow->getTargetDecl()->getLocation(),
2829              diag::note_using_decl_target);
2830         Diag(Shadow->getUsingDecl()->getLocation(),
2831              diag::note_using_decl) << 0;
2832         return true;
2833       }
2834
2835       // Check whether the two declarations might declare the same function.
2836       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2837         return true;
2838       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2839     } else {
2840       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2841         << New->getDeclName();
2842       Diag(OldD->getLocation(), diag::note_previous_definition);
2843       return true;
2844     }
2845   }
2846
2847   // If the old declaration is invalid, just give up here.
2848   if (Old->isInvalidDecl())
2849     return true;
2850
2851   diag::kind PrevDiag;
2852   SourceLocation OldLocation;
2853   std::tie(PrevDiag, OldLocation) =
2854       getNoteDiagForInvalidRedeclaration(Old, New);
2855
2856   // Don't complain about this if we're in GNU89 mode and the old function
2857   // is an extern inline function.
2858   // Don't complain about specializations. They are not supposed to have
2859   // storage classes.
2860   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2861       New->getStorageClass() == SC_Static &&
2862       Old->hasExternalFormalLinkage() &&
2863       !New->getTemplateSpecializationInfo() &&
2864       !canRedefineFunction(Old, getLangOpts())) {
2865     if (getLangOpts().MicrosoftExt) {
2866       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2867       Diag(OldLocation, PrevDiag);
2868     } else {
2869       Diag(New->getLocation(), diag::err_static_non_static) << New;
2870       Diag(OldLocation, PrevDiag);
2871       return true;
2872     }
2873   }
2874
2875   if (New->hasAttr<InternalLinkageAttr>() &&
2876       !Old->hasAttr<InternalLinkageAttr>()) {
2877     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2878         << New->getDeclName();
2879     Diag(Old->getLocation(), diag::note_previous_definition);
2880     New->dropAttr<InternalLinkageAttr>();
2881   }
2882
2883   // If a function is first declared with a calling convention, but is later
2884   // declared or defined without one, all following decls assume the calling
2885   // convention of the first.
2886   //
2887   // It's OK if a function is first declared without a calling convention,
2888   // but is later declared or defined with the default calling convention.
2889   //
2890   // To test if either decl has an explicit calling convention, we look for
2891   // AttributedType sugar nodes on the type as written.  If they are missing or
2892   // were canonicalized away, we assume the calling convention was implicit.
2893   //
2894   // Note also that we DO NOT return at this point, because we still have
2895   // other tests to run.
2896   QualType OldQType = Context.getCanonicalType(Old->getType());
2897   QualType NewQType = Context.getCanonicalType(New->getType());
2898   const FunctionType *OldType = cast<FunctionType>(OldQType);
2899   const FunctionType *NewType = cast<FunctionType>(NewQType);
2900   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2901   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2902   bool RequiresAdjustment = false;
2903
2904   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2905     FunctionDecl *First = Old->getFirstDecl();
2906     const FunctionType *FT =
2907         First->getType().getCanonicalType()->castAs<FunctionType>();
2908     FunctionType::ExtInfo FI = FT->getExtInfo();
2909     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2910     if (!NewCCExplicit) {
2911       // Inherit the CC from the previous declaration if it was specified
2912       // there but not here.
2913       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2914       RequiresAdjustment = true;
2915     } else {
2916       // Calling conventions aren't compatible, so complain.
2917       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2918       Diag(New->getLocation(), diag::err_cconv_change)
2919         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2920         << !FirstCCExplicit
2921         << (!FirstCCExplicit ? "" :
2922             FunctionType::getNameForCallConv(FI.getCC()));
2923
2924       // Put the note on the first decl, since it is the one that matters.
2925       Diag(First->getLocation(), diag::note_previous_declaration);
2926       return true;
2927     }
2928   }
2929
2930   // FIXME: diagnose the other way around?
2931   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2932     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2933     RequiresAdjustment = true;
2934   }
2935
2936   // Merge regparm attribute.
2937   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2938       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2939     if (NewTypeInfo.getHasRegParm()) {
2940       Diag(New->getLocation(), diag::err_regparm_mismatch)
2941         << NewType->getRegParmType()
2942         << OldType->getRegParmType();
2943       Diag(OldLocation, diag::note_previous_declaration);
2944       return true;
2945     }
2946
2947     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2948     RequiresAdjustment = true;
2949   }
2950
2951   // Merge ns_returns_retained attribute.
2952   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2953     if (NewTypeInfo.getProducesResult()) {
2954       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
2955           << "'ns_returns_retained'";
2956       Diag(OldLocation, diag::note_previous_declaration);
2957       return true;
2958     }
2959
2960     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2961     RequiresAdjustment = true;
2962   }
2963
2964   if (OldTypeInfo.getNoCallerSavedRegs() !=
2965       NewTypeInfo.getNoCallerSavedRegs()) {
2966     if (NewTypeInfo.getNoCallerSavedRegs()) {
2967       AnyX86NoCallerSavedRegistersAttr *Attr = 
2968         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
2969       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
2970       Diag(OldLocation, diag::note_previous_declaration);
2971       return true;
2972     }
2973
2974     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
2975     RequiresAdjustment = true;
2976   }
2977
2978   if (RequiresAdjustment) {
2979     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2980     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2981     New->setType(QualType(AdjustedType, 0));
2982     NewQType = Context.getCanonicalType(New->getType());
2983     NewType = cast<FunctionType>(NewQType);
2984   }
2985
2986   // If this redeclaration makes the function inline, we may need to add it to
2987   // UndefinedButUsed.
2988   if (!Old->isInlined() && New->isInlined() &&
2989       !New->hasAttr<GNUInlineAttr>() &&
2990       !getLangOpts().GNUInline &&
2991       Old->isUsed(false) &&
2992       !Old->isDefined() && !New->isThisDeclarationADefinition())
2993     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2994                                            SourceLocation()));
2995
2996   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2997   // about it.
2998   if (New->hasAttr<GNUInlineAttr>() &&
2999       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3000     UndefinedButUsed.erase(Old->getCanonicalDecl());
3001   }
3002
3003   // If pass_object_size params don't match up perfectly, this isn't a valid
3004   // redeclaration.
3005   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3006       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3007     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3008         << New->getDeclName();
3009     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3010     return true;
3011   }
3012
3013   if (getLangOpts().CPlusPlus) {
3014     // C++1z [over.load]p2
3015     //   Certain function declarations cannot be overloaded:
3016     //     -- Function declarations that differ only in the return type,
3017     //        the exception specification, or both cannot be overloaded.
3018
3019     // Check the exception specifications match. This may recompute the type of
3020     // both Old and New if it resolved exception specifications, so grab the
3021     // types again after this. Because this updates the type, we do this before
3022     // any of the other checks below, which may update the "de facto" NewQType
3023     // but do not necessarily update the type of New.
3024     if (CheckEquivalentExceptionSpec(Old, New))
3025       return true;
3026     OldQType = Context.getCanonicalType(Old->getType());
3027     NewQType = Context.getCanonicalType(New->getType());
3028
3029     // Go back to the type source info to compare the declared return types,
3030     // per C++1y [dcl.type.auto]p13:
3031     //   Redeclarations or specializations of a function or function template
3032     //   with a declared return type that uses a placeholder type shall also
3033     //   use that placeholder, not a deduced type.
3034     QualType OldDeclaredReturnType =
3035         (Old->getTypeSourceInfo()
3036              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3037              : OldType)->getReturnType();
3038     QualType NewDeclaredReturnType =
3039         (New->getTypeSourceInfo()
3040              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3041              : NewType)->getReturnType();
3042     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3043         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3044           New->isLocalExternDecl())) {
3045       QualType ResQT;
3046       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3047           OldDeclaredReturnType->isObjCObjectPointerType())
3048         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3049       if (ResQT.isNull()) {
3050         if (New->isCXXClassMember() && New->isOutOfLine())
3051           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3052               << New << New->getReturnTypeSourceRange();
3053         else
3054           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3055               << New->getReturnTypeSourceRange();
3056         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3057                                     << Old->getReturnTypeSourceRange();
3058         return true;
3059       }
3060       else
3061         NewQType = ResQT;
3062     }
3063
3064     QualType OldReturnType = OldType->getReturnType();
3065     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3066     if (OldReturnType != NewReturnType) {
3067       // If this function has a deduced return type and has already been
3068       // defined, copy the deduced value from the old declaration.
3069       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3070       if (OldAT && OldAT->isDeduced()) {
3071         New->setType(
3072             SubstAutoType(New->getType(),
3073                           OldAT->isDependentType() ? Context.DependentTy
3074                                                    : OldAT->getDeducedType()));
3075         NewQType = Context.getCanonicalType(
3076             SubstAutoType(NewQType,
3077                           OldAT->isDependentType() ? Context.DependentTy
3078                                                    : OldAT->getDeducedType()));
3079       }
3080     }
3081
3082     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3083     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3084     if (OldMethod && NewMethod) {
3085       // Preserve triviality.
3086       NewMethod->setTrivial(OldMethod->isTrivial());
3087
3088       // MSVC allows explicit template specialization at class scope:
3089       // 2 CXXMethodDecls referring to the same function will be injected.
3090       // We don't want a redeclaration error.
3091       bool IsClassScopeExplicitSpecialization =
3092                               OldMethod->isFunctionTemplateSpecialization() &&
3093                               NewMethod->isFunctionTemplateSpecialization();
3094       bool isFriend = NewMethod->getFriendObjectKind();
3095
3096       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3097           !IsClassScopeExplicitSpecialization) {
3098         //    -- Member function declarations with the same name and the
3099         //       same parameter types cannot be overloaded if any of them
3100         //       is a static member function declaration.
3101         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3102           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3103           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3104           return true;
3105         }
3106
3107         // C++ [class.mem]p1:
3108         //   [...] A member shall not be declared twice in the
3109         //   member-specification, except that a nested class or member
3110         //   class template can be declared and then later defined.
3111         if (!inTemplateInstantiation()) {
3112           unsigned NewDiag;
3113           if (isa<CXXConstructorDecl>(OldMethod))
3114             NewDiag = diag::err_constructor_redeclared;
3115           else if (isa<CXXDestructorDecl>(NewMethod))
3116             NewDiag = diag::err_destructor_redeclared;
3117           else if (isa<CXXConversionDecl>(NewMethod))
3118             NewDiag = diag::err_conv_function_redeclared;
3119           else
3120             NewDiag = diag::err_member_redeclared;
3121
3122           Diag(New->getLocation(), NewDiag);
3123         } else {
3124           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3125             << New << New->getType();
3126         }
3127         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3128         return true;
3129
3130       // Complain if this is an explicit declaration of a special
3131       // member that was initially declared implicitly.
3132       //
3133       // As an exception, it's okay to befriend such methods in order
3134       // to permit the implicit constructor/destructor/operator calls.
3135       } else if (OldMethod->isImplicit()) {
3136         if (isFriend) {
3137           NewMethod->setImplicit();
3138         } else {
3139           Diag(NewMethod->getLocation(),
3140                diag::err_definition_of_implicitly_declared_member)
3141             << New << getSpecialMember(OldMethod);
3142           return true;
3143         }
3144       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3145         Diag(NewMethod->getLocation(),
3146              diag::err_definition_of_explicitly_defaulted_member)
3147           << getSpecialMember(OldMethod);
3148         return true;
3149       }
3150     }
3151
3152     // C++11 [dcl.attr.noreturn]p1:
3153     //   The first declaration of a function shall specify the noreturn
3154     //   attribute if any declaration of that function specifies the noreturn
3155     //   attribute.
3156     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3157     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3158       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3159       Diag(Old->getFirstDecl()->getLocation(),
3160            diag::note_noreturn_missing_first_decl);
3161     }
3162
3163     // C++11 [dcl.attr.depend]p2:
3164     //   The first declaration of a function shall specify the
3165     //   carries_dependency attribute for its declarator-id if any declaration
3166     //   of the function specifies the carries_dependency attribute.
3167     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3168     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3169       Diag(CDA->getLocation(),
3170            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3171       Diag(Old->getFirstDecl()->getLocation(),
3172            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3173     }
3174
3175     // (C++98 8.3.5p3):
3176     //   All declarations for a function shall agree exactly in both the
3177     //   return type and the parameter-type-list.
3178     // We also want to respect all the extended bits except noreturn.
3179
3180     // noreturn should now match unless the old type info didn't have it.
3181     QualType OldQTypeForComparison = OldQType;
3182     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3183       auto *OldType = OldQType->castAs<FunctionProtoType>();
3184       const FunctionType *OldTypeForComparison
3185         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3186       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3187       assert(OldQTypeForComparison.isCanonical());
3188     }
3189
3190     if (haveIncompatibleLanguageLinkages(Old, New)) {
3191       // As a special case, retain the language linkage from previous
3192       // declarations of a friend function as an extension.
3193       //
3194       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3195       // and is useful because there's otherwise no way to specify language
3196       // linkage within class scope.
3197       //
3198       // Check cautiously as the friend object kind isn't yet complete.
3199       if (New->getFriendObjectKind() != Decl::FOK_None) {
3200         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3201         Diag(OldLocation, PrevDiag);
3202       } else {
3203         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3204         Diag(OldLocation, PrevDiag);
3205         return true;
3206       }
3207     }
3208
3209     if (OldQTypeForComparison == NewQType)
3210       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3211
3212     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3213         New->isLocalExternDecl()) {
3214       // It's OK if we couldn't merge types for a local function declaraton
3215       // if either the old or new type is dependent. We'll merge the types
3216       // when we instantiate the function.
3217       return false;
3218     }
3219
3220     // Fall through for conflicting redeclarations and redefinitions.
3221   }
3222
3223   // C: Function types need to be compatible, not identical. This handles
3224   // duplicate function decls like "void f(int); void f(enum X);" properly.
3225   if (!getLangOpts().CPlusPlus &&
3226       Context.typesAreCompatible(OldQType, NewQType)) {
3227     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3228     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3229     const FunctionProtoType *OldProto = nullptr;
3230     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3231         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3232       // The old declaration provided a function prototype, but the
3233       // new declaration does not. Merge in the prototype.
3234       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3235       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3236       NewQType =
3237           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3238                                   OldProto->getExtProtoInfo());
3239       New->setType(NewQType);
3240       New->setHasInheritedPrototype();
3241
3242       // Synthesize parameters with the same types.
3243       SmallVector<ParmVarDecl*, 16> Params;
3244       for (const auto &ParamType : OldProto->param_types()) {
3245         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3246                                                  SourceLocation(), nullptr,
3247                                                  ParamType, /*TInfo=*/nullptr,
3248                                                  SC_None, nullptr);
3249         Param->setScopeInfo(0, Params.size());
3250         Param->setImplicit();
3251         Params.push_back(Param);
3252       }
3253
3254       New->setParams(Params);
3255     }
3256
3257     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3258   }
3259
3260   // GNU C permits a K&R definition to follow a prototype declaration
3261   // if the declared types of the parameters in the K&R definition
3262   // match the types in the prototype declaration, even when the
3263   // promoted types of the parameters from the K&R definition differ
3264   // from the types in the prototype. GCC then keeps the types from
3265   // the prototype.
3266   //
3267   // If a variadic prototype is followed by a non-variadic K&R definition,
3268   // the K&R definition becomes variadic.  This is sort of an edge case, but
3269   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3270   // C99 6.9.1p8.
3271   if (!getLangOpts().CPlusPlus &&
3272       Old->hasPrototype() && !New->hasPrototype() &&
3273       New->getType()->getAs<FunctionProtoType>() &&
3274       Old->getNumParams() == New->getNumParams()) {
3275     SmallVector<QualType, 16> ArgTypes;
3276     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3277     const FunctionProtoType *OldProto
3278       = Old->getType()->getAs<FunctionProtoType>();
3279     const FunctionProtoType *NewProto
3280       = New->getType()->getAs<FunctionProtoType>();
3281
3282     // Determine whether this is the GNU C extension.
3283     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3284                                                NewProto->getReturnType());
3285     bool LooseCompatible = !MergedReturn.isNull();
3286     for (unsigned Idx = 0, End = Old->getNumParams();
3287          LooseCompatible && Idx != End; ++Idx) {
3288       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3289       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3290       if (Context.typesAreCompatible(OldParm->getType(),
3291                                      NewProto->getParamType(Idx))) {
3292         ArgTypes.push_back(NewParm->getType());
3293       } else if (Context.typesAreCompatible(OldParm->getType(),
3294                                             NewParm->getType(),
3295                                             /*CompareUnqualified=*/true)) {
3296         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3297                                            NewProto->getParamType(Idx) };
3298         Warnings.push_back(Warn);
3299         ArgTypes.push_back(NewParm->getType());
3300       } else
3301         LooseCompatible = false;
3302     }
3303
3304     if (LooseCompatible) {
3305       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3306         Diag(Warnings[Warn].NewParm->getLocation(),
3307              diag::ext_param_promoted_not_compatible_with_prototype)
3308           << Warnings[Warn].PromotedType
3309           << Warnings[Warn].OldParm->getType();
3310         if (Warnings[Warn].OldParm->getLocation().isValid())
3311           Diag(Warnings[Warn].OldParm->getLocation(),
3312                diag::note_previous_declaration);
3313       }
3314
3315       if (MergeTypeWithOld)
3316         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3317                                              OldProto->getExtProtoInfo()));
3318       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3319     }
3320
3321     // Fall through to diagnose conflicting types.
3322   }
3323
3324   // A function that has already been declared has been redeclared or
3325   // defined with a different type; show an appropriate diagnostic.
3326
3327   // If the previous declaration was an implicitly-generated builtin
3328   // declaration, then at the very least we should use a specialized note.
3329   unsigned BuiltinID;
3330   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3331     // If it's actually a library-defined builtin function like 'malloc'
3332     // or 'printf', just warn about the incompatible redeclaration.
3333     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3334       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3335       Diag(OldLocation, diag::note_previous_builtin_declaration)
3336         << Old << Old->getType();
3337
3338       // If this is a global redeclaration, just forget hereafter
3339       // about the "builtin-ness" of the function.
3340       //
3341       // Doing this for local extern declarations is problematic.  If
3342       // the builtin declaration remains visible, a second invalid
3343       // local declaration will produce a hard error; if it doesn't
3344       // remain visible, a single bogus local redeclaration (which is
3345       // actually only a warning) could break all the downstream code.
3346       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3347         New->getIdentifier()->revertBuiltin();
3348
3349       return false;
3350     }
3351
3352     PrevDiag = diag::note_previous_builtin_declaration;
3353   }
3354
3355   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3356   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3357   return true;
3358 }
3359
3360 /// \brief Completes the merge of two function declarations that are
3361 /// known to be compatible.
3362 ///
3363 /// This routine handles the merging of attributes and other
3364 /// properties of function declarations from the old declaration to
3365 /// the new declaration, once we know that New is in fact a
3366 /// redeclaration of Old.
3367 ///
3368 /// \returns false
3369 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3370                                         Scope *S, bool MergeTypeWithOld) {
3371   // Merge the attributes
3372   mergeDeclAttributes(New, Old);
3373
3374   // Merge "pure" flag.
3375   if (Old->isPure())
3376     New->setPure();
3377
3378   // Merge "used" flag.
3379   if (Old->getMostRecentDecl()->isUsed(false))
3380     New->setIsUsed();
3381
3382   // Merge attributes from the parameters.  These can mismatch with K&R
3383   // declarations.
3384   if (New->getNumParams() == Old->getNumParams())
3385       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3386         ParmVarDecl *NewParam = New->getParamDecl(i);
3387         ParmVarDecl *OldParam = Old->getParamDecl(i);
3388         mergeParamDeclAttributes(NewParam, OldParam, *this);
3389         mergeParamDeclTypes(NewParam, OldParam, *this);
3390       }
3391
3392   if (getLangOpts().CPlusPlus)
3393     return MergeCXXFunctionDecl(New, Old, S);
3394
3395   // Merge the function types so the we get the composite types for the return
3396   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3397   // was visible.
3398   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3399   if (!Merged.isNull() && MergeTypeWithOld)
3400     New->setType(Merged);
3401
3402   return false;
3403 }
3404
3405 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3406                                 ObjCMethodDecl *oldMethod) {
3407   // Merge the attributes, including deprecated/unavailable
3408   AvailabilityMergeKind MergeKind =
3409     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3410       ? AMK_ProtocolImplementation
3411       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3412                                                        : AMK_Override;
3413
3414   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3415
3416   // Merge attributes from the parameters.
3417   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3418                                        oe = oldMethod->param_end();
3419   for (ObjCMethodDecl::param_iterator
3420          ni = newMethod->param_begin(), ne = newMethod->param_end();
3421        ni != ne && oi != oe; ++ni, ++oi)
3422     mergeParamDeclAttributes(*ni, *oi, *this);
3423
3424   CheckObjCMethodOverride(newMethod, oldMethod);
3425 }
3426
3427 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3428   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3429
3430   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3431          ? diag::err_redefinition_different_type
3432          : diag::err_redeclaration_different_type)
3433     << New->getDeclName() << New->getType() << Old->getType();
3434
3435   diag::kind PrevDiag;
3436   SourceLocation OldLocation;
3437   std::tie(PrevDiag, OldLocation)
3438     = getNoteDiagForInvalidRedeclaration(Old, New);
3439   S.Diag(OldLocation, PrevDiag);
3440   New->setInvalidDecl();
3441 }
3442
3443 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3444 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3445 /// emitting diagnostics as appropriate.
3446 ///
3447 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3448 /// to here in AddInitializerToDecl. We can't check them before the initializer
3449 /// is attached.
3450 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3451                              bool MergeTypeWithOld) {
3452   if (New->isInvalidDecl() || Old->isInvalidDecl())
3453     return;
3454
3455   QualType MergedT;
3456   if (getLangOpts().CPlusPlus) {
3457     if (New->getType()->isUndeducedType()) {
3458       // We don't know what the new type is until the initializer is attached.
3459       return;
3460     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3461       // These could still be something that needs exception specs checked.
3462       return MergeVarDeclExceptionSpecs(New, Old);
3463     }
3464     // C++ [basic.link]p10:
3465     //   [...] the types specified by all declarations referring to a given
3466     //   object or function shall be identical, except that declarations for an
3467     //   array object can specify array types that differ by the presence or
3468     //   absence of a major array bound (8.3.4).
3469     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3470       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3471       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3472
3473       // We are merging a variable declaration New into Old. If it has an array
3474       // bound, and that bound differs from Old's bound, we should diagnose the
3475       // mismatch.
3476       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3477         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3478              PrevVD = PrevVD->getPreviousDecl()) {
3479           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3480           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3481             continue;
3482
3483           if (!Context.hasSameType(NewArray, PrevVDTy))
3484             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3485         }
3486       }
3487
3488       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3489         if (Context.hasSameType(OldArray->getElementType(),
3490                                 NewArray->getElementType()))
3491           MergedT = New->getType();
3492       }
3493       // FIXME: Check visibility. New is hidden but has a complete type. If New
3494       // has no array bound, it should not inherit one from Old, if Old is not
3495       // visible.
3496       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3497         if (Context.hasSameType(OldArray->getElementType(),
3498                                 NewArray->getElementType()))
3499           MergedT = Old->getType();
3500       }
3501     }
3502     else if (New->getType()->isObjCObjectPointerType() &&
3503                Old->getType()->isObjCObjectPointerType()) {
3504       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3505                                               Old->getType());
3506     }
3507   } else {
3508     // C 6.2.7p2:
3509     //   All declarations that refer to the same object or function shall have
3510     //   compatible type.
3511     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3512   }
3513   if (MergedT.isNull()) {
3514     // It's OK if we couldn't merge types if either type is dependent, for a
3515     // block-scope variable. In other cases (static data members of class
3516     // templates, variable templates, ...), we require the types to be
3517     // equivalent.
3518     // FIXME: The C++ standard doesn't say anything about this.
3519     if ((New->getType()->isDependentType() ||
3520          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3521       // If the old type was dependent, we can't merge with it, so the new type
3522       // becomes dependent for now. We'll reproduce the original type when we
3523       // instantiate the TypeSourceInfo for the variable.
3524       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3525         New->setType(Context.DependentTy);
3526       return;
3527     }
3528     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3529   }
3530
3531   // Don't actually update the type on the new declaration if the old
3532   // declaration was an extern declaration in a different scope.
3533   if (MergeTypeWithOld)
3534     New->setType(MergedT);
3535 }
3536
3537 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3538                                   LookupResult &Previous) {
3539   // C11 6.2.7p4:
3540   //   For an identifier with internal or external linkage declared
3541   //   in a scope in which a prior declaration of that identifier is
3542   //   visible, if the prior declaration specifies internal or
3543   //   external linkage, the type of the identifier at the later
3544   //   declaration becomes the composite type.
3545   //
3546   // If the variable isn't visible, we do not merge with its type.
3547   if (Previous.isShadowed())
3548     return false;
3549
3550   if (S.getLangOpts().CPlusPlus) {
3551     // C++11 [dcl.array]p3:
3552     //   If there is a preceding declaration of the entity in the same
3553     //   scope in which the bound was specified, an omitted array bound
3554     //   is taken to be the same as in that earlier declaration.
3555     return NewVD->isPreviousDeclInSameBlockScope() ||
3556            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3557             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3558   } else {
3559     // If the old declaration was function-local, don't merge with its
3560     // type unless we're in the same function.
3561     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3562            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3563   }
3564 }
3565
3566 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3567 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3568 /// situation, merging decls or emitting diagnostics as appropriate.
3569 ///
3570 /// Tentative definition rules (C99 6.9.2p2) are checked by
3571 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3572 /// definitions here, since the initializer hasn't been attached.
3573 ///
3574 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3575   // If the new decl is already invalid, don't do any other checking.
3576   if (New->isInvalidDecl())
3577     return;
3578
3579   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3580     return;
3581
3582   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3583
3584   // Verify the old decl was also a variable or variable template.
3585   VarDecl *Old = nullptr;
3586   VarTemplateDecl *OldTemplate = nullptr;
3587   if (Previous.isSingleResult()) {
3588     if (NewTemplate) {
3589       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3590       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3591
3592       if (auto *Shadow =
3593               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3594         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3595           return New->setInvalidDecl();
3596     } else {
3597       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3598
3599       if (auto *Shadow =
3600               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3601         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3602           return New->setInvalidDecl();
3603     }
3604   }
3605   if (!Old) {
3606     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3607       << New->getDeclName();
3608     Diag(Previous.getRepresentativeDecl()->getLocation(),
3609          diag::note_previous_definition);
3610     return New->setInvalidDecl();
3611   }
3612
3613   // Ensure the template parameters are compatible.
3614   if (NewTemplate &&
3615       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3616                                       OldTemplate->getTemplateParameters(),
3617                                       /*Complain=*/true, TPL_TemplateMatch))
3618     return New->setInvalidDecl();
3619
3620   // C++ [class.mem]p1:
3621   //   A member shall not be declared twice in the member-specification [...]
3622   //
3623   // Here, we need only consider static data members.
3624   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3625     Diag(New->getLocation(), diag::err_duplicate_member)
3626       << New->getIdentifier();
3627     Diag(Old->getLocation(), diag::note_previous_declaration);
3628     New->setInvalidDecl();
3629   }
3630
3631   mergeDeclAttributes(New, Old);
3632   // Warn if an already-declared variable is made a weak_import in a subsequent
3633   // declaration
3634   if (New->hasAttr<WeakImportAttr>() &&
3635       Old->getStorageClass() == SC_None &&
3636       !Old->hasAttr<WeakImportAttr>()) {
3637     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3638     Diag(Old->getLocation(), diag::note_previous_definition);
3639     // Remove weak_import attribute on new declaration.
3640     New->dropAttr<WeakImportAttr>();
3641   }
3642
3643   if (New->hasAttr<InternalLinkageAttr>() &&
3644       !Old->hasAttr<InternalLinkageAttr>()) {
3645     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3646         << New->getDeclName();
3647     Diag(Old->getLocation(), diag::note_previous_definition);
3648     New->dropAttr<InternalLinkageAttr>();
3649   }
3650
3651   // Merge the types.
3652   VarDecl *MostRecent = Old->getMostRecentDecl();
3653   if (MostRecent != Old) {
3654     MergeVarDeclTypes(New, MostRecent,
3655                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3656     if (New->isInvalidDecl())
3657       return;
3658   }
3659
3660   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3661   if (New->isInvalidDecl())
3662     return;
3663
3664   diag::kind PrevDiag;
3665   SourceLocation OldLocation;
3666   std::tie(PrevDiag, OldLocation) =
3667       getNoteDiagForInvalidRedeclaration(Old, New);
3668
3669   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3670   if (New->getStorageClass() == SC_Static &&
3671       !New->isStaticDataMember() &&
3672       Old->hasExternalFormalLinkage()) {
3673     if (getLangOpts().MicrosoftExt) {
3674       Diag(New->getLocation(), diag::ext_static_non_static)
3675           << New->getDeclName();
3676       Diag(OldLocation, PrevDiag);
3677     } else {
3678       Diag(New->getLocation(), diag::err_static_non_static)
3679           << New->getDeclName();
3680       Diag(OldLocation, PrevDiag);
3681       return New->setInvalidDecl();
3682     }
3683   }
3684   // C99 6.2.2p4:
3685   //   For an identifier declared with the storage-class specifier
3686   //   extern in a scope in which a prior declaration of that
3687   //   identifier is visible,23) if the prior declaration specifies
3688   //   internal or external linkage, the linkage of the identifier at
3689   //   the later declaration is the same as the linkage specified at
3690   //   the prior declaration. If no prior declaration is visible, or
3691   //   if the prior declaration specifies no linkage, then the
3692   //   identifier has external linkage.
3693   if (New->hasExternalStorage() && Old->hasLinkage())
3694     /* Okay */;
3695   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3696            !New->isStaticDataMember() &&
3697            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3698     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3699     Diag(OldLocation, PrevDiag);
3700     return New->setInvalidDecl();
3701   }
3702
3703   // Check if extern is followed by non-extern and vice-versa.
3704   if (New->hasExternalStorage() &&
3705       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3706     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3707     Diag(OldLocation, PrevDiag);
3708     return New->setInvalidDecl();
3709   }
3710   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3711       !New->hasExternalStorage()) {
3712     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3713     Diag(OldLocation, PrevDiag);
3714     return New->setInvalidDecl();
3715   }
3716
3717   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3718
3719   // FIXME: The test for external storage here seems wrong? We still
3720   // need to check for mismatches.
3721   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3722       // Don't complain about out-of-line definitions of static members.
3723       !(Old->getLexicalDeclContext()->isRecord() &&
3724         !New->getLexicalDeclContext()->isRecord())) {
3725     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3726     Diag(OldLocation, PrevDiag);
3727     return New->setInvalidDecl();
3728   }
3729
3730   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3731     if (VarDecl *Def = Old->getDefinition()) {
3732       // C++1z [dcl.fcn.spec]p4:
3733       //   If the definition of a variable appears in a translation unit before
3734       //   its first declaration as inline, the program is ill-formed.
3735       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3736       Diag(Def->getLocation(), diag::note_previous_definition);
3737     }
3738   }
3739
3740   // If this redeclaration makes the function inline, we may need to add it to
3741   // UndefinedButUsed.
3742   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3743       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3744     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3745                                            SourceLocation()));
3746
3747   if (New->getTLSKind() != Old->getTLSKind()) {
3748     if (!Old->getTLSKind()) {
3749       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3750       Diag(OldLocation, PrevDiag);
3751     } else if (!New->getTLSKind()) {
3752       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3753       Diag(OldLocation, PrevDiag);
3754     } else {
3755       // Do not allow redeclaration to change the variable between requiring
3756       // static and dynamic initialization.
3757       // FIXME: GCC allows this, but uses the TLS keyword on the first
3758       // declaration to determine the kind. Do we need to be compatible here?
3759       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3760         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3761       Diag(OldLocation, PrevDiag);
3762     }
3763   }
3764
3765   // C++ doesn't have tentative definitions, so go right ahead and check here.
3766   if (getLangOpts().CPlusPlus &&
3767       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3768     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3769         Old->getCanonicalDecl()->isConstexpr()) {
3770       // This definition won't be a definition any more once it's been merged.
3771       Diag(New->getLocation(),
3772            diag::warn_deprecated_redundant_constexpr_static_def);
3773     } else if (VarDecl *Def = Old->getDefinition()) {
3774       if (checkVarDeclRedefinition(Def, New))
3775         return;
3776     }
3777   }
3778
3779   if (haveIncompatibleLanguageLinkages(Old, New)) {
3780     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3781     Diag(OldLocation, PrevDiag);
3782     New->setInvalidDecl();
3783     return;
3784   }
3785
3786   // Merge "used" flag.
3787   if (Old->getMostRecentDecl()->isUsed(false))
3788     New->setIsUsed();
3789
3790   // Keep a chain of previous declarations.
3791   New->setPreviousDecl(Old);
3792   if (NewTemplate)
3793     NewTemplate->setPreviousDecl(OldTemplate);
3794
3795   // Inherit access appropriately.
3796   New->setAccess(Old->getAccess());
3797   if (NewTemplate)
3798     NewTemplate->setAccess(New->getAccess());
3799
3800   if (Old->isInline())
3801     New->setImplicitlyInline();
3802 }
3803
3804 /// We've just determined that \p Old and \p New both appear to be definitions
3805 /// of the same variable. Either diagnose or fix the problem.
3806 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3807   if (!hasVisibleDefinition(Old) &&
3808       (New->getFormalLinkage() == InternalLinkage ||
3809        New->isInline() ||
3810        New->getDescribedVarTemplate() ||
3811        New->getNumTemplateParameterLists() ||
3812        New->getDeclContext()->isDependentContext())) {
3813     // The previous definition is hidden, and multiple definitions are
3814     // permitted (in separate TUs). Demote this to a declaration.
3815     New->demoteThisDefinitionToDeclaration();
3816
3817     // Make the canonical definition visible.
3818     if (auto *OldTD = Old->getDescribedVarTemplate())
3819       makeMergedDefinitionVisible(OldTD, New->getLocation());
3820     makeMergedDefinitionVisible(Old, New->getLocation());
3821     return false;
3822   } else {
3823     Diag(New->getLocation(), diag::err_redefinition) << New;
3824     Diag(Old->getLocation(), diag::note_previous_definition);
3825     New->setInvalidDecl();
3826     return true;
3827   }
3828 }
3829
3830 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3831 /// no declarator (e.g. "struct foo;") is parsed.
3832 Decl *
3833 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3834                                  RecordDecl *&AnonRecord) {
3835   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3836                                     AnonRecord);
3837 }
3838
3839 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3840 // disambiguate entities defined in different scopes.
3841 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3842 // compatibility.
3843 // We will pick our mangling number depending on which version of MSVC is being
3844 // targeted.
3845 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3846   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3847              ? S->getMSCurManglingNumber()
3848              : S->getMSLastManglingNumber();
3849 }
3850
3851 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3852   if (!Context.getLangOpts().CPlusPlus)
3853     return;
3854
3855   if (isa<CXXRecordDecl>(Tag->getParent())) {
3856     // If this tag is the direct child of a class, number it if
3857     // it is anonymous.
3858     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3859       return;
3860     MangleNumberingContext &MCtx =
3861         Context.getManglingNumberContext(Tag->getParent());
3862     Context.setManglingNumber(
3863         Tag, MCtx.getManglingNumber(
3864                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3865     return;
3866   }
3867
3868   // If this tag isn't a direct child of a class, number it if it is local.
3869   Decl *ManglingContextDecl;
3870   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3871           Tag->getDeclContext(), ManglingContextDecl)) {
3872     Context.setManglingNumber(
3873         Tag, MCtx->getManglingNumber(
3874                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3875   }
3876 }
3877
3878 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3879                                         TypedefNameDecl *NewTD) {
3880   if (TagFromDeclSpec->isInvalidDecl())
3881     return;
3882
3883   // Do nothing if the tag already has a name for linkage purposes.
3884   if (TagFromDeclSpec->hasNameForLinkage())
3885     return;
3886
3887   // A well-formed anonymous tag must always be a TUK_Definition.
3888   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3889
3890   // The type must match the tag exactly;  no qualifiers allowed.
3891   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3892                            Context.getTagDeclType(TagFromDeclSpec))) {
3893     if (getLangOpts().CPlusPlus)
3894       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3895     return;
3896   }
3897
3898   // If we've already computed linkage for the anonymous tag, then
3899   // adding a typedef name for the anonymous decl can change that
3900   // linkage, which might be a serious problem.  Diagnose this as
3901   // unsupported and ignore the typedef name.  TODO: we should
3902   // pursue this as a language defect and establish a formal rule
3903   // for how to handle it.
3904   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3905     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3906
3907     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3908     tagLoc = getLocForEndOfToken(tagLoc);
3909
3910     llvm::SmallString<40> textToInsert;
3911     textToInsert += ' ';
3912     textToInsert += NewTD->getIdentifier()->getName();
3913     Diag(tagLoc, diag::note_typedef_changes_linkage)
3914         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3915     return;
3916   }
3917
3918   // Otherwise, set this is the anon-decl typedef for the tag.
3919   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3920 }
3921
3922 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3923   switch (T) {
3924   case DeclSpec::TST_class:
3925     return 0;
3926   case DeclSpec::TST_struct:
3927     return 1;
3928   case DeclSpec::TST_interface:
3929     return 2;
3930   case DeclSpec::TST_union:
3931     return 3;
3932   case DeclSpec::TST_enum:
3933     return 4;
3934   default:
3935     llvm_unreachable("unexpected type specifier");
3936   }
3937 }
3938
3939 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3940 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3941 /// parameters to cope with template friend declarations.
3942 Decl *
3943 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3944                                  MultiTemplateParamsArg TemplateParams,
3945                                  bool IsExplicitInstantiation,
3946                                  RecordDecl *&AnonRecord) {
3947   Decl *TagD = nullptr;
3948   TagDecl *Tag = nullptr;
3949   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3950       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3951       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3952       DS.getTypeSpecType() == DeclSpec::TST_union ||
3953       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3954     TagD = DS.getRepAsDecl();
3955
3956     if (!TagD) // We probably had an error
3957       return nullptr;
3958
3959     // Note that the above type specs guarantee that the
3960     // type rep is a Decl, whereas in many of the others
3961     // it's a Type.
3962     if (isa<TagDecl>(TagD))
3963       Tag = cast<TagDecl>(TagD);
3964     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3965       Tag = CTD->getTemplatedDecl();
3966   }
3967
3968   if (Tag) {
3969     handleTagNumbering(Tag, S);
3970     Tag->setFreeStanding();
3971     if (Tag->isInvalidDecl())
3972       return Tag;
3973   }
3974
3975   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3976     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3977     // or incomplete types shall not be restrict-qualified."
3978     if (TypeQuals & DeclSpec::TQ_restrict)
3979       Diag(DS.getRestrictSpecLoc(),
3980            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3981            << DS.getSourceRange();
3982   }
3983
3984   if (DS.isInlineSpecified())
3985     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3986         << getLangOpts().CPlusPlus1z;
3987
3988   if (DS.isConstexprSpecified()) {
3989     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3990     // and definitions of functions and variables.
3991     if (Tag)
3992       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3993           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3994     else
3995       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3996     // Don't emit warnings after this error.
3997     return TagD;
3998   }
3999
4000   if (DS.isConceptSpecified()) {
4001     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4002     // either a function concept and its definition or a variable concept and
4003     // its initializer.
4004     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4005     return TagD;
4006   }
4007
4008   DiagnoseFunctionSpecifiers(DS);
4009
4010   if (DS.isFriendSpecified()) {
4011     // If we're dealing with a decl but not a TagDecl, assume that
4012     // whatever routines created it handled the friendship aspect.
4013     if (TagD && !Tag)
4014       return nullptr;
4015     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4016   }
4017
4018   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4019   bool IsExplicitSpecialization =
4020     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4021   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4022       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4023       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4024     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4025     // nested-name-specifier unless it is an explicit instantiation
4026     // or an explicit specialization.
4027     //
4028     // FIXME: We allow class template partial specializations here too, per the
4029     // obvious intent of DR1819.
4030     //
4031     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4032     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4033         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4034     return nullptr;
4035   }
4036
4037   // Track whether this decl-specifier declares anything.
4038   bool DeclaresAnything = true;
4039
4040   // Handle anonymous struct definitions.
4041   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4042     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4043         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4044       if (getLangOpts().CPlusPlus ||
4045           Record->getDeclContext()->isRecord()) {
4046         // If CurContext is a DeclContext that can contain statements,
4047         // RecursiveASTVisitor won't visit the decls that
4048         // BuildAnonymousStructOrUnion() will put into CurContext.
4049         // Also store them here so that they can be part of the
4050         // DeclStmt that gets created in this case.
4051         // FIXME: Also return the IndirectFieldDecls created by
4052         // BuildAnonymousStructOr union, for the same reason?
4053         if (CurContext->isFunctionOrMethod())
4054           AnonRecord = Record;
4055         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4056                                            Context.getPrintingPolicy());
4057       }
4058
4059       DeclaresAnything = false;
4060     }
4061   }
4062
4063   // C11 6.7.2.1p2:
4064   //   A struct-declaration that does not declare an anonymous structure or
4065   //   anonymous union shall contain a struct-declarator-list.
4066   //
4067   // This rule also existed in C89 and C99; the grammar for struct-declaration
4068   // did not permit a struct-declaration without a struct-declarator-list.
4069   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4070       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4071     // Check for Microsoft C extension: anonymous struct/union member.
4072     // Handle 2 kinds of anonymous struct/union:
4073     //   struct STRUCT;
4074     //   union UNION;
4075     // and
4076     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4077     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4078     if ((Tag && Tag->getDeclName()) ||
4079         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4080       RecordDecl *Record = nullptr;
4081       if (Tag)
4082         Record = dyn_cast<RecordDecl>(Tag);
4083       else if (const RecordType *RT =
4084                    DS.getRepAsType().get()->getAsStructureType())
4085         Record = RT->getDecl();
4086       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4087         Record = UT->getDecl();
4088
4089       if (Record && getLangOpts().MicrosoftExt) {
4090         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4091           << Record->isUnion() << DS.getSourceRange();
4092         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4093       }
4094
4095       DeclaresAnything = false;
4096     }
4097   }
4098
4099   // Skip all the checks below if we have a type error.
4100   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4101       (TagD && TagD->isInvalidDecl()))
4102     return TagD;
4103
4104   if (getLangOpts().CPlusPlus &&
4105       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4106     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4107       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4108           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4109         DeclaresAnything = false;
4110
4111   if (!DS.isMissingDeclaratorOk()) {
4112     // Customize diagnostic for a typedef missing a name.
4113     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4114       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4115         << DS.getSourceRange();
4116     else
4117       DeclaresAnything = false;
4118   }
4119
4120   if (DS.isModulePrivateSpecified() &&
4121       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4122     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4123       << Tag->getTagKind()
4124       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4125
4126   ActOnDocumentableDecl(TagD);
4127
4128   // C 6.7/2:
4129   //   A declaration [...] shall declare at least a declarator [...], a tag,
4130   //   or the members of an enumeration.
4131   // C++ [dcl.dcl]p3:
4132   //   [If there are no declarators], and except for the declaration of an
4133   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4134   //   names into the program, or shall redeclare a name introduced by a
4135   //   previous declaration.
4136   if (!DeclaresAnything) {
4137     // In C, we allow this as a (popular) extension / bug. Don't bother
4138     // producing further diagnostics for redundant qualifiers after this.
4139     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4140     return TagD;
4141   }
4142
4143   // C++ [dcl.stc]p1:
4144   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4145   //   init-declarator-list of the declaration shall not be empty.
4146   // C++ [dcl.fct.spec]p1:
4147   //   If a cv-qualifier appears in a decl-specifier-seq, the
4148   //   init-declarator-list of the declaration shall not be empty.
4149   //
4150   // Spurious qualifiers here appear to be valid in C.
4151   unsigned DiagID = diag::warn_standalone_specifier;
4152   if (getLangOpts().CPlusPlus)
4153     DiagID = diag::ext_standalone_specifier;
4154
4155   // Note that a linkage-specification sets a storage class, but
4156   // 'extern "C" struct foo;' is actually valid and not theoretically
4157   // useless.
4158   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4159     if (SCS == DeclSpec::SCS_mutable)
4160       // Since mutable is not a viable storage class specifier in C, there is
4161       // no reason to treat it as an extension. Instead, diagnose as an error.
4162       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4163     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4164       Diag(DS.getStorageClassSpecLoc(), DiagID)
4165         << DeclSpec::getSpecifierName(SCS);
4166   }
4167
4168   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4169     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4170       << DeclSpec::getSpecifierName(TSCS);
4171   if (DS.getTypeQualifiers()) {
4172     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4173       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4174     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4175       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4176     // Restrict is covered above.
4177     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4178       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4179     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4180       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4181   }
4182
4183   // Warn about ignored type attributes, for example:
4184   // __attribute__((aligned)) struct A;
4185   // Attributes should be placed after tag to apply to type declaration.
4186   if (!DS.getAttributes().empty()) {
4187     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4188     if (TypeSpecType == DeclSpec::TST_class ||
4189         TypeSpecType == DeclSpec::TST_struct ||
4190         TypeSpecType == DeclSpec::TST_interface ||
4191         TypeSpecType == DeclSpec::TST_union ||
4192         TypeSpecType == DeclSpec::TST_enum) {
4193       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4194            attrs = attrs->getNext())
4195         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4196             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4197     }
4198   }
4199
4200   return TagD;
4201 }
4202
4203 /// We are trying to inject an anonymous member into the given scope;
4204 /// check if there's an existing declaration that can't be overloaded.
4205 ///
4206 /// \return true if this is a forbidden redeclaration
4207 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4208                                          Scope *S,
4209                                          DeclContext *Owner,
4210                                          DeclarationName Name,
4211                                          SourceLocation NameLoc,
4212                                          bool IsUnion) {
4213   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4214                  Sema::ForRedeclaration);
4215   if (!SemaRef.LookupName(R, S)) return false;
4216
4217   // Pick a representative declaration.
4218   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4219   assert(PrevDecl && "Expected a non-null Decl");
4220
4221   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4222     return false;
4223
4224   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4225     << IsUnion << Name;
4226   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4227
4228   return true;
4229 }
4230
4231 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4232 /// anonymous struct or union AnonRecord into the owning context Owner
4233 /// and scope S. This routine will be invoked just after we realize
4234 /// that an unnamed union or struct is actually an anonymous union or
4235 /// struct, e.g.,
4236 ///
4237 /// @code
4238 /// union {
4239 ///   int i;
4240 ///   float f;
4241 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4242 ///    // f into the surrounding scope.x
4243 /// @endcode
4244 ///
4245 /// This routine is recursive, injecting the names of nested anonymous
4246 /// structs/unions into the owning context and scope as well.
4247 static bool
4248 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4249                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4250                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4251   bool Invalid = false;
4252
4253   // Look every FieldDecl and IndirectFieldDecl with a name.
4254   for (auto *D : AnonRecord->decls()) {
4255     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4256         cast<NamedDecl>(D)->getDeclName()) {
4257       ValueDecl *VD = cast<ValueDecl>(D);
4258       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4259                                        VD->getLocation(),
4260                                        AnonRecord->isUnion())) {
4261         // C++ [class.union]p2:
4262         //   The names of the members of an anonymous union shall be
4263         //   distinct from the names of any other entity in the
4264         //   scope in which the anonymous union is declared.
4265         Invalid = true;
4266       } else {
4267         // C++ [class.union]p2:
4268         //   For the purpose of name lookup, after the anonymous union
4269         //   definition, the members of the anonymous union are
4270         //   considered to have been defined in the scope in which the
4271         //   anonymous union is declared.
4272         unsigned OldChainingSize = Chaining.size();
4273         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4274           Chaining.append(IF->chain_begin(), IF->chain_end());
4275         else
4276           Chaining.push_back(VD);
4277
4278         assert(Chaining.size() >= 2);
4279         NamedDecl **NamedChain =
4280           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4281         for (unsigned i = 0; i < Chaining.size(); i++)
4282           NamedChain[i] = Chaining[i];
4283
4284         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4285             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4286             VD->getType(), {NamedChain, Chaining.size()});
4287
4288         for (const auto *Attr : VD->attrs())
4289           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4290
4291         IndirectField->setAccess(AS);
4292         IndirectField->setImplicit();
4293         SemaRef.PushOnScopeChains(IndirectField, S);
4294
4295         // That includes picking up the appropriate access specifier.
4296         if (AS != AS_none) IndirectField->setAccess(AS);
4297
4298         Chaining.resize(OldChainingSize);
4299       }
4300     }
4301   }
4302
4303   return Invalid;
4304 }
4305
4306 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4307 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4308 /// illegal input values are mapped to SC_None.
4309 static StorageClass
4310 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4311   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4312   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4313          "Parser allowed 'typedef' as storage class VarDecl.");
4314   switch (StorageClassSpec) {
4315   case DeclSpec::SCS_unspecified:    return SC_None;
4316   case DeclSpec::SCS_extern:
4317     if (DS.isExternInLinkageSpec())
4318       return SC_None;
4319     return SC_Extern;
4320   case DeclSpec::SCS_static:         return SC_Static;
4321   case DeclSpec::SCS_auto:           return SC_Auto;
4322   case DeclSpec::SCS_register:       return SC_Register;
4323   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4324     // Illegal SCSs map to None: error reporting is up to the caller.
4325   case DeclSpec::SCS_mutable:        // Fall through.
4326   case DeclSpec::SCS_typedef:        return SC_None;
4327   }
4328   llvm_unreachable("unknown storage class specifier");
4329 }
4330
4331 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4332   assert(Record->hasInClassInitializer());
4333
4334   for (const auto *I : Record->decls()) {
4335     const auto *FD = dyn_cast<FieldDecl>(I);
4336     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4337       FD = IFD->getAnonField();
4338     if (FD && FD->hasInClassInitializer())
4339       return FD->getLocation();
4340   }
4341
4342   llvm_unreachable("couldn't find in-class initializer");
4343 }
4344
4345 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4346                                       SourceLocation DefaultInitLoc) {
4347   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4348     return;
4349
4350   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4351   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4352 }
4353
4354 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4355                                       CXXRecordDecl *AnonUnion) {
4356   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4357     return;
4358
4359   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4360 }
4361
4362 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4363 /// anonymous structure or union. Anonymous unions are a C++ feature
4364 /// (C++ [class.union]) and a C11 feature; anonymous structures
4365 /// are a C11 feature and GNU C++ extension.
4366 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4367                                         AccessSpecifier AS,
4368                                         RecordDecl *Record,
4369                                         const PrintingPolicy &Policy) {
4370   DeclContext *Owner = Record->getDeclContext();
4371
4372   // Diagnose whether this anonymous struct/union is an extension.
4373   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4374     Diag(Record->getLocation(), diag::ext_anonymous_union);
4375   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4376     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4377   else if (!Record->isUnion() && !getLangOpts().C11)
4378     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4379
4380   // C and C++ require different kinds of checks for anonymous
4381   // structs/unions.
4382   bool Invalid = false;
4383   if (getLangOpts().CPlusPlus) {
4384     const char *PrevSpec = nullptr;
4385     unsigned DiagID;
4386     if (Record->isUnion()) {
4387       // C++ [class.union]p6:
4388       //   Anonymous unions declared in a named namespace or in the
4389       //   global namespace shall be declared static.
4390       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4391           (isa<TranslationUnitDecl>(Owner) ||
4392            (isa<NamespaceDecl>(Owner) &&
4393             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4394         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4395           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4396
4397         // Recover by adding 'static'.
4398         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4399                                PrevSpec, DiagID, Policy);
4400       }
4401       // C++ [class.union]p6:
4402       //   A storage class is not allowed in a declaration of an
4403       //   anonymous union in a class scope.
4404       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4405                isa<RecordDecl>(Owner)) {
4406         Diag(DS.getStorageClassSpecLoc(),
4407              diag::err_anonymous_union_with_storage_spec)
4408           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4409
4410         // Recover by removing the storage specifier.
4411         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4412                                SourceLocation(),
4413                                PrevSpec, DiagID, Context.getPrintingPolicy());
4414       }
4415     }
4416
4417     // Ignore const/volatile/restrict qualifiers.
4418     if (DS.getTypeQualifiers()) {
4419       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4420         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4421           << Record->isUnion() << "const"
4422           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4423       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4424         Diag(DS.getVolatileSpecLoc(),
4425              diag::ext_anonymous_struct_union_qualified)
4426           << Record->isUnion() << "volatile"
4427           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4428       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4429         Diag(DS.getRestrictSpecLoc(),
4430              diag::ext_anonymous_struct_union_qualified)
4431           << Record->isUnion() << "restrict"
4432           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4433       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4434         Diag(DS.getAtomicSpecLoc(),
4435              diag::ext_anonymous_struct_union_qualified)
4436           << Record->isUnion() << "_Atomic"
4437           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4438       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4439         Diag(DS.getUnalignedSpecLoc(),
4440              diag::ext_anonymous_struct_union_qualified)
4441           << Record->isUnion() << "__unaligned"
4442           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4443
4444       DS.ClearTypeQualifiers();
4445     }
4446
4447     // C++ [class.union]p2:
4448     //   The member-specification of an anonymous union shall only
4449     //   define non-static data members. [Note: nested types and
4450     //   functions cannot be declared within an anonymous union. ]
4451     for (auto *Mem : Record->decls()) {
4452       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4453         // C++ [class.union]p3:
4454         //   An anonymous union shall not have private or protected
4455         //   members (clause 11).
4456         assert(FD->getAccess() != AS_none);
4457         if (FD->getAccess() != AS_public) {
4458           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4459             << Record->isUnion() << (FD->getAccess() == AS_protected);
4460           Invalid = true;
4461         }
4462
4463         // C++ [class.union]p1
4464         //   An object of a class with a non-trivial constructor, a non-trivial
4465         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4466         //   assignment operator cannot be a member of a union, nor can an
4467         //   array of such objects.
4468         if (CheckNontrivialField(FD))
4469           Invalid = true;
4470       } else if (Mem->isImplicit()) {
4471         // Any implicit members are fine.
4472       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4473         // This is a type that showed up in an
4474         // elaborated-type-specifier inside the anonymous struct or
4475         // union, but which actually declares a type outside of the
4476         // anonymous struct or union. It's okay.
4477       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4478         if (!MemRecord->isAnonymousStructOrUnion() &&
4479             MemRecord->getDeclName()) {
4480           // Visual C++ allows type definition in anonymous struct or union.
4481           if (getLangOpts().MicrosoftExt)
4482             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4483               << Record->isUnion();
4484           else {
4485             // This is a nested type declaration.
4486             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4487               << Record->isUnion();
4488             Invalid = true;
4489           }
4490         } else {
4491           // This is an anonymous type definition within another anonymous type.
4492           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4493           // not part of standard C++.
4494           Diag(MemRecord->getLocation(),
4495                diag::ext_anonymous_record_with_anonymous_type)
4496             << Record->isUnion();
4497         }
4498       } else if (isa<AccessSpecDecl>(Mem)) {
4499         // Any access specifier is fine.
4500       } else if (isa<StaticAssertDecl>(Mem)) {
4501         // In C++1z, static_assert declarations are also fine.
4502       } else {
4503         // We have something that isn't a non-static data
4504         // member. Complain about it.
4505         unsigned DK = diag::err_anonymous_record_bad_member;
4506         if (isa<TypeDecl>(Mem))
4507           DK = diag::err_anonymous_record_with_type;
4508         else if (isa<FunctionDecl>(Mem))
4509           DK = diag::err_anonymous_record_with_function;
4510         else if (isa<VarDecl>(Mem))
4511           DK = diag::err_anonymous_record_with_static;
4512
4513         // Visual C++ allows type definition in anonymous struct or union.
4514         if (getLangOpts().MicrosoftExt &&
4515             DK == diag::err_anonymous_record_with_type)
4516           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4517             << Record->isUnion();
4518         else {
4519           Diag(Mem->getLocation(), DK) << Record->isUnion();
4520           Invalid = true;
4521         }
4522       }
4523     }
4524
4525     // C++11 [class.union]p8 (DR1460):
4526     //   At most one variant member of a union may have a
4527     //   brace-or-equal-initializer.
4528     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4529         Owner->isRecord())
4530       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4531                                 cast<CXXRecordDecl>(Record));
4532   }
4533
4534   if (!Record->isUnion() && !Owner->isRecord()) {
4535     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4536       << getLangOpts().CPlusPlus;
4537     Invalid = true;
4538   }
4539
4540   // Mock up a declarator.
4541   Declarator Dc(DS, Declarator::MemberContext);
4542   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4543   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4544
4545   // Create a declaration for this anonymous struct/union.
4546   NamedDecl *Anon = nullptr;
4547   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4548     Anon = FieldDecl::Create(Context, OwningClass,
4549                              DS.getLocStart(),
4550                              Record->getLocation(),
4551                              /*IdentifierInfo=*/nullptr,
4552                              Context.getTypeDeclType(Record),
4553                              TInfo,
4554                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4555                              /*InitStyle=*/ICIS_NoInit);
4556     Anon->setAccess(AS);
4557     if (getLangOpts().CPlusPlus)
4558       FieldCollector->Add(cast<FieldDecl>(Anon));
4559   } else {
4560     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4561     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4562     if (SCSpec == DeclSpec::SCS_mutable) {
4563       // mutable can only appear on non-static class members, so it's always
4564       // an error here
4565       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4566       Invalid = true;
4567       SC = SC_None;
4568     }
4569
4570     Anon = VarDecl::Create(Context, Owner,
4571                            DS.getLocStart(),
4572                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4573                            Context.getTypeDeclType(Record),
4574                            TInfo, SC);
4575
4576     // Default-initialize the implicit variable. This initialization will be
4577     // trivial in almost all cases, except if a union member has an in-class
4578     // initializer:
4579     //   union { int n = 0; };
4580     ActOnUninitializedDecl(Anon);
4581   }
4582   Anon->setImplicit();
4583
4584   // Mark this as an anonymous struct/union type.
4585   Record->setAnonymousStructOrUnion(true);
4586
4587   // Add the anonymous struct/union object to the current
4588   // context. We'll be referencing this object when we refer to one of
4589   // its members.
4590   Owner->addDecl(Anon);
4591
4592   // Inject the members of the anonymous struct/union into the owning
4593   // context and into the identifier resolver chain for name lookup
4594   // purposes.
4595   SmallVector<NamedDecl*, 2> Chain;
4596   Chain.push_back(Anon);
4597
4598   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4599     Invalid = true;
4600
4601   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4602     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4603       Decl *ManglingContextDecl;
4604       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4605               NewVD->getDeclContext(), ManglingContextDecl)) {
4606         Context.setManglingNumber(
4607             NewVD, MCtx->getManglingNumber(
4608                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4609         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4610       }
4611     }
4612   }
4613
4614   if (Invalid)
4615     Anon->setInvalidDecl();
4616
4617   return Anon;
4618 }
4619
4620 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4621 /// Microsoft C anonymous structure.
4622 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4623 /// Example:
4624 ///
4625 /// struct A { int a; };
4626 /// struct B { struct A; int b; };
4627 ///
4628 /// void foo() {
4629 ///   B var;
4630 ///   var.a = 3;
4631 /// }
4632 ///
4633 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4634                                            RecordDecl *Record) {
4635   assert(Record && "expected a record!");
4636
4637   // Mock up a declarator.
4638   Declarator Dc(DS, Declarator::TypeNameContext);
4639   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4640   assert(TInfo && "couldn't build declarator info for anonymous struct");
4641
4642   auto *ParentDecl = cast<RecordDecl>(CurContext);
4643   QualType RecTy = Context.getTypeDeclType(Record);
4644
4645   // Create a declaration for this anonymous struct.
4646   NamedDecl *Anon = FieldDecl::Create(Context,
4647                              ParentDecl,
4648                              DS.getLocStart(),
4649                              DS.getLocStart(),
4650                              /*IdentifierInfo=*/nullptr,
4651                              RecTy,
4652                              TInfo,
4653                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4654                              /*InitStyle=*/ICIS_NoInit);
4655   Anon->setImplicit();
4656
4657   // Add the anonymous struct object to the current context.
4658   CurContext->addDecl(Anon);
4659
4660   // Inject the members of the anonymous struct into the current
4661   // context and into the identifier resolver chain for name lookup
4662   // purposes.
4663   SmallVector<NamedDecl*, 2> Chain;
4664   Chain.push_back(Anon);
4665
4666   RecordDecl *RecordDef = Record->getDefinition();
4667   if (RequireCompleteType(Anon->getLocation(), RecTy,
4668                           diag::err_field_incomplete) ||
4669       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4670                                           AS_none, Chain)) {
4671     Anon->setInvalidDecl();
4672     ParentDecl->setInvalidDecl();
4673   }
4674
4675   return Anon;
4676 }
4677
4678 /// GetNameForDeclarator - Determine the full declaration name for the
4679 /// given Declarator.
4680 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4681   return GetNameFromUnqualifiedId(D.getName());
4682 }
4683
4684 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4685 DeclarationNameInfo
4686 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4687   DeclarationNameInfo NameInfo;
4688   NameInfo.setLoc(Name.StartLocation);
4689
4690   switch (Name.getKind()) {
4691
4692   case UnqualifiedId::IK_ImplicitSelfParam:
4693   case UnqualifiedId::IK_Identifier:
4694     NameInfo.setName(Name.Identifier);
4695     NameInfo.setLoc(Name.StartLocation);
4696     return NameInfo;
4697
4698   case UnqualifiedId::IK_DeductionGuideName: {
4699     // C++ [temp.deduct.guide]p3:
4700     //   The simple-template-id shall name a class template specialization.
4701     //   The template-name shall be the same identifier as the template-name
4702     //   of the simple-template-id.
4703     // These together intend to imply that the template-name shall name a
4704     // class template.
4705     // FIXME: template<typename T> struct X {};
4706     //        template<typename T> using Y = X<T>;
4707     //        Y(int) -> Y<int>;
4708     //   satisfies these rules but does not name a class template.
4709     TemplateName TN = Name.TemplateName.get().get();
4710     auto *Template = TN.getAsTemplateDecl();
4711     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4712       Diag(Name.StartLocation,
4713            diag::err_deduction_guide_name_not_class_template)
4714         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4715       if (Template)
4716         Diag(Template->getLocation(), diag::note_template_decl_here);
4717       return DeclarationNameInfo();
4718     }
4719
4720     NameInfo.setName(
4721         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4722     NameInfo.setLoc(Name.StartLocation);
4723     return NameInfo;
4724   }
4725
4726   case UnqualifiedId::IK_OperatorFunctionId:
4727     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4728                                            Name.OperatorFunctionId.Operator));
4729     NameInfo.setLoc(Name.StartLocation);
4730     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4731       = Name.OperatorFunctionId.SymbolLocations[0];
4732     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4733       = Name.EndLocation.getRawEncoding();
4734     return NameInfo;
4735
4736   case UnqualifiedId::IK_LiteralOperatorId:
4737     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4738                                                            Name.Identifier));
4739     NameInfo.setLoc(Name.StartLocation);
4740     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4741     return NameInfo;
4742
4743   case UnqualifiedId::IK_ConversionFunctionId: {
4744     TypeSourceInfo *TInfo;
4745     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4746     if (Ty.isNull())
4747       return DeclarationNameInfo();
4748     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4749                                                Context.getCanonicalType(Ty)));
4750     NameInfo.setLoc(Name.StartLocation);
4751     NameInfo.setNamedTypeInfo(TInfo);
4752     return NameInfo;
4753   }
4754
4755   case UnqualifiedId::IK_ConstructorName: {
4756     TypeSourceInfo *TInfo;
4757     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4758     if (Ty.isNull())
4759       return DeclarationNameInfo();
4760     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4761                                               Context.getCanonicalType(Ty)));
4762     NameInfo.setLoc(Name.StartLocation);
4763     NameInfo.setNamedTypeInfo(TInfo);
4764     return NameInfo;
4765   }
4766
4767   case UnqualifiedId::IK_ConstructorTemplateId: {
4768     // In well-formed code, we can only have a constructor
4769     // template-id that refers to the current context, so go there
4770     // to find the actual type being constructed.
4771     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4772     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4773       return DeclarationNameInfo();
4774
4775     // Determine the type of the class being constructed.
4776     QualType CurClassType = Context.getTypeDeclType(CurClass);
4777
4778     // FIXME: Check two things: that the template-id names the same type as
4779     // CurClassType, and that the template-id does not occur when the name
4780     // was qualified.
4781
4782     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4783                                     Context.getCanonicalType(CurClassType)));
4784     NameInfo.setLoc(Name.StartLocation);
4785     // FIXME: should we retrieve TypeSourceInfo?
4786     NameInfo.setNamedTypeInfo(nullptr);
4787     return NameInfo;
4788   }
4789
4790   case UnqualifiedId::IK_DestructorName: {
4791     TypeSourceInfo *TInfo;
4792     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4793     if (Ty.isNull())
4794       return DeclarationNameInfo();
4795     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4796                                               Context.getCanonicalType(Ty)));
4797     NameInfo.setLoc(Name.StartLocation);
4798     NameInfo.setNamedTypeInfo(TInfo);
4799     return NameInfo;
4800   }
4801
4802   case UnqualifiedId::IK_TemplateId: {
4803     TemplateName TName = Name.TemplateId->Template.get();
4804     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4805     return Context.getNameForTemplate(TName, TNameLoc);
4806   }
4807
4808   } // switch (Name.getKind())
4809
4810   llvm_unreachable("Unknown name kind");
4811 }
4812
4813 static QualType getCoreType(QualType Ty) {
4814   do {
4815     if (Ty->isPointerType() || Ty->isReferenceType())
4816       Ty = Ty->getPointeeType();
4817     else if (Ty->isArrayType())
4818       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4819     else
4820       return Ty.withoutLocalFastQualifiers();
4821   } while (true);
4822 }
4823
4824 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4825 /// and Definition have "nearly" matching parameters. This heuristic is
4826 /// used to improve diagnostics in the case where an out-of-line function
4827 /// definition doesn't match any declaration within the class or namespace.
4828 /// Also sets Params to the list of indices to the parameters that differ
4829 /// between the declaration and the definition. If hasSimilarParameters
4830 /// returns true and Params is empty, then all of the parameters match.
4831 static bool hasSimilarParameters(ASTContext &Context,
4832                                      FunctionDecl *Declaration,
4833                                      FunctionDecl *Definition,
4834                                      SmallVectorImpl<unsigned> &Params) {
4835   Params.clear();
4836   if (Declaration->param_size() != Definition->param_size())
4837     return false;
4838   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4839     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4840     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4841
4842     // The parameter types are identical
4843     if (Context.hasSameType(DefParamTy, DeclParamTy))
4844       continue;
4845
4846     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4847     QualType DefParamBaseTy = getCoreType(DefParamTy);
4848     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4849     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4850
4851     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4852         (DeclTyName && DeclTyName == DefTyName))
4853       Params.push_back(Idx);
4854     else  // The two parameters aren't even close
4855       return false;
4856   }
4857
4858   return true;
4859 }
4860
4861 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4862 /// declarator needs to be rebuilt in the current instantiation.
4863 /// Any bits of declarator which appear before the name are valid for
4864 /// consideration here.  That's specifically the type in the decl spec
4865 /// and the base type in any member-pointer chunks.
4866 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4867                                                     DeclarationName Name) {
4868   // The types we specifically need to rebuild are:
4869   //   - typenames, typeofs, and decltypes
4870   //   - types which will become injected class names
4871   // Of course, we also need to rebuild any type referencing such a
4872   // type.  It's safest to just say "dependent", but we call out a
4873   // few cases here.
4874
4875   DeclSpec &DS = D.getMutableDeclSpec();
4876   switch (DS.getTypeSpecType()) {
4877   case DeclSpec::TST_typename:
4878   case DeclSpec::TST_typeofType:
4879   case DeclSpec::TST_underlyingType:
4880   case DeclSpec::TST_atomic: {
4881     // Grab the type from the parser.
4882     TypeSourceInfo *TSI = nullptr;
4883     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4884     if (T.isNull() || !T->isDependentType()) break;
4885
4886     // Make sure there's a type source info.  This isn't really much
4887     // of a waste; most dependent types should have type source info
4888     // attached already.
4889     if (!TSI)
4890       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4891
4892     // Rebuild the type in the current instantiation.
4893     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4894     if (!TSI) return true;
4895
4896     // Store the new type back in the decl spec.
4897     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4898     DS.UpdateTypeRep(LocType);
4899     break;
4900   }
4901
4902   case DeclSpec::TST_decltype:
4903   case DeclSpec::TST_typeofExpr: {
4904     Expr *E = DS.getRepAsExpr();
4905     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4906     if (Result.isInvalid()) return true;
4907     DS.UpdateExprRep(Result.get());
4908     break;
4909   }
4910
4911   default:
4912     // Nothing to do for these decl specs.
4913     break;
4914   }
4915
4916   // It doesn't matter what order we do this in.
4917   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4918     DeclaratorChunk &Chunk = D.getTypeObject(I);
4919
4920     // The only type information in the declarator which can come
4921     // before the declaration name is the base type of a member
4922     // pointer.
4923     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4924       continue;
4925
4926     // Rebuild the scope specifier in-place.
4927     CXXScopeSpec &SS = Chunk.Mem.Scope();
4928     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4929       return true;
4930   }
4931
4932   return false;
4933 }
4934
4935 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4936   D.setFunctionDefinitionKind(FDK_Declaration);
4937   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4938
4939   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4940       Dcl && Dcl->getDeclContext()->isFileContext())
4941     Dcl->setTopLevelDeclInObjCContainer();
4942
4943   if (getLangOpts().OpenCL)
4944     setCurrentOpenCLExtensionForDecl(Dcl);
4945
4946   return Dcl;
4947 }
4948
4949 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4950 ///   If T is the name of a class, then each of the following shall have a
4951 ///   name different from T:
4952 ///     - every static data member of class T;
4953 ///     - every member function of class T
4954 ///     - every member of class T that is itself a type;
4955 /// \returns true if the declaration name violates these rules.
4956 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4957                                    DeclarationNameInfo NameInfo) {
4958   DeclarationName Name = NameInfo.getName();
4959
4960   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4961   while (Record && Record->isAnonymousStructOrUnion())
4962     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4963   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4964     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4965     return true;
4966   }
4967
4968   return false;
4969 }
4970
4971 /// \brief Diagnose a declaration whose declarator-id has the given
4972 /// nested-name-specifier.
4973 ///
4974 /// \param SS The nested-name-specifier of the declarator-id.
4975 ///
4976 /// \param DC The declaration context to which the nested-name-specifier
4977 /// resolves.
4978 ///
4979 /// \param Name The name of the entity being declared.
4980 ///
4981 /// \param Loc The location of the name of the entity being declared.
4982 ///
4983 /// \returns true if we cannot safely recover from this error, false otherwise.
4984 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4985                                         DeclarationName Name,
4986                                         SourceLocation Loc) {
4987   DeclContext *Cur = CurContext;
4988   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4989     Cur = Cur->getParent();
4990
4991   // If the user provided a superfluous scope specifier that refers back to the
4992   // class in which the entity is already declared, diagnose and ignore it.
4993   //
4994   // class X {
4995   //   void X::f();
4996   // };
4997   //
4998   // Note, it was once ill-formed to give redundant qualification in all
4999   // contexts, but that rule was removed by DR482.
5000   if (Cur->Equals(DC)) {
5001     if (Cur->isRecord()) {
5002       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5003                                       : diag::err_member_extra_qualification)
5004         << Name << FixItHint::CreateRemoval(SS.getRange());
5005       SS.clear();
5006     } else {
5007       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5008     }
5009     return false;
5010   }
5011
5012   // Check whether the qualifying scope encloses the scope of the original
5013   // declaration.
5014   if (!Cur->Encloses(DC)) {
5015     if (Cur->isRecord())
5016       Diag(Loc, diag::err_member_qualification)
5017         << Name << SS.getRange();
5018     else if (isa<TranslationUnitDecl>(DC))
5019       Diag(Loc, diag::err_invalid_declarator_global_scope)
5020         << Name << SS.getRange();
5021     else if (isa<FunctionDecl>(Cur))
5022       Diag(Loc, diag::err_invalid_declarator_in_function)
5023         << Name << SS.getRange();
5024     else if (isa<BlockDecl>(Cur))
5025       Diag(Loc, diag::err_invalid_declarator_in_block)
5026         << Name << SS.getRange();
5027     else
5028       Diag(Loc, diag::err_invalid_declarator_scope)
5029       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5030
5031     return true;
5032   }
5033
5034   if (Cur->isRecord()) {
5035     // Cannot qualify members within a class.
5036     Diag(Loc, diag::err_member_qualification)
5037       << Name << SS.getRange();
5038     SS.clear();
5039
5040     // C++ constructors and destructors with incorrect scopes can break
5041     // our AST invariants by having the wrong underlying types. If
5042     // that's the case, then drop this declaration entirely.
5043     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5044          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5045         !Context.hasSameType(Name.getCXXNameType(),
5046                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5047       return true;
5048
5049     return false;
5050   }
5051
5052   // C++11 [dcl.meaning]p1:
5053   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5054   //   not begin with a decltype-specifer"
5055   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5056   while (SpecLoc.getPrefix())
5057     SpecLoc = SpecLoc.getPrefix();
5058   if (dyn_cast_or_null<DecltypeType>(
5059         SpecLoc.getNestedNameSpecifier()->getAsType()))
5060     Diag(Loc, diag::err_decltype_in_declarator)
5061       << SpecLoc.getTypeLoc().getSourceRange();
5062
5063   return false;
5064 }
5065
5066 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5067                                   MultiTemplateParamsArg TemplateParamLists) {
5068   // TODO: consider using NameInfo for diagnostic.
5069   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5070   DeclarationName Name = NameInfo.getName();
5071
5072   // All of these full declarators require an identifier.  If it doesn't have
5073   // one, the ParsedFreeStandingDeclSpec action should be used.
5074   if (D.isDecompositionDeclarator()) {
5075     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5076   } else if (!Name) {
5077     if (!D.isInvalidType())  // Reject this if we think it is valid.
5078       Diag(D.getDeclSpec().getLocStart(),
5079            diag::err_declarator_need_ident)
5080         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5081     return nullptr;
5082   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5083     return nullptr;
5084
5085   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5086   // we find one that is.
5087   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5088          (S->getFlags() & Scope::TemplateParamScope) != 0)
5089     S = S->getParent();
5090
5091   DeclContext *DC = CurContext;
5092   if (D.getCXXScopeSpec().isInvalid())
5093     D.setInvalidType();
5094   else if (D.getCXXScopeSpec().isSet()) {
5095     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5096                                         UPPC_DeclarationQualifier))
5097       return nullptr;
5098
5099     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5100     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5101     if (!DC || isa<EnumDecl>(DC)) {
5102       // If we could not compute the declaration context, it's because the
5103       // declaration context is dependent but does not refer to a class,
5104       // class template, or class template partial specialization. Complain
5105       // and return early, to avoid the coming semantic disaster.
5106       Diag(D.getIdentifierLoc(),
5107            diag::err_template_qualified_declarator_no_match)
5108         << D.getCXXScopeSpec().getScopeRep()
5109         << D.getCXXScopeSpec().getRange();
5110       return nullptr;
5111     }
5112     bool IsDependentContext = DC->isDependentContext();
5113
5114     if (!IsDependentContext &&
5115         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5116       return nullptr;
5117
5118     // If a class is incomplete, do not parse entities inside it.
5119     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5120       Diag(D.getIdentifierLoc(),
5121            diag::err_member_def_undefined_record)
5122         << Name << DC << D.getCXXScopeSpec().getRange();
5123       return nullptr;
5124     }
5125     if (!D.getDeclSpec().isFriendSpecified()) {
5126       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5127                                       Name, D.getIdentifierLoc())) {
5128         if (DC->isRecord())
5129           return nullptr;
5130
5131         D.setInvalidType();
5132       }
5133     }
5134
5135     // Check whether we need to rebuild the type of the given
5136     // declaration in the current instantiation.
5137     if (EnteringContext && IsDependentContext &&
5138         TemplateParamLists.size() != 0) {
5139       ContextRAII SavedContext(*this, DC);
5140       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5141         D.setInvalidType();
5142     }
5143   }
5144
5145   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5146   QualType R = TInfo->getType();
5147
5148   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5149     // If this is a typedef, we'll end up spewing multiple diagnostics.
5150     // Just return early; it's safer. If this is a function, let the
5151     // "constructor cannot have a return type" diagnostic handle it.
5152     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5153       return nullptr;
5154
5155   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5156                                       UPPC_DeclarationType))
5157     D.setInvalidType();
5158
5159   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5160                         ForRedeclaration);
5161
5162   // See if this is a redefinition of a variable in the same scope.
5163   if (!D.getCXXScopeSpec().isSet()) {
5164     bool IsLinkageLookup = false;
5165     bool CreateBuiltins = false;
5166
5167     // If the declaration we're planning to build will be a function
5168     // or object with linkage, then look for another declaration with
5169     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5170     //
5171     // If the declaration we're planning to build will be declared with
5172     // external linkage in the translation unit, create any builtin with
5173     // the same name.
5174     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5175       /* Do nothing*/;
5176     else if (CurContext->isFunctionOrMethod() &&
5177              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5178               R->isFunctionType())) {
5179       IsLinkageLookup = true;
5180       CreateBuiltins =
5181           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5182     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5183                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5184       CreateBuiltins = true;
5185
5186     if (IsLinkageLookup)
5187       Previous.clear(LookupRedeclarationWithLinkage);
5188
5189     LookupName(Previous, S, CreateBuiltins);
5190   } else { // Something like "int foo::x;"
5191     LookupQualifiedName(Previous, DC);
5192
5193     // C++ [dcl.meaning]p1:
5194     //   When the declarator-id is qualified, the declaration shall refer to a
5195     //  previously declared member of the class or namespace to which the
5196     //  qualifier refers (or, in the case of a namespace, of an element of the
5197     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5198     //  thereof; [...]
5199     //
5200     // Note that we already checked the context above, and that we do not have
5201     // enough information to make sure that Previous contains the declaration
5202     // we want to match. For example, given:
5203     //
5204     //   class X {
5205     //     void f();
5206     //     void f(float);
5207     //   };
5208     //
5209     //   void X::f(int) { } // ill-formed
5210     //
5211     // In this case, Previous will point to the overload set
5212     // containing the two f's declared in X, but neither of them
5213     // matches.
5214
5215     // C++ [dcl.meaning]p1:
5216     //   [...] the member shall not merely have been introduced by a
5217     //   using-declaration in the scope of the class or namespace nominated by
5218     //   the nested-name-specifier of the declarator-id.
5219     RemoveUsingDecls(Previous);
5220   }
5221
5222   if (Previous.isSingleResult() &&
5223       Previous.getFoundDecl()->isTemplateParameter()) {
5224     // Maybe we will complain about the shadowed template parameter.
5225     if (!D.isInvalidType())
5226       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5227                                       Previous.getFoundDecl());
5228
5229     // Just pretend that we didn't see the previous declaration.
5230     Previous.clear();
5231   }
5232
5233   // In C++, the previous declaration we find might be a tag type
5234   // (class or enum). In this case, the new declaration will hide the
5235   // tag type. Note that this does does not apply if we're declaring a
5236   // typedef (C++ [dcl.typedef]p4).
5237   if (Previous.isSingleTagDecl() &&
5238       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5239     Previous.clear();
5240
5241   // Check that there are no default arguments other than in the parameters
5242   // of a function declaration (C++ only).
5243   if (getLangOpts().CPlusPlus)
5244     CheckExtraCXXDefaultArguments(D);
5245
5246   if (D.getDeclSpec().isConceptSpecified()) {
5247     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5248     // applied only to the definition of a function template or variable
5249     // template, declared in namespace scope
5250     if (!TemplateParamLists.size()) {
5251       Diag(D.getDeclSpec().getConceptSpecLoc(),
5252            diag:: err_concept_wrong_decl_kind);
5253       return nullptr;
5254     }
5255
5256     if (!DC->getRedeclContext()->isFileContext()) {
5257       Diag(D.getIdentifierLoc(),
5258            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5259       return nullptr;
5260     }
5261   }
5262
5263   NamedDecl *New;
5264
5265   bool AddToScope = true;
5266   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5267     if (TemplateParamLists.size()) {
5268       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5269       return nullptr;
5270     }
5271
5272     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5273   } else if (R->isFunctionType()) {
5274     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5275                                   TemplateParamLists,
5276                                   AddToScope);
5277   } else {
5278     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5279                                   AddToScope);
5280   }
5281
5282   if (!New)
5283     return nullptr;
5284
5285   // If this has an identifier and is not a function template specialization,
5286   // add it to the scope stack.
5287   if (New->getDeclName() && AddToScope) {
5288     // Only make a locally-scoped extern declaration visible if it is the first
5289     // declaration of this entity. Qualified lookup for such an entity should
5290     // only find this declaration if there is no visible declaration of it.
5291     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5292     PushOnScopeChains(New, S, AddToContext);
5293     if (!AddToContext)
5294       CurContext->addHiddenDecl(New);
5295   }
5296
5297   if (isInOpenMPDeclareTargetContext())
5298     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5299
5300   return New;
5301 }
5302
5303 /// Helper method to turn variable array types into constant array
5304 /// types in certain situations which would otherwise be errors (for
5305 /// GCC compatibility).
5306 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5307                                                     ASTContext &Context,
5308                                                     bool &SizeIsNegative,
5309                                                     llvm::APSInt &Oversized) {
5310   // This method tries to turn a variable array into a constant
5311   // array even when the size isn't an ICE.  This is necessary
5312   // for compatibility with code that depends on gcc's buggy
5313   // constant expression folding, like struct {char x[(int)(char*)2];}
5314   SizeIsNegative = false;
5315   Oversized = 0;
5316
5317   if (T->isDependentType())
5318     return QualType();
5319
5320   QualifierCollector Qs;
5321   const Type *Ty = Qs.strip(T);
5322
5323   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5324     QualType Pointee = PTy->getPointeeType();
5325     QualType FixedType =
5326         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5327                                             Oversized);
5328     if (FixedType.isNull()) return FixedType;
5329     FixedType = Context.getPointerType(FixedType);
5330     return Qs.apply(Context, FixedType);
5331   }
5332   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5333     QualType Inner = PTy->getInnerType();
5334     QualType FixedType =
5335         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5336                                             Oversized);
5337     if (FixedType.isNull()) return FixedType;
5338     FixedType = Context.getParenType(FixedType);
5339     return Qs.apply(Context, FixedType);
5340   }
5341
5342   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5343   if (!VLATy)
5344     return QualType();
5345   // FIXME: We should probably handle this case
5346   if (VLATy->getElementType()->isVariablyModifiedType())
5347     return QualType();
5348
5349   llvm::APSInt Res;
5350   if (!VLATy->getSizeExpr() ||
5351       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5352     return QualType();
5353
5354   // Check whether the array size is negative.
5355   if (Res.isSigned() && Res.isNegative()) {
5356     SizeIsNegative = true;
5357     return QualType();
5358   }
5359
5360   // Check whether the array is too large to be addressed.
5361   unsigned ActiveSizeBits
5362     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5363                                               Res);
5364   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5365     Oversized = Res;
5366     return QualType();
5367   }
5368
5369   return Context.getConstantArrayType(VLATy->getElementType(),
5370                                       Res, ArrayType::Normal, 0);
5371 }
5372
5373 static void
5374 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5375   SrcTL = SrcTL.getUnqualifiedLoc();
5376   DstTL = DstTL.getUnqualifiedLoc();
5377   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5378     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5379     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5380                                       DstPTL.getPointeeLoc());
5381     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5382     return;
5383   }
5384   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5385     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5386     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5387                                       DstPTL.getInnerLoc());
5388     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5389     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5390     return;
5391   }
5392   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5393   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5394   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5395   TypeLoc DstElemTL = DstATL.getElementLoc();
5396   DstElemTL.initializeFullCopy(SrcElemTL);
5397   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5398   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5399   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5400 }
5401
5402 /// Helper method to turn variable array types into constant array
5403 /// types in certain situations which would otherwise be errors (for
5404 /// GCC compatibility).
5405 static TypeSourceInfo*
5406 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5407                                               ASTContext &Context,
5408                                               bool &SizeIsNegative,
5409                                               llvm::APSInt &Oversized) {
5410   QualType FixedTy
5411     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5412                                           SizeIsNegative, Oversized);
5413   if (FixedTy.isNull())
5414     return nullptr;
5415   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5416   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5417                                     FixedTInfo->getTypeLoc());
5418   return FixedTInfo;
5419 }
5420
5421 /// \brief Register the given locally-scoped extern "C" declaration so
5422 /// that it can be found later for redeclarations. We include any extern "C"
5423 /// declaration that is not visible in the translation unit here, not just
5424 /// function-scope declarations.
5425 void
5426 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5427   if (!getLangOpts().CPlusPlus &&
5428       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5429     // Don't need to track declarations in the TU in C.
5430     return;
5431
5432   // Note that we have a locally-scoped external with this name.
5433   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5434 }
5435
5436 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5437   // FIXME: We can have multiple results via __attribute__((overloadable)).
5438   auto Result = Context.getExternCContextDecl()->lookup(Name);
5439   return Result.empty() ? nullptr : *Result.begin();
5440 }
5441
5442 /// \brief Diagnose function specifiers on a declaration of an identifier that
5443 /// does not identify a function.
5444 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5445   // FIXME: We should probably indicate the identifier in question to avoid
5446   // confusion for constructs like "virtual int a(), b;"
5447   if (DS.isVirtualSpecified())
5448     Diag(DS.getVirtualSpecLoc(),
5449          diag::err_virtual_non_function);
5450
5451   if (DS.isExplicitSpecified())
5452     Diag(DS.getExplicitSpecLoc(),
5453          diag::err_explicit_non_function);
5454
5455   if (DS.isNoreturnSpecified())
5456     Diag(DS.getNoreturnSpecLoc(),
5457          diag::err_noreturn_non_function);
5458 }
5459
5460 NamedDecl*
5461 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5462                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5463   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5464   if (D.getCXXScopeSpec().isSet()) {
5465     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5466       << D.getCXXScopeSpec().getRange();
5467     D.setInvalidType();
5468     // Pretend we didn't see the scope specifier.
5469     DC = CurContext;
5470     Previous.clear();
5471   }
5472
5473   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5474
5475   if (D.getDeclSpec().isInlineSpecified())
5476     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5477         << getLangOpts().CPlusPlus1z;
5478   if (D.getDeclSpec().isConstexprSpecified())
5479     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5480       << 1;
5481   if (D.getDeclSpec().isConceptSpecified())
5482     Diag(D.getDeclSpec().getConceptSpecLoc(),
5483          diag::err_concept_wrong_decl_kind);
5484
5485   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5486     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5487       Diag(D.getName().StartLocation,
5488            diag::err_deduction_guide_invalid_specifier)
5489           << "typedef";
5490     else
5491       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5492           << D.getName().getSourceRange();
5493     return nullptr;
5494   }
5495
5496   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5497   if (!NewTD) return nullptr;
5498
5499   // Handle attributes prior to checking for duplicates in MergeVarDecl
5500   ProcessDeclAttributes(S, NewTD, D);
5501
5502   CheckTypedefForVariablyModifiedType(S, NewTD);
5503
5504   bool Redeclaration = D.isRedeclaration();
5505   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5506   D.setRedeclaration(Redeclaration);
5507   return ND;
5508 }
5509
5510 void
5511 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5512   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5513   // then it shall have block scope.
5514   // Note that variably modified types must be fixed before merging the decl so
5515   // that redeclarations will match.
5516   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5517   QualType T = TInfo->getType();
5518   if (T->isVariablyModifiedType()) {
5519     getCurFunction()->setHasBranchProtectedScope();
5520
5521     if (S->getFnParent() == nullptr) {
5522       bool SizeIsNegative;
5523       llvm::APSInt Oversized;
5524       TypeSourceInfo *FixedTInfo =
5525         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5526                                                       SizeIsNegative,
5527                                                       Oversized);
5528       if (FixedTInfo) {
5529         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5530         NewTD->setTypeSourceInfo(FixedTInfo);
5531       } else {
5532         if (SizeIsNegative)
5533           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5534         else if (T->isVariableArrayType())
5535           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5536         else if (Oversized.getBoolValue())
5537           Diag(NewTD->getLocation(), diag::err_array_too_large)
5538             << Oversized.toString(10);
5539         else
5540           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5541         NewTD->setInvalidDecl();
5542       }
5543     }
5544   }
5545 }
5546
5547 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5548 /// declares a typedef-name, either using the 'typedef' type specifier or via
5549 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5550 NamedDecl*
5551 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5552                            LookupResult &Previous, bool &Redeclaration) {
5553
5554   // Find the shadowed declaration before filtering for scope.
5555   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5556
5557   // Merge the decl with the existing one if appropriate. If the decl is
5558   // in an outer scope, it isn't the same thing.
5559   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5560                        /*AllowInlineNamespace*/false);
5561   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5562   if (!Previous.empty()) {
5563     Redeclaration = true;
5564     MergeTypedefNameDecl(S, NewTD, Previous);
5565   }
5566
5567   if (ShadowedDecl && !Redeclaration)
5568     CheckShadow(NewTD, ShadowedDecl, Previous);
5569
5570   // If this is the C FILE type, notify the AST context.
5571   if (IdentifierInfo *II = NewTD->getIdentifier())
5572     if (!NewTD->isInvalidDecl() &&
5573         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5574       if (II->isStr("FILE"))
5575         Context.setFILEDecl(NewTD);
5576       else if (II->isStr("jmp_buf"))
5577         Context.setjmp_bufDecl(NewTD);
5578       else if (II->isStr("sigjmp_buf"))
5579         Context.setsigjmp_bufDecl(NewTD);
5580       else if (II->isStr("ucontext_t"))
5581         Context.setucontext_tDecl(NewTD);
5582     }
5583
5584   return NewTD;
5585 }
5586
5587 /// \brief Determines whether the given declaration is an out-of-scope
5588 /// previous declaration.
5589 ///
5590 /// This routine should be invoked when name lookup has found a
5591 /// previous declaration (PrevDecl) that is not in the scope where a
5592 /// new declaration by the same name is being introduced. If the new
5593 /// declaration occurs in a local scope, previous declarations with
5594 /// linkage may still be considered previous declarations (C99
5595 /// 6.2.2p4-5, C++ [basic.link]p6).
5596 ///
5597 /// \param PrevDecl the previous declaration found by name
5598 /// lookup
5599 ///
5600 /// \param DC the context in which the new declaration is being
5601 /// declared.
5602 ///
5603 /// \returns true if PrevDecl is an out-of-scope previous declaration
5604 /// for a new delcaration with the same name.
5605 static bool
5606 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5607                                 ASTContext &Context) {
5608   if (!PrevDecl)
5609     return false;
5610
5611   if (!PrevDecl->hasLinkage())
5612     return false;
5613
5614   if (Context.getLangOpts().CPlusPlus) {
5615     // C++ [basic.link]p6:
5616     //   If there is a visible declaration of an entity with linkage
5617     //   having the same name and type, ignoring entities declared
5618     //   outside the innermost enclosing namespace scope, the block
5619     //   scope declaration declares that same entity and receives the
5620     //   linkage of the previous declaration.
5621     DeclContext *OuterContext = DC->getRedeclContext();
5622     if (!OuterContext->isFunctionOrMethod())
5623       // This rule only applies to block-scope declarations.
5624       return false;
5625
5626     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5627     if (PrevOuterContext->isRecord())
5628       // We found a member function: ignore it.
5629       return false;
5630
5631     // Find the innermost enclosing namespace for the new and
5632     // previous declarations.
5633     OuterContext = OuterContext->getEnclosingNamespaceContext();
5634     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5635
5636     // The previous declaration is in a different namespace, so it
5637     // isn't the same function.
5638     if (!OuterContext->Equals(PrevOuterContext))
5639       return false;
5640   }
5641
5642   return true;
5643 }
5644
5645 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5646   CXXScopeSpec &SS = D.getCXXScopeSpec();
5647   if (!SS.isSet()) return;
5648   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5649 }
5650
5651 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5652   QualType type = decl->getType();
5653   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5654   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5655     // Various kinds of declaration aren't allowed to be __autoreleasing.
5656     unsigned kind = -1U;
5657     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5658       if (var->hasAttr<BlocksAttr>())
5659         kind = 0; // __block
5660       else if (!var->hasLocalStorage())
5661         kind = 1; // global
5662     } else if (isa<ObjCIvarDecl>(decl)) {
5663       kind = 3; // ivar
5664     } else if (isa<FieldDecl>(decl)) {
5665       kind = 2; // field
5666     }
5667
5668     if (kind != -1U) {
5669       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5670         << kind;
5671     }
5672   } else if (lifetime == Qualifiers::OCL_None) {
5673     // Try to infer lifetime.
5674     if (!type->isObjCLifetimeType())
5675       return false;
5676
5677     lifetime = type->getObjCARCImplicitLifetime();
5678     type = Context.getLifetimeQualifiedType(type, lifetime);
5679     decl->setType(type);
5680   }
5681
5682   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5683     // Thread-local variables cannot have lifetime.
5684     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5685         var->getTLSKind()) {
5686       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5687         << var->getType();
5688       return true;
5689     }
5690   }
5691
5692   return false;
5693 }
5694
5695 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5696   // Ensure that an auto decl is deduced otherwise the checks below might cache
5697   // the wrong linkage.
5698   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5699
5700   // 'weak' only applies to declarations with external linkage.
5701   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5702     if (!ND.isExternallyVisible()) {
5703       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5704       ND.dropAttr<WeakAttr>();
5705     }
5706   }
5707   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5708     if (ND.isExternallyVisible()) {
5709       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5710       ND.dropAttr<WeakRefAttr>();
5711       ND.dropAttr<AliasAttr>();
5712     }
5713   }
5714
5715   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5716     if (VD->hasInit()) {
5717       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5718         assert(VD->isThisDeclarationADefinition() &&
5719                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5720         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5721         VD->dropAttr<AliasAttr>();
5722       }
5723     }
5724   }
5725
5726   // 'selectany' only applies to externally visible variable declarations.
5727   // It does not apply to functions.
5728   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5729     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5730       S.Diag(Attr->getLocation(),
5731              diag::err_attribute_selectany_non_extern_data);
5732       ND.dropAttr<SelectAnyAttr>();
5733     }
5734   }
5735
5736   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5737     // dll attributes require external linkage. Static locals may have external
5738     // linkage but still cannot be explicitly imported or exported.
5739     auto *VD = dyn_cast<VarDecl>(&ND);
5740     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5741       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5742         << &ND << Attr;
5743       ND.setInvalidDecl();
5744     }
5745   }
5746
5747   // Virtual functions cannot be marked as 'notail'.
5748   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5749     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5750       if (MD->isVirtual()) {
5751         S.Diag(ND.getLocation(),
5752                diag::err_invalid_attribute_on_virtual_function)
5753             << Attr;
5754         ND.dropAttr<NotTailCalledAttr>();
5755       }
5756 }
5757
5758 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5759                                            NamedDecl *NewDecl,
5760                                            bool IsSpecialization,
5761                                            bool IsDefinition) {
5762   if (OldDecl->isInvalidDecl())
5763     return;
5764
5765   bool IsTemplate = false;
5766   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5767     OldDecl = OldTD->getTemplatedDecl();
5768     IsTemplate = true;
5769     if (!IsSpecialization)
5770       IsDefinition = false;
5771   }
5772   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5773     NewDecl = NewTD->getTemplatedDecl();
5774     IsTemplate = true;
5775   }
5776
5777   if (!OldDecl || !NewDecl)
5778     return;
5779
5780   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5781   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5782   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5783   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5784
5785   // dllimport and dllexport are inheritable attributes so we have to exclude
5786   // inherited attribute instances.
5787   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5788                     (NewExportAttr && !NewExportAttr->isInherited());
5789
5790   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5791   // the only exception being explicit specializations.
5792   // Implicitly generated declarations are also excluded for now because there
5793   // is no other way to switch these to use dllimport or dllexport.
5794   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5795
5796   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5797     // Allow with a warning for free functions and global variables.
5798     bool JustWarn = false;
5799     if (!OldDecl->isCXXClassMember()) {
5800       auto *VD = dyn_cast<VarDecl>(OldDecl);
5801       if (VD && !VD->getDescribedVarTemplate())
5802         JustWarn = true;
5803       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5804       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5805         JustWarn = true;
5806     }
5807
5808     // We cannot change a declaration that's been used because IR has already
5809     // been emitted. Dllimported functions will still work though (modulo
5810     // address equality) as they can use the thunk.
5811     if (OldDecl->isUsed())
5812       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5813         JustWarn = false;
5814
5815     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5816                                : diag::err_attribute_dll_redeclaration;
5817     S.Diag(NewDecl->getLocation(), DiagID)
5818         << NewDecl
5819         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5820     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5821     if (!JustWarn) {
5822       NewDecl->setInvalidDecl();
5823       return;
5824     }
5825   }
5826
5827   // A redeclaration is not allowed to drop a dllimport attribute, the only
5828   // exceptions being inline function definitions (except for function
5829   // templates), local extern declarations, qualified friend declarations or
5830   // special MSVC extension: in the last case, the declaration is treated as if
5831   // it were marked dllexport.
5832   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5833   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5834   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5835     // Ignore static data because out-of-line definitions are diagnosed
5836     // separately.
5837     IsStaticDataMember = VD->isStaticDataMember();
5838     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5839                    VarDecl::DeclarationOnly;
5840   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5841     IsInline = FD->isInlined();
5842     IsQualifiedFriend = FD->getQualifier() &&
5843                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5844   }
5845
5846   if (OldImportAttr && !HasNewAttr &&
5847       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5848       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5849     if (IsMicrosoft && IsDefinition) {
5850       S.Diag(NewDecl->getLocation(),
5851              diag::warn_redeclaration_without_import_attribute)
5852           << NewDecl;
5853       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5854       NewDecl->dropAttr<DLLImportAttr>();
5855       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5856           NewImportAttr->getRange(), S.Context,
5857           NewImportAttr->getSpellingListIndex()));
5858     } else {
5859       S.Diag(NewDecl->getLocation(),
5860              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5861           << NewDecl << OldImportAttr;
5862       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5863       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5864       OldDecl->dropAttr<DLLImportAttr>();
5865       NewDecl->dropAttr<DLLImportAttr>();
5866     }
5867   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5868     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5869     OldDecl->dropAttr<DLLImportAttr>();
5870     NewDecl->dropAttr<DLLImportAttr>();
5871     S.Diag(NewDecl->getLocation(),
5872            diag::warn_dllimport_dropped_from_inline_function)
5873         << NewDecl << OldImportAttr;
5874   }
5875 }
5876
5877 /// Given that we are within the definition of the given function,
5878 /// will that definition behave like C99's 'inline', where the
5879 /// definition is discarded except for optimization purposes?
5880 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5881   // Try to avoid calling GetGVALinkageForFunction.
5882
5883   // All cases of this require the 'inline' keyword.
5884   if (!FD->isInlined()) return false;
5885
5886   // This is only possible in C++ with the gnu_inline attribute.
5887   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5888     return false;
5889
5890   // Okay, go ahead and call the relatively-more-expensive function.
5891   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5892 }
5893
5894 /// Determine whether a variable is extern "C" prior to attaching
5895 /// an initializer. We can't just call isExternC() here, because that
5896 /// will also compute and cache whether the declaration is externally
5897 /// visible, which might change when we attach the initializer.
5898 ///
5899 /// This can only be used if the declaration is known to not be a
5900 /// redeclaration of an internal linkage declaration.
5901 ///
5902 /// For instance:
5903 ///
5904 ///   auto x = []{};
5905 ///
5906 /// Attaching the initializer here makes this declaration not externally
5907 /// visible, because its type has internal linkage.
5908 ///
5909 /// FIXME: This is a hack.
5910 template<typename T>
5911 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5912   if (S.getLangOpts().CPlusPlus) {
5913     // In C++, the overloadable attribute negates the effects of extern "C".
5914     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5915       return false;
5916
5917     // So do CUDA's host/device attributes.
5918     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5919                                  D->template hasAttr<CUDAHostAttr>()))
5920       return false;
5921   }
5922   return D->isExternC();
5923 }
5924
5925 static bool shouldConsiderLinkage(const VarDecl *VD) {
5926   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5927   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5928     return VD->hasExternalStorage();
5929   if (DC->isFileContext())
5930     return true;
5931   if (DC->isRecord())
5932     return false;
5933   llvm_unreachable("Unexpected context");
5934 }
5935
5936 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5937   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5938   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5939       isa<OMPDeclareReductionDecl>(DC))
5940     return true;
5941   if (DC->isRecord())
5942     return false;
5943   llvm_unreachable("Unexpected context");
5944 }
5945
5946 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5947                           AttributeList::Kind Kind) {
5948   for (const AttributeList *L = AttrList; L; L = L->getNext())
5949     if (L->getKind() == Kind)
5950       return true;
5951   return false;
5952 }
5953
5954 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5955                           AttributeList::Kind Kind) {
5956   // Check decl attributes on the DeclSpec.
5957   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5958     return true;
5959
5960   // Walk the declarator structure, checking decl attributes that were in a type
5961   // position to the decl itself.
5962   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5963     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5964       return true;
5965   }
5966
5967   // Finally, check attributes on the decl itself.
5968   return hasParsedAttr(S, PD.getAttributes(), Kind);
5969 }
5970
5971 /// Adjust the \c DeclContext for a function or variable that might be a
5972 /// function-local external declaration.
5973 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5974   if (!DC->isFunctionOrMethod())
5975     return false;
5976
5977   // If this is a local extern function or variable declared within a function
5978   // template, don't add it into the enclosing namespace scope until it is
5979   // instantiated; it might have a dependent type right now.
5980   if (DC->isDependentContext())
5981     return true;
5982
5983   // C++11 [basic.link]p7:
5984   //   When a block scope declaration of an entity with linkage is not found to
5985   //   refer to some other declaration, then that entity is a member of the
5986   //   innermost enclosing namespace.
5987   //
5988   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5989   // semantically-enclosing namespace, not a lexically-enclosing one.
5990   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5991     DC = DC->getParent();
5992   return true;
5993 }
5994
5995 /// \brief Returns true if given declaration has external C language linkage.
5996 static bool isDeclExternC(const Decl *D) {
5997   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5998     return FD->isExternC();
5999   if (const auto *VD = dyn_cast<VarDecl>(D))
6000     return VD->isExternC();
6001
6002   llvm_unreachable("Unknown type of decl!");
6003 }
6004
6005 NamedDecl *Sema::ActOnVariableDeclarator(
6006     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6007     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6008     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6009   QualType R = TInfo->getType();
6010   DeclarationName Name = GetNameForDeclarator(D).getName();
6011
6012   IdentifierInfo *II = Name.getAsIdentifierInfo();
6013
6014   if (D.isDecompositionDeclarator()) {
6015     AddToScope = false;
6016     // Take the name of the first declarator as our name for diagnostic
6017     // purposes.
6018     auto &Decomp = D.getDecompositionDeclarator();
6019     if (!Decomp.bindings().empty()) {
6020       II = Decomp.bindings()[0].Name;
6021       Name = II;
6022     }
6023   } else if (!II) {
6024     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6025     return nullptr;
6026   }
6027
6028   if (getLangOpts().OpenCL) {
6029     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6030     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6031     // argument.
6032     if (R->isImageType() || R->isPipeType()) {
6033       Diag(D.getIdentifierLoc(),
6034            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6035           << R;
6036       D.setInvalidType();
6037       return nullptr;
6038     }
6039
6040     // OpenCL v1.2 s6.9.r:
6041     // The event type cannot be used to declare a program scope variable.
6042     // OpenCL v2.0 s6.9.q:
6043     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6044     if (NULL == S->getParent()) {
6045       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6046         Diag(D.getIdentifierLoc(),
6047              diag::err_invalid_type_for_program_scope_var) << R;
6048         D.setInvalidType();
6049         return nullptr;
6050       }
6051     }
6052
6053     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6054     QualType NR = R;
6055     while (NR->isPointerType()) {
6056       if (NR->isFunctionPointerType()) {
6057         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
6058         D.setInvalidType();
6059         break;
6060       }
6061       NR = NR->getPointeeType();
6062     }
6063
6064     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6065       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6066       // half array type (unless the cl_khr_fp16 extension is enabled).
6067       if (Context.getBaseElementType(R)->isHalfType()) {
6068         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6069         D.setInvalidType();
6070       }
6071     }
6072
6073     // OpenCL v1.2 s6.9.b p4:
6074     // The sampler type cannot be used with the __local and __global address
6075     // space qualifiers.
6076     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
6077       R.getAddressSpace() == LangAS::opencl_global)) {
6078       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6079     }
6080
6081     // OpenCL v1.2 s6.9.r:
6082     // The event type cannot be used with the __local, __constant and __global
6083     // address space qualifiers.
6084     if (R->isEventT()) {
6085       if (R.getAddressSpace()) {
6086         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6087         D.setInvalidType();
6088       }
6089     }
6090   }
6091
6092   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6093   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6094
6095   // dllimport globals without explicit storage class are treated as extern. We
6096   // have to change the storage class this early to get the right DeclContext.
6097   if (SC == SC_None && !DC->isRecord() &&
6098       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6099       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6100     SC = SC_Extern;
6101
6102   DeclContext *OriginalDC = DC;
6103   bool IsLocalExternDecl = SC == SC_Extern &&
6104                            adjustContextForLocalExternDecl(DC);
6105
6106   if (SCSpec == DeclSpec::SCS_mutable) {
6107     // mutable can only appear on non-static class members, so it's always
6108     // an error here
6109     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6110     D.setInvalidType();
6111     SC = SC_None;
6112   }
6113
6114   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6115       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6116                               D.getDeclSpec().getStorageClassSpecLoc())) {
6117     // In C++11, the 'register' storage class specifier is deprecated.
6118     // Suppress the warning in system macros, it's used in macros in some
6119     // popular C system headers, such as in glibc's htonl() macro.
6120     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6121          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6122                                    : diag::warn_deprecated_register)
6123       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6124   }
6125
6126   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6127
6128   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6129     // C99 6.9p2: The storage-class specifiers auto and register shall not
6130     // appear in the declaration specifiers in an external declaration.
6131     // Global Register+Asm is a GNU extension we support.
6132     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6133       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6134       D.setInvalidType();
6135     }
6136   }
6137
6138   bool IsMemberSpecialization = false;
6139   bool IsVariableTemplateSpecialization = false;
6140   bool IsPartialSpecialization = false;
6141   bool IsVariableTemplate = false;
6142   VarDecl *NewVD = nullptr;
6143   VarTemplateDecl *NewTemplate = nullptr;
6144   TemplateParameterList *TemplateParams = nullptr;
6145   if (!getLangOpts().CPlusPlus) {
6146     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6147                             D.getIdentifierLoc(), II,
6148                             R, TInfo, SC);
6149
6150     if (R->getContainedDeducedType())
6151       ParsingInitForAutoVars.insert(NewVD);
6152
6153     if (D.isInvalidType())
6154       NewVD->setInvalidDecl();
6155   } else {
6156     bool Invalid = false;
6157
6158     if (DC->isRecord() && !CurContext->isRecord()) {
6159       // This is an out-of-line definition of a static data member.
6160       switch (SC) {
6161       case SC_None:
6162         break;
6163       case SC_Static:
6164         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6165              diag::err_static_out_of_line)
6166           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6167         break;
6168       case SC_Auto:
6169       case SC_Register:
6170       case SC_Extern:
6171         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6172         // to names of variables declared in a block or to function parameters.
6173         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6174         // of class members
6175
6176         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6177              diag::err_storage_class_for_static_member)
6178           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6179         break;
6180       case SC_PrivateExtern:
6181         llvm_unreachable("C storage class in c++!");
6182       }
6183     }
6184
6185     if (SC == SC_Static && CurContext->isRecord()) {
6186       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6187         if (RD->isLocalClass())
6188           Diag(D.getIdentifierLoc(),
6189                diag::err_static_data_member_not_allowed_in_local_class)
6190             << Name << RD->getDeclName();
6191
6192         // C++98 [class.union]p1: If a union contains a static data member,
6193         // the program is ill-formed. C++11 drops this restriction.
6194         if (RD->isUnion())
6195           Diag(D.getIdentifierLoc(),
6196                getLangOpts().CPlusPlus11
6197                  ? diag::warn_cxx98_compat_static_data_member_in_union
6198                  : diag::ext_static_data_member_in_union) << Name;
6199         // We conservatively disallow static data members in anonymous structs.
6200         else if (!RD->getDeclName())
6201           Diag(D.getIdentifierLoc(),
6202                diag::err_static_data_member_not_allowed_in_anon_struct)
6203             << Name << RD->isUnion();
6204       }
6205     }
6206
6207     // Match up the template parameter lists with the scope specifier, then
6208     // determine whether we have a template or a template specialization.
6209     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6210         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6211         D.getCXXScopeSpec(),
6212         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6213             ? D.getName().TemplateId
6214             : nullptr,
6215         TemplateParamLists,
6216         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6217
6218     if (TemplateParams) {
6219       if (!TemplateParams->size() &&
6220           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6221         // There is an extraneous 'template<>' for this variable. Complain
6222         // about it, but allow the declaration of the variable.
6223         Diag(TemplateParams->getTemplateLoc(),
6224              diag::err_template_variable_noparams)
6225           << II
6226           << SourceRange(TemplateParams->getTemplateLoc(),
6227                          TemplateParams->getRAngleLoc());
6228         TemplateParams = nullptr;
6229       } else {
6230         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6231           // This is an explicit specialization or a partial specialization.
6232           // FIXME: Check that we can declare a specialization here.
6233           IsVariableTemplateSpecialization = true;
6234           IsPartialSpecialization = TemplateParams->size() > 0;
6235         } else { // if (TemplateParams->size() > 0)
6236           // This is a template declaration.
6237           IsVariableTemplate = true;
6238
6239           // Check that we can declare a template here.
6240           if (CheckTemplateDeclScope(S, TemplateParams))
6241             return nullptr;
6242
6243           // Only C++1y supports variable templates (N3651).
6244           Diag(D.getIdentifierLoc(),
6245                getLangOpts().CPlusPlus14
6246                    ? diag::warn_cxx11_compat_variable_template
6247                    : diag::ext_variable_template);
6248         }
6249       }
6250     } else {
6251       assert(
6252           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6253           "should have a 'template<>' for this decl");
6254     }
6255
6256     if (IsVariableTemplateSpecialization) {
6257       SourceLocation TemplateKWLoc =
6258           TemplateParamLists.size() > 0
6259               ? TemplateParamLists[0]->getTemplateLoc()
6260               : SourceLocation();
6261       DeclResult Res = ActOnVarTemplateSpecialization(
6262           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6263           IsPartialSpecialization);
6264       if (Res.isInvalid())
6265         return nullptr;
6266       NewVD = cast<VarDecl>(Res.get());
6267       AddToScope = false;
6268     } else if (D.isDecompositionDeclarator()) {
6269       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6270                                         D.getIdentifierLoc(), R, TInfo, SC,
6271                                         Bindings);
6272     } else
6273       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6274                               D.getIdentifierLoc(), II, R, TInfo, SC);
6275
6276     // If this is supposed to be a variable template, create it as such.
6277     if (IsVariableTemplate) {
6278       NewTemplate =
6279           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6280                                   TemplateParams, NewVD);
6281       NewVD->setDescribedVarTemplate(NewTemplate);
6282     }
6283
6284     // If this decl has an auto type in need of deduction, make a note of the
6285     // Decl so we can diagnose uses of it in its own initializer.
6286     if (R->getContainedDeducedType())
6287       ParsingInitForAutoVars.insert(NewVD);
6288
6289     if (D.isInvalidType() || Invalid) {
6290       NewVD->setInvalidDecl();
6291       if (NewTemplate)
6292         NewTemplate->setInvalidDecl();
6293     }
6294
6295     SetNestedNameSpecifier(NewVD, D);
6296
6297     // If we have any template parameter lists that don't directly belong to
6298     // the variable (matching the scope specifier), store them.
6299     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6300     if (TemplateParamLists.size() > VDTemplateParamLists)
6301       NewVD->setTemplateParameterListsInfo(
6302           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6303
6304     if (D.getDeclSpec().isConstexprSpecified()) {
6305       NewVD->setConstexpr(true);
6306       // C++1z [dcl.spec.constexpr]p1:
6307       //   A static data member declared with the constexpr specifier is
6308       //   implicitly an inline variable.
6309       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6310         NewVD->setImplicitlyInline();
6311     }
6312
6313     if (D.getDeclSpec().isConceptSpecified()) {
6314       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6315         VTD->setConcept();
6316
6317       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6318       // be declared with the thread_local, inline, friend, or constexpr
6319       // specifiers, [...]
6320       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6321         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6322              diag::err_concept_decl_invalid_specifiers)
6323             << 0 << 0;
6324         NewVD->setInvalidDecl(true);
6325       }
6326
6327       if (D.getDeclSpec().isConstexprSpecified()) {
6328         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6329              diag::err_concept_decl_invalid_specifiers)
6330             << 0 << 3;
6331         NewVD->setInvalidDecl(true);
6332       }
6333
6334       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6335       // applied only to the definition of a function template or variable
6336       // template, declared in namespace scope.
6337       if (IsVariableTemplateSpecialization) {
6338         Diag(D.getDeclSpec().getConceptSpecLoc(),
6339              diag::err_concept_specified_specialization)
6340             << (IsPartialSpecialization ? 2 : 1);
6341       }
6342
6343       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6344       // following restrictions:
6345       // - The declared type shall have the type bool.
6346       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6347           !NewVD->isInvalidDecl()) {
6348         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6349         NewVD->setInvalidDecl(true);
6350       }
6351     }
6352   }
6353
6354   if (D.getDeclSpec().isInlineSpecified()) {
6355     if (!getLangOpts().CPlusPlus) {
6356       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6357           << 0;
6358     } else if (CurContext->isFunctionOrMethod()) {
6359       // 'inline' is not allowed on block scope variable declaration.
6360       Diag(D.getDeclSpec().getInlineSpecLoc(),
6361            diag::err_inline_declaration_block_scope) << Name
6362         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6363     } else {
6364       Diag(D.getDeclSpec().getInlineSpecLoc(),
6365            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6366                                      : diag::ext_inline_variable);
6367       NewVD->setInlineSpecified();
6368     }
6369   }
6370
6371   // Set the lexical context. If the declarator has a C++ scope specifier, the
6372   // lexical context will be different from the semantic context.
6373   NewVD->setLexicalDeclContext(CurContext);
6374   if (NewTemplate)
6375     NewTemplate->setLexicalDeclContext(CurContext);
6376
6377   if (IsLocalExternDecl) {
6378     if (D.isDecompositionDeclarator())
6379       for (auto *B : Bindings)
6380         B->setLocalExternDecl();
6381     else
6382       NewVD->setLocalExternDecl();
6383   }
6384
6385   bool EmitTLSUnsupportedError = false;
6386   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6387     // C++11 [dcl.stc]p4:
6388     //   When thread_local is applied to a variable of block scope the
6389     //   storage-class-specifier static is implied if it does not appear
6390     //   explicitly.
6391     // Core issue: 'static' is not implied if the variable is declared
6392     //   'extern'.
6393     if (NewVD->hasLocalStorage() &&
6394         (SCSpec != DeclSpec::SCS_unspecified ||
6395          TSCS != DeclSpec::TSCS_thread_local ||
6396          !DC->isFunctionOrMethod()))
6397       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6398            diag::err_thread_non_global)
6399         << DeclSpec::getSpecifierName(TSCS);
6400     else if (!Context.getTargetInfo().isTLSSupported()) {
6401       if (getLangOpts().CUDA) {
6402         // Postpone error emission until we've collected attributes required to
6403         // figure out whether it's a host or device variable and whether the
6404         // error should be ignored.
6405         EmitTLSUnsupportedError = true;
6406         // We still need to mark the variable as TLS so it shows up in AST with
6407         // proper storage class for other tools to use even if we're not going
6408         // to emit any code for it.
6409         NewVD->setTSCSpec(TSCS);
6410       } else
6411         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6412              diag::err_thread_unsupported);
6413     } else
6414       NewVD->setTSCSpec(TSCS);
6415   }
6416
6417   // C99 6.7.4p3
6418   //   An inline definition of a function with external linkage shall
6419   //   not contain a definition of a modifiable object with static or
6420   //   thread storage duration...
6421   // We only apply this when the function is required to be defined
6422   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6423   // that a local variable with thread storage duration still has to
6424   // be marked 'static'.  Also note that it's possible to get these
6425   // semantics in C++ using __attribute__((gnu_inline)).
6426   if (SC == SC_Static && S->getFnParent() != nullptr &&
6427       !NewVD->getType().isConstQualified()) {
6428     FunctionDecl *CurFD = getCurFunctionDecl();
6429     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6430       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6431            diag::warn_static_local_in_extern_inline);
6432       MaybeSuggestAddingStaticToDecl(CurFD);
6433     }
6434   }
6435
6436   if (D.getDeclSpec().isModulePrivateSpecified()) {
6437     if (IsVariableTemplateSpecialization)
6438       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6439           << (IsPartialSpecialization ? 1 : 0)
6440           << FixItHint::CreateRemoval(
6441                  D.getDeclSpec().getModulePrivateSpecLoc());
6442     else if (IsMemberSpecialization)
6443       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6444         << 2
6445         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6446     else if (NewVD->hasLocalStorage())
6447       Diag(NewVD->getLocation(), diag::err_module_private_local)
6448         << 0 << NewVD->getDeclName()
6449         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6450         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6451     else {
6452       NewVD->setModulePrivate();
6453       if (NewTemplate)
6454         NewTemplate->setModulePrivate();
6455       for (auto *B : Bindings)
6456         B->setModulePrivate();
6457     }
6458   }
6459
6460   // Handle attributes prior to checking for duplicates in MergeVarDecl
6461   ProcessDeclAttributes(S, NewVD, D);
6462
6463   if (getLangOpts().CUDA) {
6464     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6465       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6466            diag::err_thread_unsupported);
6467     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6468     // storage [duration]."
6469     if (SC == SC_None && S->getFnParent() != nullptr &&
6470         (NewVD->hasAttr<CUDASharedAttr>() ||
6471          NewVD->hasAttr<CUDAConstantAttr>())) {
6472       NewVD->setStorageClass(SC_Static);
6473     }
6474   }
6475
6476   // Ensure that dllimport globals without explicit storage class are treated as
6477   // extern. The storage class is set above using parsed attributes. Now we can
6478   // check the VarDecl itself.
6479   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6480          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6481          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6482
6483   // In auto-retain/release, infer strong retension for variables of
6484   // retainable type.
6485   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6486     NewVD->setInvalidDecl();
6487
6488   // Handle GNU asm-label extension (encoded as an attribute).
6489   if (Expr *E = (Expr*)D.getAsmLabel()) {
6490     // The parser guarantees this is a string.
6491     StringLiteral *SE = cast<StringLiteral>(E);
6492     StringRef Label = SE->getString();
6493     if (S->getFnParent() != nullptr) {
6494       switch (SC) {
6495       case SC_None:
6496       case SC_Auto:
6497         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6498         break;
6499       case SC_Register:
6500         // Local Named register
6501         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6502             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6503           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6504         break;
6505       case SC_Static:
6506       case SC_Extern:
6507       case SC_PrivateExtern:
6508         break;
6509       }
6510     } else if (SC == SC_Register) {
6511       // Global Named register
6512       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6513         const auto &TI = Context.getTargetInfo();
6514         bool HasSizeMismatch;
6515
6516         if (!TI.isValidGCCRegisterName(Label))
6517           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6518         else if (!TI.validateGlobalRegisterVariable(Label,
6519                                                     Context.getTypeSize(R),
6520                                                     HasSizeMismatch))
6521           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6522         else if (HasSizeMismatch)
6523           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6524       }
6525
6526       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6527         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6528         NewVD->setInvalidDecl(true);
6529       }
6530     }
6531
6532     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6533                                                 Context, Label, 0));
6534   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6535     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6536       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6537     if (I != ExtnameUndeclaredIdentifiers.end()) {
6538       if (isDeclExternC(NewVD)) {
6539         NewVD->addAttr(I->second);
6540         ExtnameUndeclaredIdentifiers.erase(I);
6541       } else
6542         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6543             << /*Variable*/1 << NewVD;
6544     }
6545   }
6546
6547   // Find the shadowed declaration before filtering for scope.
6548   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6549                                 ? getShadowedDeclaration(NewVD, Previous)
6550                                 : nullptr;
6551
6552   // Don't consider existing declarations that are in a different
6553   // scope and are out-of-semantic-context declarations (if the new
6554   // declaration has linkage).
6555   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6556                        D.getCXXScopeSpec().isNotEmpty() ||
6557                        IsMemberSpecialization ||
6558                        IsVariableTemplateSpecialization);
6559
6560   // Check whether the previous declaration is in the same block scope. This
6561   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6562   if (getLangOpts().CPlusPlus &&
6563       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6564     NewVD->setPreviousDeclInSameBlockScope(
6565         Previous.isSingleResult() && !Previous.isShadowed() &&
6566         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6567
6568   if (!getLangOpts().CPlusPlus) {
6569     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6570   } else {
6571     // If this is an explicit specialization of a static data member, check it.
6572     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6573         CheckMemberSpecialization(NewVD, Previous))
6574       NewVD->setInvalidDecl();
6575
6576     // Merge the decl with the existing one if appropriate.
6577     if (!Previous.empty()) {
6578       if (Previous.isSingleResult() &&
6579           isa<FieldDecl>(Previous.getFoundDecl()) &&
6580           D.getCXXScopeSpec().isSet()) {
6581         // The user tried to define a non-static data member
6582         // out-of-line (C++ [dcl.meaning]p1).
6583         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6584           << D.getCXXScopeSpec().getRange();
6585         Previous.clear();
6586         NewVD->setInvalidDecl();
6587       }
6588     } else if (D.getCXXScopeSpec().isSet()) {
6589       // No previous declaration in the qualifying scope.
6590       Diag(D.getIdentifierLoc(), diag::err_no_member)
6591         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6592         << D.getCXXScopeSpec().getRange();
6593       NewVD->setInvalidDecl();
6594     }
6595
6596     if (!IsVariableTemplateSpecialization)
6597       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6598
6599     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6600     // an explicit specialization (14.8.3) or a partial specialization of a
6601     // concept definition.
6602     if (IsVariableTemplateSpecialization &&
6603         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6604         Previous.isSingleResult()) {
6605       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6606       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6607         if (VarTmpl->isConcept()) {
6608           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6609               << 1                            /*variable*/
6610               << (IsPartialSpecialization ? 2 /*partially specialized*/
6611                                           : 1 /*explicitly specialized*/);
6612           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6613           NewVD->setInvalidDecl();
6614         }
6615       }
6616     }
6617
6618     if (NewTemplate) {
6619       VarTemplateDecl *PrevVarTemplate =
6620           NewVD->getPreviousDecl()
6621               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6622               : nullptr;
6623
6624       // Check the template parameter list of this declaration, possibly
6625       // merging in the template parameter list from the previous variable
6626       // template declaration.
6627       if (CheckTemplateParameterList(
6628               TemplateParams,
6629               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6630                               : nullptr,
6631               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6632                DC->isDependentContext())
6633                   ? TPC_ClassTemplateMember
6634                   : TPC_VarTemplate))
6635         NewVD->setInvalidDecl();
6636
6637       // If we are providing an explicit specialization of a static variable
6638       // template, make a note of that.
6639       if (PrevVarTemplate &&
6640           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6641         PrevVarTemplate->setMemberSpecialization();
6642     }
6643   }
6644
6645   // Diagnose shadowed variables iff this isn't a redeclaration.
6646   if (ShadowedDecl && !D.isRedeclaration())
6647     CheckShadow(NewVD, ShadowedDecl, Previous);
6648
6649   ProcessPragmaWeak(S, NewVD);
6650
6651   // If this is the first declaration of an extern C variable, update
6652   // the map of such variables.
6653   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6654       isIncompleteDeclExternC(*this, NewVD))
6655     RegisterLocallyScopedExternCDecl(NewVD, S);
6656
6657   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6658     Decl *ManglingContextDecl;
6659     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6660             NewVD->getDeclContext(), ManglingContextDecl)) {
6661       Context.setManglingNumber(
6662           NewVD, MCtx->getManglingNumber(
6663                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6664       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6665     }
6666   }
6667
6668   // Special handling of variable named 'main'.
6669   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6670       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6671       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6672
6673     // C++ [basic.start.main]p3
6674     // A program that declares a variable main at global scope is ill-formed.
6675     if (getLangOpts().CPlusPlus)
6676       Diag(D.getLocStart(), diag::err_main_global_variable);
6677
6678     // In C, and external-linkage variable named main results in undefined
6679     // behavior.
6680     else if (NewVD->hasExternalFormalLinkage())
6681       Diag(D.getLocStart(), diag::warn_main_redefined);
6682   }
6683
6684   if (D.isRedeclaration() && !Previous.empty()) {
6685     checkDLLAttributeRedeclaration(
6686         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6687         IsMemberSpecialization, D.isFunctionDefinition());
6688   }
6689
6690   if (NewTemplate) {
6691     if (NewVD->isInvalidDecl())
6692       NewTemplate->setInvalidDecl();
6693     ActOnDocumentableDecl(NewTemplate);
6694     return NewTemplate;
6695   }
6696
6697   return NewVD;
6698 }
6699
6700 /// Enum describing the %select options in diag::warn_decl_shadow.
6701 enum ShadowedDeclKind {
6702   SDK_Local,
6703   SDK_Global,
6704   SDK_StaticMember,
6705   SDK_Field,
6706   SDK_Typedef,
6707   SDK_Using
6708 };
6709
6710 /// Determine what kind of declaration we're shadowing.
6711 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6712                                                 const DeclContext *OldDC) {
6713   if (isa<TypeAliasDecl>(ShadowedDecl))
6714     return SDK_Using;
6715   else if (isa<TypedefDecl>(ShadowedDecl))
6716     return SDK_Typedef;
6717   else if (isa<RecordDecl>(OldDC))
6718     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6719
6720   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6721 }
6722
6723 /// Return the location of the capture if the given lambda captures the given
6724 /// variable \p VD, or an invalid source location otherwise.
6725 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6726                                          const VarDecl *VD) {
6727   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6728     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6729       return Capture.getLocation();
6730   }
6731   return SourceLocation();
6732 }
6733
6734 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6735                                      const LookupResult &R) {
6736   // Only diagnose if we're shadowing an unambiguous field or variable.
6737   if (R.getResultKind() != LookupResult::Found)
6738     return false;
6739
6740   // Return false if warning is ignored.
6741   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6742 }
6743
6744 /// \brief Return the declaration shadowed by the given variable \p D, or null
6745 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6746 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6747                                         const LookupResult &R) {
6748   if (!shouldWarnIfShadowedDecl(Diags, R))
6749     return nullptr;
6750
6751   // Don't diagnose declarations at file scope.
6752   if (D->hasGlobalStorage())
6753     return nullptr;
6754
6755   NamedDecl *ShadowedDecl = R.getFoundDecl();
6756   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6757              ? ShadowedDecl
6758              : nullptr;
6759 }
6760
6761 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6762 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6763 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6764                                         const LookupResult &R) {
6765   // Don't warn if typedef declaration is part of a class
6766   if (D->getDeclContext()->isRecord())
6767     return nullptr;
6768   
6769   if (!shouldWarnIfShadowedDecl(Diags, R))
6770     return nullptr;
6771
6772   NamedDecl *ShadowedDecl = R.getFoundDecl();
6773   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6774 }
6775
6776 /// \brief Diagnose variable or built-in function shadowing.  Implements
6777 /// -Wshadow.
6778 ///
6779 /// This method is called whenever a VarDecl is added to a "useful"
6780 /// scope.
6781 ///
6782 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6783 /// \param R the lookup of the name
6784 ///
6785 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6786                        const LookupResult &R) {
6787   DeclContext *NewDC = D->getDeclContext();
6788
6789   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6790     // Fields are not shadowed by variables in C++ static methods.
6791     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6792       if (MD->isStatic())
6793         return;
6794
6795     // Fields shadowed by constructor parameters are a special case. Usually
6796     // the constructor initializes the field with the parameter.
6797     if (isa<CXXConstructorDecl>(NewDC))
6798       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6799         // Remember that this was shadowed so we can either warn about its
6800         // modification or its existence depending on warning settings.
6801         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6802         return;
6803       }
6804   }
6805
6806   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6807     if (shadowedVar->isExternC()) {
6808       // For shadowing external vars, make sure that we point to the global
6809       // declaration, not a locally scoped extern declaration.
6810       for (auto I : shadowedVar->redecls())
6811         if (I->isFileVarDecl()) {
6812           ShadowedDecl = I;
6813           break;
6814         }
6815     }
6816
6817   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6818
6819   unsigned WarningDiag = diag::warn_decl_shadow;
6820   SourceLocation CaptureLoc;
6821   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6822       isa<CXXMethodDecl>(NewDC)) {
6823     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6824       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6825         if (RD->getLambdaCaptureDefault() == LCD_None) {
6826           // Try to avoid warnings for lambdas with an explicit capture list.
6827           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6828           // Warn only when the lambda captures the shadowed decl explicitly.
6829           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6830           if (CaptureLoc.isInvalid())
6831             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6832         } else {
6833           // Remember that this was shadowed so we can avoid the warning if the
6834           // shadowed decl isn't captured and the warning settings allow it.
6835           cast<LambdaScopeInfo>(getCurFunction())
6836               ->ShadowingDecls.push_back(
6837                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6838           return;
6839         }
6840       }
6841     }
6842   }
6843
6844   // Only warn about certain kinds of shadowing for class members.
6845   if (NewDC && NewDC->isRecord()) {
6846     // In particular, don't warn about shadowing non-class members.
6847     if (!OldDC->isRecord())
6848       return;
6849
6850     // TODO: should we warn about static data members shadowing
6851     // static data members from base classes?
6852
6853     // TODO: don't diagnose for inaccessible shadowed members.
6854     // This is hard to do perfectly because we might friend the
6855     // shadowing context, but that's just a false negative.
6856   }
6857
6858
6859   DeclarationName Name = R.getLookupName();
6860
6861   // Emit warning and note.
6862   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6863     return;
6864   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6865   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6866   if (!CaptureLoc.isInvalid())
6867     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6868         << Name << /*explicitly*/ 1;
6869   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6870 }
6871
6872 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6873 /// when these variables are captured by the lambda.
6874 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6875   for (const auto &Shadow : LSI->ShadowingDecls) {
6876     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6877     // Try to avoid the warning when the shadowed decl isn't captured.
6878     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6879     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6880     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6881                                        ? diag::warn_decl_shadow_uncaptured_local
6882                                        : diag::warn_decl_shadow)
6883         << Shadow.VD->getDeclName()
6884         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6885     if (!CaptureLoc.isInvalid())
6886       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6887           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6888     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6889   }
6890 }
6891
6892 /// \brief Check -Wshadow without the advantage of a previous lookup.
6893 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6894   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6895     return;
6896
6897   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6898                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6899   LookupName(R, S);
6900   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
6901     CheckShadow(D, ShadowedDecl, R);
6902 }
6903
6904 /// Check if 'E', which is an expression that is about to be modified, refers
6905 /// to a constructor parameter that shadows a field.
6906 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6907   // Quickly ignore expressions that can't be shadowing ctor parameters.
6908   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6909     return;
6910   E = E->IgnoreParenImpCasts();
6911   auto *DRE = dyn_cast<DeclRefExpr>(E);
6912   if (!DRE)
6913     return;
6914   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6915   auto I = ShadowingDecls.find(D);
6916   if (I == ShadowingDecls.end())
6917     return;
6918   const NamedDecl *ShadowedDecl = I->second;
6919   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6920   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6921   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6922   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6923
6924   // Avoid issuing multiple warnings about the same decl.
6925   ShadowingDecls.erase(I);
6926 }
6927
6928 /// Check for conflict between this global or extern "C" declaration and
6929 /// previous global or extern "C" declarations. This is only used in C++.
6930 template<typename T>
6931 static bool checkGlobalOrExternCConflict(
6932     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6933   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6934   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6935
6936   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6937     // The common case: this global doesn't conflict with any extern "C"
6938     // declaration.
6939     return false;
6940   }
6941
6942   if (Prev) {
6943     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6944       // Both the old and new declarations have C language linkage. This is a
6945       // redeclaration.
6946       Previous.clear();
6947       Previous.addDecl(Prev);
6948       return true;
6949     }
6950
6951     // This is a global, non-extern "C" declaration, and there is a previous
6952     // non-global extern "C" declaration. Diagnose if this is a variable
6953     // declaration.
6954     if (!isa<VarDecl>(ND))
6955       return false;
6956   } else {
6957     // The declaration is extern "C". Check for any declaration in the
6958     // translation unit which might conflict.
6959     if (IsGlobal) {
6960       // We have already performed the lookup into the translation unit.
6961       IsGlobal = false;
6962       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6963            I != E; ++I) {
6964         if (isa<VarDecl>(*I)) {
6965           Prev = *I;
6966           break;
6967         }
6968       }
6969     } else {
6970       DeclContext::lookup_result R =
6971           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6972       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6973            I != E; ++I) {
6974         if (isa<VarDecl>(*I)) {
6975           Prev = *I;
6976           break;
6977         }
6978         // FIXME: If we have any other entity with this name in global scope,
6979         // the declaration is ill-formed, but that is a defect: it breaks the
6980         // 'stat' hack, for instance. Only variables can have mangled name
6981         // clashes with extern "C" declarations, so only they deserve a
6982         // diagnostic.
6983       }
6984     }
6985
6986     if (!Prev)
6987       return false;
6988   }
6989
6990   // Use the first declaration's location to ensure we point at something which
6991   // is lexically inside an extern "C" linkage-spec.
6992   assert(Prev && "should have found a previous declaration to diagnose");
6993   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6994     Prev = FD->getFirstDecl();
6995   else
6996     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6997
6998   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6999     << IsGlobal << ND;
7000   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7001     << IsGlobal;
7002   return false;
7003 }
7004
7005 /// Apply special rules for handling extern "C" declarations. Returns \c true
7006 /// if we have found that this is a redeclaration of some prior entity.
7007 ///
7008 /// Per C++ [dcl.link]p6:
7009 ///   Two declarations [for a function or variable] with C language linkage
7010 ///   with the same name that appear in different scopes refer to the same
7011 ///   [entity]. An entity with C language linkage shall not be declared with
7012 ///   the same name as an entity in global scope.
7013 template<typename T>
7014 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7015                                                   LookupResult &Previous) {
7016   if (!S.getLangOpts().CPlusPlus) {
7017     // In C, when declaring a global variable, look for a corresponding 'extern'
7018     // variable declared in function scope. We don't need this in C++, because
7019     // we find local extern decls in the surrounding file-scope DeclContext.
7020     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7021       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7022         Previous.clear();
7023         Previous.addDecl(Prev);
7024         return true;
7025       }
7026     }
7027     return false;
7028   }
7029
7030   // A declaration in the translation unit can conflict with an extern "C"
7031   // declaration.
7032   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7033     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7034
7035   // An extern "C" declaration can conflict with a declaration in the
7036   // translation unit or can be a redeclaration of an extern "C" declaration
7037   // in another scope.
7038   if (isIncompleteDeclExternC(S,ND))
7039     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7040
7041   // Neither global nor extern "C": nothing to do.
7042   return false;
7043 }
7044
7045 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7046   // If the decl is already known invalid, don't check it.
7047   if (NewVD->isInvalidDecl())
7048     return;
7049
7050   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7051   QualType T = TInfo->getType();
7052
7053   // Defer checking an 'auto' type until its initializer is attached.
7054   if (T->isUndeducedType())
7055     return;
7056
7057   if (NewVD->hasAttrs())
7058     CheckAlignasUnderalignment(NewVD);
7059
7060   if (T->isObjCObjectType()) {
7061     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7062       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7063     T = Context.getObjCObjectPointerType(T);
7064     NewVD->setType(T);
7065   }
7066
7067   // Emit an error if an address space was applied to decl with local storage.
7068   // This includes arrays of objects with address space qualifiers, but not
7069   // automatic variables that point to other address spaces.
7070   // ISO/IEC TR 18037 S5.1.2
7071   if (!getLangOpts().OpenCL
7072       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7073     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
7074     NewVD->setInvalidDecl();
7075     return;
7076   }
7077
7078   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7079   // scope.
7080   if (getLangOpts().OpenCLVersion == 120 &&
7081       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7082       NewVD->isStaticLocal()) {
7083     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7084     NewVD->setInvalidDecl();
7085     return;
7086   }
7087
7088   if (getLangOpts().OpenCL) {
7089     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7090     if (NewVD->hasAttr<BlocksAttr>()) {
7091       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7092       return;
7093     }
7094
7095     if (T->isBlockPointerType()) {
7096       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7097       // can't use 'extern' storage class.
7098       if (!T.isConstQualified()) {
7099         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7100             << 0 /*const*/;
7101         NewVD->setInvalidDecl();
7102         return;
7103       }
7104       if (NewVD->hasExternalStorage()) {
7105         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7106         NewVD->setInvalidDecl();
7107         return;
7108       }
7109     }
7110     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7111     // __constant address space.
7112     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7113     // variables inside a function can also be declared in the global
7114     // address space.
7115     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7116         NewVD->hasExternalStorage()) {
7117       if (!T->isSamplerT() &&
7118           !(T.getAddressSpace() == LangAS::opencl_constant ||
7119             (T.getAddressSpace() == LangAS::opencl_global &&
7120              getLangOpts().OpenCLVersion == 200))) {
7121         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7122         if (getLangOpts().OpenCLVersion == 200)
7123           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7124               << Scope << "global or constant";
7125         else
7126           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7127               << Scope << "constant";
7128         NewVD->setInvalidDecl();
7129         return;
7130       }
7131     } else {
7132       if (T.getAddressSpace() == LangAS::opencl_global) {
7133         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7134             << 1 /*is any function*/ << "global";
7135         NewVD->setInvalidDecl();
7136         return;
7137       }
7138       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
7139       // in functions.
7140       if (T.getAddressSpace() == LangAS::opencl_constant ||
7141           T.getAddressSpace() == LangAS::opencl_local) {
7142         FunctionDecl *FD = getCurFunctionDecl();
7143         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7144           if (T.getAddressSpace() == LangAS::opencl_constant)
7145             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7146                 << 0 /*non-kernel only*/ << "constant";
7147           else
7148             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7149                 << 0 /*non-kernel only*/ << "local";
7150           NewVD->setInvalidDecl();
7151           return;
7152         }
7153       }
7154     }
7155   }
7156
7157   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7158       && !NewVD->hasAttr<BlocksAttr>()) {
7159     if (getLangOpts().getGC() != LangOptions::NonGC)
7160       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7161     else {
7162       assert(!getLangOpts().ObjCAutoRefCount);
7163       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7164     }
7165   }
7166
7167   bool isVM = T->isVariablyModifiedType();
7168   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7169       NewVD->hasAttr<BlocksAttr>())
7170     getCurFunction()->setHasBranchProtectedScope();
7171
7172   if ((isVM && NewVD->hasLinkage()) ||
7173       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7174     bool SizeIsNegative;
7175     llvm::APSInt Oversized;
7176     TypeSourceInfo *FixedTInfo =
7177       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7178                                                     SizeIsNegative, Oversized);
7179     if (!FixedTInfo && T->isVariableArrayType()) {
7180       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7181       // FIXME: This won't give the correct result for
7182       // int a[10][n];
7183       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7184
7185       if (NewVD->isFileVarDecl())
7186         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7187         << SizeRange;
7188       else if (NewVD->isStaticLocal())
7189         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7190         << SizeRange;
7191       else
7192         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7193         << SizeRange;
7194       NewVD->setInvalidDecl();
7195       return;
7196     }
7197
7198     if (!FixedTInfo) {
7199       if (NewVD->isFileVarDecl())
7200         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7201       else
7202         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7203       NewVD->setInvalidDecl();
7204       return;
7205     }
7206
7207     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7208     NewVD->setType(FixedTInfo->getType());
7209     NewVD->setTypeSourceInfo(FixedTInfo);
7210   }
7211
7212   if (T->isVoidType()) {
7213     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7214     //                    of objects and functions.
7215     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7216       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7217         << T;
7218       NewVD->setInvalidDecl();
7219       return;
7220     }
7221   }
7222
7223   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7224     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7225     NewVD->setInvalidDecl();
7226     return;
7227   }
7228
7229   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7230     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7231     NewVD->setInvalidDecl();
7232     return;
7233   }
7234
7235   if (NewVD->isConstexpr() && !T->isDependentType() &&
7236       RequireLiteralType(NewVD->getLocation(), T,
7237                          diag::err_constexpr_var_non_literal)) {
7238     NewVD->setInvalidDecl();
7239     return;
7240   }
7241 }
7242
7243 /// \brief Perform semantic checking on a newly-created variable
7244 /// declaration.
7245 ///
7246 /// This routine performs all of the type-checking required for a
7247 /// variable declaration once it has been built. It is used both to
7248 /// check variables after they have been parsed and their declarators
7249 /// have been translated into a declaration, and to check variables
7250 /// that have been instantiated from a template.
7251 ///
7252 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7253 ///
7254 /// Returns true if the variable declaration is a redeclaration.
7255 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7256   CheckVariableDeclarationType(NewVD);
7257
7258   // If the decl is already known invalid, don't check it.
7259   if (NewVD->isInvalidDecl())
7260     return false;
7261
7262   // If we did not find anything by this name, look for a non-visible
7263   // extern "C" declaration with the same name.
7264   if (Previous.empty() &&
7265       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7266     Previous.setShadowed();
7267
7268   if (!Previous.empty()) {
7269     MergeVarDecl(NewVD, Previous);
7270     return true;
7271   }
7272   return false;
7273 }
7274
7275 namespace {
7276 struct FindOverriddenMethod {
7277   Sema *S;
7278   CXXMethodDecl *Method;
7279
7280   /// Member lookup function that determines whether a given C++
7281   /// method overrides a method in a base class, to be used with
7282   /// CXXRecordDecl::lookupInBases().
7283   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7284     RecordDecl *BaseRecord =
7285         Specifier->getType()->getAs<RecordType>()->getDecl();
7286
7287     DeclarationName Name = Method->getDeclName();
7288
7289     // FIXME: Do we care about other names here too?
7290     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7291       // We really want to find the base class destructor here.
7292       QualType T = S->Context.getTypeDeclType(BaseRecord);
7293       CanQualType CT = S->Context.getCanonicalType(T);
7294
7295       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7296     }
7297
7298     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7299          Path.Decls = Path.Decls.slice(1)) {
7300       NamedDecl *D = Path.Decls.front();
7301       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7302         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7303           return true;
7304       }
7305     }
7306
7307     return false;
7308   }
7309 };
7310
7311 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7312 } // end anonymous namespace
7313
7314 /// \brief Report an error regarding overriding, along with any relevant
7315 /// overriden methods.
7316 ///
7317 /// \param DiagID the primary error to report.
7318 /// \param MD the overriding method.
7319 /// \param OEK which overrides to include as notes.
7320 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7321                             OverrideErrorKind OEK = OEK_All) {
7322   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7323   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7324                                       E = MD->end_overridden_methods();
7325        I != E; ++I) {
7326     // This check (& the OEK parameter) could be replaced by a predicate, but
7327     // without lambdas that would be overkill. This is still nicer than writing
7328     // out the diag loop 3 times.
7329     if ((OEK == OEK_All) ||
7330         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7331         (OEK == OEK_Deleted && (*I)->isDeleted()))
7332       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7333   }
7334 }
7335
7336 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7337 /// and if so, check that it's a valid override and remember it.
7338 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7339   // Look for methods in base classes that this method might override.
7340   CXXBasePaths Paths;
7341   FindOverriddenMethod FOM;
7342   FOM.Method = MD;
7343   FOM.S = this;
7344   bool hasDeletedOverridenMethods = false;
7345   bool hasNonDeletedOverridenMethods = false;
7346   bool AddedAny = false;
7347   if (DC->lookupInBases(FOM, Paths)) {
7348     for (auto *I : Paths.found_decls()) {
7349       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7350         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7351         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7352             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7353             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7354             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7355           hasDeletedOverridenMethods |= OldMD->isDeleted();
7356           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7357           AddedAny = true;
7358         }
7359       }
7360     }
7361   }
7362
7363   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7364     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7365   }
7366   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7367     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7368   }
7369
7370   return AddedAny;
7371 }
7372
7373 namespace {
7374   // Struct for holding all of the extra arguments needed by
7375   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7376   struct ActOnFDArgs {
7377     Scope *S;
7378     Declarator &D;
7379     MultiTemplateParamsArg TemplateParamLists;
7380     bool AddToScope;
7381   };
7382 } // end anonymous namespace
7383
7384 namespace {
7385
7386 // Callback to only accept typo corrections that have a non-zero edit distance.
7387 // Also only accept corrections that have the same parent decl.
7388 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7389  public:
7390   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7391                             CXXRecordDecl *Parent)
7392       : Context(Context), OriginalFD(TypoFD),
7393         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7394
7395   bool ValidateCandidate(const TypoCorrection &candidate) override {
7396     if (candidate.getEditDistance() == 0)
7397       return false;
7398
7399     SmallVector<unsigned, 1> MismatchedParams;
7400     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7401                                           CDeclEnd = candidate.end();
7402          CDecl != CDeclEnd; ++CDecl) {
7403       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7404
7405       if (FD && !FD->hasBody() &&
7406           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7407         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7408           CXXRecordDecl *Parent = MD->getParent();
7409           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7410             return true;
7411         } else if (!ExpectedParent) {
7412           return true;
7413         }
7414       }
7415     }
7416
7417     return false;
7418   }
7419
7420  private:
7421   ASTContext &Context;
7422   FunctionDecl *OriginalFD;
7423   CXXRecordDecl *ExpectedParent;
7424 };
7425
7426 } // end anonymous namespace
7427
7428 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7429   TypoCorrectedFunctionDefinitions.insert(F);
7430 }
7431
7432 /// \brief Generate diagnostics for an invalid function redeclaration.
7433 ///
7434 /// This routine handles generating the diagnostic messages for an invalid
7435 /// function redeclaration, including finding possible similar declarations
7436 /// or performing typo correction if there are no previous declarations with
7437 /// the same name.
7438 ///
7439 /// Returns a NamedDecl iff typo correction was performed and substituting in
7440 /// the new declaration name does not cause new errors.
7441 static NamedDecl *DiagnoseInvalidRedeclaration(
7442     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7443     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7444   DeclarationName Name = NewFD->getDeclName();
7445   DeclContext *NewDC = NewFD->getDeclContext();
7446   SmallVector<unsigned, 1> MismatchedParams;
7447   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7448   TypoCorrection Correction;
7449   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7450   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7451                                    : diag::err_member_decl_does_not_match;
7452   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7453                     IsLocalFriend ? Sema::LookupLocalFriendName
7454                                   : Sema::LookupOrdinaryName,
7455                     Sema::ForRedeclaration);
7456
7457   NewFD->setInvalidDecl();
7458   if (IsLocalFriend)
7459     SemaRef.LookupName(Prev, S);
7460   else
7461     SemaRef.LookupQualifiedName(Prev, NewDC);
7462   assert(!Prev.isAmbiguous() &&
7463          "Cannot have an ambiguity in previous-declaration lookup");
7464   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7465   if (!Prev.empty()) {
7466     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7467          Func != FuncEnd; ++Func) {
7468       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7469       if (FD &&
7470           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7471         // Add 1 to the index so that 0 can mean the mismatch didn't
7472         // involve a parameter
7473         unsigned ParamNum =
7474             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7475         NearMatches.push_back(std::make_pair(FD, ParamNum));
7476       }
7477     }
7478   // If the qualified name lookup yielded nothing, try typo correction
7479   } else if ((Correction = SemaRef.CorrectTypo(
7480                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7481                   &ExtraArgs.D.getCXXScopeSpec(),
7482                   llvm::make_unique<DifferentNameValidatorCCC>(
7483                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7484                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7485     // Set up everything for the call to ActOnFunctionDeclarator
7486     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7487                               ExtraArgs.D.getIdentifierLoc());
7488     Previous.clear();
7489     Previous.setLookupName(Correction.getCorrection());
7490     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7491                                     CDeclEnd = Correction.end();
7492          CDecl != CDeclEnd; ++CDecl) {
7493       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7494       if (FD && !FD->hasBody() &&
7495           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7496         Previous.addDecl(FD);
7497       }
7498     }
7499     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7500
7501     NamedDecl *Result;
7502     // Retry building the function declaration with the new previous
7503     // declarations, and with errors suppressed.
7504     {
7505       // Trap errors.
7506       Sema::SFINAETrap Trap(SemaRef);
7507
7508       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7509       // pieces need to verify the typo-corrected C++ declaration and hopefully
7510       // eliminate the need for the parameter pack ExtraArgs.
7511       Result = SemaRef.ActOnFunctionDeclarator(
7512           ExtraArgs.S, ExtraArgs.D,
7513           Correction.getCorrectionDecl()->getDeclContext(),
7514           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7515           ExtraArgs.AddToScope);
7516
7517       if (Trap.hasErrorOccurred())
7518         Result = nullptr;
7519     }
7520
7521     if (Result) {
7522       // Determine which correction we picked.
7523       Decl *Canonical = Result->getCanonicalDecl();
7524       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7525            I != E; ++I)
7526         if ((*I)->getCanonicalDecl() == Canonical)
7527           Correction.setCorrectionDecl(*I);
7528
7529       // Let Sema know about the correction.
7530       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7531       SemaRef.diagnoseTypo(
7532           Correction,
7533           SemaRef.PDiag(IsLocalFriend
7534                           ? diag::err_no_matching_local_friend_suggest
7535                           : diag::err_member_decl_does_not_match_suggest)
7536             << Name << NewDC << IsDefinition);
7537       return Result;
7538     }
7539
7540     // Pretend the typo correction never occurred
7541     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7542                               ExtraArgs.D.getIdentifierLoc());
7543     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7544     Previous.clear();
7545     Previous.setLookupName(Name);
7546   }
7547
7548   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7549       << Name << NewDC << IsDefinition << NewFD->getLocation();
7550
7551   bool NewFDisConst = false;
7552   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7553     NewFDisConst = NewMD->isConst();
7554
7555   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7556        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7557        NearMatch != NearMatchEnd; ++NearMatch) {
7558     FunctionDecl *FD = NearMatch->first;
7559     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7560     bool FDisConst = MD && MD->isConst();
7561     bool IsMember = MD || !IsLocalFriend;
7562
7563     // FIXME: These notes are poorly worded for the local friend case.
7564     if (unsigned Idx = NearMatch->second) {
7565       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7566       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7567       if (Loc.isInvalid()) Loc = FD->getLocation();
7568       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7569                                  : diag::note_local_decl_close_param_match)
7570         << Idx << FDParam->getType()
7571         << NewFD->getParamDecl(Idx - 1)->getType();
7572     } else if (FDisConst != NewFDisConst) {
7573       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7574           << NewFDisConst << FD->getSourceRange().getEnd();
7575     } else
7576       SemaRef.Diag(FD->getLocation(),
7577                    IsMember ? diag::note_member_def_close_match
7578                             : diag::note_local_decl_close_match);
7579   }
7580   return nullptr;
7581 }
7582
7583 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7584   switch (D.getDeclSpec().getStorageClassSpec()) {
7585   default: llvm_unreachable("Unknown storage class!");
7586   case DeclSpec::SCS_auto:
7587   case DeclSpec::SCS_register:
7588   case DeclSpec::SCS_mutable:
7589     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7590                  diag::err_typecheck_sclass_func);
7591     D.getMutableDeclSpec().ClearStorageClassSpecs();
7592     D.setInvalidType();
7593     break;
7594   case DeclSpec::SCS_unspecified: break;
7595   case DeclSpec::SCS_extern:
7596     if (D.getDeclSpec().isExternInLinkageSpec())
7597       return SC_None;
7598     return SC_Extern;
7599   case DeclSpec::SCS_static: {
7600     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7601       // C99 6.7.1p5:
7602       //   The declaration of an identifier for a function that has
7603       //   block scope shall have no explicit storage-class specifier
7604       //   other than extern
7605       // See also (C++ [dcl.stc]p4).
7606       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7607                    diag::err_static_block_func);
7608       break;
7609     } else
7610       return SC_Static;
7611   }
7612   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7613   }
7614
7615   // No explicit storage class has already been returned
7616   return SC_None;
7617 }
7618
7619 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7620                                            DeclContext *DC, QualType &R,
7621                                            TypeSourceInfo *TInfo,
7622                                            StorageClass SC,
7623                                            bool &IsVirtualOkay) {
7624   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7625   DeclarationName Name = NameInfo.getName();
7626
7627   FunctionDecl *NewFD = nullptr;
7628   bool isInline = D.getDeclSpec().isInlineSpecified();
7629
7630   if (!SemaRef.getLangOpts().CPlusPlus) {
7631     // Determine whether the function was written with a
7632     // prototype. This true when:
7633     //   - there is a prototype in the declarator, or
7634     //   - the type R of the function is some kind of typedef or other non-
7635     //     attributed reference to a type name (which eventually refers to a
7636     //     function type).
7637     bool HasPrototype =
7638       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7639       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7640
7641     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7642                                  D.getLocStart(), NameInfo, R,
7643                                  TInfo, SC, isInline,
7644                                  HasPrototype, false);
7645     if (D.isInvalidType())
7646       NewFD->setInvalidDecl();
7647
7648     return NewFD;
7649   }
7650
7651   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7652   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7653
7654   // Check that the return type is not an abstract class type.
7655   // For record types, this is done by the AbstractClassUsageDiagnoser once
7656   // the class has been completely parsed.
7657   if (!DC->isRecord() &&
7658       SemaRef.RequireNonAbstractType(
7659           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7660           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7661     D.setInvalidType();
7662
7663   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7664     // This is a C++ constructor declaration.
7665     assert(DC->isRecord() &&
7666            "Constructors can only be declared in a member context");
7667
7668     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7669     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7670                                       D.getLocStart(), NameInfo,
7671                                       R, TInfo, isExplicit, isInline,
7672                                       /*isImplicitlyDeclared=*/false,
7673                                       isConstexpr);
7674
7675   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7676     // This is a C++ destructor declaration.
7677     if (DC->isRecord()) {
7678       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7679       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7680       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7681                                         SemaRef.Context, Record,
7682                                         D.getLocStart(),
7683                                         NameInfo, R, TInfo, isInline,
7684                                         /*isImplicitlyDeclared=*/false);
7685
7686       // If the class is complete, then we now create the implicit exception
7687       // specification. If the class is incomplete or dependent, we can't do
7688       // it yet.
7689       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7690           Record->getDefinition() && !Record->isBeingDefined() &&
7691           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7692         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7693       }
7694
7695       IsVirtualOkay = true;
7696       return NewDD;
7697
7698     } else {
7699       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7700       D.setInvalidType();
7701
7702       // Create a FunctionDecl to satisfy the function definition parsing
7703       // code path.
7704       return FunctionDecl::Create(SemaRef.Context, DC,
7705                                   D.getLocStart(),
7706                                   D.getIdentifierLoc(), Name, R, TInfo,
7707                                   SC, isInline,
7708                                   /*hasPrototype=*/true, isConstexpr);
7709     }
7710
7711   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7712     if (!DC->isRecord()) {
7713       SemaRef.Diag(D.getIdentifierLoc(),
7714            diag::err_conv_function_not_member);
7715       return nullptr;
7716     }
7717
7718     SemaRef.CheckConversionDeclarator(D, R, SC);
7719     IsVirtualOkay = true;
7720     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7721                                      D.getLocStart(), NameInfo,
7722                                      R, TInfo, isInline, isExplicit,
7723                                      isConstexpr, SourceLocation());
7724
7725   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7726     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7727
7728     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7729                                          isExplicit, NameInfo, R, TInfo,
7730                                          D.getLocEnd());
7731   } else if (DC->isRecord()) {
7732     // If the name of the function is the same as the name of the record,
7733     // then this must be an invalid constructor that has a return type.
7734     // (The parser checks for a return type and makes the declarator a
7735     // constructor if it has no return type).
7736     if (Name.getAsIdentifierInfo() &&
7737         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7738       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7739         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7740         << SourceRange(D.getIdentifierLoc());
7741       return nullptr;
7742     }
7743
7744     // This is a C++ method declaration.
7745     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7746                                                cast<CXXRecordDecl>(DC),
7747                                                D.getLocStart(), NameInfo, R,
7748                                                TInfo, SC, isInline,
7749                                                isConstexpr, SourceLocation());
7750     IsVirtualOkay = !Ret->isStatic();
7751     return Ret;
7752   } else {
7753     bool isFriend =
7754         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7755     if (!isFriend && SemaRef.CurContext->isRecord())
7756       return nullptr;
7757
7758     // Determine whether the function was written with a
7759     // prototype. This true when:
7760     //   - we're in C++ (where every function has a prototype),
7761     return FunctionDecl::Create(SemaRef.Context, DC,
7762                                 D.getLocStart(),
7763                                 NameInfo, R, TInfo, SC, isInline,
7764                                 true/*HasPrototype*/, isConstexpr);
7765   }
7766 }
7767
7768 enum OpenCLParamType {
7769   ValidKernelParam,
7770   PtrPtrKernelParam,
7771   PtrKernelParam,
7772   InvalidAddrSpacePtrKernelParam,
7773   InvalidKernelParam,
7774   RecordKernelParam
7775 };
7776
7777 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7778   if (PT->isPointerType()) {
7779     QualType PointeeType = PT->getPointeeType();
7780     if (PointeeType->isPointerType())
7781       return PtrPtrKernelParam;
7782     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7783         PointeeType.getAddressSpace() == 0)
7784       return InvalidAddrSpacePtrKernelParam;
7785     return PtrKernelParam;
7786   }
7787
7788   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7789   // be used as builtin types.
7790
7791   if (PT->isImageType())
7792     return PtrKernelParam;
7793
7794   if (PT->isBooleanType())
7795     return InvalidKernelParam;
7796
7797   if (PT->isEventT())
7798     return InvalidKernelParam;
7799
7800   // OpenCL extension spec v1.2 s9.5:
7801   // This extension adds support for half scalar and vector types as built-in
7802   // types that can be used for arithmetic operations, conversions etc.
7803   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7804     return InvalidKernelParam;
7805
7806   if (PT->isRecordType())
7807     return RecordKernelParam;
7808
7809   return ValidKernelParam;
7810 }
7811
7812 static void checkIsValidOpenCLKernelParameter(
7813   Sema &S,
7814   Declarator &D,
7815   ParmVarDecl *Param,
7816   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7817   QualType PT = Param->getType();
7818
7819   // Cache the valid types we encounter to avoid rechecking structs that are
7820   // used again
7821   if (ValidTypes.count(PT.getTypePtr()))
7822     return;
7823
7824   switch (getOpenCLKernelParameterType(S, PT)) {
7825   case PtrPtrKernelParam:
7826     // OpenCL v1.2 s6.9.a:
7827     // A kernel function argument cannot be declared as a
7828     // pointer to a pointer type.
7829     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7830     D.setInvalidType();
7831     return;
7832
7833   case InvalidAddrSpacePtrKernelParam:
7834     // OpenCL v1.0 s6.5:
7835     // __kernel function arguments declared to be a pointer of a type can point
7836     // to one of the following address spaces only : __global, __local or
7837     // __constant.
7838     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7839     D.setInvalidType();
7840     return;
7841
7842     // OpenCL v1.2 s6.9.k:
7843     // Arguments to kernel functions in a program cannot be declared with the
7844     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7845     // uintptr_t or a struct and/or union that contain fields declared to be
7846     // one of these built-in scalar types.
7847
7848   case InvalidKernelParam:
7849     // OpenCL v1.2 s6.8 n:
7850     // A kernel function argument cannot be declared
7851     // of event_t type.
7852     // Do not diagnose half type since it is diagnosed as invalid argument
7853     // type for any function elsewhere.
7854     if (!PT->isHalfType())
7855       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7856     D.setInvalidType();
7857     return;
7858
7859   case PtrKernelParam:
7860   case ValidKernelParam:
7861     ValidTypes.insert(PT.getTypePtr());
7862     return;
7863
7864   case RecordKernelParam:
7865     break;
7866   }
7867
7868   // Track nested structs we will inspect
7869   SmallVector<const Decl *, 4> VisitStack;
7870
7871   // Track where we are in the nested structs. Items will migrate from
7872   // VisitStack to HistoryStack as we do the DFS for bad field.
7873   SmallVector<const FieldDecl *, 4> HistoryStack;
7874   HistoryStack.push_back(nullptr);
7875
7876   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7877   VisitStack.push_back(PD);
7878
7879   assert(VisitStack.back() && "First decl null?");
7880
7881   do {
7882     const Decl *Next = VisitStack.pop_back_val();
7883     if (!Next) {
7884       assert(!HistoryStack.empty());
7885       // Found a marker, we have gone up a level
7886       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7887         ValidTypes.insert(Hist->getType().getTypePtr());
7888
7889       continue;
7890     }
7891
7892     // Adds everything except the original parameter declaration (which is not a
7893     // field itself) to the history stack.
7894     const RecordDecl *RD;
7895     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7896       HistoryStack.push_back(Field);
7897       RD = Field->getType()->castAs<RecordType>()->getDecl();
7898     } else {
7899       RD = cast<RecordDecl>(Next);
7900     }
7901
7902     // Add a null marker so we know when we've gone back up a level
7903     VisitStack.push_back(nullptr);
7904
7905     for (const auto *FD : RD->fields()) {
7906       QualType QT = FD->getType();
7907
7908       if (ValidTypes.count(QT.getTypePtr()))
7909         continue;
7910
7911       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7912       if (ParamType == ValidKernelParam)
7913         continue;
7914
7915       if (ParamType == RecordKernelParam) {
7916         VisitStack.push_back(FD);
7917         continue;
7918       }
7919
7920       // OpenCL v1.2 s6.9.p:
7921       // Arguments to kernel functions that are declared to be a struct or union
7922       // do not allow OpenCL objects to be passed as elements of the struct or
7923       // union.
7924       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7925           ParamType == InvalidAddrSpacePtrKernelParam) {
7926         S.Diag(Param->getLocation(),
7927                diag::err_record_with_pointers_kernel_param)
7928           << PT->isUnionType()
7929           << PT;
7930       } else {
7931         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7932       }
7933
7934       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7935         << PD->getDeclName();
7936
7937       // We have an error, now let's go back up through history and show where
7938       // the offending field came from
7939       for (ArrayRef<const FieldDecl *>::const_iterator
7940                I = HistoryStack.begin() + 1,
7941                E = HistoryStack.end();
7942            I != E; ++I) {
7943         const FieldDecl *OuterField = *I;
7944         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7945           << OuterField->getType();
7946       }
7947
7948       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7949         << QT->isPointerType()
7950         << QT;
7951       D.setInvalidType();
7952       return;
7953     }
7954   } while (!VisitStack.empty());
7955 }
7956
7957 /// Find the DeclContext in which a tag is implicitly declared if we see an
7958 /// elaborated type specifier in the specified context, and lookup finds
7959 /// nothing.
7960 static DeclContext *getTagInjectionContext(DeclContext *DC) {
7961   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
7962     DC = DC->getParent();
7963   return DC;
7964 }
7965
7966 /// Find the Scope in which a tag is implicitly declared if we see an
7967 /// elaborated type specifier in the specified context, and lookup finds
7968 /// nothing.
7969 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
7970   while (S->isClassScope() ||
7971          (LangOpts.CPlusPlus &&
7972           S->isFunctionPrototypeScope()) ||
7973          ((S->getFlags() & Scope::DeclScope) == 0) ||
7974          (S->getEntity() && S->getEntity()->isTransparentContext()))
7975     S = S->getParent();
7976   return S;
7977 }
7978
7979 NamedDecl*
7980 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7981                               TypeSourceInfo *TInfo, LookupResult &Previous,
7982                               MultiTemplateParamsArg TemplateParamLists,
7983                               bool &AddToScope) {
7984   QualType R = TInfo->getType();
7985
7986   assert(R.getTypePtr()->isFunctionType());
7987
7988   // TODO: consider using NameInfo for diagnostic.
7989   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7990   DeclarationName Name = NameInfo.getName();
7991   StorageClass SC = getFunctionStorageClass(*this, D);
7992
7993   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7994     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7995          diag::err_invalid_thread)
7996       << DeclSpec::getSpecifierName(TSCS);
7997
7998   if (D.isFirstDeclarationOfMember())
7999     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8000                            D.getIdentifierLoc());
8001
8002   bool isFriend = false;
8003   FunctionTemplateDecl *FunctionTemplate = nullptr;
8004   bool isMemberSpecialization = false;
8005   bool isFunctionTemplateSpecialization = false;
8006
8007   bool isDependentClassScopeExplicitSpecialization = false;
8008   bool HasExplicitTemplateArgs = false;
8009   TemplateArgumentListInfo TemplateArgs;
8010
8011   bool isVirtualOkay = false;
8012
8013   DeclContext *OriginalDC = DC;
8014   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8015
8016   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8017                                               isVirtualOkay);
8018   if (!NewFD) return nullptr;
8019
8020   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8021     NewFD->setTopLevelDeclInObjCContainer();
8022
8023   // Set the lexical context. If this is a function-scope declaration, or has a
8024   // C++ scope specifier, or is the object of a friend declaration, the lexical
8025   // context will be different from the semantic context.
8026   NewFD->setLexicalDeclContext(CurContext);
8027
8028   if (IsLocalExternDecl)
8029     NewFD->setLocalExternDecl();
8030
8031   if (getLangOpts().CPlusPlus) {
8032     bool isInline = D.getDeclSpec().isInlineSpecified();
8033     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8034     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8035     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8036     bool isConcept = D.getDeclSpec().isConceptSpecified();
8037     isFriend = D.getDeclSpec().isFriendSpecified();
8038     if (isFriend && !isInline && D.isFunctionDefinition()) {
8039       // C++ [class.friend]p5
8040       //   A function can be defined in a friend declaration of a
8041       //   class . . . . Such a function is implicitly inline.
8042       NewFD->setImplicitlyInline();
8043     }
8044
8045     // If this is a method defined in an __interface, and is not a constructor
8046     // or an overloaded operator, then set the pure flag (isVirtual will already
8047     // return true).
8048     if (const CXXRecordDecl *Parent =
8049           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8050       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8051         NewFD->setPure(true);
8052
8053       // C++ [class.union]p2
8054       //   A union can have member functions, but not virtual functions.
8055       if (isVirtual && Parent->isUnion())
8056         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8057     }
8058
8059     SetNestedNameSpecifier(NewFD, D);
8060     isMemberSpecialization = false;
8061     isFunctionTemplateSpecialization = false;
8062     if (D.isInvalidType())
8063       NewFD->setInvalidDecl();
8064
8065     // Match up the template parameter lists with the scope specifier, then
8066     // determine whether we have a template or a template specialization.
8067     bool Invalid = false;
8068     if (TemplateParameterList *TemplateParams =
8069             MatchTemplateParametersToScopeSpecifier(
8070                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8071                 D.getCXXScopeSpec(),
8072                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8073                     ? D.getName().TemplateId
8074                     : nullptr,
8075                 TemplateParamLists, isFriend, isMemberSpecialization,
8076                 Invalid)) {
8077       if (TemplateParams->size() > 0) {
8078         // This is a function template
8079
8080         // Check that we can declare a template here.
8081         if (CheckTemplateDeclScope(S, TemplateParams))
8082           NewFD->setInvalidDecl();
8083
8084         // A destructor cannot be a template.
8085         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8086           Diag(NewFD->getLocation(), diag::err_destructor_template);
8087           NewFD->setInvalidDecl();
8088         }
8089
8090         // If we're adding a template to a dependent context, we may need to
8091         // rebuilding some of the types used within the template parameter list,
8092         // now that we know what the current instantiation is.
8093         if (DC->isDependentContext()) {
8094           ContextRAII SavedContext(*this, DC);
8095           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8096             Invalid = true;
8097         }
8098
8099         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8100                                                         NewFD->getLocation(),
8101                                                         Name, TemplateParams,
8102                                                         NewFD);
8103         FunctionTemplate->setLexicalDeclContext(CurContext);
8104         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8105
8106         // For source fidelity, store the other template param lists.
8107         if (TemplateParamLists.size() > 1) {
8108           NewFD->setTemplateParameterListsInfo(Context,
8109                                                TemplateParamLists.drop_back(1));
8110         }
8111       } else {
8112         // This is a function template specialization.
8113         isFunctionTemplateSpecialization = true;
8114         // For source fidelity, store all the template param lists.
8115         if (TemplateParamLists.size() > 0)
8116           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8117
8118         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8119         if (isFriend) {
8120           // We want to remove the "template<>", found here.
8121           SourceRange RemoveRange = TemplateParams->getSourceRange();
8122
8123           // If we remove the template<> and the name is not a
8124           // template-id, we're actually silently creating a problem:
8125           // the friend declaration will refer to an untemplated decl,
8126           // and clearly the user wants a template specialization.  So
8127           // we need to insert '<>' after the name.
8128           SourceLocation InsertLoc;
8129           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8130             InsertLoc = D.getName().getSourceRange().getEnd();
8131             InsertLoc = getLocForEndOfToken(InsertLoc);
8132           }
8133
8134           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8135             << Name << RemoveRange
8136             << FixItHint::CreateRemoval(RemoveRange)
8137             << FixItHint::CreateInsertion(InsertLoc, "<>");
8138         }
8139       }
8140     }
8141     else {
8142       // All template param lists were matched against the scope specifier:
8143       // this is NOT (an explicit specialization of) a template.
8144       if (TemplateParamLists.size() > 0)
8145         // For source fidelity, store all the template param lists.
8146         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8147     }
8148
8149     if (Invalid) {
8150       NewFD->setInvalidDecl();
8151       if (FunctionTemplate)
8152         FunctionTemplate->setInvalidDecl();
8153     }
8154
8155     // C++ [dcl.fct.spec]p5:
8156     //   The virtual specifier shall only be used in declarations of
8157     //   nonstatic class member functions that appear within a
8158     //   member-specification of a class declaration; see 10.3.
8159     //
8160     if (isVirtual && !NewFD->isInvalidDecl()) {
8161       if (!isVirtualOkay) {
8162         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8163              diag::err_virtual_non_function);
8164       } else if (!CurContext->isRecord()) {
8165         // 'virtual' was specified outside of the class.
8166         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8167              diag::err_virtual_out_of_class)
8168           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8169       } else if (NewFD->getDescribedFunctionTemplate()) {
8170         // C++ [temp.mem]p3:
8171         //  A member function template shall not be virtual.
8172         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8173              diag::err_virtual_member_function_template)
8174           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8175       } else {
8176         // Okay: Add virtual to the method.
8177         NewFD->setVirtualAsWritten(true);
8178       }
8179
8180       if (getLangOpts().CPlusPlus14 &&
8181           NewFD->getReturnType()->isUndeducedType())
8182         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8183     }
8184
8185     if (getLangOpts().CPlusPlus14 &&
8186         (NewFD->isDependentContext() ||
8187          (isFriend && CurContext->isDependentContext())) &&
8188         NewFD->getReturnType()->isUndeducedType()) {
8189       // If the function template is referenced directly (for instance, as a
8190       // member of the current instantiation), pretend it has a dependent type.
8191       // This is not really justified by the standard, but is the only sane
8192       // thing to do.
8193       // FIXME: For a friend function, we have not marked the function as being
8194       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8195       const FunctionProtoType *FPT =
8196           NewFD->getType()->castAs<FunctionProtoType>();
8197       QualType Result =
8198           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8199       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8200                                              FPT->getExtProtoInfo()));
8201     }
8202
8203     // C++ [dcl.fct.spec]p3:
8204     //  The inline specifier shall not appear on a block scope function
8205     //  declaration.
8206     if (isInline && !NewFD->isInvalidDecl()) {
8207       if (CurContext->isFunctionOrMethod()) {
8208         // 'inline' is not allowed on block scope function declaration.
8209         Diag(D.getDeclSpec().getInlineSpecLoc(),
8210              diag::err_inline_declaration_block_scope) << Name
8211           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8212       }
8213     }
8214
8215     // C++ [dcl.fct.spec]p6:
8216     //  The explicit specifier shall be used only in the declaration of a
8217     //  constructor or conversion function within its class definition;
8218     //  see 12.3.1 and 12.3.2.
8219     if (isExplicit && !NewFD->isInvalidDecl() &&
8220         !isa<CXXDeductionGuideDecl>(NewFD)) {
8221       if (!CurContext->isRecord()) {
8222         // 'explicit' was specified outside of the class.
8223         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8224              diag::err_explicit_out_of_class)
8225           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8226       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8227                  !isa<CXXConversionDecl>(NewFD)) {
8228         // 'explicit' was specified on a function that wasn't a constructor
8229         // or conversion function.
8230         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8231              diag::err_explicit_non_ctor_or_conv_function)
8232           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8233       }
8234     }
8235
8236     if (isConstexpr) {
8237       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8238       // are implicitly inline.
8239       NewFD->setImplicitlyInline();
8240
8241       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8242       // be either constructors or to return a literal type. Therefore,
8243       // destructors cannot be declared constexpr.
8244       if (isa<CXXDestructorDecl>(NewFD))
8245         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8246     }
8247
8248     if (isConcept) {
8249       // This is a function concept.
8250       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8251         FTD->setConcept();
8252
8253       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8254       // applied only to the definition of a function template [...]
8255       if (!D.isFunctionDefinition()) {
8256         Diag(D.getDeclSpec().getConceptSpecLoc(),
8257              diag::err_function_concept_not_defined);
8258         NewFD->setInvalidDecl();
8259       }
8260
8261       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8262       // have no exception-specification and is treated as if it were specified
8263       // with noexcept(true) (15.4). [...]
8264       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8265         if (FPT->hasExceptionSpec()) {
8266           SourceRange Range;
8267           if (D.isFunctionDeclarator())
8268             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8269           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8270               << FixItHint::CreateRemoval(Range);
8271           NewFD->setInvalidDecl();
8272         } else {
8273           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8274         }
8275
8276         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8277         // following restrictions:
8278         // - The declared return type shall have the type bool.
8279         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8280           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8281           NewFD->setInvalidDecl();
8282         }
8283
8284         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8285         // following restrictions:
8286         // - The declaration's parameter list shall be equivalent to an empty
8287         //   parameter list.
8288         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8289           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8290       }
8291
8292       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8293       // implicity defined to be a constexpr declaration (implicitly inline)
8294       NewFD->setImplicitlyInline();
8295
8296       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8297       // be declared with the thread_local, inline, friend, or constexpr
8298       // specifiers, [...]
8299       if (isInline) {
8300         Diag(D.getDeclSpec().getInlineSpecLoc(),
8301              diag::err_concept_decl_invalid_specifiers)
8302             << 1 << 1;
8303         NewFD->setInvalidDecl(true);
8304       }
8305
8306       if (isFriend) {
8307         Diag(D.getDeclSpec().getFriendSpecLoc(),
8308              diag::err_concept_decl_invalid_specifiers)
8309             << 1 << 2;
8310         NewFD->setInvalidDecl(true);
8311       }
8312
8313       if (isConstexpr) {
8314         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8315              diag::err_concept_decl_invalid_specifiers)
8316             << 1 << 3;
8317         NewFD->setInvalidDecl(true);
8318       }
8319
8320       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8321       // applied only to the definition of a function template or variable
8322       // template, declared in namespace scope.
8323       if (isFunctionTemplateSpecialization) {
8324         Diag(D.getDeclSpec().getConceptSpecLoc(),
8325              diag::err_concept_specified_specialization) << 1;
8326         NewFD->setInvalidDecl(true);
8327         return NewFD;
8328       }
8329     }
8330
8331     // If __module_private__ was specified, mark the function accordingly.
8332     if (D.getDeclSpec().isModulePrivateSpecified()) {
8333       if (isFunctionTemplateSpecialization) {
8334         SourceLocation ModulePrivateLoc
8335           = D.getDeclSpec().getModulePrivateSpecLoc();
8336         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8337           << 0
8338           << FixItHint::CreateRemoval(ModulePrivateLoc);
8339       } else {
8340         NewFD->setModulePrivate();
8341         if (FunctionTemplate)
8342           FunctionTemplate->setModulePrivate();
8343       }
8344     }
8345
8346     if (isFriend) {
8347       if (FunctionTemplate) {
8348         FunctionTemplate->setObjectOfFriendDecl();
8349         FunctionTemplate->setAccess(AS_public);
8350       }
8351       NewFD->setObjectOfFriendDecl();
8352       NewFD->setAccess(AS_public);
8353     }
8354
8355     // If a function is defined as defaulted or deleted, mark it as such now.
8356     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8357     // definition kind to FDK_Definition.
8358     switch (D.getFunctionDefinitionKind()) {
8359       case FDK_Declaration:
8360       case FDK_Definition:
8361         break;
8362
8363       case FDK_Defaulted:
8364         NewFD->setDefaulted();
8365         break;
8366
8367       case FDK_Deleted:
8368         NewFD->setDeletedAsWritten();
8369         break;
8370     }
8371
8372     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8373         D.isFunctionDefinition()) {
8374       // C++ [class.mfct]p2:
8375       //   A member function may be defined (8.4) in its class definition, in
8376       //   which case it is an inline member function (7.1.2)
8377       NewFD->setImplicitlyInline();
8378     }
8379
8380     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8381         !CurContext->isRecord()) {
8382       // C++ [class.static]p1:
8383       //   A data or function member of a class may be declared static
8384       //   in a class definition, in which case it is a static member of
8385       //   the class.
8386
8387       // Complain about the 'static' specifier if it's on an out-of-line
8388       // member function definition.
8389       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8390            diag::err_static_out_of_line)
8391         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8392     }
8393
8394     // C++11 [except.spec]p15:
8395     //   A deallocation function with no exception-specification is treated
8396     //   as if it were specified with noexcept(true).
8397     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8398     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8399          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8400         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8401       NewFD->setType(Context.getFunctionType(
8402           FPT->getReturnType(), FPT->getParamTypes(),
8403           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8404   }
8405
8406   // Filter out previous declarations that don't match the scope.
8407   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8408                        D.getCXXScopeSpec().isNotEmpty() ||
8409                        isMemberSpecialization ||
8410                        isFunctionTemplateSpecialization);
8411
8412   // Handle GNU asm-label extension (encoded as an attribute).
8413   if (Expr *E = (Expr*) D.getAsmLabel()) {
8414     // The parser guarantees this is a string.
8415     StringLiteral *SE = cast<StringLiteral>(E);
8416     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8417                                                 SE->getString(), 0));
8418   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8419     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8420       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8421     if (I != ExtnameUndeclaredIdentifiers.end()) {
8422       if (isDeclExternC(NewFD)) {
8423         NewFD->addAttr(I->second);
8424         ExtnameUndeclaredIdentifiers.erase(I);
8425       } else
8426         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8427             << /*Variable*/0 << NewFD;
8428     }
8429   }
8430
8431   // Copy the parameter declarations from the declarator D to the function
8432   // declaration NewFD, if they are available.  First scavenge them into Params.
8433   SmallVector<ParmVarDecl*, 16> Params;
8434   unsigned FTIIdx;
8435   if (D.isFunctionDeclarator(FTIIdx)) {
8436     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8437
8438     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8439     // function that takes no arguments, not a function that takes a
8440     // single void argument.
8441     // We let through "const void" here because Sema::GetTypeForDeclarator
8442     // already checks for that case.
8443     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8444       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8445         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8446         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8447         Param->setDeclContext(NewFD);
8448         Params.push_back(Param);
8449
8450         if (Param->isInvalidDecl())
8451           NewFD->setInvalidDecl();
8452       }
8453     }
8454
8455     if (!getLangOpts().CPlusPlus) {
8456       // In C, find all the tag declarations from the prototype and move them
8457       // into the function DeclContext. Remove them from the surrounding tag
8458       // injection context of the function, which is typically but not always
8459       // the TU.
8460       DeclContext *PrototypeTagContext =
8461           getTagInjectionContext(NewFD->getLexicalDeclContext());
8462       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8463         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8464
8465         // We don't want to reparent enumerators. Look at their parent enum
8466         // instead.
8467         if (!TD) {
8468           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8469             TD = cast<EnumDecl>(ECD->getDeclContext());
8470         }
8471         if (!TD)
8472           continue;
8473         DeclContext *TagDC = TD->getLexicalDeclContext();
8474         if (!TagDC->containsDecl(TD))
8475           continue;
8476         TagDC->removeDecl(TD);
8477         TD->setDeclContext(NewFD);
8478         NewFD->addDecl(TD);
8479
8480         // Preserve the lexical DeclContext if it is not the surrounding tag
8481         // injection context of the FD. In this example, the semantic context of
8482         // E will be f and the lexical context will be S, while both the
8483         // semantic and lexical contexts of S will be f:
8484         //   void f(struct S { enum E { a } f; } s);
8485         if (TagDC != PrototypeTagContext)
8486           TD->setLexicalDeclContext(TagDC);
8487       }
8488     }
8489   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8490     // When we're declaring a function with a typedef, typeof, etc as in the
8491     // following example, we'll need to synthesize (unnamed)
8492     // parameters for use in the declaration.
8493     //
8494     // @code
8495     // typedef void fn(int);
8496     // fn f;
8497     // @endcode
8498
8499     // Synthesize a parameter for each argument type.
8500     for (const auto &AI : FT->param_types()) {
8501       ParmVarDecl *Param =
8502           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8503       Param->setScopeInfo(0, Params.size());
8504       Params.push_back(Param);
8505     }
8506   } else {
8507     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8508            "Should not need args for typedef of non-prototype fn");
8509   }
8510
8511   // Finally, we know we have the right number of parameters, install them.
8512   NewFD->setParams(Params);
8513
8514   if (D.getDeclSpec().isNoreturnSpecified())
8515     NewFD->addAttr(
8516         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8517                                        Context, 0));
8518
8519   // Functions returning a variably modified type violate C99 6.7.5.2p2
8520   // because all functions have linkage.
8521   if (!NewFD->isInvalidDecl() &&
8522       NewFD->getReturnType()->isVariablyModifiedType()) {
8523     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8524     NewFD->setInvalidDecl();
8525   }
8526
8527   // Apply an implicit SectionAttr if #pragma code_seg is active.
8528   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8529       !NewFD->hasAttr<SectionAttr>()) {
8530     NewFD->addAttr(
8531         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8532                                     CodeSegStack.CurrentValue->getString(),
8533                                     CodeSegStack.CurrentPragmaLocation));
8534     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8535                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8536                          ASTContext::PSF_Read,
8537                      NewFD))
8538       NewFD->dropAttr<SectionAttr>();
8539   }
8540
8541   // Handle attributes.
8542   ProcessDeclAttributes(S, NewFD, D);
8543
8544   if (getLangOpts().OpenCL) {
8545     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8546     // type declaration will generate a compilation error.
8547     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8548     if (AddressSpace == LangAS::opencl_local ||
8549         AddressSpace == LangAS::opencl_global ||
8550         AddressSpace == LangAS::opencl_constant) {
8551       Diag(NewFD->getLocation(),
8552            diag::err_opencl_return_value_with_address_space);
8553       NewFD->setInvalidDecl();
8554     }
8555   }
8556
8557   if (!getLangOpts().CPlusPlus) {
8558     // Perform semantic checking on the function declaration.
8559     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8560       CheckMain(NewFD, D.getDeclSpec());
8561
8562     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8563       CheckMSVCRTEntryPoint(NewFD);
8564
8565     if (!NewFD->isInvalidDecl())
8566       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8567                                                   isMemberSpecialization));
8568     else if (!Previous.empty())
8569       // Recover gracefully from an invalid redeclaration.
8570       D.setRedeclaration(true);
8571     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8572             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8573            "previous declaration set still overloaded");
8574
8575     // Diagnose no-prototype function declarations with calling conventions that
8576     // don't support variadic calls. Only do this in C and do it after merging
8577     // possibly prototyped redeclarations.
8578     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8579     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8580       CallingConv CC = FT->getExtInfo().getCC();
8581       if (!supportsVariadicCall(CC)) {
8582         // Windows system headers sometimes accidentally use stdcall without
8583         // (void) parameters, so we relax this to a warning.
8584         int DiagID =
8585             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8586         Diag(NewFD->getLocation(), DiagID)
8587             << FunctionType::getNameForCallConv(CC);
8588       }
8589     }
8590   } else {
8591     // C++11 [replacement.functions]p3:
8592     //  The program's definitions shall not be specified as inline.
8593     //
8594     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8595     //
8596     // Suppress the diagnostic if the function is __attribute__((used)), since
8597     // that forces an external definition to be emitted.
8598     if (D.getDeclSpec().isInlineSpecified() &&
8599         NewFD->isReplaceableGlobalAllocationFunction() &&
8600         !NewFD->hasAttr<UsedAttr>())
8601       Diag(D.getDeclSpec().getInlineSpecLoc(),
8602            diag::ext_operator_new_delete_declared_inline)
8603         << NewFD->getDeclName();
8604
8605     // If the declarator is a template-id, translate the parser's template
8606     // argument list into our AST format.
8607     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8608       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8609       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8610       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8611       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8612                                          TemplateId->NumArgs);
8613       translateTemplateArguments(TemplateArgsPtr,
8614                                  TemplateArgs);
8615
8616       HasExplicitTemplateArgs = true;
8617
8618       if (NewFD->isInvalidDecl()) {
8619         HasExplicitTemplateArgs = false;
8620       } else if (FunctionTemplate) {
8621         // Function template with explicit template arguments.
8622         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8623           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8624
8625         HasExplicitTemplateArgs = false;
8626       } else {
8627         assert((isFunctionTemplateSpecialization ||
8628                 D.getDeclSpec().isFriendSpecified()) &&
8629                "should have a 'template<>' for this decl");
8630         // "friend void foo<>(int);" is an implicit specialization decl.
8631         isFunctionTemplateSpecialization = true;
8632       }
8633     } else if (isFriend && isFunctionTemplateSpecialization) {
8634       // This combination is only possible in a recovery case;  the user
8635       // wrote something like:
8636       //   template <> friend void foo(int);
8637       // which we're recovering from as if the user had written:
8638       //   friend void foo<>(int);
8639       // Go ahead and fake up a template id.
8640       HasExplicitTemplateArgs = true;
8641       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8642       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8643     }
8644
8645     // We do not add HD attributes to specializations here because
8646     // they may have different constexpr-ness compared to their
8647     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8648     // may end up with different effective targets. Instead, a
8649     // specialization inherits its target attributes from its template
8650     // in the CheckFunctionTemplateSpecialization() call below.
8651     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8652       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8653
8654     // If it's a friend (and only if it's a friend), it's possible
8655     // that either the specialized function type or the specialized
8656     // template is dependent, and therefore matching will fail.  In
8657     // this case, don't check the specialization yet.
8658     bool InstantiationDependent = false;
8659     if (isFunctionTemplateSpecialization && isFriend &&
8660         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8661          TemplateSpecializationType::anyDependentTemplateArguments(
8662             TemplateArgs,
8663             InstantiationDependent))) {
8664       assert(HasExplicitTemplateArgs &&
8665              "friend function specialization without template args");
8666       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8667                                                        Previous))
8668         NewFD->setInvalidDecl();
8669     } else if (isFunctionTemplateSpecialization) {
8670       if (CurContext->isDependentContext() && CurContext->isRecord()
8671           && !isFriend) {
8672         isDependentClassScopeExplicitSpecialization = true;
8673         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8674           diag::ext_function_specialization_in_class :
8675           diag::err_function_specialization_in_class)
8676           << NewFD->getDeclName();
8677       } else if (CheckFunctionTemplateSpecialization(NewFD,
8678                                   (HasExplicitTemplateArgs ? &TemplateArgs
8679                                                            : nullptr),
8680                                                      Previous))
8681         NewFD->setInvalidDecl();
8682
8683       // C++ [dcl.stc]p1:
8684       //   A storage-class-specifier shall not be specified in an explicit
8685       //   specialization (14.7.3)
8686       FunctionTemplateSpecializationInfo *Info =
8687           NewFD->getTemplateSpecializationInfo();
8688       if (Info && SC != SC_None) {
8689         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8690           Diag(NewFD->getLocation(),
8691                diag::err_explicit_specialization_inconsistent_storage_class)
8692             << SC
8693             << FixItHint::CreateRemoval(
8694                                       D.getDeclSpec().getStorageClassSpecLoc());
8695
8696         else
8697           Diag(NewFD->getLocation(),
8698                diag::ext_explicit_specialization_storage_class)
8699             << FixItHint::CreateRemoval(
8700                                       D.getDeclSpec().getStorageClassSpecLoc());
8701       }
8702     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8703       if (CheckMemberSpecialization(NewFD, Previous))
8704           NewFD->setInvalidDecl();
8705     }
8706
8707     // Perform semantic checking on the function declaration.
8708     if (!isDependentClassScopeExplicitSpecialization) {
8709       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8710         CheckMain(NewFD, D.getDeclSpec());
8711
8712       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8713         CheckMSVCRTEntryPoint(NewFD);
8714
8715       if (!NewFD->isInvalidDecl())
8716         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8717                                                     isMemberSpecialization));
8718       else if (!Previous.empty())
8719         // Recover gracefully from an invalid redeclaration.
8720         D.setRedeclaration(true);
8721     }
8722
8723     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8724             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8725            "previous declaration set still overloaded");
8726
8727     NamedDecl *PrincipalDecl = (FunctionTemplate
8728                                 ? cast<NamedDecl>(FunctionTemplate)
8729                                 : NewFD);
8730
8731     if (isFriend && NewFD->getPreviousDecl()) {
8732       AccessSpecifier Access = AS_public;
8733       if (!NewFD->isInvalidDecl())
8734         Access = NewFD->getPreviousDecl()->getAccess();
8735
8736       NewFD->setAccess(Access);
8737       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8738     }
8739
8740     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8741         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8742       PrincipalDecl->setNonMemberOperator();
8743
8744     // If we have a function template, check the template parameter
8745     // list. This will check and merge default template arguments.
8746     if (FunctionTemplate) {
8747       FunctionTemplateDecl *PrevTemplate =
8748                                      FunctionTemplate->getPreviousDecl();
8749       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8750                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8751                                     : nullptr,
8752                             D.getDeclSpec().isFriendSpecified()
8753                               ? (D.isFunctionDefinition()
8754                                    ? TPC_FriendFunctionTemplateDefinition
8755                                    : TPC_FriendFunctionTemplate)
8756                               : (D.getCXXScopeSpec().isSet() &&
8757                                  DC && DC->isRecord() &&
8758                                  DC->isDependentContext())
8759                                   ? TPC_ClassTemplateMember
8760                                   : TPC_FunctionTemplate);
8761     }
8762
8763     if (NewFD->isInvalidDecl()) {
8764       // Ignore all the rest of this.
8765     } else if (!D.isRedeclaration()) {
8766       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8767                                        AddToScope };
8768       // Fake up an access specifier if it's supposed to be a class member.
8769       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8770         NewFD->setAccess(AS_public);
8771
8772       // Qualified decls generally require a previous declaration.
8773       if (D.getCXXScopeSpec().isSet()) {
8774         // ...with the major exception of templated-scope or
8775         // dependent-scope friend declarations.
8776
8777         // TODO: we currently also suppress this check in dependent
8778         // contexts because (1) the parameter depth will be off when
8779         // matching friend templates and (2) we might actually be
8780         // selecting a friend based on a dependent factor.  But there
8781         // are situations where these conditions don't apply and we
8782         // can actually do this check immediately.
8783         if (isFriend &&
8784             (TemplateParamLists.size() ||
8785              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8786              CurContext->isDependentContext())) {
8787           // ignore these
8788         } else {
8789           // The user tried to provide an out-of-line definition for a
8790           // function that is a member of a class or namespace, but there
8791           // was no such member function declared (C++ [class.mfct]p2,
8792           // C++ [namespace.memdef]p2). For example:
8793           //
8794           // class X {
8795           //   void f() const;
8796           // };
8797           //
8798           // void X::f() { } // ill-formed
8799           //
8800           // Complain about this problem, and attempt to suggest close
8801           // matches (e.g., those that differ only in cv-qualifiers and
8802           // whether the parameter types are references).
8803
8804           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8805                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8806             AddToScope = ExtraArgs.AddToScope;
8807             return Result;
8808           }
8809         }
8810
8811         // Unqualified local friend declarations are required to resolve
8812         // to something.
8813       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8814         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8815                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8816           AddToScope = ExtraArgs.AddToScope;
8817           return Result;
8818         }
8819       }
8820     } else if (!D.isFunctionDefinition() &&
8821                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8822                !isFriend && !isFunctionTemplateSpecialization &&
8823                !isMemberSpecialization) {
8824       // An out-of-line member function declaration must also be a
8825       // definition (C++ [class.mfct]p2).
8826       // Note that this is not the case for explicit specializations of
8827       // function templates or member functions of class templates, per
8828       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8829       // extension for compatibility with old SWIG code which likes to
8830       // generate them.
8831       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8832         << D.getCXXScopeSpec().getRange();
8833     }
8834   }
8835
8836   ProcessPragmaWeak(S, NewFD);
8837   checkAttributesAfterMerging(*this, *NewFD);
8838
8839   AddKnownFunctionAttributes(NewFD);
8840
8841   if (NewFD->hasAttr<OverloadableAttr>() &&
8842       !NewFD->getType()->getAs<FunctionProtoType>()) {
8843     Diag(NewFD->getLocation(),
8844          diag::err_attribute_overloadable_no_prototype)
8845       << NewFD;
8846
8847     // Turn this into a variadic function with no parameters.
8848     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8849     FunctionProtoType::ExtProtoInfo EPI(
8850         Context.getDefaultCallingConvention(true, false));
8851     EPI.Variadic = true;
8852     EPI.ExtInfo = FT->getExtInfo();
8853
8854     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8855     NewFD->setType(R);
8856   }
8857
8858   // If there's a #pragma GCC visibility in scope, and this isn't a class
8859   // member, set the visibility of this function.
8860   if (!DC->isRecord() && NewFD->isExternallyVisible())
8861     AddPushedVisibilityAttribute(NewFD);
8862
8863   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8864   // marking the function.
8865   AddCFAuditedAttribute(NewFD);
8866
8867   // If this is a function definition, check if we have to apply optnone due to
8868   // a pragma.
8869   if(D.isFunctionDefinition())
8870     AddRangeBasedOptnone(NewFD);
8871
8872   // If this is the first declaration of an extern C variable, update
8873   // the map of such variables.
8874   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8875       isIncompleteDeclExternC(*this, NewFD))
8876     RegisterLocallyScopedExternCDecl(NewFD, S);
8877
8878   // Set this FunctionDecl's range up to the right paren.
8879   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8880
8881   if (D.isRedeclaration() && !Previous.empty()) {
8882     checkDLLAttributeRedeclaration(
8883         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8884         isMemberSpecialization || isFunctionTemplateSpecialization,
8885         D.isFunctionDefinition());
8886   }
8887
8888   if (getLangOpts().CUDA) {
8889     IdentifierInfo *II = NewFD->getIdentifier();
8890     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8891         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8892       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8893         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8894
8895       Context.setcudaConfigureCallDecl(NewFD);
8896     }
8897
8898     // Variadic functions, other than a *declaration* of printf, are not allowed
8899     // in device-side CUDA code, unless someone passed
8900     // -fcuda-allow-variadic-functions.
8901     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8902         (NewFD->hasAttr<CUDADeviceAttr>() ||
8903          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8904         !(II && II->isStr("printf") && NewFD->isExternC() &&
8905           !D.isFunctionDefinition())) {
8906       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8907     }
8908   }
8909
8910   if (getLangOpts().CPlusPlus) {
8911     if (FunctionTemplate) {
8912       if (NewFD->isInvalidDecl())
8913         FunctionTemplate->setInvalidDecl();
8914       return FunctionTemplate;
8915     }
8916   }
8917
8918   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8919     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8920     if ((getLangOpts().OpenCLVersion >= 120)
8921         && (SC == SC_Static)) {
8922       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8923       D.setInvalidType();
8924     }
8925
8926     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8927     if (!NewFD->getReturnType()->isVoidType()) {
8928       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8929       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8930           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8931                                 : FixItHint());
8932       D.setInvalidType();
8933     }
8934
8935     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8936     for (auto Param : NewFD->parameters())
8937       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8938   }
8939   for (const ParmVarDecl *Param : NewFD->parameters()) {
8940     QualType PT = Param->getType();
8941
8942     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8943     // types.
8944     if (getLangOpts().OpenCLVersion >= 200) {
8945       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8946         QualType ElemTy = PipeTy->getElementType();
8947           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8948             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8949             D.setInvalidType();
8950           }
8951       }
8952     }
8953   }
8954
8955   MarkUnusedFileScopedDecl(NewFD);
8956
8957   // Here we have an function template explicit specialization at class scope.
8958   // The actually specialization will be postponed to template instatiation
8959   // time via the ClassScopeFunctionSpecializationDecl node.
8960   if (isDependentClassScopeExplicitSpecialization) {
8961     ClassScopeFunctionSpecializationDecl *NewSpec =
8962                          ClassScopeFunctionSpecializationDecl::Create(
8963                                 Context, CurContext, SourceLocation(),
8964                                 cast<CXXMethodDecl>(NewFD),
8965                                 HasExplicitTemplateArgs, TemplateArgs);
8966     CurContext->addDecl(NewSpec);
8967     AddToScope = false;
8968   }
8969
8970   return NewFD;
8971 }
8972
8973 /// \brief Checks if the new declaration declared in dependent context must be
8974 /// put in the same redeclaration chain as the specified declaration.
8975 ///
8976 /// \param D Declaration that is checked.
8977 /// \param PrevDecl Previous declaration found with proper lookup method for the
8978 ///                 same declaration name.
8979 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8980 ///          belongs to.
8981 ///
8982 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8983   // Any declarations should be put into redeclaration chains except for
8984   // friend declaration in a dependent context that names a function in
8985   // namespace scope.
8986   //
8987   // This allows to compile code like:
8988   //
8989   //       void func();
8990   //       template<typename T> class C1 { friend void func() { } };
8991   //       template<typename T> class C2 { friend void func() { } };
8992   //
8993   // This code snippet is a valid code unless both templates are instantiated.
8994   return !(D->getLexicalDeclContext()->isDependentContext() &&
8995            D->getDeclContext()->isFileContext() &&
8996            D->getFriendObjectKind() != Decl::FOK_None);
8997 }
8998
8999 /// \brief Perform semantic checking of a new function declaration.
9000 ///
9001 /// Performs semantic analysis of the new function declaration
9002 /// NewFD. This routine performs all semantic checking that does not
9003 /// require the actual declarator involved in the declaration, and is
9004 /// used both for the declaration of functions as they are parsed
9005 /// (called via ActOnDeclarator) and for the declaration of functions
9006 /// that have been instantiated via C++ template instantiation (called
9007 /// via InstantiateDecl).
9008 ///
9009 /// \param IsMemberSpecialization whether this new function declaration is
9010 /// a member specialization (that replaces any definition provided by the
9011 /// previous declaration).
9012 ///
9013 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9014 ///
9015 /// \returns true if the function declaration is a redeclaration.
9016 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9017                                     LookupResult &Previous,
9018                                     bool IsMemberSpecialization) {
9019   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9020          "Variably modified return types are not handled here");
9021
9022   // Determine whether the type of this function should be merged with
9023   // a previous visible declaration. This never happens for functions in C++,
9024   // and always happens in C if the previous declaration was visible.
9025   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9026                                !Previous.isShadowed();
9027
9028   bool Redeclaration = false;
9029   NamedDecl *OldDecl = nullptr;
9030
9031   // Merge or overload the declaration with an existing declaration of
9032   // the same name, if appropriate.
9033   if (!Previous.empty()) {
9034     // Determine whether NewFD is an overload of PrevDecl or
9035     // a declaration that requires merging. If it's an overload,
9036     // there's no more work to do here; we'll just add the new
9037     // function to the scope.
9038     if (!AllowOverloadingOfFunction(Previous, Context)) {
9039       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9040       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9041         Redeclaration = true;
9042         OldDecl = Candidate;
9043       }
9044     } else {
9045       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9046                             /*NewIsUsingDecl*/ false)) {
9047       case Ovl_Match:
9048         Redeclaration = true;
9049         break;
9050
9051       case Ovl_NonFunction:
9052         Redeclaration = true;
9053         break;
9054
9055       case Ovl_Overload:
9056         Redeclaration = false;
9057         break;
9058       }
9059
9060       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9061         // If a function name is overloadable in C, then every function
9062         // with that name must be marked "overloadable".
9063         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9064           << Redeclaration << NewFD;
9065         NamedDecl *OverloadedDecl =
9066             Redeclaration ? OldDecl : Previous.getRepresentativeDecl();
9067         Diag(OverloadedDecl->getLocation(),
9068              diag::note_attribute_overloadable_prev_overload);
9069         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9070       }
9071     }
9072   }
9073
9074   // Check for a previous extern "C" declaration with this name.
9075   if (!Redeclaration &&
9076       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9077     if (!Previous.empty()) {
9078       // This is an extern "C" declaration with the same name as a previous
9079       // declaration, and thus redeclares that entity...
9080       Redeclaration = true;
9081       OldDecl = Previous.getFoundDecl();
9082       MergeTypeWithPrevious = false;
9083
9084       // ... except in the presence of __attribute__((overloadable)).
9085       if (OldDecl->hasAttr<OverloadableAttr>()) {
9086         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9087           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9088             << Redeclaration << NewFD;
9089           Diag(Previous.getFoundDecl()->getLocation(),
9090                diag::note_attribute_overloadable_prev_overload);
9091           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9092         }
9093         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9094           Redeclaration = false;
9095           OldDecl = nullptr;
9096         }
9097       }
9098     }
9099   }
9100
9101   // C++11 [dcl.constexpr]p8:
9102   //   A constexpr specifier for a non-static member function that is not
9103   //   a constructor declares that member function to be const.
9104   //
9105   // This needs to be delayed until we know whether this is an out-of-line
9106   // definition of a static member function.
9107   //
9108   // This rule is not present in C++1y, so we produce a backwards
9109   // compatibility warning whenever it happens in C++11.
9110   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9111   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9112       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9113       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9114     CXXMethodDecl *OldMD = nullptr;
9115     if (OldDecl)
9116       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9117     if (!OldMD || !OldMD->isStatic()) {
9118       const FunctionProtoType *FPT =
9119         MD->getType()->castAs<FunctionProtoType>();
9120       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9121       EPI.TypeQuals |= Qualifiers::Const;
9122       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9123                                           FPT->getParamTypes(), EPI));
9124
9125       // Warn that we did this, if we're not performing template instantiation.
9126       // In that case, we'll have warned already when the template was defined.
9127       if (!inTemplateInstantiation()) {
9128         SourceLocation AddConstLoc;
9129         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9130                 .IgnoreParens().getAs<FunctionTypeLoc>())
9131           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9132
9133         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9134           << FixItHint::CreateInsertion(AddConstLoc, " const");
9135       }
9136     }
9137   }
9138
9139   if (Redeclaration) {
9140     // NewFD and OldDecl represent declarations that need to be
9141     // merged.
9142     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9143       NewFD->setInvalidDecl();
9144       return Redeclaration;
9145     }
9146
9147     Previous.clear();
9148     Previous.addDecl(OldDecl);
9149
9150     if (FunctionTemplateDecl *OldTemplateDecl
9151                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9152       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9153       FunctionTemplateDecl *NewTemplateDecl
9154         = NewFD->getDescribedFunctionTemplate();
9155       assert(NewTemplateDecl && "Template/non-template mismatch");
9156       if (CXXMethodDecl *Method
9157             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9158         Method->setAccess(OldTemplateDecl->getAccess());
9159         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9160       }
9161
9162       // If this is an explicit specialization of a member that is a function
9163       // template, mark it as a member specialization.
9164       if (IsMemberSpecialization &&
9165           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9166         NewTemplateDecl->setMemberSpecialization();
9167         assert(OldTemplateDecl->isMemberSpecialization());
9168         // Explicit specializations of a member template do not inherit deleted
9169         // status from the parent member template that they are specializing.
9170         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9171           FunctionDecl *const OldTemplatedDecl =
9172               OldTemplateDecl->getTemplatedDecl();
9173           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9174           OldTemplatedDecl->setDeletedAsWritten(false);
9175         }
9176       }
9177
9178     } else {
9179       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9180         // This needs to happen first so that 'inline' propagates.
9181         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9182         if (isa<CXXMethodDecl>(NewFD))
9183           NewFD->setAccess(OldDecl->getAccess());
9184       }
9185     }
9186   }
9187
9188   // Semantic checking for this function declaration (in isolation).
9189
9190   if (getLangOpts().CPlusPlus) {
9191     // C++-specific checks.
9192     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9193       CheckConstructor(Constructor);
9194     } else if (CXXDestructorDecl *Destructor =
9195                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9196       CXXRecordDecl *Record = Destructor->getParent();
9197       QualType ClassType = Context.getTypeDeclType(Record);
9198
9199       // FIXME: Shouldn't we be able to perform this check even when the class
9200       // type is dependent? Both gcc and edg can handle that.
9201       if (!ClassType->isDependentType()) {
9202         DeclarationName Name
9203           = Context.DeclarationNames.getCXXDestructorName(
9204                                         Context.getCanonicalType(ClassType));
9205         if (NewFD->getDeclName() != Name) {
9206           Diag(NewFD->getLocation(), diag::err_destructor_name);
9207           NewFD->setInvalidDecl();
9208           return Redeclaration;
9209         }
9210       }
9211     } else if (CXXConversionDecl *Conversion
9212                = dyn_cast<CXXConversionDecl>(NewFD)) {
9213       ActOnConversionDeclarator(Conversion);
9214     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9215       if (auto *TD = Guide->getDescribedFunctionTemplate())
9216         CheckDeductionGuideTemplate(TD);
9217
9218       // A deduction guide is not on the list of entities that can be
9219       // explicitly specialized.
9220       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9221         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9222             << /*explicit specialization*/ 1;
9223     }
9224
9225     // Find any virtual functions that this function overrides.
9226     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9227       if (!Method->isFunctionTemplateSpecialization() &&
9228           !Method->getDescribedFunctionTemplate() &&
9229           Method->isCanonicalDecl()) {
9230         if (AddOverriddenMethods(Method->getParent(), Method)) {
9231           // If the function was marked as "static", we have a problem.
9232           if (NewFD->getStorageClass() == SC_Static) {
9233             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9234           }
9235         }
9236       }
9237
9238       if (Method->isStatic())
9239         checkThisInStaticMemberFunctionType(Method);
9240     }
9241
9242     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9243     if (NewFD->isOverloadedOperator() &&
9244         CheckOverloadedOperatorDeclaration(NewFD)) {
9245       NewFD->setInvalidDecl();
9246       return Redeclaration;
9247     }
9248
9249     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9250     if (NewFD->getLiteralIdentifier() &&
9251         CheckLiteralOperatorDeclaration(NewFD)) {
9252       NewFD->setInvalidDecl();
9253       return Redeclaration;
9254     }
9255
9256     // In C++, check default arguments now that we have merged decls. Unless
9257     // the lexical context is the class, because in this case this is done
9258     // during delayed parsing anyway.
9259     if (!CurContext->isRecord())
9260       CheckCXXDefaultArguments(NewFD);
9261
9262     // If this function declares a builtin function, check the type of this
9263     // declaration against the expected type for the builtin.
9264     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9265       ASTContext::GetBuiltinTypeError Error;
9266       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9267       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9268       // If the type of the builtin differs only in its exception
9269       // specification, that's OK.
9270       // FIXME: If the types do differ in this way, it would be better to
9271       // retain the 'noexcept' form of the type.
9272       if (!T.isNull() &&
9273           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9274                                                             NewFD->getType()))
9275         // The type of this function differs from the type of the builtin,
9276         // so forget about the builtin entirely.
9277         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9278     }
9279
9280     // If this function is declared as being extern "C", then check to see if
9281     // the function returns a UDT (class, struct, or union type) that is not C
9282     // compatible, and if it does, warn the user.
9283     // But, issue any diagnostic on the first declaration only.
9284     if (Previous.empty() && NewFD->isExternC()) {
9285       QualType R = NewFD->getReturnType();
9286       if (R->isIncompleteType() && !R->isVoidType())
9287         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9288             << NewFD << R;
9289       else if (!R.isPODType(Context) && !R->isVoidType() &&
9290                !R->isObjCObjectPointerType())
9291         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9292     }
9293
9294     // C++1z [dcl.fct]p6:
9295     //   [...] whether the function has a non-throwing exception-specification
9296     //   [is] part of the function type
9297     //
9298     // This results in an ABI break between C++14 and C++17 for functions whose
9299     // declared type includes an exception-specification in a parameter or
9300     // return type. (Exception specifications on the function itself are OK in
9301     // most cases, and exception specifications are not permitted in most other
9302     // contexts where they could make it into a mangling.)
9303     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9304       auto HasNoexcept = [&](QualType T) -> bool {
9305         // Strip off declarator chunks that could be between us and a function
9306         // type. We don't need to look far, exception specifications are very
9307         // restricted prior to C++17.
9308         if (auto *RT = T->getAs<ReferenceType>())
9309           T = RT->getPointeeType();
9310         else if (T->isAnyPointerType())
9311           T = T->getPointeeType();
9312         else if (auto *MPT = T->getAs<MemberPointerType>())
9313           T = MPT->getPointeeType();
9314         if (auto *FPT = T->getAs<FunctionProtoType>())
9315           if (FPT->isNothrow(Context))
9316             return true;
9317         return false;
9318       };
9319
9320       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9321       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9322       for (QualType T : FPT->param_types())
9323         AnyNoexcept |= HasNoexcept(T);
9324       if (AnyNoexcept)
9325         Diag(NewFD->getLocation(),
9326              diag::warn_cxx1z_compat_exception_spec_in_signature)
9327             << NewFD;
9328     }
9329
9330     if (!Redeclaration && LangOpts.CUDA)
9331       checkCUDATargetOverload(NewFD, Previous);
9332   }
9333   return Redeclaration;
9334 }
9335
9336 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9337   // C++11 [basic.start.main]p3:
9338   //   A program that [...] declares main to be inline, static or
9339   //   constexpr is ill-formed.
9340   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9341   //   appear in a declaration of main.
9342   // static main is not an error under C99, but we should warn about it.
9343   // We accept _Noreturn main as an extension.
9344   if (FD->getStorageClass() == SC_Static)
9345     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9346          ? diag::err_static_main : diag::warn_static_main)
9347       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9348   if (FD->isInlineSpecified())
9349     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9350       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9351   if (DS.isNoreturnSpecified()) {
9352     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9353     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9354     Diag(NoreturnLoc, diag::ext_noreturn_main);
9355     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9356       << FixItHint::CreateRemoval(NoreturnRange);
9357   }
9358   if (FD->isConstexpr()) {
9359     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9360       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9361     FD->setConstexpr(false);
9362   }
9363
9364   if (getLangOpts().OpenCL) {
9365     Diag(FD->getLocation(), diag::err_opencl_no_main)
9366         << FD->hasAttr<OpenCLKernelAttr>();
9367     FD->setInvalidDecl();
9368     return;
9369   }
9370
9371   QualType T = FD->getType();
9372   assert(T->isFunctionType() && "function decl is not of function type");
9373   const FunctionType* FT = T->castAs<FunctionType>();
9374
9375   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9376     // In C with GNU extensions we allow main() to have non-integer return
9377     // type, but we should warn about the extension, and we disable the
9378     // implicit-return-zero rule.
9379
9380     // GCC in C mode accepts qualified 'int'.
9381     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9382       FD->setHasImplicitReturnZero(true);
9383     else {
9384       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9385       SourceRange RTRange = FD->getReturnTypeSourceRange();
9386       if (RTRange.isValid())
9387         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9388             << FixItHint::CreateReplacement(RTRange, "int");
9389     }
9390   } else {
9391     // In C and C++, main magically returns 0 if you fall off the end;
9392     // set the flag which tells us that.
9393     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9394
9395     // All the standards say that main() should return 'int'.
9396     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9397       FD->setHasImplicitReturnZero(true);
9398     else {
9399       // Otherwise, this is just a flat-out error.
9400       SourceRange RTRange = FD->getReturnTypeSourceRange();
9401       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9402           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9403                                 : FixItHint());
9404       FD->setInvalidDecl(true);
9405     }
9406   }
9407
9408   // Treat protoless main() as nullary.
9409   if (isa<FunctionNoProtoType>(FT)) return;
9410
9411   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9412   unsigned nparams = FTP->getNumParams();
9413   assert(FD->getNumParams() == nparams);
9414
9415   bool HasExtraParameters = (nparams > 3);
9416
9417   if (FTP->isVariadic()) {
9418     Diag(FD->getLocation(), diag::ext_variadic_main);
9419     // FIXME: if we had information about the location of the ellipsis, we
9420     // could add a FixIt hint to remove it as a parameter.
9421   }
9422
9423   // Darwin passes an undocumented fourth argument of type char**.  If
9424   // other platforms start sprouting these, the logic below will start
9425   // getting shifty.
9426   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9427     HasExtraParameters = false;
9428
9429   if (HasExtraParameters) {
9430     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9431     FD->setInvalidDecl(true);
9432     nparams = 3;
9433   }
9434
9435   // FIXME: a lot of the following diagnostics would be improved
9436   // if we had some location information about types.
9437
9438   QualType CharPP =
9439     Context.getPointerType(Context.getPointerType(Context.CharTy));
9440   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9441
9442   for (unsigned i = 0; i < nparams; ++i) {
9443     QualType AT = FTP->getParamType(i);
9444
9445     bool mismatch = true;
9446
9447     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9448       mismatch = false;
9449     else if (Expected[i] == CharPP) {
9450       // As an extension, the following forms are okay:
9451       //   char const **
9452       //   char const * const *
9453       //   char * const *
9454
9455       QualifierCollector qs;
9456       const PointerType* PT;
9457       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9458           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9459           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9460                               Context.CharTy)) {
9461         qs.removeConst();
9462         mismatch = !qs.empty();
9463       }
9464     }
9465
9466     if (mismatch) {
9467       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9468       // TODO: suggest replacing given type with expected type
9469       FD->setInvalidDecl(true);
9470     }
9471   }
9472
9473   if (nparams == 1 && !FD->isInvalidDecl()) {
9474     Diag(FD->getLocation(), diag::warn_main_one_arg);
9475   }
9476
9477   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9478     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9479     FD->setInvalidDecl();
9480   }
9481 }
9482
9483 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9484   QualType T = FD->getType();
9485   assert(T->isFunctionType() && "function decl is not of function type");
9486   const FunctionType *FT = T->castAs<FunctionType>();
9487
9488   // Set an implicit return of 'zero' if the function can return some integral,
9489   // enumeration, pointer or nullptr type.
9490   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9491       FT->getReturnType()->isAnyPointerType() ||
9492       FT->getReturnType()->isNullPtrType())
9493     // DllMain is exempt because a return value of zero means it failed.
9494     if (FD->getName() != "DllMain")
9495       FD->setHasImplicitReturnZero(true);
9496
9497   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9498     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9499     FD->setInvalidDecl();
9500   }
9501 }
9502
9503 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9504   // FIXME: Need strict checking.  In C89, we need to check for
9505   // any assignment, increment, decrement, function-calls, or
9506   // commas outside of a sizeof.  In C99, it's the same list,
9507   // except that the aforementioned are allowed in unevaluated
9508   // expressions.  Everything else falls under the
9509   // "may accept other forms of constant expressions" exception.
9510   // (We never end up here for C++, so the constant expression
9511   // rules there don't matter.)
9512   const Expr *Culprit;
9513   if (Init->isConstantInitializer(Context, false, &Culprit))
9514     return false;
9515   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9516     << Culprit->getSourceRange();
9517   return true;
9518 }
9519
9520 namespace {
9521   // Visits an initialization expression to see if OrigDecl is evaluated in
9522   // its own initialization and throws a warning if it does.
9523   class SelfReferenceChecker
9524       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9525     Sema &S;
9526     Decl *OrigDecl;
9527     bool isRecordType;
9528     bool isPODType;
9529     bool isReferenceType;
9530
9531     bool isInitList;
9532     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9533
9534   public:
9535     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9536
9537     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9538                                                     S(S), OrigDecl(OrigDecl) {
9539       isPODType = false;
9540       isRecordType = false;
9541       isReferenceType = false;
9542       isInitList = false;
9543       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9544         isPODType = VD->getType().isPODType(S.Context);
9545         isRecordType = VD->getType()->isRecordType();
9546         isReferenceType = VD->getType()->isReferenceType();
9547       }
9548     }
9549
9550     // For most expressions, just call the visitor.  For initializer lists,
9551     // track the index of the field being initialized since fields are
9552     // initialized in order allowing use of previously initialized fields.
9553     void CheckExpr(Expr *E) {
9554       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9555       if (!InitList) {
9556         Visit(E);
9557         return;
9558       }
9559
9560       // Track and increment the index here.
9561       isInitList = true;
9562       InitFieldIndex.push_back(0);
9563       for (auto Child : InitList->children()) {
9564         CheckExpr(cast<Expr>(Child));
9565         ++InitFieldIndex.back();
9566       }
9567       InitFieldIndex.pop_back();
9568     }
9569
9570     // Returns true if MemberExpr is checked and no further checking is needed.
9571     // Returns false if additional checking is required.
9572     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9573       llvm::SmallVector<FieldDecl*, 4> Fields;
9574       Expr *Base = E;
9575       bool ReferenceField = false;
9576
9577       // Get the field memebers used.
9578       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9579         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9580         if (!FD)
9581           return false;
9582         Fields.push_back(FD);
9583         if (FD->getType()->isReferenceType())
9584           ReferenceField = true;
9585         Base = ME->getBase()->IgnoreParenImpCasts();
9586       }
9587
9588       // Keep checking only if the base Decl is the same.
9589       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9590       if (!DRE || DRE->getDecl() != OrigDecl)
9591         return false;
9592
9593       // A reference field can be bound to an unininitialized field.
9594       if (CheckReference && !ReferenceField)
9595         return true;
9596
9597       // Convert FieldDecls to their index number.
9598       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9599       for (const FieldDecl *I : llvm::reverse(Fields))
9600         UsedFieldIndex.push_back(I->getFieldIndex());
9601
9602       // See if a warning is needed by checking the first difference in index
9603       // numbers.  If field being used has index less than the field being
9604       // initialized, then the use is safe.
9605       for (auto UsedIter = UsedFieldIndex.begin(),
9606                 UsedEnd = UsedFieldIndex.end(),
9607                 OrigIter = InitFieldIndex.begin(),
9608                 OrigEnd = InitFieldIndex.end();
9609            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9610         if (*UsedIter < *OrigIter)
9611           return true;
9612         if (*UsedIter > *OrigIter)
9613           break;
9614       }
9615
9616       // TODO: Add a different warning which will print the field names.
9617       HandleDeclRefExpr(DRE);
9618       return true;
9619     }
9620
9621     // For most expressions, the cast is directly above the DeclRefExpr.
9622     // For conditional operators, the cast can be outside the conditional
9623     // operator if both expressions are DeclRefExpr's.
9624     void HandleValue(Expr *E) {
9625       E = E->IgnoreParens();
9626       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9627         HandleDeclRefExpr(DRE);
9628         return;
9629       }
9630
9631       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9632         Visit(CO->getCond());
9633         HandleValue(CO->getTrueExpr());
9634         HandleValue(CO->getFalseExpr());
9635         return;
9636       }
9637
9638       if (BinaryConditionalOperator *BCO =
9639               dyn_cast<BinaryConditionalOperator>(E)) {
9640         Visit(BCO->getCond());
9641         HandleValue(BCO->getFalseExpr());
9642         return;
9643       }
9644
9645       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9646         HandleValue(OVE->getSourceExpr());
9647         return;
9648       }
9649
9650       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9651         if (BO->getOpcode() == BO_Comma) {
9652           Visit(BO->getLHS());
9653           HandleValue(BO->getRHS());
9654           return;
9655         }
9656       }
9657
9658       if (isa<MemberExpr>(E)) {
9659         if (isInitList) {
9660           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9661                                       false /*CheckReference*/))
9662             return;
9663         }
9664
9665         Expr *Base = E->IgnoreParenImpCasts();
9666         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9667           // Check for static member variables and don't warn on them.
9668           if (!isa<FieldDecl>(ME->getMemberDecl()))
9669             return;
9670           Base = ME->getBase()->IgnoreParenImpCasts();
9671         }
9672         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9673           HandleDeclRefExpr(DRE);
9674         return;
9675       }
9676
9677       Visit(E);
9678     }
9679
9680     // Reference types not handled in HandleValue are handled here since all
9681     // uses of references are bad, not just r-value uses.
9682     void VisitDeclRefExpr(DeclRefExpr *E) {
9683       if (isReferenceType)
9684         HandleDeclRefExpr(E);
9685     }
9686
9687     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9688       if (E->getCastKind() == CK_LValueToRValue) {
9689         HandleValue(E->getSubExpr());
9690         return;
9691       }
9692
9693       Inherited::VisitImplicitCastExpr(E);
9694     }
9695
9696     void VisitMemberExpr(MemberExpr *E) {
9697       if (isInitList) {
9698         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9699           return;
9700       }
9701
9702       // Don't warn on arrays since they can be treated as pointers.
9703       if (E->getType()->canDecayToPointerType()) return;
9704
9705       // Warn when a non-static method call is followed by non-static member
9706       // field accesses, which is followed by a DeclRefExpr.
9707       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9708       bool Warn = (MD && !MD->isStatic());
9709       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9710       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9711         if (!isa<FieldDecl>(ME->getMemberDecl()))
9712           Warn = false;
9713         Base = ME->getBase()->IgnoreParenImpCasts();
9714       }
9715
9716       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9717         if (Warn)
9718           HandleDeclRefExpr(DRE);
9719         return;
9720       }
9721
9722       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9723       // Visit that expression.
9724       Visit(Base);
9725     }
9726
9727     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9728       Expr *Callee = E->getCallee();
9729
9730       if (isa<UnresolvedLookupExpr>(Callee))
9731         return Inherited::VisitCXXOperatorCallExpr(E);
9732
9733       Visit(Callee);
9734       for (auto Arg: E->arguments())
9735         HandleValue(Arg->IgnoreParenImpCasts());
9736     }
9737
9738     void VisitUnaryOperator(UnaryOperator *E) {
9739       // For POD record types, addresses of its own members are well-defined.
9740       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9741           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9742         if (!isPODType)
9743           HandleValue(E->getSubExpr());
9744         return;
9745       }
9746
9747       if (E->isIncrementDecrementOp()) {
9748         HandleValue(E->getSubExpr());
9749         return;
9750       }
9751
9752       Inherited::VisitUnaryOperator(E);
9753     }
9754
9755     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9756
9757     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9758       if (E->getConstructor()->isCopyConstructor()) {
9759         Expr *ArgExpr = E->getArg(0);
9760         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9761           if (ILE->getNumInits() == 1)
9762             ArgExpr = ILE->getInit(0);
9763         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9764           if (ICE->getCastKind() == CK_NoOp)
9765             ArgExpr = ICE->getSubExpr();
9766         HandleValue(ArgExpr);
9767         return;
9768       }
9769       Inherited::VisitCXXConstructExpr(E);
9770     }
9771
9772     void VisitCallExpr(CallExpr *E) {
9773       // Treat std::move as a use.
9774       if (E->getNumArgs() == 1) {
9775         if (FunctionDecl *FD = E->getDirectCallee()) {
9776           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9777               FD->getIdentifier()->isStr("move")) {
9778             HandleValue(E->getArg(0));
9779             return;
9780           }
9781         }
9782       }
9783
9784       Inherited::VisitCallExpr(E);
9785     }
9786
9787     void VisitBinaryOperator(BinaryOperator *E) {
9788       if (E->isCompoundAssignmentOp()) {
9789         HandleValue(E->getLHS());
9790         Visit(E->getRHS());
9791         return;
9792       }
9793
9794       Inherited::VisitBinaryOperator(E);
9795     }
9796
9797     // A custom visitor for BinaryConditionalOperator is needed because the
9798     // regular visitor would check the condition and true expression separately
9799     // but both point to the same place giving duplicate diagnostics.
9800     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9801       Visit(E->getCond());
9802       Visit(E->getFalseExpr());
9803     }
9804
9805     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9806       Decl* ReferenceDecl = DRE->getDecl();
9807       if (OrigDecl != ReferenceDecl) return;
9808       unsigned diag;
9809       if (isReferenceType) {
9810         diag = diag::warn_uninit_self_reference_in_reference_init;
9811       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9812         diag = diag::warn_static_self_reference_in_init;
9813       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9814                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9815                  DRE->getDecl()->getType()->isRecordType()) {
9816         diag = diag::warn_uninit_self_reference_in_init;
9817       } else {
9818         // Local variables will be handled by the CFG analysis.
9819         return;
9820       }
9821
9822       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9823                             S.PDiag(diag)
9824                               << DRE->getNameInfo().getName()
9825                               << OrigDecl->getLocation()
9826                               << DRE->getSourceRange());
9827     }
9828   };
9829
9830   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9831   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9832                                  bool DirectInit) {
9833     // Parameters arguments are occassionially constructed with itself,
9834     // for instance, in recursive functions.  Skip them.
9835     if (isa<ParmVarDecl>(OrigDecl))
9836       return;
9837
9838     E = E->IgnoreParens();
9839
9840     // Skip checking T a = a where T is not a record or reference type.
9841     // Doing so is a way to silence uninitialized warnings.
9842     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9843       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9844         if (ICE->getCastKind() == CK_LValueToRValue)
9845           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9846             if (DRE->getDecl() == OrigDecl)
9847               return;
9848
9849     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9850   }
9851 } // end anonymous namespace
9852
9853 namespace {
9854   // Simple wrapper to add the name of a variable or (if no variable is
9855   // available) a DeclarationName into a diagnostic.
9856   struct VarDeclOrName {
9857     VarDecl *VDecl;
9858     DeclarationName Name;
9859
9860     friend const Sema::SemaDiagnosticBuilder &
9861     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9862       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9863     }
9864   };
9865 } // end anonymous namespace
9866
9867 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9868                                             DeclarationName Name, QualType Type,
9869                                             TypeSourceInfo *TSI,
9870                                             SourceRange Range, bool DirectInit,
9871                                             Expr *Init) {
9872   bool IsInitCapture = !VDecl;
9873   assert((!VDecl || !VDecl->isInitCapture()) &&
9874          "init captures are expected to be deduced prior to initialization");
9875
9876   VarDeclOrName VN{VDecl, Name};
9877
9878   DeducedType *Deduced = Type->getContainedDeducedType();
9879   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
9880
9881   // C++11 [dcl.spec.auto]p3
9882   if (!Init) {
9883     assert(VDecl && "no init for init capture deduction?");
9884     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
9885       << VDecl->getDeclName() << Type;
9886     return QualType();
9887   }
9888
9889   ArrayRef<Expr*> DeduceInits = Init;
9890   if (DirectInit) {
9891     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
9892       DeduceInits = PL->exprs();
9893   }
9894
9895   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
9896     assert(VDecl && "non-auto type for init capture deduction?");
9897     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9898     InitializationKind Kind = InitializationKind::CreateForInit(
9899         VDecl->getLocation(), DirectInit, Init);
9900     // FIXME: Initialization should not be taking a mutable list of inits. 
9901     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
9902     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
9903                                                        InitsCopy);
9904   }
9905
9906   if (DirectInit) {
9907     if (auto *IL = dyn_cast<InitListExpr>(Init))
9908       DeduceInits = IL->inits();
9909   }
9910
9911   // Deduction only works if we have exactly one source expression.
9912   if (DeduceInits.empty()) {
9913     // It isn't possible to write this directly, but it is possible to
9914     // end up in this situation with "auto x(some_pack...);"
9915     Diag(Init->getLocStart(), IsInitCapture
9916                                   ? diag::err_init_capture_no_expression
9917                                   : diag::err_auto_var_init_no_expression)
9918         << VN << Type << Range;
9919     return QualType();
9920   }
9921
9922   if (DeduceInits.size() > 1) {
9923     Diag(DeduceInits[1]->getLocStart(),
9924          IsInitCapture ? diag::err_init_capture_multiple_expressions
9925                        : diag::err_auto_var_init_multiple_expressions)
9926         << VN << Type << Range;
9927     return QualType();
9928   }
9929
9930   Expr *DeduceInit = DeduceInits[0];
9931   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9932     Diag(Init->getLocStart(), IsInitCapture
9933                                   ? diag::err_init_capture_paren_braces
9934                                   : diag::err_auto_var_init_paren_braces)
9935         << isa<InitListExpr>(Init) << VN << Type << Range;
9936     return QualType();
9937   }
9938
9939   // Expressions default to 'id' when we're in a debugger.
9940   bool DefaultedAnyToId = false;
9941   if (getLangOpts().DebuggerCastResultToId &&
9942       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9943     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9944     if (Result.isInvalid()) {
9945       return QualType();
9946     }
9947     Init = Result.get();
9948     DefaultedAnyToId = true;
9949   }
9950
9951   // C++ [dcl.decomp]p1:
9952   //   If the assignment-expression [...] has array type A and no ref-qualifier
9953   //   is present, e has type cv A
9954   if (VDecl && isa<DecompositionDecl>(VDecl) &&
9955       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
9956       DeduceInit->getType()->isConstantArrayType())
9957     return Context.getQualifiedType(DeduceInit->getType(),
9958                                     Type.getQualifiers());
9959
9960   QualType DeducedType;
9961   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9962     if (!IsInitCapture)
9963       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9964     else if (isa<InitListExpr>(Init))
9965       Diag(Range.getBegin(),
9966            diag::err_init_capture_deduction_failure_from_init_list)
9967           << VN
9968           << (DeduceInit->getType().isNull() ? TSI->getType()
9969                                              : DeduceInit->getType())
9970           << DeduceInit->getSourceRange();
9971     else
9972       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9973           << VN << TSI->getType()
9974           << (DeduceInit->getType().isNull() ? TSI->getType()
9975                                              : DeduceInit->getType())
9976           << DeduceInit->getSourceRange();
9977   }
9978
9979   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9980   // 'id' instead of a specific object type prevents most of our usual
9981   // checks.
9982   // We only want to warn outside of template instantiations, though:
9983   // inside a template, the 'id' could have come from a parameter.
9984   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
9985       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9986     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9987     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9988   }
9989
9990   return DeducedType;
9991 }
9992
9993 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
9994                                          Expr *Init) {
9995   QualType DeducedType = deduceVarTypeFromInitializer(
9996       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
9997       VDecl->getSourceRange(), DirectInit, Init);
9998   if (DeducedType.isNull()) {
9999     VDecl->setInvalidDecl();
10000     return true;
10001   }
10002
10003   VDecl->setType(DeducedType);
10004   assert(VDecl->isLinkageValid());
10005
10006   // In ARC, infer lifetime.
10007   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10008     VDecl->setInvalidDecl();
10009
10010   // If this is a redeclaration, check that the type we just deduced matches
10011   // the previously declared type.
10012   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10013     // We never need to merge the type, because we cannot form an incomplete
10014     // array of auto, nor deduce such a type.
10015     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10016   }
10017
10018   // Check the deduced type is valid for a variable declaration.
10019   CheckVariableDeclarationType(VDecl);
10020   return VDecl->isInvalidDecl();
10021 }
10022
10023 /// AddInitializerToDecl - Adds the initializer Init to the
10024 /// declaration dcl. If DirectInit is true, this is C++ direct
10025 /// initialization rather than copy initialization.
10026 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10027   // If there is no declaration, there was an error parsing it.  Just ignore
10028   // the initializer.
10029   if (!RealDecl || RealDecl->isInvalidDecl()) {
10030     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10031     return;
10032   }
10033
10034   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10035     // Pure-specifiers are handled in ActOnPureSpecifier.
10036     Diag(Method->getLocation(), diag::err_member_function_initialization)
10037       << Method->getDeclName() << Init->getSourceRange();
10038     Method->setInvalidDecl();
10039     return;
10040   }
10041
10042   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10043   if (!VDecl) {
10044     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10045     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10046     RealDecl->setInvalidDecl();
10047     return;
10048   }
10049
10050   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10051   if (VDecl->getType()->isUndeducedType()) {
10052     // Attempt typo correction early so that the type of the init expression can
10053     // be deduced based on the chosen correction if the original init contains a
10054     // TypoExpr.
10055     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10056     if (!Res.isUsable()) {
10057       RealDecl->setInvalidDecl();
10058       return;
10059     }
10060     Init = Res.get();
10061
10062     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10063       return;
10064   }
10065
10066   // dllimport cannot be used on variable definitions.
10067   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10068     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10069     VDecl->setInvalidDecl();
10070     return;
10071   }
10072
10073   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10074     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10075     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10076     VDecl->setInvalidDecl();
10077     return;
10078   }
10079
10080   if (!VDecl->getType()->isDependentType()) {
10081     // A definition must end up with a complete type, which means it must be
10082     // complete with the restriction that an array type might be completed by
10083     // the initializer; note that later code assumes this restriction.
10084     QualType BaseDeclType = VDecl->getType();
10085     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10086       BaseDeclType = Array->getElementType();
10087     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10088                             diag::err_typecheck_decl_incomplete_type)) {
10089       RealDecl->setInvalidDecl();
10090       return;
10091     }
10092
10093     // The variable can not have an abstract class type.
10094     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10095                                diag::err_abstract_type_in_decl,
10096                                AbstractVariableType))
10097       VDecl->setInvalidDecl();
10098   }
10099
10100   // If adding the initializer will turn this declaration into a definition,
10101   // and we already have a definition for this variable, diagnose or otherwise
10102   // handle the situation.
10103   VarDecl *Def;
10104   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10105       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10106       !VDecl->isThisDeclarationADemotedDefinition() &&
10107       checkVarDeclRedefinition(Def, VDecl))
10108     return;
10109
10110   if (getLangOpts().CPlusPlus) {
10111     // C++ [class.static.data]p4
10112     //   If a static data member is of const integral or const
10113     //   enumeration type, its declaration in the class definition can
10114     //   specify a constant-initializer which shall be an integral
10115     //   constant expression (5.19). In that case, the member can appear
10116     //   in integral constant expressions. The member shall still be
10117     //   defined in a namespace scope if it is used in the program and the
10118     //   namespace scope definition shall not contain an initializer.
10119     //
10120     // We already performed a redefinition check above, but for static
10121     // data members we also need to check whether there was an in-class
10122     // declaration with an initializer.
10123     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10124       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10125           << VDecl->getDeclName();
10126       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10127            diag::note_previous_initializer)
10128           << 0;
10129       return;
10130     }
10131
10132     if (VDecl->hasLocalStorage())
10133       getCurFunction()->setHasBranchProtectedScope();
10134
10135     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10136       VDecl->setInvalidDecl();
10137       return;
10138     }
10139   }
10140
10141   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10142   // a kernel function cannot be initialized."
10143   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10144     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10145     VDecl->setInvalidDecl();
10146     return;
10147   }
10148
10149   // Get the decls type and save a reference for later, since
10150   // CheckInitializerTypes may change it.
10151   QualType DclT = VDecl->getType(), SavT = DclT;
10152
10153   // Expressions default to 'id' when we're in a debugger
10154   // and we are assigning it to a variable of Objective-C pointer type.
10155   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10156       Init->getType() == Context.UnknownAnyTy) {
10157     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10158     if (Result.isInvalid()) {
10159       VDecl->setInvalidDecl();
10160       return;
10161     }
10162     Init = Result.get();
10163   }
10164
10165   // Perform the initialization.
10166   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10167   if (!VDecl->isInvalidDecl()) {
10168     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10169     InitializationKind Kind = InitializationKind::CreateForInit(
10170         VDecl->getLocation(), DirectInit, Init);
10171
10172     MultiExprArg Args = Init;
10173     if (CXXDirectInit)
10174       Args = MultiExprArg(CXXDirectInit->getExprs(),
10175                           CXXDirectInit->getNumExprs());
10176
10177     // Try to correct any TypoExprs in the initialization arguments.
10178     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10179       ExprResult Res = CorrectDelayedTyposInExpr(
10180           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10181             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10182             return Init.Failed() ? ExprError() : E;
10183           });
10184       if (Res.isInvalid()) {
10185         VDecl->setInvalidDecl();
10186       } else if (Res.get() != Args[Idx]) {
10187         Args[Idx] = Res.get();
10188       }
10189     }
10190     if (VDecl->isInvalidDecl())
10191       return;
10192
10193     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10194                                    /*TopLevelOfInitList=*/false,
10195                                    /*TreatUnavailableAsInvalid=*/false);
10196     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10197     if (Result.isInvalid()) {
10198       VDecl->setInvalidDecl();
10199       return;
10200     }
10201
10202     Init = Result.getAs<Expr>();
10203   }
10204
10205   // Check for self-references within variable initializers.
10206   // Variables declared within a function/method body (except for references)
10207   // are handled by a dataflow analysis.
10208   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10209       VDecl->getType()->isReferenceType()) {
10210     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10211   }
10212
10213   // If the type changed, it means we had an incomplete type that was
10214   // completed by the initializer. For example:
10215   //   int ary[] = { 1, 3, 5 };
10216   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10217   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10218     VDecl->setType(DclT);
10219
10220   if (!VDecl->isInvalidDecl()) {
10221     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10222
10223     if (VDecl->hasAttr<BlocksAttr>())
10224       checkRetainCycles(VDecl, Init);
10225
10226     // It is safe to assign a weak reference into a strong variable.
10227     // Although this code can still have problems:
10228     //   id x = self.weakProp;
10229     //   id y = self.weakProp;
10230     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10231     // paths through the function. This should be revisited if
10232     // -Wrepeated-use-of-weak is made flow-sensitive.
10233     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10234          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10235         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10236                          Init->getLocStart()))
10237       getCurFunction()->markSafeWeakUse(Init);
10238   }
10239
10240   // The initialization is usually a full-expression.
10241   //
10242   // FIXME: If this is a braced initialization of an aggregate, it is not
10243   // an expression, and each individual field initializer is a separate
10244   // full-expression. For instance, in:
10245   //
10246   //   struct Temp { ~Temp(); };
10247   //   struct S { S(Temp); };
10248   //   struct T { S a, b; } t = { Temp(), Temp() }
10249   //
10250   // we should destroy the first Temp before constructing the second.
10251   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10252                                           false,
10253                                           VDecl->isConstexpr());
10254   if (Result.isInvalid()) {
10255     VDecl->setInvalidDecl();
10256     return;
10257   }
10258   Init = Result.get();
10259
10260   // Attach the initializer to the decl.
10261   VDecl->setInit(Init);
10262
10263   if (VDecl->isLocalVarDecl()) {
10264     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10265     // static storage duration shall be constant expressions or string literals.
10266     // C++ does not have this restriction.
10267     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10268       const Expr *Culprit;
10269       if (VDecl->getStorageClass() == SC_Static)
10270         CheckForConstantInitializer(Init, DclT);
10271       // C89 is stricter than C99 for non-static aggregate types.
10272       // C89 6.5.7p3: All the expressions [...] in an initializer list
10273       // for an object that has aggregate or union type shall be
10274       // constant expressions.
10275       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10276                isa<InitListExpr>(Init) &&
10277                !Init->isConstantInitializer(Context, false, &Culprit))
10278         Diag(Culprit->getExprLoc(),
10279              diag::ext_aggregate_init_not_constant)
10280           << Culprit->getSourceRange();
10281     }
10282   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10283              VDecl->getLexicalDeclContext()->isRecord()) {
10284     // This is an in-class initialization for a static data member, e.g.,
10285     //
10286     // struct S {
10287     //   static const int value = 17;
10288     // };
10289
10290     // C++ [class.mem]p4:
10291     //   A member-declarator can contain a constant-initializer only
10292     //   if it declares a static member (9.4) of const integral or
10293     //   const enumeration type, see 9.4.2.
10294     //
10295     // C++11 [class.static.data]p3:
10296     //   If a non-volatile non-inline const static data member is of integral
10297     //   or enumeration type, its declaration in the class definition can
10298     //   specify a brace-or-equal-initializer in which every initializer-clause
10299     //   that is an assignment-expression is a constant expression. A static
10300     //   data member of literal type can be declared in the class definition
10301     //   with the constexpr specifier; if so, its declaration shall specify a
10302     //   brace-or-equal-initializer in which every initializer-clause that is
10303     //   an assignment-expression is a constant expression.
10304
10305     // Do nothing on dependent types.
10306     if (DclT->isDependentType()) {
10307
10308     // Allow any 'static constexpr' members, whether or not they are of literal
10309     // type. We separately check that every constexpr variable is of literal
10310     // type.
10311     } else if (VDecl->isConstexpr()) {
10312
10313     // Require constness.
10314     } else if (!DclT.isConstQualified()) {
10315       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10316         << Init->getSourceRange();
10317       VDecl->setInvalidDecl();
10318
10319     // We allow integer constant expressions in all cases.
10320     } else if (DclT->isIntegralOrEnumerationType()) {
10321       // Check whether the expression is a constant expression.
10322       SourceLocation Loc;
10323       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10324         // In C++11, a non-constexpr const static data member with an
10325         // in-class initializer cannot be volatile.
10326         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10327       else if (Init->isValueDependent())
10328         ; // Nothing to check.
10329       else if (Init->isIntegerConstantExpr(Context, &Loc))
10330         ; // Ok, it's an ICE!
10331       else if (Init->isEvaluatable(Context)) {
10332         // If we can constant fold the initializer through heroics, accept it,
10333         // but report this as a use of an extension for -pedantic.
10334         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10335           << Init->getSourceRange();
10336       } else {
10337         // Otherwise, this is some crazy unknown case.  Report the issue at the
10338         // location provided by the isIntegerConstantExpr failed check.
10339         Diag(Loc, diag::err_in_class_initializer_non_constant)
10340           << Init->getSourceRange();
10341         VDecl->setInvalidDecl();
10342       }
10343
10344     // We allow foldable floating-point constants as an extension.
10345     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10346       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10347       // it anyway and provide a fixit to add the 'constexpr'.
10348       if (getLangOpts().CPlusPlus11) {
10349         Diag(VDecl->getLocation(),
10350              diag::ext_in_class_initializer_float_type_cxx11)
10351             << DclT << Init->getSourceRange();
10352         Diag(VDecl->getLocStart(),
10353              diag::note_in_class_initializer_float_type_cxx11)
10354             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10355       } else {
10356         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10357           << DclT << Init->getSourceRange();
10358
10359         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10360           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10361             << Init->getSourceRange();
10362           VDecl->setInvalidDecl();
10363         }
10364       }
10365
10366     // Suggest adding 'constexpr' in C++11 for literal types.
10367     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10368       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10369         << DclT << Init->getSourceRange()
10370         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10371       VDecl->setConstexpr(true);
10372
10373     } else {
10374       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10375         << DclT << Init->getSourceRange();
10376       VDecl->setInvalidDecl();
10377     }
10378   } else if (VDecl->isFileVarDecl()) {
10379     // In C, extern is typically used to avoid tentative definitions when
10380     // declaring variables in headers, but adding an intializer makes it a
10381     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10382     // In C++, extern is often used to give implictly static const variables
10383     // external linkage, so don't warn in that case. If selectany is present,
10384     // this might be header code intended for C and C++ inclusion, so apply the
10385     // C++ rules.
10386     if (VDecl->getStorageClass() == SC_Extern &&
10387         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10388          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10389         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10390         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10391       Diag(VDecl->getLocation(), diag::warn_extern_init);
10392
10393     // C99 6.7.8p4. All file scoped initializers need to be constant.
10394     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10395       CheckForConstantInitializer(Init, DclT);
10396   }
10397
10398   // We will represent direct-initialization similarly to copy-initialization:
10399   //    int x(1);  -as-> int x = 1;
10400   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10401   //
10402   // Clients that want to distinguish between the two forms, can check for
10403   // direct initializer using VarDecl::getInitStyle().
10404   // A major benefit is that clients that don't particularly care about which
10405   // exactly form was it (like the CodeGen) can handle both cases without
10406   // special case code.
10407
10408   // C++ 8.5p11:
10409   // The form of initialization (using parentheses or '=') is generally
10410   // insignificant, but does matter when the entity being initialized has a
10411   // class type.
10412   if (CXXDirectInit) {
10413     assert(DirectInit && "Call-style initializer must be direct init.");
10414     VDecl->setInitStyle(VarDecl::CallInit);
10415   } else if (DirectInit) {
10416     // This must be list-initialization. No other way is direct-initialization.
10417     VDecl->setInitStyle(VarDecl::ListInit);
10418   }
10419
10420   CheckCompleteVariableDeclaration(VDecl);
10421 }
10422
10423 /// ActOnInitializerError - Given that there was an error parsing an
10424 /// initializer for the given declaration, try to return to some form
10425 /// of sanity.
10426 void Sema::ActOnInitializerError(Decl *D) {
10427   // Our main concern here is re-establishing invariants like "a
10428   // variable's type is either dependent or complete".
10429   if (!D || D->isInvalidDecl()) return;
10430
10431   VarDecl *VD = dyn_cast<VarDecl>(D);
10432   if (!VD) return;
10433
10434   // Bindings are not usable if we can't make sense of the initializer.
10435   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10436     for (auto *BD : DD->bindings())
10437       BD->setInvalidDecl();
10438
10439   // Auto types are meaningless if we can't make sense of the initializer.
10440   if (ParsingInitForAutoVars.count(D)) {
10441     D->setInvalidDecl();
10442     return;
10443   }
10444
10445   QualType Ty = VD->getType();
10446   if (Ty->isDependentType()) return;
10447
10448   // Require a complete type.
10449   if (RequireCompleteType(VD->getLocation(),
10450                           Context.getBaseElementType(Ty),
10451                           diag::err_typecheck_decl_incomplete_type)) {
10452     VD->setInvalidDecl();
10453     return;
10454   }
10455
10456   // Require a non-abstract type.
10457   if (RequireNonAbstractType(VD->getLocation(), Ty,
10458                              diag::err_abstract_type_in_decl,
10459                              AbstractVariableType)) {
10460     VD->setInvalidDecl();
10461     return;
10462   }
10463
10464   // Don't bother complaining about constructors or destructors,
10465   // though.
10466 }
10467
10468 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10469   // If there is no declaration, there was an error parsing it. Just ignore it.
10470   if (!RealDecl)
10471     return;
10472
10473   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10474     QualType Type = Var->getType();
10475
10476     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10477     if (isa<DecompositionDecl>(RealDecl)) {
10478       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10479       Var->setInvalidDecl();
10480       return;
10481     }
10482
10483     if (Type->isUndeducedType() &&
10484         DeduceVariableDeclarationType(Var, false, nullptr))
10485       return;
10486
10487     // C++11 [class.static.data]p3: A static data member can be declared with
10488     // the constexpr specifier; if so, its declaration shall specify
10489     // a brace-or-equal-initializer.
10490     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10491     // the definition of a variable [...] or the declaration of a static data
10492     // member.
10493     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10494         !Var->isThisDeclarationADemotedDefinition()) {
10495       if (Var->isStaticDataMember()) {
10496         // C++1z removes the relevant rule; the in-class declaration is always
10497         // a definition there.
10498         if (!getLangOpts().CPlusPlus1z) {
10499           Diag(Var->getLocation(),
10500                diag::err_constexpr_static_mem_var_requires_init)
10501             << Var->getDeclName();
10502           Var->setInvalidDecl();
10503           return;
10504         }
10505       } else {
10506         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10507         Var->setInvalidDecl();
10508         return;
10509       }
10510     }
10511
10512     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10513     // definition having the concept specifier is called a variable concept. A
10514     // concept definition refers to [...] a variable concept and its initializer.
10515     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10516       if (VTD->isConcept()) {
10517         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10518         Var->setInvalidDecl();
10519         return;
10520       }
10521     }
10522
10523     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10524     // be initialized.
10525     if (!Var->isInvalidDecl() &&
10526         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10527         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10528       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10529       Var->setInvalidDecl();
10530       return;
10531     }
10532
10533     switch (Var->isThisDeclarationADefinition()) {
10534     case VarDecl::Definition:
10535       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10536         break;
10537
10538       // We have an out-of-line definition of a static data member
10539       // that has an in-class initializer, so we type-check this like
10540       // a declaration.
10541       //
10542       // Fall through
10543
10544     case VarDecl::DeclarationOnly:
10545       // It's only a declaration.
10546
10547       // Block scope. C99 6.7p7: If an identifier for an object is
10548       // declared with no linkage (C99 6.2.2p6), the type for the
10549       // object shall be complete.
10550       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10551           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10552           RequireCompleteType(Var->getLocation(), Type,
10553                               diag::err_typecheck_decl_incomplete_type))
10554         Var->setInvalidDecl();
10555
10556       // Make sure that the type is not abstract.
10557       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10558           RequireNonAbstractType(Var->getLocation(), Type,
10559                                  diag::err_abstract_type_in_decl,
10560                                  AbstractVariableType))
10561         Var->setInvalidDecl();
10562       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10563           Var->getStorageClass() == SC_PrivateExtern) {
10564         Diag(Var->getLocation(), diag::warn_private_extern);
10565         Diag(Var->getLocation(), diag::note_private_extern);
10566       }
10567
10568       return;
10569
10570     case VarDecl::TentativeDefinition:
10571       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10572       // object that has file scope without an initializer, and without a
10573       // storage-class specifier or with the storage-class specifier "static",
10574       // constitutes a tentative definition. Note: A tentative definition with
10575       // external linkage is valid (C99 6.2.2p5).
10576       if (!Var->isInvalidDecl()) {
10577         if (const IncompleteArrayType *ArrayT
10578                                     = Context.getAsIncompleteArrayType(Type)) {
10579           if (RequireCompleteType(Var->getLocation(),
10580                                   ArrayT->getElementType(),
10581                                   diag::err_illegal_decl_array_incomplete_type))
10582             Var->setInvalidDecl();
10583         } else if (Var->getStorageClass() == SC_Static) {
10584           // C99 6.9.2p3: If the declaration of an identifier for an object is
10585           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10586           // declared type shall not be an incomplete type.
10587           // NOTE: code such as the following
10588           //     static struct s;
10589           //     struct s { int a; };
10590           // is accepted by gcc. Hence here we issue a warning instead of
10591           // an error and we do not invalidate the static declaration.
10592           // NOTE: to avoid multiple warnings, only check the first declaration.
10593           if (Var->isFirstDecl())
10594             RequireCompleteType(Var->getLocation(), Type,
10595                                 diag::ext_typecheck_decl_incomplete_type);
10596         }
10597       }
10598
10599       // Record the tentative definition; we're done.
10600       if (!Var->isInvalidDecl())
10601         TentativeDefinitions.push_back(Var);
10602       return;
10603     }
10604
10605     // Provide a specific diagnostic for uninitialized variable
10606     // definitions with incomplete array type.
10607     if (Type->isIncompleteArrayType()) {
10608       Diag(Var->getLocation(),
10609            diag::err_typecheck_incomplete_array_needs_initializer);
10610       Var->setInvalidDecl();
10611       return;
10612     }
10613
10614     // Provide a specific diagnostic for uninitialized variable
10615     // definitions with reference type.
10616     if (Type->isReferenceType()) {
10617       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10618         << Var->getDeclName()
10619         << SourceRange(Var->getLocation(), Var->getLocation());
10620       Var->setInvalidDecl();
10621       return;
10622     }
10623
10624     // Do not attempt to type-check the default initializer for a
10625     // variable with dependent type.
10626     if (Type->isDependentType())
10627       return;
10628
10629     if (Var->isInvalidDecl())
10630       return;
10631
10632     if (!Var->hasAttr<AliasAttr>()) {
10633       if (RequireCompleteType(Var->getLocation(),
10634                               Context.getBaseElementType(Type),
10635                               diag::err_typecheck_decl_incomplete_type)) {
10636         Var->setInvalidDecl();
10637         return;
10638       }
10639     } else {
10640       return;
10641     }
10642
10643     // The variable can not have an abstract class type.
10644     if (RequireNonAbstractType(Var->getLocation(), Type,
10645                                diag::err_abstract_type_in_decl,
10646                                AbstractVariableType)) {
10647       Var->setInvalidDecl();
10648       return;
10649     }
10650
10651     // Check for jumps past the implicit initializer.  C++0x
10652     // clarifies that this applies to a "variable with automatic
10653     // storage duration", not a "local variable".
10654     // C++11 [stmt.dcl]p3
10655     //   A program that jumps from a point where a variable with automatic
10656     //   storage duration is not in scope to a point where it is in scope is
10657     //   ill-formed unless the variable has scalar type, class type with a
10658     //   trivial default constructor and a trivial destructor, a cv-qualified
10659     //   version of one of these types, or an array of one of the preceding
10660     //   types and is declared without an initializer.
10661     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10662       if (const RecordType *Record
10663             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10664         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10665         // Mark the function for further checking even if the looser rules of
10666         // C++11 do not require such checks, so that we can diagnose
10667         // incompatibilities with C++98.
10668         if (!CXXRecord->isPOD())
10669           getCurFunction()->setHasBranchProtectedScope();
10670       }
10671     }
10672
10673     // C++03 [dcl.init]p9:
10674     //   If no initializer is specified for an object, and the
10675     //   object is of (possibly cv-qualified) non-POD class type (or
10676     //   array thereof), the object shall be default-initialized; if
10677     //   the object is of const-qualified type, the underlying class
10678     //   type shall have a user-declared default
10679     //   constructor. Otherwise, if no initializer is specified for
10680     //   a non- static object, the object and its subobjects, if
10681     //   any, have an indeterminate initial value); if the object
10682     //   or any of its subobjects are of const-qualified type, the
10683     //   program is ill-formed.
10684     // C++0x [dcl.init]p11:
10685     //   If no initializer is specified for an object, the object is
10686     //   default-initialized; [...].
10687     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10688     InitializationKind Kind
10689       = InitializationKind::CreateDefault(Var->getLocation());
10690
10691     InitializationSequence InitSeq(*this, Entity, Kind, None);
10692     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10693     if (Init.isInvalid())
10694       Var->setInvalidDecl();
10695     else if (Init.get()) {
10696       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10697       // This is important for template substitution.
10698       Var->setInitStyle(VarDecl::CallInit);
10699     }
10700
10701     CheckCompleteVariableDeclaration(Var);
10702   }
10703 }
10704
10705 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10706   // If there is no declaration, there was an error parsing it. Ignore it.
10707   if (!D)
10708     return;
10709
10710   VarDecl *VD = dyn_cast<VarDecl>(D);
10711   if (!VD) {
10712     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10713     D->setInvalidDecl();
10714     return;
10715   }
10716
10717   VD->setCXXForRangeDecl(true);
10718
10719   // for-range-declaration cannot be given a storage class specifier.
10720   int Error = -1;
10721   switch (VD->getStorageClass()) {
10722   case SC_None:
10723     break;
10724   case SC_Extern:
10725     Error = 0;
10726     break;
10727   case SC_Static:
10728     Error = 1;
10729     break;
10730   case SC_PrivateExtern:
10731     Error = 2;
10732     break;
10733   case SC_Auto:
10734     Error = 3;
10735     break;
10736   case SC_Register:
10737     Error = 4;
10738     break;
10739   }
10740   if (Error != -1) {
10741     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10742       << VD->getDeclName() << Error;
10743     D->setInvalidDecl();
10744   }
10745 }
10746
10747 StmtResult
10748 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10749                                  IdentifierInfo *Ident,
10750                                  ParsedAttributes &Attrs,
10751                                  SourceLocation AttrEnd) {
10752   // C++1y [stmt.iter]p1:
10753   //   A range-based for statement of the form
10754   //      for ( for-range-identifier : for-range-initializer ) statement
10755   //   is equivalent to
10756   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10757   DeclSpec DS(Attrs.getPool().getFactory());
10758
10759   const char *PrevSpec;
10760   unsigned DiagID;
10761   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10762                      getPrintingPolicy());
10763
10764   Declarator D(DS, Declarator::ForContext);
10765   D.SetIdentifier(Ident, IdentLoc);
10766   D.takeAttributes(Attrs, AttrEnd);
10767
10768   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10769   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10770                 EmptyAttrs, IdentLoc);
10771   Decl *Var = ActOnDeclarator(S, D);
10772   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10773   FinalizeDeclaration(Var);
10774   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10775                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10776 }
10777
10778 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10779   if (var->isInvalidDecl()) return;
10780
10781   if (getLangOpts().OpenCL) {
10782     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10783     // initialiser
10784     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10785         !var->hasInit()) {
10786       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10787           << 1 /*Init*/;
10788       var->setInvalidDecl();
10789       return;
10790     }
10791   }
10792
10793   // In Objective-C, don't allow jumps past the implicit initialization of a
10794   // local retaining variable.
10795   if (getLangOpts().ObjC1 &&
10796       var->hasLocalStorage()) {
10797     switch (var->getType().getObjCLifetime()) {
10798     case Qualifiers::OCL_None:
10799     case Qualifiers::OCL_ExplicitNone:
10800     case Qualifiers::OCL_Autoreleasing:
10801       break;
10802
10803     case Qualifiers::OCL_Weak:
10804     case Qualifiers::OCL_Strong:
10805       getCurFunction()->setHasBranchProtectedScope();
10806       break;
10807     }
10808   }
10809
10810   // Warn about externally-visible variables being defined without a
10811   // prior declaration.  We only want to do this for global
10812   // declarations, but we also specifically need to avoid doing it for
10813   // class members because the linkage of an anonymous class can
10814   // change if it's later given a typedef name.
10815   if (var->isThisDeclarationADefinition() &&
10816       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10817       var->isExternallyVisible() && var->hasLinkage() &&
10818       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10819                                   var->getLocation())) {
10820     // Find a previous declaration that's not a definition.
10821     VarDecl *prev = var->getPreviousDecl();
10822     while (prev && prev->isThisDeclarationADefinition())
10823       prev = prev->getPreviousDecl();
10824
10825     if (!prev)
10826       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10827   }
10828
10829   // Cache the result of checking for constant initialization.
10830   Optional<bool> CacheHasConstInit;
10831   const Expr *CacheCulprit;
10832   auto checkConstInit = [&]() mutable {
10833     if (!CacheHasConstInit)
10834       CacheHasConstInit = var->getInit()->isConstantInitializer(
10835             Context, var->getType()->isReferenceType(), &CacheCulprit);
10836     return *CacheHasConstInit;
10837   };
10838
10839   if (var->getTLSKind() == VarDecl::TLS_Static) {
10840     if (var->getType().isDestructedType()) {
10841       // GNU C++98 edits for __thread, [basic.start.term]p3:
10842       //   The type of an object with thread storage duration shall not
10843       //   have a non-trivial destructor.
10844       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10845       if (getLangOpts().CPlusPlus11)
10846         Diag(var->getLocation(), diag::note_use_thread_local);
10847     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10848       if (!checkConstInit()) {
10849         // GNU C++98 edits for __thread, [basic.start.init]p4:
10850         //   An object of thread storage duration shall not require dynamic
10851         //   initialization.
10852         // FIXME: Need strict checking here.
10853         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10854           << CacheCulprit->getSourceRange();
10855         if (getLangOpts().CPlusPlus11)
10856           Diag(var->getLocation(), diag::note_use_thread_local);
10857       }
10858     }
10859   }
10860
10861   // Apply section attributes and pragmas to global variables.
10862   bool GlobalStorage = var->hasGlobalStorage();
10863   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10864       !inTemplateInstantiation()) {
10865     PragmaStack<StringLiteral *> *Stack = nullptr;
10866     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10867     if (var->getType().isConstQualified())
10868       Stack = &ConstSegStack;
10869     else if (!var->getInit()) {
10870       Stack = &BSSSegStack;
10871       SectionFlags |= ASTContext::PSF_Write;
10872     } else {
10873       Stack = &DataSegStack;
10874       SectionFlags |= ASTContext::PSF_Write;
10875     }
10876     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10877       var->addAttr(SectionAttr::CreateImplicit(
10878           Context, SectionAttr::Declspec_allocate,
10879           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10880     }
10881     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10882       if (UnifySection(SA->getName(), SectionFlags, var))
10883         var->dropAttr<SectionAttr>();
10884
10885     // Apply the init_seg attribute if this has an initializer.  If the
10886     // initializer turns out to not be dynamic, we'll end up ignoring this
10887     // attribute.
10888     if (CurInitSeg && var->getInit())
10889       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10890                                                CurInitSegLoc));
10891   }
10892
10893   // All the following checks are C++ only.
10894   if (!getLangOpts().CPlusPlus) {
10895       // If this variable must be emitted, add it as an initializer for the
10896       // current module.
10897      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10898        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10899      return;
10900   }
10901
10902   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10903     CheckCompleteDecompositionDeclaration(DD);
10904
10905   QualType type = var->getType();
10906   if (type->isDependentType()) return;
10907
10908   // __block variables might require us to capture a copy-initializer.
10909   if (var->hasAttr<BlocksAttr>()) {
10910     // It's currently invalid to ever have a __block variable with an
10911     // array type; should we diagnose that here?
10912
10913     // Regardless, we don't want to ignore array nesting when
10914     // constructing this copy.
10915     if (type->isStructureOrClassType()) {
10916       EnterExpressionEvaluationContext scope(
10917           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
10918       SourceLocation poi = var->getLocation();
10919       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10920       ExprResult result
10921         = PerformMoveOrCopyInitialization(
10922             InitializedEntity::InitializeBlock(poi, type, false),
10923             var, var->getType(), varRef, /*AllowNRVO=*/true);
10924       if (!result.isInvalid()) {
10925         result = MaybeCreateExprWithCleanups(result);
10926         Expr *init = result.getAs<Expr>();
10927         Context.setBlockVarCopyInits(var, init);
10928       }
10929     }
10930   }
10931
10932   Expr *Init = var->getInit();
10933   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10934   QualType baseType = Context.getBaseElementType(type);
10935
10936   if (!var->getDeclContext()->isDependentContext() &&
10937       Init && !Init->isValueDependent()) {
10938
10939     if (var->isConstexpr()) {
10940       SmallVector<PartialDiagnosticAt, 8> Notes;
10941       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10942         SourceLocation DiagLoc = var->getLocation();
10943         // If the note doesn't add any useful information other than a source
10944         // location, fold it into the primary diagnostic.
10945         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10946               diag::note_invalid_subexpr_in_const_expr) {
10947           DiagLoc = Notes[0].first;
10948           Notes.clear();
10949         }
10950         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10951           << var << Init->getSourceRange();
10952         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10953           Diag(Notes[I].first, Notes[I].second);
10954       }
10955     } else if (var->isUsableInConstantExpressions(Context)) {
10956       // Check whether the initializer of a const variable of integral or
10957       // enumeration type is an ICE now, since we can't tell whether it was
10958       // initialized by a constant expression if we check later.
10959       var->checkInitIsICE();
10960     }
10961
10962     // Don't emit further diagnostics about constexpr globals since they
10963     // were just diagnosed.
10964     if (!var->isConstexpr() && GlobalStorage &&
10965             var->hasAttr<RequireConstantInitAttr>()) {
10966       // FIXME: Need strict checking in C++03 here.
10967       bool DiagErr = getLangOpts().CPlusPlus11
10968           ? !var->checkInitIsICE() : !checkConstInit();
10969       if (DiagErr) {
10970         auto attr = var->getAttr<RequireConstantInitAttr>();
10971         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10972           << Init->getSourceRange();
10973         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10974           << attr->getRange();
10975       }
10976     }
10977     else if (!var->isConstexpr() && IsGlobal &&
10978              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10979                                     var->getLocation())) {
10980       // Warn about globals which don't have a constant initializer.  Don't
10981       // warn about globals with a non-trivial destructor because we already
10982       // warned about them.
10983       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10984       if (!(RD && !RD->hasTrivialDestructor())) {
10985         if (!checkConstInit())
10986           Diag(var->getLocation(), diag::warn_global_constructor)
10987             << Init->getSourceRange();
10988       }
10989     }
10990   }
10991
10992   // Require the destructor.
10993   if (const RecordType *recordType = baseType->getAs<RecordType>())
10994     FinalizeVarWithDestructor(var, recordType);
10995
10996   // If this variable must be emitted, add it as an initializer for the current
10997   // module.
10998   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10999     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11000 }
11001
11002 /// \brief Determines if a variable's alignment is dependent.
11003 static bool hasDependentAlignment(VarDecl *VD) {
11004   if (VD->getType()->isDependentType())
11005     return true;
11006   for (auto *I : VD->specific_attrs<AlignedAttr>())
11007     if (I->isAlignmentDependent())
11008       return true;
11009   return false;
11010 }
11011
11012 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11013 /// any semantic actions necessary after any initializer has been attached.
11014 void
11015 Sema::FinalizeDeclaration(Decl *ThisDecl) {
11016   // Note that we are no longer parsing the initializer for this declaration.
11017   ParsingInitForAutoVars.erase(ThisDecl);
11018
11019   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11020   if (!VD)
11021     return;
11022
11023   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11024     for (auto *BD : DD->bindings()) {
11025       FinalizeDeclaration(BD);
11026     }
11027   }
11028
11029   checkAttributesAfterMerging(*this, *VD);
11030
11031   // Perform TLS alignment check here after attributes attached to the variable
11032   // which may affect the alignment have been processed. Only perform the check
11033   // if the target has a maximum TLS alignment (zero means no constraints).
11034   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11035     // Protect the check so that it's not performed on dependent types and
11036     // dependent alignments (we can't determine the alignment in that case).
11037     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11038         !VD->isInvalidDecl()) {
11039       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11040       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11041         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11042           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11043           << (unsigned)MaxAlignChars.getQuantity();
11044       }
11045     }
11046   }
11047
11048   if (VD->isStaticLocal()) {
11049     if (FunctionDecl *FD =
11050             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11051       // Static locals inherit dll attributes from their function.
11052       if (Attr *A = getDLLAttr(FD)) {
11053         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11054         NewAttr->setInherited(true);
11055         VD->addAttr(NewAttr);
11056       }
11057       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11058       // function, only __shared__ variables may be declared with
11059       // static storage class.
11060       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11061           CUDADiagIfDeviceCode(VD->getLocation(),
11062                                diag::err_device_static_local_var)
11063               << CurrentCUDATarget())
11064         VD->setInvalidDecl();
11065     }
11066   }
11067
11068   // Perform check for initializers of device-side global variables.
11069   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11070   // 7.5). We must also apply the same checks to all __shared__
11071   // variables whether they are local or not. CUDA also allows
11072   // constant initializers for __constant__ and __device__ variables.
11073   if (getLangOpts().CUDA) {
11074     const Expr *Init = VD->getInit();
11075     if (Init && VD->hasGlobalStorage()) {
11076       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11077           VD->hasAttr<CUDASharedAttr>()) {
11078         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11079         bool AllowedInit = false;
11080         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11081           AllowedInit =
11082               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11083         // We'll allow constant initializers even if it's a non-empty
11084         // constructor according to CUDA rules. This deviates from NVCC,
11085         // but allows us to handle things like constexpr constructors.
11086         if (!AllowedInit &&
11087             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11088           AllowedInit = VD->getInit()->isConstantInitializer(
11089               Context, VD->getType()->isReferenceType());
11090
11091         // Also make sure that destructor, if there is one, is empty.
11092         if (AllowedInit)
11093           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11094             AllowedInit =
11095                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11096
11097         if (!AllowedInit) {
11098           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11099                                       ? diag::err_shared_var_init
11100                                       : diag::err_dynamic_var_init)
11101               << Init->getSourceRange();
11102           VD->setInvalidDecl();
11103         }
11104       } else {
11105         // This is a host-side global variable.  Check that the initializer is
11106         // callable from the host side.
11107         const FunctionDecl *InitFn = nullptr;
11108         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11109           InitFn = CE->getConstructor();
11110         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11111           InitFn = CE->getDirectCallee();
11112         }
11113         if (InitFn) {
11114           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11115           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11116             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11117                 << InitFnTarget << InitFn;
11118             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11119             VD->setInvalidDecl();
11120           }
11121         }
11122       }
11123     }
11124   }
11125
11126   // Grab the dllimport or dllexport attribute off of the VarDecl.
11127   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11128
11129   // Imported static data members cannot be defined out-of-line.
11130   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11131     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11132         VD->isThisDeclarationADefinition()) {
11133       // We allow definitions of dllimport class template static data members
11134       // with a warning.
11135       CXXRecordDecl *Context =
11136         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11137       bool IsClassTemplateMember =
11138           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11139           Context->getDescribedClassTemplate();
11140
11141       Diag(VD->getLocation(),
11142            IsClassTemplateMember
11143                ? diag::warn_attribute_dllimport_static_field_definition
11144                : diag::err_attribute_dllimport_static_field_definition);
11145       Diag(IA->getLocation(), diag::note_attribute);
11146       if (!IsClassTemplateMember)
11147         VD->setInvalidDecl();
11148     }
11149   }
11150
11151   // dllimport/dllexport variables cannot be thread local, their TLS index
11152   // isn't exported with the variable.
11153   if (DLLAttr && VD->getTLSKind()) {
11154     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11155     if (F && getDLLAttr(F)) {
11156       assert(VD->isStaticLocal());
11157       // But if this is a static local in a dlimport/dllexport function, the
11158       // function will never be inlined, which means the var would never be
11159       // imported, so having it marked import/export is safe.
11160     } else {
11161       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11162                                                                     << DLLAttr;
11163       VD->setInvalidDecl();
11164     }
11165   }
11166
11167   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11168     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11169       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11170       VD->dropAttr<UsedAttr>();
11171     }
11172   }
11173
11174   const DeclContext *DC = VD->getDeclContext();
11175   // If there's a #pragma GCC visibility in scope, and this isn't a class
11176   // member, set the visibility of this variable.
11177   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11178     AddPushedVisibilityAttribute(VD);
11179
11180   // FIXME: Warn on unused templates.
11181   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
11182       !isa<VarTemplatePartialSpecializationDecl>(VD))
11183     MarkUnusedFileScopedDecl(VD);
11184
11185   // Now we have parsed the initializer and can update the table of magic
11186   // tag values.
11187   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11188       !VD->getType()->isIntegralOrEnumerationType())
11189     return;
11190
11191   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11192     const Expr *MagicValueExpr = VD->getInit();
11193     if (!MagicValueExpr) {
11194       continue;
11195     }
11196     llvm::APSInt MagicValueInt;
11197     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11198       Diag(I->getRange().getBegin(),
11199            diag::err_type_tag_for_datatype_not_ice)
11200         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11201       continue;
11202     }
11203     if (MagicValueInt.getActiveBits() > 64) {
11204       Diag(I->getRange().getBegin(),
11205            diag::err_type_tag_for_datatype_too_large)
11206         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11207       continue;
11208     }
11209     uint64_t MagicValue = MagicValueInt.getZExtValue();
11210     RegisterTypeTagForDatatype(I->getArgumentKind(),
11211                                MagicValue,
11212                                I->getMatchingCType(),
11213                                I->getLayoutCompatible(),
11214                                I->getMustBeNull());
11215   }
11216 }
11217
11218 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11219   auto *VD = dyn_cast<VarDecl>(DD);
11220   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11221 }
11222
11223 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11224                                                    ArrayRef<Decl *> Group) {
11225   SmallVector<Decl*, 8> Decls;
11226
11227   if (DS.isTypeSpecOwned())
11228     Decls.push_back(DS.getRepAsDecl());
11229
11230   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11231   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11232   bool DiagnosedMultipleDecomps = false;
11233   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11234   bool DiagnosedNonDeducedAuto = false;
11235
11236   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11237     if (Decl *D = Group[i]) {
11238       // For declarators, there are some additional syntactic-ish checks we need
11239       // to perform.
11240       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11241         if (!FirstDeclaratorInGroup)
11242           FirstDeclaratorInGroup = DD;
11243         if (!FirstDecompDeclaratorInGroup)
11244           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11245         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11246             !hasDeducedAuto(DD))
11247           FirstNonDeducedAutoInGroup = DD;
11248
11249         if (FirstDeclaratorInGroup != DD) {
11250           // A decomposition declaration cannot be combined with any other
11251           // declaration in the same group.
11252           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11253             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11254                  diag::err_decomp_decl_not_alone)
11255                 << FirstDeclaratorInGroup->getSourceRange()
11256                 << DD->getSourceRange();
11257             DiagnosedMultipleDecomps = true;
11258           }
11259
11260           // A declarator that uses 'auto' in any way other than to declare a
11261           // variable with a deduced type cannot be combined with any other
11262           // declarator in the same group.
11263           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11264             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11265                  diag::err_auto_non_deduced_not_alone)
11266                 << FirstNonDeducedAutoInGroup->getType()
11267                        ->hasAutoForTrailingReturnType()
11268                 << FirstDeclaratorInGroup->getSourceRange()
11269                 << DD->getSourceRange();
11270             DiagnosedNonDeducedAuto = true;
11271           }
11272         }
11273       }
11274
11275       Decls.push_back(D);
11276     }
11277   }
11278
11279   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11280     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11281       handleTagNumbering(Tag, S);
11282       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11283           getLangOpts().CPlusPlus)
11284         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11285     }
11286   }
11287
11288   return BuildDeclaratorGroup(Decls);
11289 }
11290
11291 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11292 /// group, performing any necessary semantic checking.
11293 Sema::DeclGroupPtrTy
11294 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11295   // C++14 [dcl.spec.auto]p7: (DR1347)
11296   //   If the type that replaces the placeholder type is not the same in each
11297   //   deduction, the program is ill-formed.
11298   if (Group.size() > 1) {
11299     QualType Deduced;
11300     VarDecl *DeducedDecl = nullptr;
11301     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11302       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11303       if (!D || D->isInvalidDecl())
11304         break;
11305       DeducedType *DT = D->getType()->getContainedDeducedType();
11306       if (!DT || DT->getDeducedType().isNull())
11307         continue;
11308       if (Deduced.isNull()) {
11309         Deduced = DT->getDeducedType();
11310         DeducedDecl = D;
11311       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11312         auto *AT = dyn_cast<AutoType>(DT);
11313         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11314              diag::err_auto_different_deductions)
11315           << (AT ? (unsigned)AT->getKeyword() : 3)
11316           << Deduced << DeducedDecl->getDeclName()
11317           << DT->getDeducedType() << D->getDeclName()
11318           << DeducedDecl->getInit()->getSourceRange()
11319           << D->getInit()->getSourceRange();
11320         D->setInvalidDecl();
11321         break;
11322       }
11323     }
11324   }
11325
11326   ActOnDocumentableDecls(Group);
11327
11328   return DeclGroupPtrTy::make(
11329       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11330 }
11331
11332 void Sema::ActOnDocumentableDecl(Decl *D) {
11333   ActOnDocumentableDecls(D);
11334 }
11335
11336 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11337   // Don't parse the comment if Doxygen diagnostics are ignored.
11338   if (Group.empty() || !Group[0])
11339     return;
11340
11341   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11342                       Group[0]->getLocation()) &&
11343       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11344                       Group[0]->getLocation()))
11345     return;
11346
11347   if (Group.size() >= 2) {
11348     // This is a decl group.  Normally it will contain only declarations
11349     // produced from declarator list.  But in case we have any definitions or
11350     // additional declaration references:
11351     //   'typedef struct S {} S;'
11352     //   'typedef struct S *S;'
11353     //   'struct S *pS;'
11354     // FinalizeDeclaratorGroup adds these as separate declarations.
11355     Decl *MaybeTagDecl = Group[0];
11356     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11357       Group = Group.slice(1);
11358     }
11359   }
11360
11361   // See if there are any new comments that are not attached to a decl.
11362   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11363   if (!Comments.empty() &&
11364       !Comments.back()->isAttached()) {
11365     // There is at least one comment that not attached to a decl.
11366     // Maybe it should be attached to one of these decls?
11367     //
11368     // Note that this way we pick up not only comments that precede the
11369     // declaration, but also comments that *follow* the declaration -- thanks to
11370     // the lookahead in the lexer: we've consumed the semicolon and looked
11371     // ahead through comments.
11372     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11373       Context.getCommentForDecl(Group[i], &PP);
11374   }
11375 }
11376
11377 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11378 /// to introduce parameters into function prototype scope.
11379 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11380   const DeclSpec &DS = D.getDeclSpec();
11381
11382   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11383
11384   // C++03 [dcl.stc]p2 also permits 'auto'.
11385   StorageClass SC = SC_None;
11386   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11387     SC = SC_Register;
11388   } else if (getLangOpts().CPlusPlus &&
11389              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11390     SC = SC_Auto;
11391   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11392     Diag(DS.getStorageClassSpecLoc(),
11393          diag::err_invalid_storage_class_in_func_decl);
11394     D.getMutableDeclSpec().ClearStorageClassSpecs();
11395   }
11396
11397   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11398     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11399       << DeclSpec::getSpecifierName(TSCS);
11400   if (DS.isInlineSpecified())
11401     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11402         << getLangOpts().CPlusPlus1z;
11403   if (DS.isConstexprSpecified())
11404     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11405       << 0;
11406   if (DS.isConceptSpecified())
11407     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11408
11409   DiagnoseFunctionSpecifiers(DS);
11410
11411   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11412   QualType parmDeclType = TInfo->getType();
11413
11414   if (getLangOpts().CPlusPlus) {
11415     // Check that there are no default arguments inside the type of this
11416     // parameter.
11417     CheckExtraCXXDefaultArguments(D);
11418
11419     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11420     if (D.getCXXScopeSpec().isSet()) {
11421       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11422         << D.getCXXScopeSpec().getRange();
11423       D.getCXXScopeSpec().clear();
11424     }
11425   }
11426
11427   // Ensure we have a valid name
11428   IdentifierInfo *II = nullptr;
11429   if (D.hasName()) {
11430     II = D.getIdentifier();
11431     if (!II) {
11432       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11433         << GetNameForDeclarator(D).getName();
11434       D.setInvalidType(true);
11435     }
11436   }
11437
11438   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11439   if (II) {
11440     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11441                    ForRedeclaration);
11442     LookupName(R, S);
11443     if (R.isSingleResult()) {
11444       NamedDecl *PrevDecl = R.getFoundDecl();
11445       if (PrevDecl->isTemplateParameter()) {
11446         // Maybe we will complain about the shadowed template parameter.
11447         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11448         // Just pretend that we didn't see the previous declaration.
11449         PrevDecl = nullptr;
11450       } else if (S->isDeclScope(PrevDecl)) {
11451         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11452         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11453
11454         // Recover by removing the name
11455         II = nullptr;
11456         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11457         D.setInvalidType(true);
11458       }
11459     }
11460   }
11461
11462   // Temporarily put parameter variables in the translation unit, not
11463   // the enclosing context.  This prevents them from accidentally
11464   // looking like class members in C++.
11465   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11466                                     D.getLocStart(),
11467                                     D.getIdentifierLoc(), II,
11468                                     parmDeclType, TInfo,
11469                                     SC);
11470
11471   if (D.isInvalidType())
11472     New->setInvalidDecl();
11473
11474   assert(S->isFunctionPrototypeScope());
11475   assert(S->getFunctionPrototypeDepth() >= 1);
11476   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11477                     S->getNextFunctionPrototypeIndex());
11478
11479   // Add the parameter declaration into this scope.
11480   S->AddDecl(New);
11481   if (II)
11482     IdResolver.AddDecl(New);
11483
11484   ProcessDeclAttributes(S, New, D);
11485
11486   if (D.getDeclSpec().isModulePrivateSpecified())
11487     Diag(New->getLocation(), diag::err_module_private_local)
11488       << 1 << New->getDeclName()
11489       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11490       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11491
11492   if (New->hasAttr<BlocksAttr>()) {
11493     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11494   }
11495   return New;
11496 }
11497
11498 /// \brief Synthesizes a variable for a parameter arising from a
11499 /// typedef.
11500 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11501                                               SourceLocation Loc,
11502                                               QualType T) {
11503   /* FIXME: setting StartLoc == Loc.
11504      Would it be worth to modify callers so as to provide proper source
11505      location for the unnamed parameters, embedding the parameter's type? */
11506   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11507                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11508                                            SC_None, nullptr);
11509   Param->setImplicit();
11510   return Param;
11511 }
11512
11513 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11514   // Don't diagnose unused-parameter errors in template instantiations; we
11515   // will already have done so in the template itself.
11516   if (inTemplateInstantiation())
11517     return;
11518
11519   for (const ParmVarDecl *Parameter : Parameters) {
11520     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11521         !Parameter->hasAttr<UnusedAttr>()) {
11522       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11523         << Parameter->getDeclName();
11524     }
11525   }
11526 }
11527
11528 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11529     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11530   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11531     return;
11532
11533   // Warn if the return value is pass-by-value and larger than the specified
11534   // threshold.
11535   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11536     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11537     if (Size > LangOpts.NumLargeByValueCopy)
11538       Diag(D->getLocation(), diag::warn_return_value_size)
11539           << D->getDeclName() << Size;
11540   }
11541
11542   // Warn if any parameter is pass-by-value and larger than the specified
11543   // threshold.
11544   for (const ParmVarDecl *Parameter : Parameters) {
11545     QualType T = Parameter->getType();
11546     if (T->isDependentType() || !T.isPODType(Context))
11547       continue;
11548     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11549     if (Size > LangOpts.NumLargeByValueCopy)
11550       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11551           << Parameter->getDeclName() << Size;
11552   }
11553 }
11554
11555 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11556                                   SourceLocation NameLoc, IdentifierInfo *Name,
11557                                   QualType T, TypeSourceInfo *TSInfo,
11558                                   StorageClass SC) {
11559   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11560   if (getLangOpts().ObjCAutoRefCount &&
11561       T.getObjCLifetime() == Qualifiers::OCL_None &&
11562       T->isObjCLifetimeType()) {
11563
11564     Qualifiers::ObjCLifetime lifetime;
11565
11566     // Special cases for arrays:
11567     //   - if it's const, use __unsafe_unretained
11568     //   - otherwise, it's an error
11569     if (T->isArrayType()) {
11570       if (!T.isConstQualified()) {
11571         DelayedDiagnostics.add(
11572             sema::DelayedDiagnostic::makeForbiddenType(
11573             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11574       }
11575       lifetime = Qualifiers::OCL_ExplicitNone;
11576     } else {
11577       lifetime = T->getObjCARCImplicitLifetime();
11578     }
11579     T = Context.getLifetimeQualifiedType(T, lifetime);
11580   }
11581
11582   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11583                                          Context.getAdjustedParameterType(T),
11584                                          TSInfo, SC, nullptr);
11585
11586   // Parameters can not be abstract class types.
11587   // For record types, this is done by the AbstractClassUsageDiagnoser once
11588   // the class has been completely parsed.
11589   if (!CurContext->isRecord() &&
11590       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11591                              AbstractParamType))
11592     New->setInvalidDecl();
11593
11594   // Parameter declarators cannot be interface types. All ObjC objects are
11595   // passed by reference.
11596   if (T->isObjCObjectType()) {
11597     SourceLocation TypeEndLoc =
11598         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11599     Diag(NameLoc,
11600          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11601       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11602     T = Context.getObjCObjectPointerType(T);
11603     New->setType(T);
11604   }
11605
11606   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11607   // duration shall not be qualified by an address-space qualifier."
11608   // Since all parameters have automatic store duration, they can not have
11609   // an address space.
11610   if (T.getAddressSpace() != 0) {
11611     // OpenCL allows function arguments declared to be an array of a type
11612     // to be qualified with an address space.
11613     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11614       Diag(NameLoc, diag::err_arg_with_address_space);
11615       New->setInvalidDecl();
11616     }
11617   }
11618
11619   return New;
11620 }
11621
11622 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11623                                            SourceLocation LocAfterDecls) {
11624   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11625
11626   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11627   // for a K&R function.
11628   if (!FTI.hasPrototype) {
11629     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11630       --i;
11631       if (FTI.Params[i].Param == nullptr) {
11632         SmallString<256> Code;
11633         llvm::raw_svector_ostream(Code)
11634             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11635         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11636             << FTI.Params[i].Ident
11637             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11638
11639         // Implicitly declare the argument as type 'int' for lack of a better
11640         // type.
11641         AttributeFactory attrs;
11642         DeclSpec DS(attrs);
11643         const char* PrevSpec; // unused
11644         unsigned DiagID; // unused
11645         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11646                            DiagID, Context.getPrintingPolicy());
11647         // Use the identifier location for the type source range.
11648         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11649         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11650         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11651         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11652         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11653       }
11654     }
11655   }
11656 }
11657
11658 Decl *
11659 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11660                               MultiTemplateParamsArg TemplateParameterLists,
11661                               SkipBodyInfo *SkipBody) {
11662   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11663   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11664   Scope *ParentScope = FnBodyScope->getParent();
11665
11666   D.setFunctionDefinitionKind(FDK_Definition);
11667   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11668   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11669 }
11670
11671 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11672   Consumer.HandleInlineFunctionDefinition(D);
11673 }
11674
11675 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11676                              const FunctionDecl*& PossibleZeroParamPrototype) {
11677   // Don't warn about invalid declarations.
11678   if (FD->isInvalidDecl())
11679     return false;
11680
11681   // Or declarations that aren't global.
11682   if (!FD->isGlobal())
11683     return false;
11684
11685   // Don't warn about C++ member functions.
11686   if (isa<CXXMethodDecl>(FD))
11687     return false;
11688
11689   // Don't warn about 'main'.
11690   if (FD->isMain())
11691     return false;
11692
11693   // Don't warn about inline functions.
11694   if (FD->isInlined())
11695     return false;
11696
11697   // Don't warn about function templates.
11698   if (FD->getDescribedFunctionTemplate())
11699     return false;
11700
11701   // Don't warn about function template specializations.
11702   if (FD->isFunctionTemplateSpecialization())
11703     return false;
11704
11705   // Don't warn for OpenCL kernels.
11706   if (FD->hasAttr<OpenCLKernelAttr>())
11707     return false;
11708
11709   // Don't warn on explicitly deleted functions.
11710   if (FD->isDeleted())
11711     return false;
11712
11713   bool MissingPrototype = true;
11714   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11715        Prev; Prev = Prev->getPreviousDecl()) {
11716     // Ignore any declarations that occur in function or method
11717     // scope, because they aren't visible from the header.
11718     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11719       continue;
11720
11721     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11722     if (FD->getNumParams() == 0)
11723       PossibleZeroParamPrototype = Prev;
11724     break;
11725   }
11726
11727   return MissingPrototype;
11728 }
11729
11730 void
11731 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11732                                    const FunctionDecl *EffectiveDefinition,
11733                                    SkipBodyInfo *SkipBody) {
11734   const FunctionDecl *Definition = EffectiveDefinition;
11735   if (!Definition)
11736     if (!FD->isDefined(Definition))
11737       return;
11738
11739   if (canRedefineFunction(Definition, getLangOpts()))
11740     return;
11741
11742   // Don't emit an error when this is redifinition of a typo-corrected
11743   // definition.
11744   if (TypoCorrectedFunctionDefinitions.count(Definition))
11745     return;
11746
11747   // If we don't have a visible definition of the function, and it's inline or
11748   // a template, skip the new definition.
11749   if (SkipBody && !hasVisibleDefinition(Definition) &&
11750       (Definition->getFormalLinkage() == InternalLinkage ||
11751        Definition->isInlined() ||
11752        Definition->getDescribedFunctionTemplate() ||
11753        Definition->getNumTemplateParameterLists())) {
11754     SkipBody->ShouldSkip = true;
11755     if (auto *TD = Definition->getDescribedFunctionTemplate())
11756       makeMergedDefinitionVisible(TD, FD->getLocation());
11757     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11758                                 FD->getLocation());
11759     return;
11760   }
11761
11762   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11763       Definition->getStorageClass() == SC_Extern)
11764     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11765         << FD->getDeclName() << getLangOpts().CPlusPlus;
11766   else
11767     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11768
11769   Diag(Definition->getLocation(), diag::note_previous_definition);
11770   FD->setInvalidDecl();
11771 }
11772
11773 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11774                                    Sema &S) {
11775   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11776
11777   LambdaScopeInfo *LSI = S.PushLambdaScope();
11778   LSI->CallOperator = CallOperator;
11779   LSI->Lambda = LambdaClass;
11780   LSI->ReturnType = CallOperator->getReturnType();
11781   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11782
11783   if (LCD == LCD_None)
11784     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11785   else if (LCD == LCD_ByCopy)
11786     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11787   else if (LCD == LCD_ByRef)
11788     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11789   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11790
11791   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11792   LSI->Mutable = !CallOperator->isConst();
11793
11794   // Add the captures to the LSI so they can be noted as already
11795   // captured within tryCaptureVar.
11796   auto I = LambdaClass->field_begin();
11797   for (const auto &C : LambdaClass->captures()) {
11798     if (C.capturesVariable()) {
11799       VarDecl *VD = C.getCapturedVar();
11800       if (VD->isInitCapture())
11801         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11802       QualType CaptureType = VD->getType();
11803       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11804       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11805           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11806           /*EllipsisLoc*/C.isPackExpansion()
11807                          ? C.getEllipsisLoc() : SourceLocation(),
11808           CaptureType, /*Expr*/ nullptr);
11809
11810     } else if (C.capturesThis()) {
11811       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11812                               /*Expr*/ nullptr,
11813                               C.getCaptureKind() == LCK_StarThis);
11814     } else {
11815       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11816     }
11817     ++I;
11818   }
11819 }
11820
11821 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11822                                     SkipBodyInfo *SkipBody) {
11823   if (!D)
11824     return D;
11825   FunctionDecl *FD = nullptr;
11826
11827   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11828     FD = FunTmpl->getTemplatedDecl();
11829   else
11830     FD = cast<FunctionDecl>(D);
11831
11832   // Check for defining attributes before the check for redefinition.
11833   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
11834     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
11835     FD->dropAttr<AliasAttr>();
11836     FD->setInvalidDecl();
11837   }
11838   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
11839     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
11840     FD->dropAttr<IFuncAttr>();
11841     FD->setInvalidDecl();
11842   }
11843
11844   // See if this is a redefinition.
11845   if (!FD->isLateTemplateParsed()) {
11846     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11847
11848     // If we're skipping the body, we're done. Don't enter the scope.
11849     if (SkipBody && SkipBody->ShouldSkip)
11850       return D;
11851   }
11852
11853   // Mark this function as "will have a body eventually".  This lets users to
11854   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11855   // this function.
11856   FD->setWillHaveBody();
11857
11858   // If we are instantiating a generic lambda call operator, push
11859   // a LambdaScopeInfo onto the function stack.  But use the information
11860   // that's already been calculated (ActOnLambdaExpr) to prime the current
11861   // LambdaScopeInfo.
11862   // When the template operator is being specialized, the LambdaScopeInfo,
11863   // has to be properly restored so that tryCaptureVariable doesn't try
11864   // and capture any new variables. In addition when calculating potential
11865   // captures during transformation of nested lambdas, it is necessary to
11866   // have the LSI properly restored.
11867   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11868     assert(inTemplateInstantiation() &&
11869            "There should be an active template instantiation on the stack "
11870            "when instantiating a generic lambda!");
11871     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11872   } else {
11873     // Enter a new function scope
11874     PushFunctionScope();
11875   }
11876
11877   // Builtin functions cannot be defined.
11878   if (unsigned BuiltinID = FD->getBuiltinID()) {
11879     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11880         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11881       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11882       FD->setInvalidDecl();
11883     }
11884   }
11885
11886   // The return type of a function definition must be complete
11887   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11888   QualType ResultType = FD->getReturnType();
11889   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11890       !FD->isInvalidDecl() &&
11891       RequireCompleteType(FD->getLocation(), ResultType,
11892                           diag::err_func_def_incomplete_result))
11893     FD->setInvalidDecl();
11894
11895   if (FnBodyScope)
11896     PushDeclContext(FnBodyScope, FD);
11897
11898   // Check the validity of our function parameters
11899   CheckParmsForFunctionDef(FD->parameters(),
11900                            /*CheckParameterNames=*/true);
11901
11902   // Add non-parameter declarations already in the function to the current
11903   // scope.
11904   if (FnBodyScope) {
11905     for (Decl *NPD : FD->decls()) {
11906       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11907       if (!NonParmDecl)
11908         continue;
11909       assert(!isa<ParmVarDecl>(NonParmDecl) &&
11910              "parameters should not be in newly created FD yet");
11911
11912       // If the decl has a name, make it accessible in the current scope.
11913       if (NonParmDecl->getDeclName())
11914         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11915
11916       // Similarly, dive into enums and fish their constants out, making them
11917       // accessible in this scope.
11918       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11919         for (auto *EI : ED->enumerators())
11920           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11921       }
11922     }
11923   }
11924
11925   // Introduce our parameters into the function scope
11926   for (auto Param : FD->parameters()) {
11927     Param->setOwningFunction(FD);
11928
11929     // If this has an identifier, add it to the scope stack.
11930     if (Param->getIdentifier() && FnBodyScope) {
11931       CheckShadow(FnBodyScope, Param);
11932
11933       PushOnScopeChains(Param, FnBodyScope);
11934     }
11935   }
11936
11937   // Ensure that the function's exception specification is instantiated.
11938   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11939     ResolveExceptionSpec(D->getLocation(), FPT);
11940
11941   // dllimport cannot be applied to non-inline function definitions.
11942   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11943       !FD->isTemplateInstantiation()) {
11944     assert(!FD->hasAttr<DLLExportAttr>());
11945     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11946     FD->setInvalidDecl();
11947     return D;
11948   }
11949   // We want to attach documentation to original Decl (which might be
11950   // a function template).
11951   ActOnDocumentableDecl(D);
11952   if (getCurLexicalContext()->isObjCContainer() &&
11953       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11954       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11955     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11956
11957   return D;
11958 }
11959
11960 /// \brief Given the set of return statements within a function body,
11961 /// compute the variables that are subject to the named return value
11962 /// optimization.
11963 ///
11964 /// Each of the variables that is subject to the named return value
11965 /// optimization will be marked as NRVO variables in the AST, and any
11966 /// return statement that has a marked NRVO variable as its NRVO candidate can
11967 /// use the named return value optimization.
11968 ///
11969 /// This function applies a very simplistic algorithm for NRVO: if every return
11970 /// statement in the scope of a variable has the same NRVO candidate, that
11971 /// candidate is an NRVO variable.
11972 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11973   ReturnStmt **Returns = Scope->Returns.data();
11974
11975   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11976     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11977       if (!NRVOCandidate->isNRVOVariable())
11978         Returns[I]->setNRVOCandidate(nullptr);
11979     }
11980   }
11981 }
11982
11983 bool Sema::canDelayFunctionBody(const Declarator &D) {
11984   // We can't delay parsing the body of a constexpr function template (yet).
11985   if (D.getDeclSpec().isConstexprSpecified())
11986     return false;
11987
11988   // We can't delay parsing the body of a function template with a deduced
11989   // return type (yet).
11990   if (D.getDeclSpec().hasAutoTypeSpec()) {
11991     // If the placeholder introduces a non-deduced trailing return type,
11992     // we can still delay parsing it.
11993     if (D.getNumTypeObjects()) {
11994       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11995       if (Outer.Kind == DeclaratorChunk::Function &&
11996           Outer.Fun.hasTrailingReturnType()) {
11997         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11998         return Ty.isNull() || !Ty->isUndeducedType();
11999       }
12000     }
12001     return false;
12002   }
12003
12004   return true;
12005 }
12006
12007 bool Sema::canSkipFunctionBody(Decl *D) {
12008   // We cannot skip the body of a function (or function template) which is
12009   // constexpr, since we may need to evaluate its body in order to parse the
12010   // rest of the file.
12011   // We cannot skip the body of a function with an undeduced return type,
12012   // because any callers of that function need to know the type.
12013   if (const FunctionDecl *FD = D->getAsFunction())
12014     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12015       return false;
12016   return Consumer.shouldSkipFunctionBody(D);
12017 }
12018
12019 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12020   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12021     FD->setHasSkippedBody();
12022   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12023     MD->setHasSkippedBody();
12024   return Decl;
12025 }
12026
12027 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12028   return ActOnFinishFunctionBody(D, BodyArg, false);
12029 }
12030
12031 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12032                                     bool IsInstantiation) {
12033   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12034
12035   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12036   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12037
12038   if (getLangOpts().CoroutinesTS && getCurFunction()->CoroutinePromise)
12039     CheckCompletedCoroutineBody(FD, Body);
12040
12041   if (FD) {
12042     FD->setBody(Body);
12043
12044     if (getLangOpts().CPlusPlus14) {
12045       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12046           FD->getReturnType()->isUndeducedType()) {
12047         // If the function has a deduced result type but contains no 'return'
12048         // statements, the result type as written must be exactly 'auto', and
12049         // the deduced result type is 'void'.
12050         if (!FD->getReturnType()->getAs<AutoType>()) {
12051           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12052               << FD->getReturnType();
12053           FD->setInvalidDecl();
12054         } else {
12055           // Substitute 'void' for the 'auto' in the type.
12056           TypeLoc ResultType = getReturnTypeLoc(FD);
12057           Context.adjustDeducedFunctionResultType(
12058               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12059         }
12060       }
12061     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12062       // In C++11, we don't use 'auto' deduction rules for lambda call
12063       // operators because we don't support return type deduction.
12064       auto *LSI = getCurLambda();
12065       if (LSI->HasImplicitReturnType) {
12066         deduceClosureReturnType(*LSI);
12067
12068         // C++11 [expr.prim.lambda]p4:
12069         //   [...] if there are no return statements in the compound-statement
12070         //   [the deduced type is] the type void
12071         QualType RetType =
12072             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12073
12074         // Update the return type to the deduced type.
12075         const FunctionProtoType *Proto =
12076             FD->getType()->getAs<FunctionProtoType>();
12077         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12078                                             Proto->getExtProtoInfo()));
12079       }
12080     }
12081
12082     // The only way to be included in UndefinedButUsed is if there is an
12083     // ODR use before the definition. Avoid the expensive map lookup if this
12084     // is the first declaration.
12085     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12086       if (!FD->isExternallyVisible())
12087         UndefinedButUsed.erase(FD);
12088       else if (FD->isInlined() &&
12089                !LangOpts.GNUInline &&
12090                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12091         UndefinedButUsed.erase(FD);
12092     }
12093
12094     // If the function implicitly returns zero (like 'main') or is naked,
12095     // don't complain about missing return statements.
12096     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12097       WP.disableCheckFallThrough();
12098
12099     // MSVC permits the use of pure specifier (=0) on function definition,
12100     // defined at class scope, warn about this non-standard construct.
12101     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12102       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12103
12104     if (!FD->isInvalidDecl()) {
12105       // Don't diagnose unused parameters of defaulted or deleted functions.
12106       if (!FD->isDeleted() && !FD->isDefaulted())
12107         DiagnoseUnusedParameters(FD->parameters());
12108       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12109                                              FD->getReturnType(), FD);
12110
12111       // If this is a structor, we need a vtable.
12112       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12113         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12114       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12115         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12116
12117       // Try to apply the named return value optimization. We have to check
12118       // if we can do this here because lambdas keep return statements around
12119       // to deduce an implicit return type.
12120       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12121           !FD->isDependentContext())
12122         computeNRVO(Body, getCurFunction());
12123     }
12124
12125     // GNU warning -Wmissing-prototypes:
12126     //   Warn if a global function is defined without a previous
12127     //   prototype declaration. This warning is issued even if the
12128     //   definition itself provides a prototype. The aim is to detect
12129     //   global functions that fail to be declared in header files.
12130     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12131     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12132       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12133
12134       if (PossibleZeroParamPrototype) {
12135         // We found a declaration that is not a prototype,
12136         // but that could be a zero-parameter prototype
12137         if (TypeSourceInfo *TI =
12138                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12139           TypeLoc TL = TI->getTypeLoc();
12140           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12141             Diag(PossibleZeroParamPrototype->getLocation(),
12142                  diag::note_declaration_not_a_prototype)
12143                 << PossibleZeroParamPrototype
12144                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12145         }
12146       }
12147
12148       // GNU warning -Wstrict-prototypes
12149       //   Warn if K&R function is defined without a previous declaration.
12150       //   This warning is issued only if the definition itself does not provide
12151       //   a prototype. Only K&R definitions do not provide a prototype.
12152       //   An empty list in a function declarator that is part of a definition
12153       //   of that function specifies that the function has no parameters
12154       //   (C99 6.7.5.3p14)
12155       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12156           !LangOpts.CPlusPlus) {
12157         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12158         TypeLoc TL = TI->getTypeLoc();
12159         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12160         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
12161       }
12162     }
12163
12164     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12165       const CXXMethodDecl *KeyFunction;
12166       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12167           MD->isVirtual() &&
12168           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12169           MD == KeyFunction->getCanonicalDecl()) {
12170         // Update the key-function state if necessary for this ABI.
12171         if (FD->isInlined() &&
12172             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12173           Context.setNonKeyFunction(MD);
12174
12175           // If the newly-chosen key function is already defined, then we
12176           // need to mark the vtable as used retroactively.
12177           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12178           const FunctionDecl *Definition;
12179           if (KeyFunction && KeyFunction->isDefined(Definition))
12180             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12181         } else {
12182           // We just defined they key function; mark the vtable as used.
12183           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12184         }
12185       }
12186     }
12187
12188     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12189            "Function parsing confused");
12190   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12191     assert(MD == getCurMethodDecl() && "Method parsing confused");
12192     MD->setBody(Body);
12193     if (!MD->isInvalidDecl()) {
12194       DiagnoseUnusedParameters(MD->parameters());
12195       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12196                                              MD->getReturnType(), MD);
12197
12198       if (Body)
12199         computeNRVO(Body, getCurFunction());
12200     }
12201     if (getCurFunction()->ObjCShouldCallSuper) {
12202       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12203         << MD->getSelector().getAsString();
12204       getCurFunction()->ObjCShouldCallSuper = false;
12205     }
12206     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12207       const ObjCMethodDecl *InitMethod = nullptr;
12208       bool isDesignated =
12209           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12210       assert(isDesignated && InitMethod);
12211       (void)isDesignated;
12212
12213       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12214         auto IFace = MD->getClassInterface();
12215         if (!IFace)
12216           return false;
12217         auto SuperD = IFace->getSuperClass();
12218         if (!SuperD)
12219           return false;
12220         return SuperD->getIdentifier() ==
12221             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12222       };
12223       // Don't issue this warning for unavailable inits or direct subclasses
12224       // of NSObject.
12225       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12226         Diag(MD->getLocation(),
12227              diag::warn_objc_designated_init_missing_super_call);
12228         Diag(InitMethod->getLocation(),
12229              diag::note_objc_designated_init_marked_here);
12230       }
12231       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12232     }
12233     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12234       // Don't issue this warning for unavaialable inits.
12235       if (!MD->isUnavailable())
12236         Diag(MD->getLocation(),
12237              diag::warn_objc_secondary_init_missing_init_call);
12238       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12239     }
12240   } else {
12241     return nullptr;
12242   }
12243
12244   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12245     DiagnoseUnguardedAvailabilityViolations(dcl);
12246
12247   assert(!getCurFunction()->ObjCShouldCallSuper &&
12248          "This should only be set for ObjC methods, which should have been "
12249          "handled in the block above.");
12250
12251   // Verify and clean out per-function state.
12252   if (Body && (!FD || !FD->isDefaulted())) {
12253     // C++ constructors that have function-try-blocks can't have return
12254     // statements in the handlers of that block. (C++ [except.handle]p14)
12255     // Verify this.
12256     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12257       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12258
12259     // Verify that gotos and switch cases don't jump into scopes illegally.
12260     if (getCurFunction()->NeedsScopeChecking() &&
12261         !PP.isCodeCompletionEnabled())
12262       DiagnoseInvalidJumps(Body);
12263
12264     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12265       if (!Destructor->getParent()->isDependentType())
12266         CheckDestructor(Destructor);
12267
12268       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12269                                              Destructor->getParent());
12270     }
12271
12272     // If any errors have occurred, clear out any temporaries that may have
12273     // been leftover. This ensures that these temporaries won't be picked up for
12274     // deletion in some later function.
12275     if (getDiagnostics().hasErrorOccurred() ||
12276         getDiagnostics().getSuppressAllDiagnostics()) {
12277       DiscardCleanupsInEvaluationContext();
12278     }
12279     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12280         !isa<FunctionTemplateDecl>(dcl)) {
12281       // Since the body is valid, issue any analysis-based warnings that are
12282       // enabled.
12283       ActivePolicy = &WP;
12284     }
12285
12286     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12287         (!CheckConstexprFunctionDecl(FD) ||
12288          !CheckConstexprFunctionBody(FD, Body)))
12289       FD->setInvalidDecl();
12290
12291     if (FD && FD->hasAttr<NakedAttr>()) {
12292       for (const Stmt *S : Body->children()) {
12293         // Allow local register variables without initializer as they don't
12294         // require prologue.
12295         bool RegisterVariables = false;
12296         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12297           for (const auto *Decl : DS->decls()) {
12298             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12299               RegisterVariables =
12300                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12301               if (!RegisterVariables)
12302                 break;
12303             }
12304           }
12305         }
12306         if (RegisterVariables)
12307           continue;
12308         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12309           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12310           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12311           FD->setInvalidDecl();
12312           break;
12313         }
12314       }
12315     }
12316
12317     assert(ExprCleanupObjects.size() ==
12318                ExprEvalContexts.back().NumCleanupObjects &&
12319            "Leftover temporaries in function");
12320     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12321     assert(MaybeODRUseExprs.empty() &&
12322            "Leftover expressions for odr-use checking");
12323   }
12324
12325   if (!IsInstantiation)
12326     PopDeclContext();
12327
12328   PopFunctionScopeInfo(ActivePolicy, dcl);
12329   // If any errors have occurred, clear out any temporaries that may have
12330   // been leftover. This ensures that these temporaries won't be picked up for
12331   // deletion in some later function.
12332   if (getDiagnostics().hasErrorOccurred()) {
12333     DiscardCleanupsInEvaluationContext();
12334   }
12335
12336   return dcl;
12337 }
12338
12339 /// When we finish delayed parsing of an attribute, we must attach it to the
12340 /// relevant Decl.
12341 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12342                                        ParsedAttributes &Attrs) {
12343   // Always attach attributes to the underlying decl.
12344   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12345     D = TD->getTemplatedDecl();
12346   ProcessDeclAttributeList(S, D, Attrs.getList());
12347
12348   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12349     if (Method->isStatic())
12350       checkThisInStaticMemberFunctionAttributes(Method);
12351 }
12352
12353 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12354 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12355 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12356                                           IdentifierInfo &II, Scope *S) {
12357   // Before we produce a declaration for an implicitly defined
12358   // function, see whether there was a locally-scoped declaration of
12359   // this name as a function or variable. If so, use that
12360   // (non-visible) declaration, and complain about it.
12361   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12362     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12363     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12364     return ExternCPrev;
12365   }
12366
12367   // Extension in C99.  Legal in C90, but warn about it.
12368   unsigned diag_id;
12369   if (II.getName().startswith("__builtin_"))
12370     diag_id = diag::warn_builtin_unknown;
12371   else if (getLangOpts().C99)
12372     diag_id = diag::ext_implicit_function_decl;
12373   else
12374     diag_id = diag::warn_implicit_function_decl;
12375   Diag(Loc, diag_id) << &II;
12376
12377   // Because typo correction is expensive, only do it if the implicit
12378   // function declaration is going to be treated as an error.
12379   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12380     TypoCorrection Corrected;
12381     if (S &&
12382         (Corrected = CorrectTypo(
12383              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12384              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12385       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12386                    /*ErrorRecovery*/false);
12387   }
12388
12389   // Set a Declarator for the implicit definition: int foo();
12390   const char *Dummy;
12391   AttributeFactory attrFactory;
12392   DeclSpec DS(attrFactory);
12393   unsigned DiagID;
12394   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12395                                   Context.getPrintingPolicy());
12396   (void)Error; // Silence warning.
12397   assert(!Error && "Error setting up implicit decl!");
12398   SourceLocation NoLoc;
12399   Declarator D(DS, Declarator::BlockContext);
12400   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12401                                              /*IsAmbiguous=*/false,
12402                                              /*LParenLoc=*/NoLoc,
12403                                              /*Params=*/nullptr,
12404                                              /*NumParams=*/0,
12405                                              /*EllipsisLoc=*/NoLoc,
12406                                              /*RParenLoc=*/NoLoc,
12407                                              /*TypeQuals=*/0,
12408                                              /*RefQualifierIsLvalueRef=*/true,
12409                                              /*RefQualifierLoc=*/NoLoc,
12410                                              /*ConstQualifierLoc=*/NoLoc,
12411                                              /*VolatileQualifierLoc=*/NoLoc,
12412                                              /*RestrictQualifierLoc=*/NoLoc,
12413                                              /*MutableLoc=*/NoLoc,
12414                                              EST_None,
12415                                              /*ESpecRange=*/SourceRange(),
12416                                              /*Exceptions=*/nullptr,
12417                                              /*ExceptionRanges=*/nullptr,
12418                                              /*NumExceptions=*/0,
12419                                              /*NoexceptExpr=*/nullptr,
12420                                              /*ExceptionSpecTokens=*/nullptr,
12421                                              /*DeclsInPrototype=*/None,
12422                                              Loc, Loc, D),
12423                 DS.getAttributes(),
12424                 SourceLocation());
12425   D.SetIdentifier(&II, Loc);
12426
12427   // Insert this function into translation-unit scope.
12428
12429   DeclContext *PrevDC = CurContext;
12430   CurContext = Context.getTranslationUnitDecl();
12431
12432   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12433   FD->setImplicit();
12434
12435   CurContext = PrevDC;
12436
12437   AddKnownFunctionAttributes(FD);
12438
12439   return FD;
12440 }
12441
12442 /// \brief Adds any function attributes that we know a priori based on
12443 /// the declaration of this function.
12444 ///
12445 /// These attributes can apply both to implicitly-declared builtins
12446 /// (like __builtin___printf_chk) or to library-declared functions
12447 /// like NSLog or printf.
12448 ///
12449 /// We need to check for duplicate attributes both here and where user-written
12450 /// attributes are applied to declarations.
12451 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12452   if (FD->isInvalidDecl())
12453     return;
12454
12455   // If this is a built-in function, map its builtin attributes to
12456   // actual attributes.
12457   if (unsigned BuiltinID = FD->getBuiltinID()) {
12458     // Handle printf-formatting attributes.
12459     unsigned FormatIdx;
12460     bool HasVAListArg;
12461     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12462       if (!FD->hasAttr<FormatAttr>()) {
12463         const char *fmt = "printf";
12464         unsigned int NumParams = FD->getNumParams();
12465         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12466             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12467           fmt = "NSString";
12468         FD->addAttr(FormatAttr::CreateImplicit(Context,
12469                                                &Context.Idents.get(fmt),
12470                                                FormatIdx+1,
12471                                                HasVAListArg ? 0 : FormatIdx+2,
12472                                                FD->getLocation()));
12473       }
12474     }
12475     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12476                                              HasVAListArg)) {
12477      if (!FD->hasAttr<FormatAttr>())
12478        FD->addAttr(FormatAttr::CreateImplicit(Context,
12479                                               &Context.Idents.get("scanf"),
12480                                               FormatIdx+1,
12481                                               HasVAListArg ? 0 : FormatIdx+2,
12482                                               FD->getLocation()));
12483     }
12484
12485     // Mark const if we don't care about errno and that is the only
12486     // thing preventing the function from being const. This allows
12487     // IRgen to use LLVM intrinsics for such functions.
12488     if (!getLangOpts().MathErrno &&
12489         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12490       if (!FD->hasAttr<ConstAttr>())
12491         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12492     }
12493
12494     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12495         !FD->hasAttr<ReturnsTwiceAttr>())
12496       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12497                                          FD->getLocation()));
12498     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12499       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12500     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12501       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12502     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12503       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12504     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12505         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12506       // Add the appropriate attribute, depending on the CUDA compilation mode
12507       // and which target the builtin belongs to. For example, during host
12508       // compilation, aux builtins are __device__, while the rest are __host__.
12509       if (getLangOpts().CUDAIsDevice !=
12510           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12511         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12512       else
12513         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12514     }
12515   }
12516
12517   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12518   // throw, add an implicit nothrow attribute to any extern "C" function we come
12519   // across.
12520   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12521       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12522     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12523     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12524       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12525   }
12526
12527   IdentifierInfo *Name = FD->getIdentifier();
12528   if (!Name)
12529     return;
12530   if ((!getLangOpts().CPlusPlus &&
12531        FD->getDeclContext()->isTranslationUnit()) ||
12532       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12533        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12534        LinkageSpecDecl::lang_c)) {
12535     // Okay: this could be a libc/libm/Objective-C function we know
12536     // about.
12537   } else
12538     return;
12539
12540   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12541     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12542     // target-specific builtins, perhaps?
12543     if (!FD->hasAttr<FormatAttr>())
12544       FD->addAttr(FormatAttr::CreateImplicit(Context,
12545                                              &Context.Idents.get("printf"), 2,
12546                                              Name->isStr("vasprintf") ? 0 : 3,
12547                                              FD->getLocation()));
12548   }
12549
12550   if (Name->isStr("__CFStringMakeConstantString")) {
12551     // We already have a __builtin___CFStringMakeConstantString,
12552     // but builds that use -fno-constant-cfstrings don't go through that.
12553     if (!FD->hasAttr<FormatArgAttr>())
12554       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12555                                                 FD->getLocation()));
12556   }
12557 }
12558
12559 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12560                                     TypeSourceInfo *TInfo) {
12561   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12562   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12563
12564   if (!TInfo) {
12565     assert(D.isInvalidType() && "no declarator info for valid type");
12566     TInfo = Context.getTrivialTypeSourceInfo(T);
12567   }
12568
12569   // Scope manipulation handled by caller.
12570   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12571                                            D.getLocStart(),
12572                                            D.getIdentifierLoc(),
12573                                            D.getIdentifier(),
12574                                            TInfo);
12575
12576   // Bail out immediately if we have an invalid declaration.
12577   if (D.isInvalidType()) {
12578     NewTD->setInvalidDecl();
12579     return NewTD;
12580   }
12581
12582   if (D.getDeclSpec().isModulePrivateSpecified()) {
12583     if (CurContext->isFunctionOrMethod())
12584       Diag(NewTD->getLocation(), diag::err_module_private_local)
12585         << 2 << NewTD->getDeclName()
12586         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12587         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12588     else
12589       NewTD->setModulePrivate();
12590   }
12591
12592   // C++ [dcl.typedef]p8:
12593   //   If the typedef declaration defines an unnamed class (or
12594   //   enum), the first typedef-name declared by the declaration
12595   //   to be that class type (or enum type) is used to denote the
12596   //   class type (or enum type) for linkage purposes only.
12597   // We need to check whether the type was declared in the declaration.
12598   switch (D.getDeclSpec().getTypeSpecType()) {
12599   case TST_enum:
12600   case TST_struct:
12601   case TST_interface:
12602   case TST_union:
12603   case TST_class: {
12604     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12605     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12606     break;
12607   }
12608
12609   default:
12610     break;
12611   }
12612
12613   return NewTD;
12614 }
12615
12616 /// \brief Check that this is a valid underlying type for an enum declaration.
12617 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12618   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12619   QualType T = TI->getType();
12620
12621   if (T->isDependentType())
12622     return false;
12623
12624   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12625     if (BT->isInteger())
12626       return false;
12627
12628   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12629   return true;
12630 }
12631
12632 /// Check whether this is a valid redeclaration of a previous enumeration.
12633 /// \return true if the redeclaration was invalid.
12634 bool Sema::CheckEnumRedeclaration(
12635     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12636     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12637   bool IsFixed = !EnumUnderlyingTy.isNull();
12638
12639   if (IsScoped != Prev->isScoped()) {
12640     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12641       << Prev->isScoped();
12642     Diag(Prev->getLocation(), diag::note_previous_declaration);
12643     return true;
12644   }
12645
12646   if (IsFixed && Prev->isFixed()) {
12647     if (!EnumUnderlyingTy->isDependentType() &&
12648         !Prev->getIntegerType()->isDependentType() &&
12649         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12650                                         Prev->getIntegerType())) {
12651       // TODO: Highlight the underlying type of the redeclaration.
12652       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12653         << EnumUnderlyingTy << Prev->getIntegerType();
12654       Diag(Prev->getLocation(), diag::note_previous_declaration)
12655           << Prev->getIntegerTypeRange();
12656       return true;
12657     }
12658   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12659     ;
12660   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12661     ;
12662   } else if (IsFixed != Prev->isFixed()) {
12663     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12664       << Prev->isFixed();
12665     Diag(Prev->getLocation(), diag::note_previous_declaration);
12666     return true;
12667   }
12668
12669   return false;
12670 }
12671
12672 /// \brief Get diagnostic %select index for tag kind for
12673 /// redeclaration diagnostic message.
12674 /// WARNING: Indexes apply to particular diagnostics only!
12675 ///
12676 /// \returns diagnostic %select index.
12677 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12678   switch (Tag) {
12679   case TTK_Struct: return 0;
12680   case TTK_Interface: return 1;
12681   case TTK_Class:  return 2;
12682   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12683   }
12684 }
12685
12686 /// \brief Determine if tag kind is a class-key compatible with
12687 /// class for redeclaration (class, struct, or __interface).
12688 ///
12689 /// \returns true iff the tag kind is compatible.
12690 static bool isClassCompatTagKind(TagTypeKind Tag)
12691 {
12692   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12693 }
12694
12695 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12696                                              TagTypeKind TTK) {
12697   if (isa<TypedefDecl>(PrevDecl))
12698     return NTK_Typedef;
12699   else if (isa<TypeAliasDecl>(PrevDecl))
12700     return NTK_TypeAlias;
12701   else if (isa<ClassTemplateDecl>(PrevDecl))
12702     return NTK_Template;
12703   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12704     return NTK_TypeAliasTemplate;
12705   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12706     return NTK_TemplateTemplateArgument;
12707   switch (TTK) {
12708   case TTK_Struct:
12709   case TTK_Interface:
12710   case TTK_Class:
12711     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12712   case TTK_Union:
12713     return NTK_NonUnion;
12714   case TTK_Enum:
12715     return NTK_NonEnum;
12716   }
12717   llvm_unreachable("invalid TTK");
12718 }
12719
12720 /// \brief Determine whether a tag with a given kind is acceptable
12721 /// as a redeclaration of the given tag declaration.
12722 ///
12723 /// \returns true if the new tag kind is acceptable, false otherwise.
12724 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12725                                         TagTypeKind NewTag, bool isDefinition,
12726                                         SourceLocation NewTagLoc,
12727                                         const IdentifierInfo *Name) {
12728   // C++ [dcl.type.elab]p3:
12729   //   The class-key or enum keyword present in the
12730   //   elaborated-type-specifier shall agree in kind with the
12731   //   declaration to which the name in the elaborated-type-specifier
12732   //   refers. This rule also applies to the form of
12733   //   elaborated-type-specifier that declares a class-name or
12734   //   friend class since it can be construed as referring to the
12735   //   definition of the class. Thus, in any
12736   //   elaborated-type-specifier, the enum keyword shall be used to
12737   //   refer to an enumeration (7.2), the union class-key shall be
12738   //   used to refer to a union (clause 9), and either the class or
12739   //   struct class-key shall be used to refer to a class (clause 9)
12740   //   declared using the class or struct class-key.
12741   TagTypeKind OldTag = Previous->getTagKind();
12742   if (!isDefinition || !isClassCompatTagKind(NewTag))
12743     if (OldTag == NewTag)
12744       return true;
12745
12746   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12747     // Warn about the struct/class tag mismatch.
12748     bool isTemplate = false;
12749     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12750       isTemplate = Record->getDescribedClassTemplate();
12751
12752     if (inTemplateInstantiation()) {
12753       // In a template instantiation, do not offer fix-its for tag mismatches
12754       // since they usually mess up the template instead of fixing the problem.
12755       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12756         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12757         << getRedeclDiagFromTagKind(OldTag);
12758       return true;
12759     }
12760
12761     if (isDefinition) {
12762       // On definitions, check previous tags and issue a fix-it for each
12763       // one that doesn't match the current tag.
12764       if (Previous->getDefinition()) {
12765         // Don't suggest fix-its for redefinitions.
12766         return true;
12767       }
12768
12769       bool previousMismatch = false;
12770       for (auto I : Previous->redecls()) {
12771         if (I->getTagKind() != NewTag) {
12772           if (!previousMismatch) {
12773             previousMismatch = true;
12774             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12775               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12776               << getRedeclDiagFromTagKind(I->getTagKind());
12777           }
12778           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12779             << getRedeclDiagFromTagKind(NewTag)
12780             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12781                  TypeWithKeyword::getTagTypeKindName(NewTag));
12782         }
12783       }
12784       return true;
12785     }
12786
12787     // Check for a previous definition.  If current tag and definition
12788     // are same type, do nothing.  If no definition, but disagree with
12789     // with previous tag type, give a warning, but no fix-it.
12790     const TagDecl *Redecl = Previous->getDefinition() ?
12791                             Previous->getDefinition() : Previous;
12792     if (Redecl->getTagKind() == NewTag) {
12793       return true;
12794     }
12795
12796     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12797       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12798       << getRedeclDiagFromTagKind(OldTag);
12799     Diag(Redecl->getLocation(), diag::note_previous_use);
12800
12801     // If there is a previous definition, suggest a fix-it.
12802     if (Previous->getDefinition()) {
12803         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12804           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12805           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12806                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12807     }
12808
12809     return true;
12810   }
12811   return false;
12812 }
12813
12814 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12815 /// from an outer enclosing namespace or file scope inside a friend declaration.
12816 /// This should provide the commented out code in the following snippet:
12817 ///   namespace N {
12818 ///     struct X;
12819 ///     namespace M {
12820 ///       struct Y { friend struct /*N::*/ X; };
12821 ///     }
12822 ///   }
12823 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12824                                          SourceLocation NameLoc) {
12825   // While the decl is in a namespace, do repeated lookup of that name and see
12826   // if we get the same namespace back.  If we do not, continue until
12827   // translation unit scope, at which point we have a fully qualified NNS.
12828   SmallVector<IdentifierInfo *, 4> Namespaces;
12829   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12830   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12831     // This tag should be declared in a namespace, which can only be enclosed by
12832     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12833     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12834     if (!Namespace || Namespace->isAnonymousNamespace())
12835       return FixItHint();
12836     IdentifierInfo *II = Namespace->getIdentifier();
12837     Namespaces.push_back(II);
12838     NamedDecl *Lookup = SemaRef.LookupSingleName(
12839         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12840     if (Lookup == Namespace)
12841       break;
12842   }
12843
12844   // Once we have all the namespaces, reverse them to go outermost first, and
12845   // build an NNS.
12846   SmallString<64> Insertion;
12847   llvm::raw_svector_ostream OS(Insertion);
12848   if (DC->isTranslationUnit())
12849     OS << "::";
12850   std::reverse(Namespaces.begin(), Namespaces.end());
12851   for (auto *II : Namespaces)
12852     OS << II->getName() << "::";
12853   return FixItHint::CreateInsertion(NameLoc, Insertion);
12854 }
12855
12856 /// \brief Determine whether a tag originally declared in context \p OldDC can
12857 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12858 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12859 /// using-declaration).
12860 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12861                                          DeclContext *NewDC) {
12862   OldDC = OldDC->getRedeclContext();
12863   NewDC = NewDC->getRedeclContext();
12864
12865   if (OldDC->Equals(NewDC))
12866     return true;
12867
12868   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12869   // encloses the other).
12870   if (S.getLangOpts().MSVCCompat &&
12871       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12872     return true;
12873
12874   return false;
12875 }
12876
12877 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12878 /// former case, Name will be non-null.  In the later case, Name will be null.
12879 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12880 /// reference/declaration/definition of a tag.
12881 ///
12882 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12883 /// trailing-type-specifier) other than one in an alias-declaration.
12884 ///
12885 /// \param SkipBody If non-null, will be set to indicate if the caller should
12886 /// skip the definition of this tag and treat it as if it were a declaration.
12887 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12888                      SourceLocation KWLoc, CXXScopeSpec &SS,
12889                      IdentifierInfo *Name, SourceLocation NameLoc,
12890                      AttributeList *Attr, AccessSpecifier AS,
12891                      SourceLocation ModulePrivateLoc,
12892                      MultiTemplateParamsArg TemplateParameterLists,
12893                      bool &OwnedDecl, bool &IsDependent,
12894                      SourceLocation ScopedEnumKWLoc,
12895                      bool ScopedEnumUsesClassTag,
12896                      TypeResult UnderlyingType,
12897                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12898   // If this is not a definition, it must have a name.
12899   IdentifierInfo *OrigName = Name;
12900   assert((Name != nullptr || TUK == TUK_Definition) &&
12901          "Nameless record must be a definition!");
12902   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12903
12904   OwnedDecl = false;
12905   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12906   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12907
12908   // FIXME: Check member specializations more carefully.
12909   bool isMemberSpecialization = false;
12910   bool Invalid = false;
12911
12912   // We only need to do this matching if we have template parameters
12913   // or a scope specifier, which also conveniently avoids this work
12914   // for non-C++ cases.
12915   if (TemplateParameterLists.size() > 0 ||
12916       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12917     if (TemplateParameterList *TemplateParams =
12918             MatchTemplateParametersToScopeSpecifier(
12919                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12920                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
12921       if (Kind == TTK_Enum) {
12922         Diag(KWLoc, diag::err_enum_template);
12923         return nullptr;
12924       }
12925
12926       if (TemplateParams->size() > 0) {
12927         // This is a declaration or definition of a class template (which may
12928         // be a member of another template).
12929
12930         if (Invalid)
12931           return nullptr;
12932
12933         OwnedDecl = false;
12934         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12935                                                SS, Name, NameLoc, Attr,
12936                                                TemplateParams, AS,
12937                                                ModulePrivateLoc,
12938                                                /*FriendLoc*/SourceLocation(),
12939                                                TemplateParameterLists.size()-1,
12940                                                TemplateParameterLists.data(),
12941                                                SkipBody);
12942         return Result.get();
12943       } else {
12944         // The "template<>" header is extraneous.
12945         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12946           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12947         isMemberSpecialization = true;
12948       }
12949     }
12950   }
12951
12952   // Figure out the underlying type if this a enum declaration. We need to do
12953   // this early, because it's needed to detect if this is an incompatible
12954   // redeclaration.
12955   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12956   bool EnumUnderlyingIsImplicit = false;
12957
12958   if (Kind == TTK_Enum) {
12959     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12960       // No underlying type explicitly specified, or we failed to parse the
12961       // type, default to int.
12962       EnumUnderlying = Context.IntTy.getTypePtr();
12963     else if (UnderlyingType.get()) {
12964       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12965       // integral type; any cv-qualification is ignored.
12966       TypeSourceInfo *TI = nullptr;
12967       GetTypeFromParser(UnderlyingType.get(), &TI);
12968       EnumUnderlying = TI;
12969
12970       if (CheckEnumUnderlyingType(TI))
12971         // Recover by falling back to int.
12972         EnumUnderlying = Context.IntTy.getTypePtr();
12973
12974       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12975                                           UPPC_FixedUnderlyingType))
12976         EnumUnderlying = Context.IntTy.getTypePtr();
12977
12978     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12979       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12980         // Microsoft enums are always of int type.
12981         EnumUnderlying = Context.IntTy.getTypePtr();
12982         EnumUnderlyingIsImplicit = true;
12983       }
12984     }
12985   }
12986
12987   DeclContext *SearchDC = CurContext;
12988   DeclContext *DC = CurContext;
12989   bool isStdBadAlloc = false;
12990   bool isStdAlignValT = false;
12991
12992   RedeclarationKind Redecl = ForRedeclaration;
12993   if (TUK == TUK_Friend || TUK == TUK_Reference)
12994     Redecl = NotForRedeclaration;
12995
12996   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12997   if (Name && SS.isNotEmpty()) {
12998     // We have a nested-name tag ('struct foo::bar').
12999
13000     // Check for invalid 'foo::'.
13001     if (SS.isInvalid()) {
13002       Name = nullptr;
13003       goto CreateNewDecl;
13004     }
13005
13006     // If this is a friend or a reference to a class in a dependent
13007     // context, don't try to make a decl for it.
13008     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13009       DC = computeDeclContext(SS, false);
13010       if (!DC) {
13011         IsDependent = true;
13012         return nullptr;
13013       }
13014     } else {
13015       DC = computeDeclContext(SS, true);
13016       if (!DC) {
13017         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13018           << SS.getRange();
13019         return nullptr;
13020       }
13021     }
13022
13023     if (RequireCompleteDeclContext(SS, DC))
13024       return nullptr;
13025
13026     SearchDC = DC;
13027     // Look-up name inside 'foo::'.
13028     LookupQualifiedName(Previous, DC);
13029
13030     if (Previous.isAmbiguous())
13031       return nullptr;
13032
13033     if (Previous.empty()) {
13034       // Name lookup did not find anything. However, if the
13035       // nested-name-specifier refers to the current instantiation,
13036       // and that current instantiation has any dependent base
13037       // classes, we might find something at instantiation time: treat
13038       // this as a dependent elaborated-type-specifier.
13039       // But this only makes any sense for reference-like lookups.
13040       if (Previous.wasNotFoundInCurrentInstantiation() &&
13041           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13042         IsDependent = true;
13043         return nullptr;
13044       }
13045
13046       // A tag 'foo::bar' must already exist.
13047       Diag(NameLoc, diag::err_not_tag_in_scope)
13048         << Kind << Name << DC << SS.getRange();
13049       Name = nullptr;
13050       Invalid = true;
13051       goto CreateNewDecl;
13052     }
13053   } else if (Name) {
13054     // C++14 [class.mem]p14:
13055     //   If T is the name of a class, then each of the following shall have a
13056     //   name different from T:
13057     //    -- every member of class T that is itself a type
13058     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13059         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13060       return nullptr;
13061
13062     // If this is a named struct, check to see if there was a previous forward
13063     // declaration or definition.
13064     // FIXME: We're looking into outer scopes here, even when we
13065     // shouldn't be. Doing so can result in ambiguities that we
13066     // shouldn't be diagnosing.
13067     LookupName(Previous, S);
13068
13069     // When declaring or defining a tag, ignore ambiguities introduced
13070     // by types using'ed into this scope.
13071     if (Previous.isAmbiguous() &&
13072         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13073       LookupResult::Filter F = Previous.makeFilter();
13074       while (F.hasNext()) {
13075         NamedDecl *ND = F.next();
13076         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13077                 SearchDC->getRedeclContext()))
13078           F.erase();
13079       }
13080       F.done();
13081     }
13082
13083     // C++11 [namespace.memdef]p3:
13084     //   If the name in a friend declaration is neither qualified nor
13085     //   a template-id and the declaration is a function or an
13086     //   elaborated-type-specifier, the lookup to determine whether
13087     //   the entity has been previously declared shall not consider
13088     //   any scopes outside the innermost enclosing namespace.
13089     //
13090     // MSVC doesn't implement the above rule for types, so a friend tag
13091     // declaration may be a redeclaration of a type declared in an enclosing
13092     // scope.  They do implement this rule for friend functions.
13093     //
13094     // Does it matter that this should be by scope instead of by
13095     // semantic context?
13096     if (!Previous.empty() && TUK == TUK_Friend) {
13097       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13098       LookupResult::Filter F = Previous.makeFilter();
13099       bool FriendSawTagOutsideEnclosingNamespace = false;
13100       while (F.hasNext()) {
13101         NamedDecl *ND = F.next();
13102         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13103         if (DC->isFileContext() &&
13104             !EnclosingNS->Encloses(ND->getDeclContext())) {
13105           if (getLangOpts().MSVCCompat)
13106             FriendSawTagOutsideEnclosingNamespace = true;
13107           else
13108             F.erase();
13109         }
13110       }
13111       F.done();
13112
13113       // Diagnose this MSVC extension in the easy case where lookup would have
13114       // unambiguously found something outside the enclosing namespace.
13115       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13116         NamedDecl *ND = Previous.getFoundDecl();
13117         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13118             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13119       }
13120     }
13121
13122     // Note:  there used to be some attempt at recovery here.
13123     if (Previous.isAmbiguous())
13124       return nullptr;
13125
13126     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13127       // FIXME: This makes sure that we ignore the contexts associated
13128       // with C structs, unions, and enums when looking for a matching
13129       // tag declaration or definition. See the similar lookup tweak
13130       // in Sema::LookupName; is there a better way to deal with this?
13131       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13132         SearchDC = SearchDC->getParent();
13133     }
13134   }
13135
13136   if (Previous.isSingleResult() &&
13137       Previous.getFoundDecl()->isTemplateParameter()) {
13138     // Maybe we will complain about the shadowed template parameter.
13139     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13140     // Just pretend that we didn't see the previous declaration.
13141     Previous.clear();
13142   }
13143
13144   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13145       DC->Equals(getStdNamespace())) {
13146     if (Name->isStr("bad_alloc")) {
13147       // This is a declaration of or a reference to "std::bad_alloc".
13148       isStdBadAlloc = true;
13149
13150       // If std::bad_alloc has been implicitly declared (but made invisible to
13151       // name lookup), fill in this implicit declaration as the previous
13152       // declaration, so that the declarations get chained appropriately.
13153       if (Previous.empty() && StdBadAlloc)
13154         Previous.addDecl(getStdBadAlloc());
13155     } else if (Name->isStr("align_val_t")) {
13156       isStdAlignValT = true;
13157       if (Previous.empty() && StdAlignValT)
13158         Previous.addDecl(getStdAlignValT());
13159     }
13160   }
13161
13162   // If we didn't find a previous declaration, and this is a reference
13163   // (or friend reference), move to the correct scope.  In C++, we
13164   // also need to do a redeclaration lookup there, just in case
13165   // there's a shadow friend decl.
13166   if (Name && Previous.empty() &&
13167       (TUK == TUK_Reference || TUK == TUK_Friend)) {
13168     if (Invalid) goto CreateNewDecl;
13169     assert(SS.isEmpty());
13170
13171     if (TUK == TUK_Reference) {
13172       // C++ [basic.scope.pdecl]p5:
13173       //   -- for an elaborated-type-specifier of the form
13174       //
13175       //          class-key identifier
13176       //
13177       //      if the elaborated-type-specifier is used in the
13178       //      decl-specifier-seq or parameter-declaration-clause of a
13179       //      function defined in namespace scope, the identifier is
13180       //      declared as a class-name in the namespace that contains
13181       //      the declaration; otherwise, except as a friend
13182       //      declaration, the identifier is declared in the smallest
13183       //      non-class, non-function-prototype scope that contains the
13184       //      declaration.
13185       //
13186       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13187       // C structs and unions.
13188       //
13189       // It is an error in C++ to declare (rather than define) an enum
13190       // type, including via an elaborated type specifier.  We'll
13191       // diagnose that later; for now, declare the enum in the same
13192       // scope as we would have picked for any other tag type.
13193       //
13194       // GNU C also supports this behavior as part of its incomplete
13195       // enum types extension, while GNU C++ does not.
13196       //
13197       // Find the context where we'll be declaring the tag.
13198       // FIXME: We would like to maintain the current DeclContext as the
13199       // lexical context,
13200       SearchDC = getTagInjectionContext(SearchDC);
13201
13202       // Find the scope where we'll be declaring the tag.
13203       S = getTagInjectionScope(S, getLangOpts());
13204     } else {
13205       assert(TUK == TUK_Friend);
13206       // C++ [namespace.memdef]p3:
13207       //   If a friend declaration in a non-local class first declares a
13208       //   class or function, the friend class or function is a member of
13209       //   the innermost enclosing namespace.
13210       SearchDC = SearchDC->getEnclosingNamespaceContext();
13211     }
13212
13213     // In C++, we need to do a redeclaration lookup to properly
13214     // diagnose some problems.
13215     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13216     // hidden declaration so that we don't get ambiguity errors when using a
13217     // type declared by an elaborated-type-specifier.  In C that is not correct
13218     // and we should instead merge compatible types found by lookup.
13219     if (getLangOpts().CPlusPlus) {
13220       Previous.setRedeclarationKind(ForRedeclaration);
13221       LookupQualifiedName(Previous, SearchDC);
13222     } else {
13223       Previous.setRedeclarationKind(ForRedeclaration);
13224       LookupName(Previous, S);
13225     }
13226   }
13227
13228   // If we have a known previous declaration to use, then use it.
13229   if (Previous.empty() && SkipBody && SkipBody->Previous)
13230     Previous.addDecl(SkipBody->Previous);
13231
13232   if (!Previous.empty()) {
13233     NamedDecl *PrevDecl = Previous.getFoundDecl();
13234     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13235
13236     // It's okay to have a tag decl in the same scope as a typedef
13237     // which hides a tag decl in the same scope.  Finding this
13238     // insanity with a redeclaration lookup can only actually happen
13239     // in C++.
13240     //
13241     // This is also okay for elaborated-type-specifiers, which is
13242     // technically forbidden by the current standard but which is
13243     // okay according to the likely resolution of an open issue;
13244     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13245     if (getLangOpts().CPlusPlus) {
13246       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13247         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13248           TagDecl *Tag = TT->getDecl();
13249           if (Tag->getDeclName() == Name &&
13250               Tag->getDeclContext()->getRedeclContext()
13251                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13252             PrevDecl = Tag;
13253             Previous.clear();
13254             Previous.addDecl(Tag);
13255             Previous.resolveKind();
13256           }
13257         }
13258       }
13259     }
13260
13261     // If this is a redeclaration of a using shadow declaration, it must
13262     // declare a tag in the same context. In MSVC mode, we allow a
13263     // redefinition if either context is within the other.
13264     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13265       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13266       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13267           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13268           !(OldTag && isAcceptableTagRedeclContext(
13269                           *this, OldTag->getDeclContext(), SearchDC))) {
13270         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13271         Diag(Shadow->getTargetDecl()->getLocation(),
13272              diag::note_using_decl_target);
13273         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13274             << 0;
13275         // Recover by ignoring the old declaration.
13276         Previous.clear();
13277         goto CreateNewDecl;
13278       }
13279     }
13280
13281     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13282       // If this is a use of a previous tag, or if the tag is already declared
13283       // in the same scope (so that the definition/declaration completes or
13284       // rementions the tag), reuse the decl.
13285       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13286           isDeclInScope(DirectPrevDecl, SearchDC, S,
13287                         SS.isNotEmpty() || isMemberSpecialization)) {
13288         // Make sure that this wasn't declared as an enum and now used as a
13289         // struct or something similar.
13290         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13291                                           TUK == TUK_Definition, KWLoc,
13292                                           Name)) {
13293           bool SafeToContinue
13294             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13295                Kind != TTK_Enum);
13296           if (SafeToContinue)
13297             Diag(KWLoc, diag::err_use_with_wrong_tag)
13298               << Name
13299               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13300                                               PrevTagDecl->getKindName());
13301           else
13302             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13303           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13304
13305           if (SafeToContinue)
13306             Kind = PrevTagDecl->getTagKind();
13307           else {
13308             // Recover by making this an anonymous redefinition.
13309             Name = nullptr;
13310             Previous.clear();
13311             Invalid = true;
13312           }
13313         }
13314
13315         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13316           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13317
13318           // If this is an elaborated-type-specifier for a scoped enumeration,
13319           // the 'class' keyword is not necessary and not permitted.
13320           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13321             if (ScopedEnum)
13322               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13323                 << PrevEnum->isScoped()
13324                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13325             return PrevTagDecl;
13326           }
13327
13328           QualType EnumUnderlyingTy;
13329           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13330             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13331           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13332             EnumUnderlyingTy = QualType(T, 0);
13333
13334           // All conflicts with previous declarations are recovered by
13335           // returning the previous declaration, unless this is a definition,
13336           // in which case we want the caller to bail out.
13337           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13338                                      ScopedEnum, EnumUnderlyingTy,
13339                                      EnumUnderlyingIsImplicit, PrevEnum))
13340             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13341         }
13342
13343         // C++11 [class.mem]p1:
13344         //   A member shall not be declared twice in the member-specification,
13345         //   except that a nested class or member class template can be declared
13346         //   and then later defined.
13347         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13348             S->isDeclScope(PrevDecl)) {
13349           Diag(NameLoc, diag::ext_member_redeclared);
13350           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13351         }
13352
13353         if (!Invalid) {
13354           // If this is a use, just return the declaration we found, unless
13355           // we have attributes.
13356           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13357             if (Attr) {
13358               // FIXME: Diagnose these attributes. For now, we create a new
13359               // declaration to hold them.
13360             } else if (TUK == TUK_Reference &&
13361                        (PrevTagDecl->getFriendObjectKind() ==
13362                             Decl::FOK_Undeclared ||
13363                         PP.getModuleContainingLocation(
13364                             PrevDecl->getLocation()) !=
13365                             PP.getModuleContainingLocation(KWLoc)) &&
13366                        SS.isEmpty()) {
13367               // This declaration is a reference to an existing entity, but
13368               // has different visibility from that entity: it either makes
13369               // a friend visible or it makes a type visible in a new module.
13370               // In either case, create a new declaration. We only do this if
13371               // the declaration would have meant the same thing if no prior
13372               // declaration were found, that is, if it was found in the same
13373               // scope where we would have injected a declaration.
13374               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13375                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13376                 return PrevTagDecl;
13377               // This is in the injected scope, create a new declaration in
13378               // that scope.
13379               S = getTagInjectionScope(S, getLangOpts());
13380             } else {
13381               return PrevTagDecl;
13382             }
13383           }
13384
13385           // Diagnose attempts to redefine a tag.
13386           if (TUK == TUK_Definition) {
13387             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13388               // If we're defining a specialization and the previous definition
13389               // is from an implicit instantiation, don't emit an error
13390               // here; we'll catch this in the general case below.
13391               bool IsExplicitSpecializationAfterInstantiation = false;
13392               if (isMemberSpecialization) {
13393                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13394                   IsExplicitSpecializationAfterInstantiation =
13395                     RD->getTemplateSpecializationKind() !=
13396                     TSK_ExplicitSpecialization;
13397                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13398                   IsExplicitSpecializationAfterInstantiation =
13399                     ED->getTemplateSpecializationKind() !=
13400                     TSK_ExplicitSpecialization;
13401               }
13402
13403               NamedDecl *Hidden = nullptr;
13404               if (SkipBody && getLangOpts().CPlusPlus &&
13405                   !hasVisibleDefinition(Def, &Hidden)) {
13406                 // There is a definition of this tag, but it is not visible. We
13407                 // explicitly make use of C++'s one definition rule here, and
13408                 // assume that this definition is identical to the hidden one
13409                 // we already have. Make the existing definition visible and
13410                 // use it in place of this one.
13411                 SkipBody->ShouldSkip = true;
13412                 makeMergedDefinitionVisible(Hidden, KWLoc);
13413                 return Def;
13414               } else if (!IsExplicitSpecializationAfterInstantiation) {
13415                 // A redeclaration in function prototype scope in C isn't
13416                 // visible elsewhere, so merely issue a warning.
13417                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13418                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13419                 else
13420                   Diag(NameLoc, diag::err_redefinition) << Name;
13421                 Diag(Def->getLocation(), diag::note_previous_definition);
13422                 // If this is a redefinition, recover by making this
13423                 // struct be anonymous, which will make any later
13424                 // references get the previous definition.
13425                 Name = nullptr;
13426                 Previous.clear();
13427                 Invalid = true;
13428               }
13429             } else {
13430               // If the type is currently being defined, complain
13431               // about a nested redefinition.
13432               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13433               if (TD->isBeingDefined()) {
13434                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13435                 Diag(PrevTagDecl->getLocation(),
13436                      diag::note_previous_definition);
13437                 Name = nullptr;
13438                 Previous.clear();
13439                 Invalid = true;
13440               }
13441             }
13442
13443             // Okay, this is definition of a previously declared or referenced
13444             // tag. We're going to create a new Decl for it.
13445           }
13446
13447           // Okay, we're going to make a redeclaration.  If this is some kind
13448           // of reference, make sure we build the redeclaration in the same DC
13449           // as the original, and ignore the current access specifier.
13450           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13451             SearchDC = PrevTagDecl->getDeclContext();
13452             AS = AS_none;
13453           }
13454         }
13455         // If we get here we have (another) forward declaration or we
13456         // have a definition.  Just create a new decl.
13457
13458       } else {
13459         // If we get here, this is a definition of a new tag type in a nested
13460         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13461         // new decl/type.  We set PrevDecl to NULL so that the entities
13462         // have distinct types.
13463         Previous.clear();
13464       }
13465       // If we get here, we're going to create a new Decl. If PrevDecl
13466       // is non-NULL, it's a definition of the tag declared by
13467       // PrevDecl. If it's NULL, we have a new definition.
13468
13469     // Otherwise, PrevDecl is not a tag, but was found with tag
13470     // lookup.  This is only actually possible in C++, where a few
13471     // things like templates still live in the tag namespace.
13472     } else {
13473       // Use a better diagnostic if an elaborated-type-specifier
13474       // found the wrong kind of type on the first
13475       // (non-redeclaration) lookup.
13476       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13477           !Previous.isForRedeclaration()) {
13478         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13479         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13480                                                        << Kind;
13481         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13482         Invalid = true;
13483
13484       // Otherwise, only diagnose if the declaration is in scope.
13485       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13486                                 SS.isNotEmpty() || isMemberSpecialization)) {
13487         // do nothing
13488
13489       // Diagnose implicit declarations introduced by elaborated types.
13490       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13491         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13492         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13493         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13494         Invalid = true;
13495
13496       // Otherwise it's a declaration.  Call out a particularly common
13497       // case here.
13498       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13499         unsigned Kind = 0;
13500         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13501         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13502           << Name << Kind << TND->getUnderlyingType();
13503         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13504         Invalid = true;
13505
13506       // Otherwise, diagnose.
13507       } else {
13508         // The tag name clashes with something else in the target scope,
13509         // issue an error and recover by making this tag be anonymous.
13510         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13511         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13512         Name = nullptr;
13513         Invalid = true;
13514       }
13515
13516       // The existing declaration isn't relevant to us; we're in a
13517       // new scope, so clear out the previous declaration.
13518       Previous.clear();
13519     }
13520   }
13521
13522 CreateNewDecl:
13523
13524   TagDecl *PrevDecl = nullptr;
13525   if (Previous.isSingleResult())
13526     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13527
13528   // If there is an identifier, use the location of the identifier as the
13529   // location of the decl, otherwise use the location of the struct/union
13530   // keyword.
13531   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13532
13533   // Otherwise, create a new declaration. If there is a previous
13534   // declaration of the same entity, the two will be linked via
13535   // PrevDecl.
13536   TagDecl *New;
13537
13538   bool IsForwardReference = false;
13539   if (Kind == TTK_Enum) {
13540     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13541     // enum X { A, B, C } D;    D should chain to X.
13542     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13543                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13544                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13545
13546     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13547       StdAlignValT = cast<EnumDecl>(New);
13548
13549     // If this is an undefined enum, warn.
13550     if (TUK != TUK_Definition && !Invalid) {
13551       TagDecl *Def;
13552       if (!EnumUnderlyingIsImplicit &&
13553           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13554           cast<EnumDecl>(New)->isFixed()) {
13555         // C++0x: 7.2p2: opaque-enum-declaration.
13556         // Conflicts are diagnosed above. Do nothing.
13557       }
13558       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13559         Diag(Loc, diag::ext_forward_ref_enum_def)
13560           << New;
13561         Diag(Def->getLocation(), diag::note_previous_definition);
13562       } else {
13563         unsigned DiagID = diag::ext_forward_ref_enum;
13564         if (getLangOpts().MSVCCompat)
13565           DiagID = diag::ext_ms_forward_ref_enum;
13566         else if (getLangOpts().CPlusPlus)
13567           DiagID = diag::err_forward_ref_enum;
13568         Diag(Loc, DiagID);
13569
13570         // If this is a forward-declared reference to an enumeration, make a
13571         // note of it; we won't actually be introducing the declaration into
13572         // the declaration context.
13573         if (TUK == TUK_Reference)
13574           IsForwardReference = true;
13575       }
13576     }
13577
13578     if (EnumUnderlying) {
13579       EnumDecl *ED = cast<EnumDecl>(New);
13580       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13581         ED->setIntegerTypeSourceInfo(TI);
13582       else
13583         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13584       ED->setPromotionType(ED->getIntegerType());
13585     }
13586   } else {
13587     // struct/union/class
13588
13589     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13590     // struct X { int A; } D;    D should chain to X.
13591     if (getLangOpts().CPlusPlus) {
13592       // FIXME: Look for a way to use RecordDecl for simple structs.
13593       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13594                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13595
13596       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13597         StdBadAlloc = cast<CXXRecordDecl>(New);
13598     } else
13599       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13600                                cast_or_null<RecordDecl>(PrevDecl));
13601   }
13602
13603   // C++11 [dcl.type]p3:
13604   //   A type-specifier-seq shall not define a class or enumeration [...].
13605   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13606     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13607       << Context.getTagDeclType(New);
13608     Invalid = true;
13609   }
13610
13611   // Maybe add qualifier info.
13612   if (SS.isNotEmpty()) {
13613     if (SS.isSet()) {
13614       // If this is either a declaration or a definition, check the
13615       // nested-name-specifier against the current context. We don't do this
13616       // for explicit specializations, because they have similar checking
13617       // (with more specific diagnostics) in the call to
13618       // CheckMemberSpecialization, below.
13619       if (!isMemberSpecialization &&
13620           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13621           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13622         Invalid = true;
13623
13624       New->setQualifierInfo(SS.getWithLocInContext(Context));
13625       if (TemplateParameterLists.size() > 0) {
13626         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13627       }
13628     }
13629     else
13630       Invalid = true;
13631   }
13632
13633   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13634     // Add alignment attributes if necessary; these attributes are checked when
13635     // the ASTContext lays out the structure.
13636     //
13637     // It is important for implementing the correct semantics that this
13638     // happen here (in act on tag decl). The #pragma pack stack is
13639     // maintained as a result of parser callbacks which can occur at
13640     // many points during the parsing of a struct declaration (because
13641     // the #pragma tokens are effectively skipped over during the
13642     // parsing of the struct).
13643     if (TUK == TUK_Definition) {
13644       AddAlignmentAttributesForRecord(RD);
13645       AddMsStructLayoutForRecord(RD);
13646     }
13647   }
13648
13649   if (ModulePrivateLoc.isValid()) {
13650     if (isMemberSpecialization)
13651       Diag(New->getLocation(), diag::err_module_private_specialization)
13652         << 2
13653         << FixItHint::CreateRemoval(ModulePrivateLoc);
13654     // __module_private__ does not apply to local classes. However, we only
13655     // diagnose this as an error when the declaration specifiers are
13656     // freestanding. Here, we just ignore the __module_private__.
13657     else if (!SearchDC->isFunctionOrMethod())
13658       New->setModulePrivate();
13659   }
13660
13661   // If this is a specialization of a member class (of a class template),
13662   // check the specialization.
13663   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13664     Invalid = true;
13665
13666   // If we're declaring or defining a tag in function prototype scope in C,
13667   // note that this type can only be used within the function and add it to
13668   // the list of decls to inject into the function definition scope.
13669   if ((Name || Kind == TTK_Enum) &&
13670       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13671     if (getLangOpts().CPlusPlus) {
13672       // C++ [dcl.fct]p6:
13673       //   Types shall not be defined in return or parameter types.
13674       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13675         Diag(Loc, diag::err_type_defined_in_param_type)
13676             << Name;
13677         Invalid = true;
13678       }
13679     } else if (!PrevDecl) {
13680       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13681     }
13682   }
13683
13684   if (Invalid)
13685     New->setInvalidDecl();
13686
13687   // Set the lexical context. If the tag has a C++ scope specifier, the
13688   // lexical context will be different from the semantic context.
13689   New->setLexicalDeclContext(CurContext);
13690
13691   // Mark this as a friend decl if applicable.
13692   // In Microsoft mode, a friend declaration also acts as a forward
13693   // declaration so we always pass true to setObjectOfFriendDecl to make
13694   // the tag name visible.
13695   if (TUK == TUK_Friend)
13696     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13697
13698   // Set the access specifier.
13699   if (!Invalid && SearchDC->isRecord())
13700     SetMemberAccessSpecifier(New, PrevDecl, AS);
13701
13702   if (TUK == TUK_Definition)
13703     New->startDefinition();
13704
13705   if (Attr)
13706     ProcessDeclAttributeList(S, New, Attr);
13707   AddPragmaAttributes(S, New);
13708
13709   // If this has an identifier, add it to the scope stack.
13710   if (TUK == TUK_Friend) {
13711     // We might be replacing an existing declaration in the lookup tables;
13712     // if so, borrow its access specifier.
13713     if (PrevDecl)
13714       New->setAccess(PrevDecl->getAccess());
13715
13716     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13717     DC->makeDeclVisibleInContext(New);
13718     if (Name) // can be null along some error paths
13719       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13720         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13721   } else if (Name) {
13722     S = getNonFieldDeclScope(S);
13723     PushOnScopeChains(New, S, !IsForwardReference);
13724     if (IsForwardReference)
13725       SearchDC->makeDeclVisibleInContext(New);
13726   } else {
13727     CurContext->addDecl(New);
13728   }
13729
13730   // If this is the C FILE type, notify the AST context.
13731   if (IdentifierInfo *II = New->getIdentifier())
13732     if (!New->isInvalidDecl() &&
13733         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13734         II->isStr("FILE"))
13735       Context.setFILEDecl(New);
13736
13737   if (PrevDecl)
13738     mergeDeclAttributes(New, PrevDecl);
13739
13740   // If there's a #pragma GCC visibility in scope, set the visibility of this
13741   // record.
13742   AddPushedVisibilityAttribute(New);
13743
13744   OwnedDecl = true;
13745   // In C++, don't return an invalid declaration. We can't recover well from
13746   // the cases where we make the type anonymous.
13747   if (Invalid && getLangOpts().CPlusPlus) {
13748     if (New->isBeingDefined())
13749       if (auto RD = dyn_cast<RecordDecl>(New))
13750         RD->completeDefinition();
13751     return nullptr;
13752   } else {
13753     return New;
13754   }
13755 }
13756
13757 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13758   AdjustDeclIfTemplate(TagD);
13759   TagDecl *Tag = cast<TagDecl>(TagD);
13760
13761   // Enter the tag context.
13762   PushDeclContext(S, Tag);
13763
13764   ActOnDocumentableDecl(TagD);
13765
13766   // If there's a #pragma GCC visibility in scope, set the visibility of this
13767   // record.
13768   AddPushedVisibilityAttribute(Tag);
13769 }
13770
13771 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13772   assert(isa<ObjCContainerDecl>(IDecl) &&
13773          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13774   DeclContext *OCD = cast<DeclContext>(IDecl);
13775   assert(getContainingDC(OCD) == CurContext &&
13776       "The next DeclContext should be lexically contained in the current one.");
13777   CurContext = OCD;
13778   return IDecl;
13779 }
13780
13781 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13782                                            SourceLocation FinalLoc,
13783                                            bool IsFinalSpelledSealed,
13784                                            SourceLocation LBraceLoc) {
13785   AdjustDeclIfTemplate(TagD);
13786   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13787
13788   FieldCollector->StartClass();
13789
13790   if (!Record->getIdentifier())
13791     return;
13792
13793   if (FinalLoc.isValid())
13794     Record->addAttr(new (Context)
13795                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13796
13797   // C++ [class]p2:
13798   //   [...] The class-name is also inserted into the scope of the
13799   //   class itself; this is known as the injected-class-name. For
13800   //   purposes of access checking, the injected-class-name is treated
13801   //   as if it were a public member name.
13802   CXXRecordDecl *InjectedClassName
13803     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13804                             Record->getLocStart(), Record->getLocation(),
13805                             Record->getIdentifier(),
13806                             /*PrevDecl=*/nullptr,
13807                             /*DelayTypeCreation=*/true);
13808   Context.getTypeDeclType(InjectedClassName, Record);
13809   InjectedClassName->setImplicit();
13810   InjectedClassName->setAccess(AS_public);
13811   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13812       InjectedClassName->setDescribedClassTemplate(Template);
13813   PushOnScopeChains(InjectedClassName, S);
13814   assert(InjectedClassName->isInjectedClassName() &&
13815          "Broken injected-class-name");
13816 }
13817
13818 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13819                                     SourceRange BraceRange) {
13820   AdjustDeclIfTemplate(TagD);
13821   TagDecl *Tag = cast<TagDecl>(TagD);
13822   Tag->setBraceRange(BraceRange);
13823
13824   // Make sure we "complete" the definition even it is invalid.
13825   if (Tag->isBeingDefined()) {
13826     assert(Tag->isInvalidDecl() && "We should already have completed it");
13827     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13828       RD->completeDefinition();
13829   }
13830
13831   if (isa<CXXRecordDecl>(Tag)) {
13832     FieldCollector->FinishClass();
13833   }
13834
13835   // Exit this scope of this tag's definition.
13836   PopDeclContext();
13837
13838   if (getCurLexicalContext()->isObjCContainer() &&
13839       Tag->getDeclContext()->isFileContext())
13840     Tag->setTopLevelDeclInObjCContainer();
13841
13842   // Notify the consumer that we've defined a tag.
13843   if (!Tag->isInvalidDecl())
13844     Consumer.HandleTagDeclDefinition(Tag);
13845 }
13846
13847 void Sema::ActOnObjCContainerFinishDefinition() {
13848   // Exit this scope of this interface definition.
13849   PopDeclContext();
13850 }
13851
13852 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13853   assert(DC == CurContext && "Mismatch of container contexts");
13854   OriginalLexicalContext = DC;
13855   ActOnObjCContainerFinishDefinition();
13856 }
13857
13858 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13859   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13860   OriginalLexicalContext = nullptr;
13861 }
13862
13863 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13864   AdjustDeclIfTemplate(TagD);
13865   TagDecl *Tag = cast<TagDecl>(TagD);
13866   Tag->setInvalidDecl();
13867
13868   // Make sure we "complete" the definition even it is invalid.
13869   if (Tag->isBeingDefined()) {
13870     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13871       RD->completeDefinition();
13872   }
13873
13874   // We're undoing ActOnTagStartDefinition here, not
13875   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13876   // the FieldCollector.
13877
13878   PopDeclContext();
13879 }
13880
13881 // Note that FieldName may be null for anonymous bitfields.
13882 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13883                                 IdentifierInfo *FieldName,
13884                                 QualType FieldTy, bool IsMsStruct,
13885                                 Expr *BitWidth, bool *ZeroWidth) {
13886   // Default to true; that shouldn't confuse checks for emptiness
13887   if (ZeroWidth)
13888     *ZeroWidth = true;
13889
13890   // C99 6.7.2.1p4 - verify the field type.
13891   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13892   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13893     // Handle incomplete types with specific error.
13894     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13895       return ExprError();
13896     if (FieldName)
13897       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13898         << FieldName << FieldTy << BitWidth->getSourceRange();
13899     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13900       << FieldTy << BitWidth->getSourceRange();
13901   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13902                                              UPPC_BitFieldWidth))
13903     return ExprError();
13904
13905   // If the bit-width is type- or value-dependent, don't try to check
13906   // it now.
13907   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13908     return BitWidth;
13909
13910   llvm::APSInt Value;
13911   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13912   if (ICE.isInvalid())
13913     return ICE;
13914   BitWidth = ICE.get();
13915
13916   if (Value != 0 && ZeroWidth)
13917     *ZeroWidth = false;
13918
13919   // Zero-width bitfield is ok for anonymous field.
13920   if (Value == 0 && FieldName)
13921     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13922
13923   if (Value.isSigned() && Value.isNegative()) {
13924     if (FieldName)
13925       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13926                << FieldName << Value.toString(10);
13927     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13928       << Value.toString(10);
13929   }
13930
13931   if (!FieldTy->isDependentType()) {
13932     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13933     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13934     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13935
13936     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13937     // ABI.
13938     bool CStdConstraintViolation =
13939         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13940     bool MSBitfieldViolation =
13941         Value.ugt(TypeStorageSize) &&
13942         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13943     if (CStdConstraintViolation || MSBitfieldViolation) {
13944       unsigned DiagWidth =
13945           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13946       if (FieldName)
13947         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13948                << FieldName << (unsigned)Value.getZExtValue()
13949                << !CStdConstraintViolation << DiagWidth;
13950
13951       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13952              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13953              << DiagWidth;
13954     }
13955
13956     // Warn on types where the user might conceivably expect to get all
13957     // specified bits as value bits: that's all integral types other than
13958     // 'bool'.
13959     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13960       if (FieldName)
13961         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13962             << FieldName << (unsigned)Value.getZExtValue()
13963             << (unsigned)TypeWidth;
13964       else
13965         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13966             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13967     }
13968   }
13969
13970   return BitWidth;
13971 }
13972
13973 /// ActOnField - Each field of a C struct/union is passed into this in order
13974 /// to create a FieldDecl object for it.
13975 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13976                        Declarator &D, Expr *BitfieldWidth) {
13977   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13978                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13979                                /*InitStyle=*/ICIS_NoInit, AS_public);
13980   return Res;
13981 }
13982
13983 /// HandleField - Analyze a field of a C struct or a C++ data member.
13984 ///
13985 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13986                              SourceLocation DeclStart,
13987                              Declarator &D, Expr *BitWidth,
13988                              InClassInitStyle InitStyle,
13989                              AccessSpecifier AS) {
13990   if (D.isDecompositionDeclarator()) {
13991     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13992     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13993       << Decomp.getSourceRange();
13994     return nullptr;
13995   }
13996
13997   IdentifierInfo *II = D.getIdentifier();
13998   SourceLocation Loc = DeclStart;
13999   if (II) Loc = D.getIdentifierLoc();
14000
14001   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14002   QualType T = TInfo->getType();
14003   if (getLangOpts().CPlusPlus) {
14004     CheckExtraCXXDefaultArguments(D);
14005
14006     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14007                                         UPPC_DataMemberType)) {
14008       D.setInvalidType();
14009       T = Context.IntTy;
14010       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14011     }
14012   }
14013
14014   // TR 18037 does not allow fields to be declared with address spaces.
14015   if (T.getQualifiers().hasAddressSpace()) {
14016     Diag(Loc, diag::err_field_with_address_space);
14017     D.setInvalidType();
14018   }
14019
14020   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14021   // used as structure or union field: image, sampler, event or block types.
14022   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14023                           T->isSamplerT() || T->isBlockPointerType())) {
14024     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14025     D.setInvalidType();
14026   }
14027
14028   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14029
14030   if (D.getDeclSpec().isInlineSpecified())
14031     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14032         << getLangOpts().CPlusPlus1z;
14033   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14034     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14035          diag::err_invalid_thread)
14036       << DeclSpec::getSpecifierName(TSCS);
14037
14038   // Check to see if this name was declared as a member previously
14039   NamedDecl *PrevDecl = nullptr;
14040   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14041   LookupName(Previous, S);
14042   switch (Previous.getResultKind()) {
14043     case LookupResult::Found:
14044     case LookupResult::FoundUnresolvedValue:
14045       PrevDecl = Previous.getAsSingle<NamedDecl>();
14046       break;
14047
14048     case LookupResult::FoundOverloaded:
14049       PrevDecl = Previous.getRepresentativeDecl();
14050       break;
14051
14052     case LookupResult::NotFound:
14053     case LookupResult::NotFoundInCurrentInstantiation:
14054     case LookupResult::Ambiguous:
14055       break;
14056   }
14057   Previous.suppressDiagnostics();
14058
14059   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14060     // Maybe we will complain about the shadowed template parameter.
14061     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14062     // Just pretend that we didn't see the previous declaration.
14063     PrevDecl = nullptr;
14064   }
14065
14066   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14067     PrevDecl = nullptr;
14068
14069   bool Mutable
14070     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14071   SourceLocation TSSL = D.getLocStart();
14072   FieldDecl *NewFD
14073     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14074                      TSSL, AS, PrevDecl, &D);
14075
14076   if (NewFD->isInvalidDecl())
14077     Record->setInvalidDecl();
14078
14079   if (D.getDeclSpec().isModulePrivateSpecified())
14080     NewFD->setModulePrivate();
14081
14082   if (NewFD->isInvalidDecl() && PrevDecl) {
14083     // Don't introduce NewFD into scope; there's already something
14084     // with the same name in the same scope.
14085   } else if (II) {
14086     PushOnScopeChains(NewFD, S);
14087   } else
14088     Record->addDecl(NewFD);
14089
14090   return NewFD;
14091 }
14092
14093 /// \brief Build a new FieldDecl and check its well-formedness.
14094 ///
14095 /// This routine builds a new FieldDecl given the fields name, type,
14096 /// record, etc. \p PrevDecl should refer to any previous declaration
14097 /// with the same name and in the same scope as the field to be
14098 /// created.
14099 ///
14100 /// \returns a new FieldDecl.
14101 ///
14102 /// \todo The Declarator argument is a hack. It will be removed once
14103 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14104                                 TypeSourceInfo *TInfo,
14105                                 RecordDecl *Record, SourceLocation Loc,
14106                                 bool Mutable, Expr *BitWidth,
14107                                 InClassInitStyle InitStyle,
14108                                 SourceLocation TSSL,
14109                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14110                                 Declarator *D) {
14111   IdentifierInfo *II = Name.getAsIdentifierInfo();
14112   bool InvalidDecl = false;
14113   if (D) InvalidDecl = D->isInvalidType();
14114
14115   // If we receive a broken type, recover by assuming 'int' and
14116   // marking this declaration as invalid.
14117   if (T.isNull()) {
14118     InvalidDecl = true;
14119     T = Context.IntTy;
14120   }
14121
14122   QualType EltTy = Context.getBaseElementType(T);
14123   if (!EltTy->isDependentType()) {
14124     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14125       // Fields of incomplete type force their record to be invalid.
14126       Record->setInvalidDecl();
14127       InvalidDecl = true;
14128     } else {
14129       NamedDecl *Def;
14130       EltTy->isIncompleteType(&Def);
14131       if (Def && Def->isInvalidDecl()) {
14132         Record->setInvalidDecl();
14133         InvalidDecl = true;
14134       }
14135     }
14136   }
14137
14138   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14139   if (BitWidth && getLangOpts().OpenCL) {
14140     Diag(Loc, diag::err_opencl_bitfields);
14141     InvalidDecl = true;
14142   }
14143
14144   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14145   // than a variably modified type.
14146   if (!InvalidDecl && T->isVariablyModifiedType()) {
14147     bool SizeIsNegative;
14148     llvm::APSInt Oversized;
14149
14150     TypeSourceInfo *FixedTInfo =
14151       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14152                                                     SizeIsNegative,
14153                                                     Oversized);
14154     if (FixedTInfo) {
14155       Diag(Loc, diag::warn_illegal_constant_array_size);
14156       TInfo = FixedTInfo;
14157       T = FixedTInfo->getType();
14158     } else {
14159       if (SizeIsNegative)
14160         Diag(Loc, diag::err_typecheck_negative_array_size);
14161       else if (Oversized.getBoolValue())
14162         Diag(Loc, diag::err_array_too_large)
14163           << Oversized.toString(10);
14164       else
14165         Diag(Loc, diag::err_typecheck_field_variable_size);
14166       InvalidDecl = true;
14167     }
14168   }
14169
14170   // Fields can not have abstract class types
14171   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14172                                              diag::err_abstract_type_in_decl,
14173                                              AbstractFieldType))
14174     InvalidDecl = true;
14175
14176   bool ZeroWidth = false;
14177   if (InvalidDecl)
14178     BitWidth = nullptr;
14179   // If this is declared as a bit-field, check the bit-field.
14180   if (BitWidth) {
14181     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14182                               &ZeroWidth).get();
14183     if (!BitWidth) {
14184       InvalidDecl = true;
14185       BitWidth = nullptr;
14186       ZeroWidth = false;
14187     }
14188   }
14189
14190   // Check that 'mutable' is consistent with the type of the declaration.
14191   if (!InvalidDecl && Mutable) {
14192     unsigned DiagID = 0;
14193     if (T->isReferenceType())
14194       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14195                                         : diag::err_mutable_reference;
14196     else if (T.isConstQualified())
14197       DiagID = diag::err_mutable_const;
14198
14199     if (DiagID) {
14200       SourceLocation ErrLoc = Loc;
14201       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14202         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14203       Diag(ErrLoc, DiagID);
14204       if (DiagID != diag::ext_mutable_reference) {
14205         Mutable = false;
14206         InvalidDecl = true;
14207       }
14208     }
14209   }
14210
14211   // C++11 [class.union]p8 (DR1460):
14212   //   At most one variant member of a union may have a
14213   //   brace-or-equal-initializer.
14214   if (InitStyle != ICIS_NoInit)
14215     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14216
14217   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14218                                        BitWidth, Mutable, InitStyle);
14219   if (InvalidDecl)
14220     NewFD->setInvalidDecl();
14221
14222   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14223     Diag(Loc, diag::err_duplicate_member) << II;
14224     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14225     NewFD->setInvalidDecl();
14226   }
14227
14228   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14229     if (Record->isUnion()) {
14230       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14231         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14232         if (RDecl->getDefinition()) {
14233           // C++ [class.union]p1: An object of a class with a non-trivial
14234           // constructor, a non-trivial copy constructor, a non-trivial
14235           // destructor, or a non-trivial copy assignment operator
14236           // cannot be a member of a union, nor can an array of such
14237           // objects.
14238           if (CheckNontrivialField(NewFD))
14239             NewFD->setInvalidDecl();
14240         }
14241       }
14242
14243       // C++ [class.union]p1: If a union contains a member of reference type,
14244       // the program is ill-formed, except when compiling with MSVC extensions
14245       // enabled.
14246       if (EltTy->isReferenceType()) {
14247         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14248                                     diag::ext_union_member_of_reference_type :
14249                                     diag::err_union_member_of_reference_type)
14250           << NewFD->getDeclName() << EltTy;
14251         if (!getLangOpts().MicrosoftExt)
14252           NewFD->setInvalidDecl();
14253       }
14254     }
14255   }
14256
14257   // FIXME: We need to pass in the attributes given an AST
14258   // representation, not a parser representation.
14259   if (D) {
14260     // FIXME: The current scope is almost... but not entirely... correct here.
14261     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14262
14263     if (NewFD->hasAttrs())
14264       CheckAlignasUnderalignment(NewFD);
14265   }
14266
14267   // In auto-retain/release, infer strong retension for fields of
14268   // retainable type.
14269   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14270     NewFD->setInvalidDecl();
14271
14272   if (T.isObjCGCWeak())
14273     Diag(Loc, diag::warn_attribute_weak_on_field);
14274
14275   NewFD->setAccess(AS);
14276   return NewFD;
14277 }
14278
14279 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14280   assert(FD);
14281   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14282
14283   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14284     return false;
14285
14286   QualType EltTy = Context.getBaseElementType(FD->getType());
14287   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14288     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14289     if (RDecl->getDefinition()) {
14290       // We check for copy constructors before constructors
14291       // because otherwise we'll never get complaints about
14292       // copy constructors.
14293
14294       CXXSpecialMember member = CXXInvalid;
14295       // We're required to check for any non-trivial constructors. Since the
14296       // implicit default constructor is suppressed if there are any
14297       // user-declared constructors, we just need to check that there is a
14298       // trivial default constructor and a trivial copy constructor. (We don't
14299       // worry about move constructors here, since this is a C++98 check.)
14300       if (RDecl->hasNonTrivialCopyConstructor())
14301         member = CXXCopyConstructor;
14302       else if (!RDecl->hasTrivialDefaultConstructor())
14303         member = CXXDefaultConstructor;
14304       else if (RDecl->hasNonTrivialCopyAssignment())
14305         member = CXXCopyAssignment;
14306       else if (RDecl->hasNonTrivialDestructor())
14307         member = CXXDestructor;
14308
14309       if (member != CXXInvalid) {
14310         if (!getLangOpts().CPlusPlus11 &&
14311             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14312           // Objective-C++ ARC: it is an error to have a non-trivial field of
14313           // a union. However, system headers in Objective-C programs
14314           // occasionally have Objective-C lifetime objects within unions,
14315           // and rather than cause the program to fail, we make those
14316           // members unavailable.
14317           SourceLocation Loc = FD->getLocation();
14318           if (getSourceManager().isInSystemHeader(Loc)) {
14319             if (!FD->hasAttr<UnavailableAttr>())
14320               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14321                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14322             return false;
14323           }
14324         }
14325
14326         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14327                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14328                diag::err_illegal_union_or_anon_struct_member)
14329           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14330         DiagnoseNontrivial(RDecl, member);
14331         return !getLangOpts().CPlusPlus11;
14332       }
14333     }
14334   }
14335
14336   return false;
14337 }
14338
14339 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14340 ///  AST enum value.
14341 static ObjCIvarDecl::AccessControl
14342 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14343   switch (ivarVisibility) {
14344   default: llvm_unreachable("Unknown visitibility kind");
14345   case tok::objc_private: return ObjCIvarDecl::Private;
14346   case tok::objc_public: return ObjCIvarDecl::Public;
14347   case tok::objc_protected: return ObjCIvarDecl::Protected;
14348   case tok::objc_package: return ObjCIvarDecl::Package;
14349   }
14350 }
14351
14352 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14353 /// in order to create an IvarDecl object for it.
14354 Decl *Sema::ActOnIvar(Scope *S,
14355                                 SourceLocation DeclStart,
14356                                 Declarator &D, Expr *BitfieldWidth,
14357                                 tok::ObjCKeywordKind Visibility) {
14358
14359   IdentifierInfo *II = D.getIdentifier();
14360   Expr *BitWidth = (Expr*)BitfieldWidth;
14361   SourceLocation Loc = DeclStart;
14362   if (II) Loc = D.getIdentifierLoc();
14363
14364   // FIXME: Unnamed fields can be handled in various different ways, for
14365   // example, unnamed unions inject all members into the struct namespace!
14366
14367   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14368   QualType T = TInfo->getType();
14369
14370   if (BitWidth) {
14371     // 6.7.2.1p3, 6.7.2.1p4
14372     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14373     if (!BitWidth)
14374       D.setInvalidType();
14375   } else {
14376     // Not a bitfield.
14377
14378     // validate II.
14379
14380   }
14381   if (T->isReferenceType()) {
14382     Diag(Loc, diag::err_ivar_reference_type);
14383     D.setInvalidType();
14384   }
14385   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14386   // than a variably modified type.
14387   else if (T->isVariablyModifiedType()) {
14388     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14389     D.setInvalidType();
14390   }
14391
14392   // Get the visibility (access control) for this ivar.
14393   ObjCIvarDecl::AccessControl ac =
14394     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14395                                         : ObjCIvarDecl::None;
14396   // Must set ivar's DeclContext to its enclosing interface.
14397   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14398   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14399     return nullptr;
14400   ObjCContainerDecl *EnclosingContext;
14401   if (ObjCImplementationDecl *IMPDecl =
14402       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14403     if (LangOpts.ObjCRuntime.isFragile()) {
14404     // Case of ivar declared in an implementation. Context is that of its class.
14405       EnclosingContext = IMPDecl->getClassInterface();
14406       assert(EnclosingContext && "Implementation has no class interface!");
14407     }
14408     else
14409       EnclosingContext = EnclosingDecl;
14410   } else {
14411     if (ObjCCategoryDecl *CDecl =
14412         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14413       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14414         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14415         return nullptr;
14416       }
14417     }
14418     EnclosingContext = EnclosingDecl;
14419   }
14420
14421   // Construct the decl.
14422   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14423                                              DeclStart, Loc, II, T,
14424                                              TInfo, ac, (Expr *)BitfieldWidth);
14425
14426   if (II) {
14427     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14428                                            ForRedeclaration);
14429     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14430         && !isa<TagDecl>(PrevDecl)) {
14431       Diag(Loc, diag::err_duplicate_member) << II;
14432       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14433       NewID->setInvalidDecl();
14434     }
14435   }
14436
14437   // Process attributes attached to the ivar.
14438   ProcessDeclAttributes(S, NewID, D);
14439
14440   if (D.isInvalidType())
14441     NewID->setInvalidDecl();
14442
14443   // In ARC, infer 'retaining' for ivars of retainable type.
14444   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14445     NewID->setInvalidDecl();
14446
14447   if (D.getDeclSpec().isModulePrivateSpecified())
14448     NewID->setModulePrivate();
14449
14450   if (II) {
14451     // FIXME: When interfaces are DeclContexts, we'll need to add
14452     // these to the interface.
14453     S->AddDecl(NewID);
14454     IdResolver.AddDecl(NewID);
14455   }
14456
14457   if (LangOpts.ObjCRuntime.isNonFragile() &&
14458       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14459     Diag(Loc, diag::warn_ivars_in_interface);
14460
14461   return NewID;
14462 }
14463
14464 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14465 /// class and class extensions. For every class \@interface and class
14466 /// extension \@interface, if the last ivar is a bitfield of any type,
14467 /// then add an implicit `char :0` ivar to the end of that interface.
14468 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14469                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14470   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14471     return;
14472
14473   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14474   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14475
14476   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14477     return;
14478   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14479   if (!ID) {
14480     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14481       if (!CD->IsClassExtension())
14482         return;
14483     }
14484     // No need to add this to end of @implementation.
14485     else
14486       return;
14487   }
14488   // All conditions are met. Add a new bitfield to the tail end of ivars.
14489   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14490   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14491
14492   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14493                               DeclLoc, DeclLoc, nullptr,
14494                               Context.CharTy,
14495                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14496                                                                DeclLoc),
14497                               ObjCIvarDecl::Private, BW,
14498                               true);
14499   AllIvarDecls.push_back(Ivar);
14500 }
14501
14502 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14503                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14504                        SourceLocation RBrac, AttributeList *Attr) {
14505   assert(EnclosingDecl && "missing record or interface decl");
14506
14507   // If this is an Objective-C @implementation or category and we have
14508   // new fields here we should reset the layout of the interface since
14509   // it will now change.
14510   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14511     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14512     switch (DC->getKind()) {
14513     default: break;
14514     case Decl::ObjCCategory:
14515       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14516       break;
14517     case Decl::ObjCImplementation:
14518       Context.
14519         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14520       break;
14521     }
14522   }
14523
14524   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14525
14526   // Start counting up the number of named members; make sure to include
14527   // members of anonymous structs and unions in the total.
14528   unsigned NumNamedMembers = 0;
14529   if (Record) {
14530     for (const auto *I : Record->decls()) {
14531       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14532         if (IFD->getDeclName())
14533           ++NumNamedMembers;
14534     }
14535   }
14536
14537   // Verify that all the fields are okay.
14538   SmallVector<FieldDecl*, 32> RecFields;
14539
14540   bool ObjCFieldLifetimeErrReported = false;
14541   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14542        i != end; ++i) {
14543     FieldDecl *FD = cast<FieldDecl>(*i);
14544
14545     // Get the type for the field.
14546     const Type *FDTy = FD->getType().getTypePtr();
14547
14548     if (!FD->isAnonymousStructOrUnion()) {
14549       // Remember all fields written by the user.
14550       RecFields.push_back(FD);
14551     }
14552
14553     // If the field is already invalid for some reason, don't emit more
14554     // diagnostics about it.
14555     if (FD->isInvalidDecl()) {
14556       EnclosingDecl->setInvalidDecl();
14557       continue;
14558     }
14559
14560     // C99 6.7.2.1p2:
14561     //   A structure or union shall not contain a member with
14562     //   incomplete or function type (hence, a structure shall not
14563     //   contain an instance of itself, but may contain a pointer to
14564     //   an instance of itself), except that the last member of a
14565     //   structure with more than one named member may have incomplete
14566     //   array type; such a structure (and any union containing,
14567     //   possibly recursively, a member that is such a structure)
14568     //   shall not be a member of a structure or an element of an
14569     //   array.
14570     if (FDTy->isFunctionType()) {
14571       // Field declared as a function.
14572       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14573         << FD->getDeclName();
14574       FD->setInvalidDecl();
14575       EnclosingDecl->setInvalidDecl();
14576       continue;
14577     } else if (FDTy->isIncompleteArrayType() && Record &&
14578                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14579                 ((getLangOpts().MicrosoftExt ||
14580                   getLangOpts().CPlusPlus) &&
14581                  (i + 1 == Fields.end() || Record->isUnion())))) {
14582       // Flexible array member.
14583       // Microsoft and g++ is more permissive regarding flexible array.
14584       // It will accept flexible array in union and also
14585       // as the sole element of a struct/class.
14586       unsigned DiagID = 0;
14587       if (Record->isUnion())
14588         DiagID = getLangOpts().MicrosoftExt
14589                      ? diag::ext_flexible_array_union_ms
14590                      : getLangOpts().CPlusPlus
14591                            ? diag::ext_flexible_array_union_gnu
14592                            : diag::err_flexible_array_union;
14593       else if (NumNamedMembers < 1)
14594         DiagID = getLangOpts().MicrosoftExt
14595                      ? diag::ext_flexible_array_empty_aggregate_ms
14596                      : getLangOpts().CPlusPlus
14597                            ? diag::ext_flexible_array_empty_aggregate_gnu
14598                            : diag::err_flexible_array_empty_aggregate;
14599
14600       if (DiagID)
14601         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14602                                         << Record->getTagKind();
14603       // While the layout of types that contain virtual bases is not specified
14604       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14605       // virtual bases after the derived members.  This would make a flexible
14606       // array member declared at the end of an object not adjacent to the end
14607       // of the type.
14608       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14609         if (RD->getNumVBases() != 0)
14610           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14611             << FD->getDeclName() << Record->getTagKind();
14612       if (!getLangOpts().C99)
14613         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14614           << FD->getDeclName() << Record->getTagKind();
14615
14616       // If the element type has a non-trivial destructor, we would not
14617       // implicitly destroy the elements, so disallow it for now.
14618       //
14619       // FIXME: GCC allows this. We should probably either implicitly delete
14620       // the destructor of the containing class, or just allow this.
14621       QualType BaseElem = Context.getBaseElementType(FD->getType());
14622       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14623         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14624           << FD->getDeclName() << FD->getType();
14625         FD->setInvalidDecl();
14626         EnclosingDecl->setInvalidDecl();
14627         continue;
14628       }
14629       // Okay, we have a legal flexible array member at the end of the struct.
14630       Record->setHasFlexibleArrayMember(true);
14631     } else if (!FDTy->isDependentType() &&
14632                RequireCompleteType(FD->getLocation(), FD->getType(),
14633                                    diag::err_field_incomplete)) {
14634       // Incomplete type
14635       FD->setInvalidDecl();
14636       EnclosingDecl->setInvalidDecl();
14637       continue;
14638     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14639       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14640         // A type which contains a flexible array member is considered to be a
14641         // flexible array member.
14642         Record->setHasFlexibleArrayMember(true);
14643         if (!Record->isUnion()) {
14644           // If this is a struct/class and this is not the last element, reject
14645           // it.  Note that GCC supports variable sized arrays in the middle of
14646           // structures.
14647           if (i + 1 != Fields.end())
14648             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14649               << FD->getDeclName() << FD->getType();
14650           else {
14651             // We support flexible arrays at the end of structs in
14652             // other structs as an extension.
14653             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14654               << FD->getDeclName();
14655           }
14656         }
14657       }
14658       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14659           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14660                                  diag::err_abstract_type_in_decl,
14661                                  AbstractIvarType)) {
14662         // Ivars can not have abstract class types
14663         FD->setInvalidDecl();
14664       }
14665       if (Record && FDTTy->getDecl()->hasObjectMember())
14666         Record->setHasObjectMember(true);
14667       if (Record && FDTTy->getDecl()->hasVolatileMember())
14668         Record->setHasVolatileMember(true);
14669     } else if (FDTy->isObjCObjectType()) {
14670       /// A field cannot be an Objective-c object
14671       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14672         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14673       QualType T = Context.getObjCObjectPointerType(FD->getType());
14674       FD->setType(T);
14675     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14676                Record && !ObjCFieldLifetimeErrReported &&
14677                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14678       // It's an error in ARC or Weak if a field has lifetime.
14679       // We don't want to report this in a system header, though,
14680       // so we just make the field unavailable.
14681       // FIXME: that's really not sufficient; we need to make the type
14682       // itself invalid to, say, initialize or copy.
14683       QualType T = FD->getType();
14684       if (T.hasNonTrivialObjCLifetime()) {
14685         SourceLocation loc = FD->getLocation();
14686         if (getSourceManager().isInSystemHeader(loc)) {
14687           if (!FD->hasAttr<UnavailableAttr>()) {
14688             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14689                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14690           }
14691         } else {
14692           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14693             << T->isBlockPointerType() << Record->getTagKind();
14694         }
14695         ObjCFieldLifetimeErrReported = true;
14696       }
14697     } else if (getLangOpts().ObjC1 &&
14698                getLangOpts().getGC() != LangOptions::NonGC &&
14699                Record && !Record->hasObjectMember()) {
14700       if (FD->getType()->isObjCObjectPointerType() ||
14701           FD->getType().isObjCGCStrong())
14702         Record->setHasObjectMember(true);
14703       else if (Context.getAsArrayType(FD->getType())) {
14704         QualType BaseType = Context.getBaseElementType(FD->getType());
14705         if (BaseType->isRecordType() &&
14706             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14707           Record->setHasObjectMember(true);
14708         else if (BaseType->isObjCObjectPointerType() ||
14709                  BaseType.isObjCGCStrong())
14710                Record->setHasObjectMember(true);
14711       }
14712     }
14713     if (Record && FD->getType().isVolatileQualified())
14714       Record->setHasVolatileMember(true);
14715     // Keep track of the number of named members.
14716     if (FD->getIdentifier())
14717       ++NumNamedMembers;
14718   }
14719
14720   // Okay, we successfully defined 'Record'.
14721   if (Record) {
14722     bool Completed = false;
14723     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14724       if (!CXXRecord->isInvalidDecl()) {
14725         // Set access bits correctly on the directly-declared conversions.
14726         for (CXXRecordDecl::conversion_iterator
14727                I = CXXRecord->conversion_begin(),
14728                E = CXXRecord->conversion_end(); I != E; ++I)
14729           I.setAccess((*I)->getAccess());
14730       }
14731
14732       if (!CXXRecord->isDependentType()) {
14733         if (CXXRecord->hasUserDeclaredDestructor()) {
14734           // Adjust user-defined destructor exception spec.
14735           if (getLangOpts().CPlusPlus11)
14736             AdjustDestructorExceptionSpec(CXXRecord,
14737                                           CXXRecord->getDestructor());
14738         }
14739
14740         if (!CXXRecord->isInvalidDecl()) {
14741           // Add any implicitly-declared members to this class.
14742           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14743
14744           // If we have virtual base classes, we may end up finding multiple
14745           // final overriders for a given virtual function. Check for this
14746           // problem now.
14747           if (CXXRecord->getNumVBases()) {
14748             CXXFinalOverriderMap FinalOverriders;
14749             CXXRecord->getFinalOverriders(FinalOverriders);
14750
14751             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14752                                              MEnd = FinalOverriders.end();
14753                  M != MEnd; ++M) {
14754               for (OverridingMethods::iterator SO = M->second.begin(),
14755                                             SOEnd = M->second.end();
14756                    SO != SOEnd; ++SO) {
14757                 assert(SO->second.size() > 0 &&
14758                        "Virtual function without overridding functions?");
14759                 if (SO->second.size() == 1)
14760                   continue;
14761
14762                 // C++ [class.virtual]p2:
14763                 //   In a derived class, if a virtual member function of a base
14764                 //   class subobject has more than one final overrider the
14765                 //   program is ill-formed.
14766                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14767                   << (const NamedDecl *)M->first << Record;
14768                 Diag(M->first->getLocation(),
14769                      diag::note_overridden_virtual_function);
14770                 for (OverridingMethods::overriding_iterator
14771                           OM = SO->second.begin(),
14772                        OMEnd = SO->second.end();
14773                      OM != OMEnd; ++OM)
14774                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14775                     << (const NamedDecl *)M->first << OM->Method->getParent();
14776
14777                 Record->setInvalidDecl();
14778               }
14779             }
14780             CXXRecord->completeDefinition(&FinalOverriders);
14781             Completed = true;
14782           }
14783         }
14784       }
14785     }
14786
14787     if (!Completed)
14788       Record->completeDefinition();
14789
14790     // We may have deferred checking for a deleted destructor. Check now.
14791     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14792       auto *Dtor = CXXRecord->getDestructor();
14793       if (Dtor && Dtor->isImplicit() &&
14794           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14795         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14796     }
14797
14798     if (Record->hasAttrs()) {
14799       CheckAlignasUnderalignment(Record);
14800
14801       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14802         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14803                                            IA->getRange(), IA->getBestCase(),
14804                                            IA->getSemanticSpelling());
14805     }
14806
14807     // Check if the structure/union declaration is a type that can have zero
14808     // size in C. For C this is a language extension, for C++ it may cause
14809     // compatibility problems.
14810     bool CheckForZeroSize;
14811     if (!getLangOpts().CPlusPlus) {
14812       CheckForZeroSize = true;
14813     } else {
14814       // For C++ filter out types that cannot be referenced in C code.
14815       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14816       CheckForZeroSize =
14817           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14818           !CXXRecord->isDependentType() &&
14819           CXXRecord->isCLike();
14820     }
14821     if (CheckForZeroSize) {
14822       bool ZeroSize = true;
14823       bool IsEmpty = true;
14824       unsigned NonBitFields = 0;
14825       for (RecordDecl::field_iterator I = Record->field_begin(),
14826                                       E = Record->field_end();
14827            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14828         IsEmpty = false;
14829         if (I->isUnnamedBitfield()) {
14830           if (I->getBitWidthValue(Context) > 0)
14831             ZeroSize = false;
14832         } else {
14833           ++NonBitFields;
14834           QualType FieldType = I->getType();
14835           if (FieldType->isIncompleteType() ||
14836               !Context.getTypeSizeInChars(FieldType).isZero())
14837             ZeroSize = false;
14838         }
14839       }
14840
14841       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14842       // allowed in C++, but warn if its declaration is inside
14843       // extern "C" block.
14844       if (ZeroSize) {
14845         Diag(RecLoc, getLangOpts().CPlusPlus ?
14846                          diag::warn_zero_size_struct_union_in_extern_c :
14847                          diag::warn_zero_size_struct_union_compat)
14848           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14849       }
14850
14851       // Structs without named members are extension in C (C99 6.7.2.1p7),
14852       // but are accepted by GCC.
14853       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14854         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14855                                diag::ext_no_named_members_in_struct_union)
14856           << Record->isUnion();
14857       }
14858     }
14859   } else {
14860     ObjCIvarDecl **ClsFields =
14861       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14862     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14863       ID->setEndOfDefinitionLoc(RBrac);
14864       // Add ivar's to class's DeclContext.
14865       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14866         ClsFields[i]->setLexicalDeclContext(ID);
14867         ID->addDecl(ClsFields[i]);
14868       }
14869       // Must enforce the rule that ivars in the base classes may not be
14870       // duplicates.
14871       if (ID->getSuperClass())
14872         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14873     } else if (ObjCImplementationDecl *IMPDecl =
14874                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14875       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14876       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14877         // Ivar declared in @implementation never belongs to the implementation.
14878         // Only it is in implementation's lexical context.
14879         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14880       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14881       IMPDecl->setIvarLBraceLoc(LBrac);
14882       IMPDecl->setIvarRBraceLoc(RBrac);
14883     } else if (ObjCCategoryDecl *CDecl =
14884                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14885       // case of ivars in class extension; all other cases have been
14886       // reported as errors elsewhere.
14887       // FIXME. Class extension does not have a LocEnd field.
14888       // CDecl->setLocEnd(RBrac);
14889       // Add ivar's to class extension's DeclContext.
14890       // Diagnose redeclaration of private ivars.
14891       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14892       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14893         if (IDecl) {
14894           if (const ObjCIvarDecl *ClsIvar =
14895               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14896             Diag(ClsFields[i]->getLocation(),
14897                  diag::err_duplicate_ivar_declaration);
14898             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14899             continue;
14900           }
14901           for (const auto *Ext : IDecl->known_extensions()) {
14902             if (const ObjCIvarDecl *ClsExtIvar
14903                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14904               Diag(ClsFields[i]->getLocation(),
14905                    diag::err_duplicate_ivar_declaration);
14906               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14907               continue;
14908             }
14909           }
14910         }
14911         ClsFields[i]->setLexicalDeclContext(CDecl);
14912         CDecl->addDecl(ClsFields[i]);
14913       }
14914       CDecl->setIvarLBraceLoc(LBrac);
14915       CDecl->setIvarRBraceLoc(RBrac);
14916     }
14917   }
14918
14919   if (Attr)
14920     ProcessDeclAttributeList(S, Record, Attr);
14921 }
14922
14923 /// \brief Determine whether the given integral value is representable within
14924 /// the given type T.
14925 static bool isRepresentableIntegerValue(ASTContext &Context,
14926                                         llvm::APSInt &Value,
14927                                         QualType T) {
14928   assert(T->isIntegralType(Context) && "Integral type required!");
14929   unsigned BitWidth = Context.getIntWidth(T);
14930
14931   if (Value.isUnsigned() || Value.isNonNegative()) {
14932     if (T->isSignedIntegerOrEnumerationType())
14933       --BitWidth;
14934     return Value.getActiveBits() <= BitWidth;
14935   }
14936   return Value.getMinSignedBits() <= BitWidth;
14937 }
14938
14939 // \brief Given an integral type, return the next larger integral type
14940 // (or a NULL type of no such type exists).
14941 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14942   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14943   // enum checking below.
14944   assert(T->isIntegralType(Context) && "Integral type required!");
14945   const unsigned NumTypes = 4;
14946   QualType SignedIntegralTypes[NumTypes] = {
14947     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14948   };
14949   QualType UnsignedIntegralTypes[NumTypes] = {
14950     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14951     Context.UnsignedLongLongTy
14952   };
14953
14954   unsigned BitWidth = Context.getTypeSize(T);
14955   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14956                                                         : UnsignedIntegralTypes;
14957   for (unsigned I = 0; I != NumTypes; ++I)
14958     if (Context.getTypeSize(Types[I]) > BitWidth)
14959       return Types[I];
14960
14961   return QualType();
14962 }
14963
14964 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14965                                           EnumConstantDecl *LastEnumConst,
14966                                           SourceLocation IdLoc,
14967                                           IdentifierInfo *Id,
14968                                           Expr *Val) {
14969   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14970   llvm::APSInt EnumVal(IntWidth);
14971   QualType EltTy;
14972
14973   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14974     Val = nullptr;
14975
14976   if (Val)
14977     Val = DefaultLvalueConversion(Val).get();
14978
14979   if (Val) {
14980     if (Enum->isDependentType() || Val->isTypeDependent())
14981       EltTy = Context.DependentTy;
14982     else {
14983       SourceLocation ExpLoc;
14984       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14985           !getLangOpts().MSVCCompat) {
14986         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14987         // constant-expression in the enumerator-definition shall be a converted
14988         // constant expression of the underlying type.
14989         EltTy = Enum->getIntegerType();
14990         ExprResult Converted =
14991           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14992                                            CCEK_Enumerator);
14993         if (Converted.isInvalid())
14994           Val = nullptr;
14995         else
14996           Val = Converted.get();
14997       } else if (!Val->isValueDependent() &&
14998                  !(Val = VerifyIntegerConstantExpression(Val,
14999                                                          &EnumVal).get())) {
15000         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15001       } else {
15002         if (Enum->isFixed()) {
15003           EltTy = Enum->getIntegerType();
15004
15005           // In Obj-C and Microsoft mode, require the enumeration value to be
15006           // representable in the underlying type of the enumeration. In C++11,
15007           // we perform a non-narrowing conversion as part of converted constant
15008           // expression checking.
15009           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15010             if (getLangOpts().MSVCCompat) {
15011               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15012               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15013             } else
15014               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15015           } else
15016             Val = ImpCastExprToType(Val, EltTy,
15017                                     EltTy->isBooleanType() ?
15018                                     CK_IntegralToBoolean : CK_IntegralCast)
15019                     .get();
15020         } else if (getLangOpts().CPlusPlus) {
15021           // C++11 [dcl.enum]p5:
15022           //   If the underlying type is not fixed, the type of each enumerator
15023           //   is the type of its initializing value:
15024           //     - If an initializer is specified for an enumerator, the
15025           //       initializing value has the same type as the expression.
15026           EltTy = Val->getType();
15027         } else {
15028           // C99 6.7.2.2p2:
15029           //   The expression that defines the value of an enumeration constant
15030           //   shall be an integer constant expression that has a value
15031           //   representable as an int.
15032
15033           // Complain if the value is not representable in an int.
15034           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15035             Diag(IdLoc, diag::ext_enum_value_not_int)
15036               << EnumVal.toString(10) << Val->getSourceRange()
15037               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15038           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15039             // Force the type of the expression to 'int'.
15040             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15041           }
15042           EltTy = Val->getType();
15043         }
15044       }
15045     }
15046   }
15047
15048   if (!Val) {
15049     if (Enum->isDependentType())
15050       EltTy = Context.DependentTy;
15051     else if (!LastEnumConst) {
15052       // C++0x [dcl.enum]p5:
15053       //   If the underlying type is not fixed, the type of each enumerator
15054       //   is the type of its initializing value:
15055       //     - If no initializer is specified for the first enumerator, the
15056       //       initializing value has an unspecified integral type.
15057       //
15058       // GCC uses 'int' for its unspecified integral type, as does
15059       // C99 6.7.2.2p3.
15060       if (Enum->isFixed()) {
15061         EltTy = Enum->getIntegerType();
15062       }
15063       else {
15064         EltTy = Context.IntTy;
15065       }
15066     } else {
15067       // Assign the last value + 1.
15068       EnumVal = LastEnumConst->getInitVal();
15069       ++EnumVal;
15070       EltTy = LastEnumConst->getType();
15071
15072       // Check for overflow on increment.
15073       if (EnumVal < LastEnumConst->getInitVal()) {
15074         // C++0x [dcl.enum]p5:
15075         //   If the underlying type is not fixed, the type of each enumerator
15076         //   is the type of its initializing value:
15077         //
15078         //     - Otherwise the type of the initializing value is the same as
15079         //       the type of the initializing value of the preceding enumerator
15080         //       unless the incremented value is not representable in that type,
15081         //       in which case the type is an unspecified integral type
15082         //       sufficient to contain the incremented value. If no such type
15083         //       exists, the program is ill-formed.
15084         QualType T = getNextLargerIntegralType(Context, EltTy);
15085         if (T.isNull() || Enum->isFixed()) {
15086           // There is no integral type larger enough to represent this
15087           // value. Complain, then allow the value to wrap around.
15088           EnumVal = LastEnumConst->getInitVal();
15089           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15090           ++EnumVal;
15091           if (Enum->isFixed())
15092             // When the underlying type is fixed, this is ill-formed.
15093             Diag(IdLoc, diag::err_enumerator_wrapped)
15094               << EnumVal.toString(10)
15095               << EltTy;
15096           else
15097             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15098               << EnumVal.toString(10);
15099         } else {
15100           EltTy = T;
15101         }
15102
15103         // Retrieve the last enumerator's value, extent that type to the
15104         // type that is supposed to be large enough to represent the incremented
15105         // value, then increment.
15106         EnumVal = LastEnumConst->getInitVal();
15107         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15108         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15109         ++EnumVal;
15110
15111         // If we're not in C++, diagnose the overflow of enumerator values,
15112         // which in C99 means that the enumerator value is not representable in
15113         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15114         // permits enumerator values that are representable in some larger
15115         // integral type.
15116         if (!getLangOpts().CPlusPlus && !T.isNull())
15117           Diag(IdLoc, diag::warn_enum_value_overflow);
15118       } else if (!getLangOpts().CPlusPlus &&
15119                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15120         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15121         Diag(IdLoc, diag::ext_enum_value_not_int)
15122           << EnumVal.toString(10) << 1;
15123       }
15124     }
15125   }
15126
15127   if (!EltTy->isDependentType()) {
15128     // Make the enumerator value match the signedness and size of the
15129     // enumerator's type.
15130     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15131     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15132   }
15133
15134   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15135                                   Val, EnumVal);
15136 }
15137
15138 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15139                                                 SourceLocation IILoc) {
15140   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15141       !getLangOpts().CPlusPlus)
15142     return SkipBodyInfo();
15143
15144   // We have an anonymous enum definition. Look up the first enumerator to
15145   // determine if we should merge the definition with an existing one and
15146   // skip the body.
15147   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15148                                          ForRedeclaration);
15149   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15150   if (!PrevECD)
15151     return SkipBodyInfo();
15152
15153   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15154   NamedDecl *Hidden;
15155   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15156     SkipBodyInfo Skip;
15157     Skip.Previous = Hidden;
15158     return Skip;
15159   }
15160
15161   return SkipBodyInfo();
15162 }
15163
15164 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15165                               SourceLocation IdLoc, IdentifierInfo *Id,
15166                               AttributeList *Attr,
15167                               SourceLocation EqualLoc, Expr *Val) {
15168   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15169   EnumConstantDecl *LastEnumConst =
15170     cast_or_null<EnumConstantDecl>(lastEnumConst);
15171
15172   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15173   // we find one that is.
15174   S = getNonFieldDeclScope(S);
15175
15176   // Verify that there isn't already something declared with this name in this
15177   // scope.
15178   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15179                                          ForRedeclaration);
15180   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15181     // Maybe we will complain about the shadowed template parameter.
15182     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15183     // Just pretend that we didn't see the previous declaration.
15184     PrevDecl = nullptr;
15185   }
15186
15187   // C++ [class.mem]p15:
15188   // If T is the name of a class, then each of the following shall have a name
15189   // different from T:
15190   // - every enumerator of every member of class T that is an unscoped
15191   // enumerated type
15192   if (!TheEnumDecl->isScoped())
15193     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15194                             DeclarationNameInfo(Id, IdLoc));
15195
15196   EnumConstantDecl *New =
15197     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15198   if (!New)
15199     return nullptr;
15200
15201   if (PrevDecl) {
15202     // When in C++, we may get a TagDecl with the same name; in this case the
15203     // enum constant will 'hide' the tag.
15204     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15205            "Received TagDecl when not in C++!");
15206     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15207         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15208       if (isa<EnumConstantDecl>(PrevDecl))
15209         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15210       else
15211         Diag(IdLoc, diag::err_redefinition) << Id;
15212       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15213       return nullptr;
15214     }
15215   }
15216
15217   // Process attributes.
15218   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15219   AddPragmaAttributes(S, New);
15220
15221   // Register this decl in the current scope stack.
15222   New->setAccess(TheEnumDecl->getAccess());
15223   PushOnScopeChains(New, S);
15224
15225   ActOnDocumentableDecl(New);
15226
15227   return New;
15228 }
15229
15230 // Returns true when the enum initial expression does not trigger the
15231 // duplicate enum warning.  A few common cases are exempted as follows:
15232 // Element2 = Element1
15233 // Element2 = Element1 + 1
15234 // Element2 = Element1 - 1
15235 // Where Element2 and Element1 are from the same enum.
15236 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15237   Expr *InitExpr = ECD->getInitExpr();
15238   if (!InitExpr)
15239     return true;
15240   InitExpr = InitExpr->IgnoreImpCasts();
15241
15242   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15243     if (!BO->isAdditiveOp())
15244       return true;
15245     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15246     if (!IL)
15247       return true;
15248     if (IL->getValue() != 1)
15249       return true;
15250
15251     InitExpr = BO->getLHS();
15252   }
15253
15254   // This checks if the elements are from the same enum.
15255   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15256   if (!DRE)
15257     return true;
15258
15259   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15260   if (!EnumConstant)
15261     return true;
15262
15263   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15264       Enum)
15265     return true;
15266
15267   return false;
15268 }
15269
15270 namespace {
15271 struct DupKey {
15272   int64_t val;
15273   bool isTombstoneOrEmptyKey;
15274   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15275     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15276 };
15277
15278 static DupKey GetDupKey(const llvm::APSInt& Val) {
15279   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15280                 false);
15281 }
15282
15283 struct DenseMapInfoDupKey {
15284   static DupKey getEmptyKey() { return DupKey(0, true); }
15285   static DupKey getTombstoneKey() { return DupKey(1, true); }
15286   static unsigned getHashValue(const DupKey Key) {
15287     return (unsigned)(Key.val * 37);
15288   }
15289   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15290     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15291            LHS.val == RHS.val;
15292   }
15293 };
15294 } // end anonymous namespace
15295
15296 // Emits a warning when an element is implicitly set a value that
15297 // a previous element has already been set to.
15298 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15299                                         EnumDecl *Enum,
15300                                         QualType EnumType) {
15301   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15302     return;
15303   // Avoid anonymous enums
15304   if (!Enum->getIdentifier())
15305     return;
15306
15307   // Only check for small enums.
15308   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15309     return;
15310
15311   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15312   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15313
15314   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15315   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15316           ValueToVectorMap;
15317
15318   DuplicatesVector DupVector;
15319   ValueToVectorMap EnumMap;
15320
15321   // Populate the EnumMap with all values represented by enum constants without
15322   // an initialier.
15323   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15324     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15325
15326     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15327     // this constant.  Skip this enum since it may be ill-formed.
15328     if (!ECD) {
15329       return;
15330     }
15331
15332     if (ECD->getInitExpr())
15333       continue;
15334
15335     DupKey Key = GetDupKey(ECD->getInitVal());
15336     DeclOrVector &Entry = EnumMap[Key];
15337
15338     // First time encountering this value.
15339     if (Entry.isNull())
15340       Entry = ECD;
15341   }
15342
15343   // Create vectors for any values that has duplicates.
15344   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15345     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15346     if (!ValidDuplicateEnum(ECD, Enum))
15347       continue;
15348
15349     DupKey Key = GetDupKey(ECD->getInitVal());
15350
15351     DeclOrVector& Entry = EnumMap[Key];
15352     if (Entry.isNull())
15353       continue;
15354
15355     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15356       // Ensure constants are different.
15357       if (D == ECD)
15358         continue;
15359
15360       // Create new vector and push values onto it.
15361       ECDVector *Vec = new ECDVector();
15362       Vec->push_back(D);
15363       Vec->push_back(ECD);
15364
15365       // Update entry to point to the duplicates vector.
15366       Entry = Vec;
15367
15368       // Store the vector somewhere we can consult later for quick emission of
15369       // diagnostics.
15370       DupVector.push_back(Vec);
15371       continue;
15372     }
15373
15374     ECDVector *Vec = Entry.get<ECDVector*>();
15375     // Make sure constants are not added more than once.
15376     if (*Vec->begin() == ECD)
15377       continue;
15378
15379     Vec->push_back(ECD);
15380   }
15381
15382   // Emit diagnostics.
15383   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15384                                   DupVectorEnd = DupVector.end();
15385        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15386     ECDVector *Vec = *DupVectorIter;
15387     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15388
15389     // Emit warning for one enum constant.
15390     ECDVector::iterator I = Vec->begin();
15391     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15392       << (*I)->getName() << (*I)->getInitVal().toString(10)
15393       << (*I)->getSourceRange();
15394     ++I;
15395
15396     // Emit one note for each of the remaining enum constants with
15397     // the same value.
15398     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15399       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15400         << (*I)->getName() << (*I)->getInitVal().toString(10)
15401         << (*I)->getSourceRange();
15402     delete Vec;
15403   }
15404 }
15405
15406 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15407                              bool AllowMask) const {
15408   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15409   assert(ED->isCompleteDefinition() && "expected enum definition");
15410
15411   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15412   llvm::APInt &FlagBits = R.first->second;
15413
15414   if (R.second) {
15415     for (auto *E : ED->enumerators()) {
15416       const auto &EVal = E->getInitVal();
15417       // Only single-bit enumerators introduce new flag values.
15418       if (EVal.isPowerOf2())
15419         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15420     }
15421   }
15422
15423   // A value is in a flag enum if either its bits are a subset of the enum's
15424   // flag bits (the first condition) or we are allowing masks and the same is
15425   // true of its complement (the second condition). When masks are allowed, we
15426   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15427   //
15428   // While it's true that any value could be used as a mask, the assumption is
15429   // that a mask will have all of the insignificant bits set. Anything else is
15430   // likely a logic error.
15431   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15432   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15433 }
15434
15435 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15436                          Decl *EnumDeclX,
15437                          ArrayRef<Decl *> Elements,
15438                          Scope *S, AttributeList *Attr) {
15439   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15440   QualType EnumType = Context.getTypeDeclType(Enum);
15441
15442   if (Attr)
15443     ProcessDeclAttributeList(S, Enum, Attr);
15444
15445   if (Enum->isDependentType()) {
15446     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15447       EnumConstantDecl *ECD =
15448         cast_or_null<EnumConstantDecl>(Elements[i]);
15449       if (!ECD) continue;
15450
15451       ECD->setType(EnumType);
15452     }
15453
15454     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15455     return;
15456   }
15457
15458   // TODO: If the result value doesn't fit in an int, it must be a long or long
15459   // long value.  ISO C does not support this, but GCC does as an extension,
15460   // emit a warning.
15461   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15462   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15463   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15464
15465   // Verify that all the values are okay, compute the size of the values, and
15466   // reverse the list.
15467   unsigned NumNegativeBits = 0;
15468   unsigned NumPositiveBits = 0;
15469
15470   // Keep track of whether all elements have type int.
15471   bool AllElementsInt = true;
15472
15473   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15474     EnumConstantDecl *ECD =
15475       cast_or_null<EnumConstantDecl>(Elements[i]);
15476     if (!ECD) continue;  // Already issued a diagnostic.
15477
15478     const llvm::APSInt &InitVal = ECD->getInitVal();
15479
15480     // Keep track of the size of positive and negative values.
15481     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15482       NumPositiveBits = std::max(NumPositiveBits,
15483                                  (unsigned)InitVal.getActiveBits());
15484     else
15485       NumNegativeBits = std::max(NumNegativeBits,
15486                                  (unsigned)InitVal.getMinSignedBits());
15487
15488     // Keep track of whether every enum element has type int (very commmon).
15489     if (AllElementsInt)
15490       AllElementsInt = ECD->getType() == Context.IntTy;
15491   }
15492
15493   // Figure out the type that should be used for this enum.
15494   QualType BestType;
15495   unsigned BestWidth;
15496
15497   // C++0x N3000 [conv.prom]p3:
15498   //   An rvalue of an unscoped enumeration type whose underlying
15499   //   type is not fixed can be converted to an rvalue of the first
15500   //   of the following types that can represent all the values of
15501   //   the enumeration: int, unsigned int, long int, unsigned long
15502   //   int, long long int, or unsigned long long int.
15503   // C99 6.4.4.3p2:
15504   //   An identifier declared as an enumeration constant has type int.
15505   // The C99 rule is modified by a gcc extension
15506   QualType BestPromotionType;
15507
15508   bool Packed = Enum->hasAttr<PackedAttr>();
15509   // -fshort-enums is the equivalent to specifying the packed attribute on all
15510   // enum definitions.
15511   if (LangOpts.ShortEnums)
15512     Packed = true;
15513
15514   if (Enum->isFixed()) {
15515     BestType = Enum->getIntegerType();
15516     if (BestType->isPromotableIntegerType())
15517       BestPromotionType = Context.getPromotedIntegerType(BestType);
15518     else
15519       BestPromotionType = BestType;
15520
15521     BestWidth = Context.getIntWidth(BestType);
15522   }
15523   else if (NumNegativeBits) {
15524     // If there is a negative value, figure out the smallest integer type (of
15525     // int/long/longlong) that fits.
15526     // If it's packed, check also if it fits a char or a short.
15527     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15528       BestType = Context.SignedCharTy;
15529       BestWidth = CharWidth;
15530     } else if (Packed && NumNegativeBits <= ShortWidth &&
15531                NumPositiveBits < ShortWidth) {
15532       BestType = Context.ShortTy;
15533       BestWidth = ShortWidth;
15534     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15535       BestType = Context.IntTy;
15536       BestWidth = IntWidth;
15537     } else {
15538       BestWidth = Context.getTargetInfo().getLongWidth();
15539
15540       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15541         BestType = Context.LongTy;
15542       } else {
15543         BestWidth = Context.getTargetInfo().getLongLongWidth();
15544
15545         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15546           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15547         BestType = Context.LongLongTy;
15548       }
15549     }
15550     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15551   } else {
15552     // If there is no negative value, figure out the smallest type that fits
15553     // all of the enumerator values.
15554     // If it's packed, check also if it fits a char or a short.
15555     if (Packed && NumPositiveBits <= CharWidth) {
15556       BestType = Context.UnsignedCharTy;
15557       BestPromotionType = Context.IntTy;
15558       BestWidth = CharWidth;
15559     } else if (Packed && NumPositiveBits <= ShortWidth) {
15560       BestType = Context.UnsignedShortTy;
15561       BestPromotionType = Context.IntTy;
15562       BestWidth = ShortWidth;
15563     } else if (NumPositiveBits <= IntWidth) {
15564       BestType = Context.UnsignedIntTy;
15565       BestWidth = IntWidth;
15566       BestPromotionType
15567         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15568                            ? Context.UnsignedIntTy : Context.IntTy;
15569     } else if (NumPositiveBits <=
15570                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15571       BestType = Context.UnsignedLongTy;
15572       BestPromotionType
15573         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15574                            ? Context.UnsignedLongTy : Context.LongTy;
15575     } else {
15576       BestWidth = Context.getTargetInfo().getLongLongWidth();
15577       assert(NumPositiveBits <= BestWidth &&
15578              "How could an initializer get larger than ULL?");
15579       BestType = Context.UnsignedLongLongTy;
15580       BestPromotionType
15581         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15582                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15583     }
15584   }
15585
15586   // Loop over all of the enumerator constants, changing their types to match
15587   // the type of the enum if needed.
15588   for (auto *D : Elements) {
15589     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15590     if (!ECD) continue;  // Already issued a diagnostic.
15591
15592     // Standard C says the enumerators have int type, but we allow, as an
15593     // extension, the enumerators to be larger than int size.  If each
15594     // enumerator value fits in an int, type it as an int, otherwise type it the
15595     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15596     // that X has type 'int', not 'unsigned'.
15597
15598     // Determine whether the value fits into an int.
15599     llvm::APSInt InitVal = ECD->getInitVal();
15600
15601     // If it fits into an integer type, force it.  Otherwise force it to match
15602     // the enum decl type.
15603     QualType NewTy;
15604     unsigned NewWidth;
15605     bool NewSign;
15606     if (!getLangOpts().CPlusPlus &&
15607         !Enum->isFixed() &&
15608         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15609       NewTy = Context.IntTy;
15610       NewWidth = IntWidth;
15611       NewSign = true;
15612     } else if (ECD->getType() == BestType) {
15613       // Already the right type!
15614       if (getLangOpts().CPlusPlus)
15615         // C++ [dcl.enum]p4: Following the closing brace of an
15616         // enum-specifier, each enumerator has the type of its
15617         // enumeration.
15618         ECD->setType(EnumType);
15619       continue;
15620     } else {
15621       NewTy = BestType;
15622       NewWidth = BestWidth;
15623       NewSign = BestType->isSignedIntegerOrEnumerationType();
15624     }
15625
15626     // Adjust the APSInt value.
15627     InitVal = InitVal.extOrTrunc(NewWidth);
15628     InitVal.setIsSigned(NewSign);
15629     ECD->setInitVal(InitVal);
15630
15631     // Adjust the Expr initializer and type.
15632     if (ECD->getInitExpr() &&
15633         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15634       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15635                                                 CK_IntegralCast,
15636                                                 ECD->getInitExpr(),
15637                                                 /*base paths*/ nullptr,
15638                                                 VK_RValue));
15639     if (getLangOpts().CPlusPlus)
15640       // C++ [dcl.enum]p4: Following the closing brace of an
15641       // enum-specifier, each enumerator has the type of its
15642       // enumeration.
15643       ECD->setType(EnumType);
15644     else
15645       ECD->setType(NewTy);
15646   }
15647
15648   Enum->completeDefinition(BestType, BestPromotionType,
15649                            NumPositiveBits, NumNegativeBits);
15650
15651   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15652
15653   if (Enum->isClosedFlag()) {
15654     for (Decl *D : Elements) {
15655       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15656       if (!ECD) continue;  // Already issued a diagnostic.
15657
15658       llvm::APSInt InitVal = ECD->getInitVal();
15659       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15660           !IsValueInFlagEnum(Enum, InitVal, true))
15661         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15662           << ECD << Enum;
15663     }
15664   }
15665
15666   // Now that the enum type is defined, ensure it's not been underaligned.
15667   if (Enum->hasAttrs())
15668     CheckAlignasUnderalignment(Enum);
15669 }
15670
15671 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15672                                   SourceLocation StartLoc,
15673                                   SourceLocation EndLoc) {
15674   StringLiteral *AsmString = cast<StringLiteral>(expr);
15675
15676   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15677                                                    AsmString, StartLoc,
15678                                                    EndLoc);
15679   CurContext->addDecl(New);
15680   return New;
15681 }
15682
15683 static void checkModuleImportContext(Sema &S, Module *M,
15684                                      SourceLocation ImportLoc, DeclContext *DC,
15685                                      bool FromInclude = false) {
15686   SourceLocation ExternCLoc;
15687
15688   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15689     switch (LSD->getLanguage()) {
15690     case LinkageSpecDecl::lang_c:
15691       if (ExternCLoc.isInvalid())
15692         ExternCLoc = LSD->getLocStart();
15693       break;
15694     case LinkageSpecDecl::lang_cxx:
15695       break;
15696     }
15697     DC = LSD->getParent();
15698   }
15699
15700   while (isa<LinkageSpecDecl>(DC))
15701     DC = DC->getParent();
15702
15703   if (!isa<TranslationUnitDecl>(DC)) {
15704     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15705                           ? diag::ext_module_import_not_at_top_level_noop
15706                           : diag::err_module_import_not_at_top_level_fatal)
15707         << M->getFullModuleName() << DC;
15708     S.Diag(cast<Decl>(DC)->getLocStart(),
15709            diag::note_module_import_not_at_top_level) << DC;
15710   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15711     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15712       << M->getFullModuleName();
15713     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15714   }
15715 }
15716
15717 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
15718                                            SourceLocation ModuleLoc,
15719                                            ModuleDeclKind MDK,
15720                                            ModuleIdPath Path) {
15721   // A module implementation unit requires that we are not compiling a module
15722   // of any kind. A module interface unit requires that we are not compiling a
15723   // module map.
15724   switch (getLangOpts().getCompilingModule()) {
15725   case LangOptions::CMK_None:
15726     // It's OK to compile a module interface as a normal translation unit.
15727     break;
15728
15729   case LangOptions::CMK_ModuleInterface:
15730     if (MDK != ModuleDeclKind::Implementation)
15731       break;
15732
15733     // We were asked to compile a module interface unit but this is a module
15734     // implementation unit. That indicates the 'export' is missing.
15735     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15736       << FixItHint::CreateInsertion(ModuleLoc, "export ");
15737     break;
15738
15739   case LangOptions::CMK_ModuleMap:
15740     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
15741     return nullptr;
15742   }
15743
15744   // FIXME: Create a ModuleDecl and return it.
15745
15746   // FIXME: Most of this work should be done by the preprocessor rather than
15747   // here, in order to support macro import.
15748
15749   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
15750   // modules, the dots here are just another character that can appear in a
15751   // module name.
15752   std::string ModuleName;
15753   for (auto &Piece : Path) {
15754     if (!ModuleName.empty())
15755       ModuleName += ".";
15756     ModuleName += Piece.first->getName();
15757   }
15758
15759   // If a module name was explicitly specified on the command line, it must be
15760   // correct.
15761   if (!getLangOpts().CurrentModule.empty() &&
15762       getLangOpts().CurrentModule != ModuleName) {
15763     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15764         << SourceRange(Path.front().second, Path.back().second)
15765         << getLangOpts().CurrentModule;
15766     return nullptr;
15767   }
15768   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15769
15770   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15771
15772   switch (MDK) {
15773   case ModuleDeclKind::Module: {
15774     // FIXME: Check we're not in a submodule.
15775
15776     // We can't have parsed or imported a definition of this module or parsed a
15777     // module map defining it already.
15778     if (auto *M = Map.findModule(ModuleName)) {
15779       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15780       if (M->DefinitionLoc.isValid())
15781         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15782       else if (const auto *FE = M->getASTFile())
15783         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15784             << FE->getName();
15785       return nullptr;
15786     }
15787
15788     // Create a Module for the module that we're defining.
15789     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15790     assert(Mod && "module creation should not fail");
15791
15792     // Enter the semantic scope of the module.
15793     ActOnModuleBegin(ModuleLoc, Mod);
15794     return nullptr;
15795   }
15796
15797   case ModuleDeclKind::Partition:
15798     // FIXME: Check we are in a submodule of the named module.
15799     return nullptr;
15800
15801   case ModuleDeclKind::Implementation:
15802     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15803         PP.getIdentifierInfo(ModuleName), Path[0].second);
15804
15805     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15806     if (Import.isInvalid())
15807       return nullptr;
15808     return ConvertDeclToDeclGroup(Import.get());
15809   }
15810
15811   llvm_unreachable("unexpected module decl kind");
15812 }
15813
15814 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15815                                    SourceLocation ImportLoc,
15816                                    ModuleIdPath Path) {
15817   Module *Mod =
15818       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15819                                    /*IsIncludeDirective=*/false);
15820   if (!Mod)
15821     return true;
15822
15823   VisibleModules.setVisible(Mod, ImportLoc);
15824
15825   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15826
15827   // FIXME: we should support importing a submodule within a different submodule
15828   // of the same top-level module. Until we do, make it an error rather than
15829   // silently ignoring the import.
15830   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15831   // warn on a redundant import of the current module?
15832   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15833       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15834     Diag(ImportLoc, getLangOpts().isCompilingModule()
15835                         ? diag::err_module_self_import
15836                         : diag::err_module_import_in_implementation)
15837         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15838
15839   SmallVector<SourceLocation, 2> IdentifierLocs;
15840   Module *ModCheck = Mod;
15841   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15842     // If we've run out of module parents, just drop the remaining identifiers.
15843     // We need the length to be consistent.
15844     if (!ModCheck)
15845       break;
15846     ModCheck = ModCheck->Parent;
15847
15848     IdentifierLocs.push_back(Path[I].second);
15849   }
15850
15851   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15852   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15853                                           Mod, IdentifierLocs);
15854   if (!ModuleScopes.empty())
15855     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15856   TU->addDecl(Import);
15857   return Import;
15858 }
15859
15860 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15861   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15862   BuildModuleInclude(DirectiveLoc, Mod);
15863 }
15864
15865 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15866   // Determine whether we're in the #include buffer for a module. The #includes
15867   // in that buffer do not qualify as module imports; they're just an
15868   // implementation detail of us building the module.
15869   //
15870   // FIXME: Should we even get ActOnModuleInclude calls for those?
15871   bool IsInModuleIncludes =
15872       TUKind == TU_Module &&
15873       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15874
15875   bool ShouldAddImport = !IsInModuleIncludes;
15876
15877   // If this module import was due to an inclusion directive, create an
15878   // implicit import declaration to capture it in the AST.
15879   if (ShouldAddImport) {
15880     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15881     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15882                                                      DirectiveLoc, Mod,
15883                                                      DirectiveLoc);
15884     if (!ModuleScopes.empty())
15885       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15886     TU->addDecl(ImportD);
15887     Consumer.HandleImplicitImportDecl(ImportD);
15888   }
15889
15890   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15891   VisibleModules.setVisible(Mod, DirectiveLoc);
15892 }
15893
15894 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15895   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15896
15897   ModuleScopes.push_back({});
15898   ModuleScopes.back().Module = Mod;
15899   if (getLangOpts().ModulesLocalVisibility)
15900     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15901
15902   VisibleModules.setVisible(Mod, DirectiveLoc);
15903 }
15904
15905 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15906   if (getLangOpts().ModulesLocalVisibility) {
15907     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15908     // Leaving a module hides namespace names, so our visible namespace cache
15909     // is now out of date.
15910     VisibleNamespaceCache.clear();
15911   }
15912
15913   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15914          "left the wrong module scope");
15915   ModuleScopes.pop_back();
15916
15917   // We got to the end of processing a #include of a local module. Create an
15918   // ImportDecl as we would for an imported module.
15919   FileID File = getSourceManager().getFileID(EofLoc);
15920   assert(File != getSourceManager().getMainFileID() &&
15921          "end of submodule in main source file");
15922   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15923   BuildModuleInclude(DirectiveLoc, Mod);
15924 }
15925
15926 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15927                                                       Module *Mod) {
15928   // Bail if we're not allowed to implicitly import a module here.
15929   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15930     return;
15931
15932   // Create the implicit import declaration.
15933   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15934   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15935                                                    Loc, Mod, Loc);
15936   TU->addDecl(ImportD);
15937   Consumer.HandleImplicitImportDecl(ImportD);
15938
15939   // Make the module visible.
15940   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15941   VisibleModules.setVisible(Mod, Loc);
15942 }
15943
15944 /// We have parsed the start of an export declaration, including the '{'
15945 /// (if present).
15946 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15947                                  SourceLocation LBraceLoc) {
15948   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15949
15950   // C++ Modules TS draft:
15951   //   An export-declaration shall appear in the purview of a module other than
15952   //   the global module.
15953   if (ModuleScopes.empty() || !ModuleScopes.back().Module ||
15954       ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
15955     Diag(ExportLoc, diag::err_export_not_in_module_interface);
15956
15957   //   An export-declaration [...] shall not contain more than one
15958   //   export keyword.
15959   //
15960   // The intent here is that an export-declaration cannot appear within another
15961   // export-declaration.
15962   if (D->isExported())
15963     Diag(ExportLoc, diag::err_export_within_export);
15964
15965   CurContext->addDecl(D);
15966   PushDeclContext(S, D);
15967   return D;
15968 }
15969
15970 /// Complete the definition of an export declaration.
15971 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15972   auto *ED = cast<ExportDecl>(D);
15973   if (RBraceLoc.isValid())
15974     ED->setRBraceLoc(RBraceLoc);
15975
15976   // FIXME: Diagnose export of internal-linkage declaration (including
15977   // anonymous namespace).
15978
15979   PopDeclContext();
15980   return D;
15981 }
15982
15983 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15984                                       IdentifierInfo* AliasName,
15985                                       SourceLocation PragmaLoc,
15986                                       SourceLocation NameLoc,
15987                                       SourceLocation AliasNameLoc) {
15988   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15989                                          LookupOrdinaryName);
15990   AsmLabelAttr *Attr =
15991       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15992
15993   // If a declaration that:
15994   // 1) declares a function or a variable
15995   // 2) has external linkage
15996   // already exists, add a label attribute to it.
15997   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15998     if (isDeclExternC(PrevDecl))
15999       PrevDecl->addAttr(Attr);
16000     else
16001       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16002           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16003   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16004   } else
16005     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16006 }
16007
16008 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16009                              SourceLocation PragmaLoc,
16010                              SourceLocation NameLoc) {
16011   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16012
16013   if (PrevDecl) {
16014     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16015   } else {
16016     (void)WeakUndeclaredIdentifiers.insert(
16017       std::pair<IdentifierInfo*,WeakInfo>
16018         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16019   }
16020 }
16021
16022 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16023                                 IdentifierInfo* AliasName,
16024                                 SourceLocation PragmaLoc,
16025                                 SourceLocation NameLoc,
16026                                 SourceLocation AliasNameLoc) {
16027   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16028                                     LookupOrdinaryName);
16029   WeakInfo W = WeakInfo(Name, NameLoc);
16030
16031   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16032     if (!PrevDecl->hasAttr<AliasAttr>())
16033       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16034         DeclApplyPragmaWeak(TUScope, ND, W);
16035   } else {
16036     (void)WeakUndeclaredIdentifiers.insert(
16037       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16038   }
16039 }
16040
16041 Decl *Sema::getObjCDeclContext() const {
16042   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16043 }