]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp
MFV r316933: 5142 libzfs support raidz root pool (loader project)
[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                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88
89       if (AllowNonTemplates)
90         return true;
91
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102
103       return false;
104     }
105
106     return !WantClassName && candidate.isKeyword();
107   }
108
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115
116 } // end anonymous namespace
117
118 /// \brief Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw___float128:
136   case tok::kw_wchar_t:
137   case tok::kw_bool:
138   case tok::kw___underlying_type:
139   case tok::kw___auto_type:
140     return true;
141
142   case tok::annot_typename:
143   case tok::kw_char16_t:
144   case tok::kw_char32_t:
145   case tok::kw_typeof:
146   case tok::annot_decltype:
147   case tok::kw_decltype:
148     return getLangOpts().CPlusPlus;
149
150   default:
151     break;
152   }
153
154   return false;
155 }
156
157 namespace {
158 enum class UnqualifiedTypeNameLookupResult {
159   NotFound,
160   FoundNonType,
161   FoundType
162 };
163 } // end anonymous namespace
164
165 /// \brief Tries to perform unqualified lookup of the type decls in bases for
166 /// dependent class.
167 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
168 /// type decl, \a FoundType if only type decls are found.
169 static UnqualifiedTypeNameLookupResult
170 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
171                                 SourceLocation NameLoc,
172                                 const CXXRecordDecl *RD) {
173   if (!RD->hasDefinition())
174     return UnqualifiedTypeNameLookupResult::NotFound;
175   // Look for type decls in base classes.
176   UnqualifiedTypeNameLookupResult FoundTypeDecl =
177       UnqualifiedTypeNameLookupResult::NotFound;
178   for (const auto &Base : RD->bases()) {
179     const CXXRecordDecl *BaseRD = nullptr;
180     if (auto *BaseTT = Base.getType()->getAs<TagType>())
181       BaseRD = BaseTT->getAsCXXRecordDecl();
182     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
183       // Look for type decls in dependent base classes that have known primary
184       // templates.
185       if (!TST || !TST->isDependentType())
186         continue;
187       auto *TD = TST->getTemplateName().getAsTemplateDecl();
188       if (!TD)
189         continue;
190       if (auto *BasePrimaryTemplate =
191           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
192         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
193           BaseRD = BasePrimaryTemplate;
194         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
195           if (const ClassTemplatePartialSpecializationDecl *PS =
196                   CTD->findPartialSpecialization(Base.getType()))
197             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
198               BaseRD = PS;
199         }
200       }
201     }
202     if (BaseRD) {
203       for (NamedDecl *ND : BaseRD->lookup(&II)) {
204         if (!isa<TypeDecl>(ND))
205           return UnqualifiedTypeNameLookupResult::FoundNonType;
206         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
207       }
208       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
209         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
210         case UnqualifiedTypeNameLookupResult::FoundNonType:
211           return UnqualifiedTypeNameLookupResult::FoundNonType;
212         case UnqualifiedTypeNameLookupResult::FoundType:
213           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
214           break;
215         case UnqualifiedTypeNameLookupResult::NotFound:
216           break;
217         }
218       }
219     }
220   }
221
222   return FoundTypeDecl;
223 }
224
225 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
226                                                       const IdentifierInfo &II,
227                                                       SourceLocation NameLoc) {
228   // Lookup in the parent class template context, if any.
229   const CXXRecordDecl *RD = nullptr;
230   UnqualifiedTypeNameLookupResult FoundTypeDecl =
231       UnqualifiedTypeNameLookupResult::NotFound;
232   for (DeclContext *DC = S.CurContext;
233        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
234        DC = DC->getParent()) {
235     // Look for type decls in dependent base classes that have known primary
236     // templates.
237     RD = dyn_cast<CXXRecordDecl>(DC);
238     if (RD && RD->getDescribedClassTemplate())
239       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
240   }
241   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
242     return nullptr;
243
244   // We found some types in dependent base classes.  Recover as if the user
245   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
246   // lookup during template instantiation.
247   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
248
249   ASTContext &Context = S.Context;
250   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
251                                           cast<Type>(Context.getRecordType(RD)));
252   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
253
254   CXXScopeSpec SS;
255   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
256
257   TypeLocBuilder Builder;
258   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
259   DepTL.setNameLoc(NameLoc);
260   DepTL.setElaboratedKeywordLoc(SourceLocation());
261   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
262   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
263 }
264
265 /// \brief If the identifier refers to a type name within this scope,
266 /// return the declaration of that type.
267 ///
268 /// This routine performs ordinary name lookup of the identifier II
269 /// within the given scope, with optional C++ scope specifier SS, to
270 /// determine whether the name refers to a type. If so, returns an
271 /// opaque pointer (actually a QualType) corresponding to that
272 /// type. Otherwise, returns NULL.
273 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
274                              Scope *S, CXXScopeSpec *SS,
275                              bool isClassName, bool HasTrailingDot,
276                              ParsedType ObjectTypePtr,
277                              bool IsCtorOrDtorName,
278                              bool WantNontrivialTypeSourceInfo,
279                              bool IsClassTemplateDeductionContext,
280                              IdentifierInfo **CorrectedII) {
281   // FIXME: Consider allowing this outside C++1z mode as an extension.
282   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
283                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
284                               !isClassName && !HasTrailingDot;
285
286   // Determine where we will perform name lookup.
287   DeclContext *LookupCtx = nullptr;
288   if (ObjectTypePtr) {
289     QualType ObjectType = ObjectTypePtr.get();
290     if (ObjectType->isRecordType())
291       LookupCtx = computeDeclContext(ObjectType);
292   } else if (SS && SS->isNotEmpty()) {
293     LookupCtx = computeDeclContext(*SS, false);
294
295     if (!LookupCtx) {
296       if (isDependentScopeSpecifier(*SS)) {
297         // C++ [temp.res]p3:
298         //   A qualified-id that refers to a type and in which the
299         //   nested-name-specifier depends on a template-parameter (14.6.2)
300         //   shall be prefixed by the keyword typename to indicate that the
301         //   qualified-id denotes a type, forming an
302         //   elaborated-type-specifier (7.1.5.3).
303         //
304         // We therefore do not perform any name lookup if the result would
305         // refer to a member of an unknown specialization.
306         if (!isClassName && !IsCtorOrDtorName)
307           return nullptr;
308
309         // We know from the grammar that this name refers to a type,
310         // so build a dependent node to describe the type.
311         if (WantNontrivialTypeSourceInfo)
312           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
313
314         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
315         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
316                                        II, NameLoc);
317         return ParsedType::make(T);
318       }
319
320       return nullptr;
321     }
322
323     if (!LookupCtx->isDependentContext() &&
324         RequireCompleteDeclContext(*SS, LookupCtx))
325       return nullptr;
326   }
327
328   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
329   // lookup for class-names.
330   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
331                                       LookupOrdinaryName;
332   LookupResult Result(*this, &II, NameLoc, Kind);
333   if (LookupCtx) {
334     // Perform "qualified" name lookup into the declaration context we
335     // computed, which is either the type of the base of a member access
336     // expression or the declaration context associated with a prior
337     // nested-name-specifier.
338     LookupQualifiedName(Result, LookupCtx);
339
340     if (ObjectTypePtr && Result.empty()) {
341       // C++ [basic.lookup.classref]p3:
342       //   If the unqualified-id is ~type-name, the type-name is looked up
343       //   in the context of the entire postfix-expression. If the type T of
344       //   the object expression is of a class type C, the type-name is also
345       //   looked up in the scope of class C. At least one of the lookups shall
346       //   find a name that refers to (possibly cv-qualified) T.
347       LookupName(Result, S);
348     }
349   } else {
350     // Perform unqualified name lookup.
351     LookupName(Result, S);
352
353     // For unqualified lookup in a class template in MSVC mode, look into
354     // dependent base classes where the primary class template is known.
355     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
356       if (ParsedType TypeInBase =
357               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
358         return TypeInBase;
359     }
360   }
361
362   NamedDecl *IIDecl = nullptr;
363   switch (Result.getResultKind()) {
364   case LookupResult::NotFound:
365   case LookupResult::NotFoundInCurrentInstantiation:
366     if (CorrectedII) {
367       TypoCorrection Correction =
368           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
369                       llvm::make_unique<TypeNameValidatorCCC>(
370                           true, isClassName, AllowDeducedTemplate),
371                       CTK_ErrorRecovery);
372       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
373       TemplateTy Template;
374       bool MemberOfUnknownSpecialization;
375       UnqualifiedId TemplateName;
376       TemplateName.setIdentifier(NewII, NameLoc);
377       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
378       CXXScopeSpec NewSS, *NewSSPtr = SS;
379       if (SS && NNS) {
380         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
381         NewSSPtr = &NewSS;
382       }
383       if (Correction && (NNS || NewII != &II) &&
384           // Ignore a correction to a template type as the to-be-corrected
385           // identifier is not a template (typo correction for template names
386           // is handled elsewhere).
387           !(getLangOpts().CPlusPlus && NewSSPtr &&
388             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
389                            Template, MemberOfUnknownSpecialization))) {
390         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
391                                     isClassName, HasTrailingDot, ObjectTypePtr,
392                                     IsCtorOrDtorName,
393                                     WantNontrivialTypeSourceInfo,
394                                     IsClassTemplateDeductionContext);
395         if (Ty) {
396           diagnoseTypo(Correction,
397                        PDiag(diag::err_unknown_type_or_class_name_suggest)
398                          << Result.getLookupName() << isClassName);
399           if (SS && NNS)
400             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
401           *CorrectedII = NewII;
402           return Ty;
403         }
404       }
405     }
406     // If typo correction failed or was not performed, fall through
407     LLVM_FALLTHROUGH;
408   case LookupResult::FoundOverloaded:
409   case LookupResult::FoundUnresolvedValue:
410     Result.suppressDiagnostics();
411     return nullptr;
412
413   case LookupResult::Ambiguous:
414     // Recover from type-hiding ambiguities by hiding the type.  We'll
415     // do the lookup again when looking for an object, and we can
416     // diagnose the error then.  If we don't do this, then the error
417     // about hiding the type will be immediately followed by an error
418     // that only makes sense if the identifier was treated like a type.
419     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
420       Result.suppressDiagnostics();
421       return nullptr;
422     }
423
424     // Look to see if we have a type anywhere in the list of results.
425     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
426          Res != ResEnd; ++Res) {
427       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
428           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
429         if (!IIDecl ||
430             (*Res)->getLocation().getRawEncoding() <
431               IIDecl->getLocation().getRawEncoding())
432           IIDecl = *Res;
433       }
434     }
435
436     if (!IIDecl) {
437       // None of the entities we found is a type, so there is no way
438       // to even assume that the result is a type. In this case, don't
439       // complain about the ambiguity. The parser will either try to
440       // perform this lookup again (e.g., as an object name), which
441       // will produce the ambiguity, or will complain that it expected
442       // a type name.
443       Result.suppressDiagnostics();
444       return nullptr;
445     }
446
447     // We found a type within the ambiguous lookup; diagnose the
448     // ambiguity and then return that type. This might be the right
449     // answer, or it might not be, but it suppresses any attempt to
450     // perform the name lookup again.
451     break;
452
453   case LookupResult::Found:
454     IIDecl = Result.getFoundDecl();
455     break;
456   }
457
458   assert(IIDecl && "Didn't find decl");
459
460   QualType T;
461   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
462     // C++ [class.qual]p2: A lookup that would find the injected-class-name
463     // instead names the constructors of the class, except when naming a class.
464     // This is ill-formed when we're not actually forming a ctor or dtor name.
465     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
466     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
467     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
468         FoundRD->isInjectedClassName() &&
469         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
470       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
471           << &II << /*Type*/1;
472
473     DiagnoseUseOfDecl(IIDecl, NameLoc);
474
475     T = Context.getTypeDeclType(TD);
476     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
477   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
478     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
479     if (!HasTrailingDot)
480       T = Context.getObjCInterfaceType(IDecl);
481   } else if (AllowDeducedTemplate) {
482     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
483       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
484                                                        QualType(), false);
485   }
486
487   if (T.isNull()) {
488     // If it's not plausibly a type, suppress diagnostics.
489     Result.suppressDiagnostics();
490     return nullptr;
491   }
492
493   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
494   // constructor or destructor name (in such a case, the scope specifier
495   // will be attached to the enclosing Expr or Decl node).
496   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
497       !isa<ObjCInterfaceDecl>(IIDecl)) {
498     if (WantNontrivialTypeSourceInfo) {
499       // Construct a type with type-source information.
500       TypeLocBuilder Builder;
501       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
502
503       T = getElaboratedType(ETK_None, *SS, T);
504       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
505       ElabTL.setElaboratedKeywordLoc(SourceLocation());
506       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
507       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
508     } else {
509       T = getElaboratedType(ETK_None, *SS, T);
510     }
511   }
512
513   return ParsedType::make(T);
514 }
515
516 // Builds a fake NNS for the given decl context.
517 static NestedNameSpecifier *
518 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
519   for (;; DC = DC->getLookupParent()) {
520     DC = DC->getPrimaryContext();
521     auto *ND = dyn_cast<NamespaceDecl>(DC);
522     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
523       return NestedNameSpecifier::Create(Context, nullptr, ND);
524     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
525       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
526                                          RD->getTypeForDecl());
527     else if (isa<TranslationUnitDecl>(DC))
528       return NestedNameSpecifier::GlobalSpecifier(Context);
529   }
530   llvm_unreachable("something isn't in TU scope?");
531 }
532
533 /// Find the parent class with dependent bases of the innermost enclosing method
534 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
535 /// up allowing unqualified dependent type names at class-level, which MSVC
536 /// correctly rejects.
537 static const CXXRecordDecl *
538 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
539   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
540     DC = DC->getPrimaryContext();
541     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
542       if (MD->getParent()->hasAnyDependentBases())
543         return MD->getParent();
544   }
545   return nullptr;
546 }
547
548 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
549                                           SourceLocation NameLoc,
550                                           bool IsTemplateTypeArg) {
551   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
552
553   NestedNameSpecifier *NNS = nullptr;
554   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
555     // If we weren't able to parse a default template argument, delay lookup
556     // until instantiation time by making a non-dependent DependentTypeName. We
557     // pretend we saw a NestedNameSpecifier referring to the current scope, and
558     // lookup is retried.
559     // FIXME: This hurts our diagnostic quality, since we get errors like "no
560     // type named 'Foo' in 'current_namespace'" when the user didn't write any
561     // name specifiers.
562     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
563     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
564   } else if (const CXXRecordDecl *RD =
565                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
566     // Build a DependentNameType that will perform lookup into RD at
567     // instantiation time.
568     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
569                                       RD->getTypeForDecl());
570
571     // Diagnose that this identifier was undeclared, and retry the lookup during
572     // template instantiation.
573     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
574                                                                       << RD;
575   } else {
576     // This is not a situation that we should recover from.
577     return ParsedType();
578   }
579
580   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
581
582   // Build type location information.  We synthesized the qualifier, so we have
583   // to build a fake NestedNameSpecifierLoc.
584   NestedNameSpecifierLocBuilder NNSLocBuilder;
585   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
586   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
587
588   TypeLocBuilder Builder;
589   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
590   DepTL.setNameLoc(NameLoc);
591   DepTL.setElaboratedKeywordLoc(SourceLocation());
592   DepTL.setQualifierLoc(QualifierLoc);
593   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
594 }
595
596 /// isTagName() - This method is called *for error recovery purposes only*
597 /// to determine if the specified name is a valid tag name ("struct foo").  If
598 /// so, this returns the TST for the tag corresponding to it (TST_enum,
599 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
600 /// cases in C where the user forgot to specify the tag.
601 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
602   // Do a tag name lookup in this scope.
603   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
604   LookupName(R, S, false);
605   R.suppressDiagnostics();
606   if (R.getResultKind() == LookupResult::Found)
607     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
608       switch (TD->getTagKind()) {
609       case TTK_Struct: return DeclSpec::TST_struct;
610       case TTK_Interface: return DeclSpec::TST_interface;
611       case TTK_Union:  return DeclSpec::TST_union;
612       case TTK_Class:  return DeclSpec::TST_class;
613       case TTK_Enum:   return DeclSpec::TST_enum;
614       }
615     }
616
617   return DeclSpec::TST_unspecified;
618 }
619
620 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
621 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
622 /// then downgrade the missing typename error to a warning.
623 /// This is needed for MSVC compatibility; Example:
624 /// @code
625 /// template<class T> class A {
626 /// public:
627 ///   typedef int TYPE;
628 /// };
629 /// template<class T> class B : public A<T> {
630 /// public:
631 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
632 /// };
633 /// @endcode
634 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
635   if (CurContext->isRecord()) {
636     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
637       return true;
638
639     const Type *Ty = SS->getScopeRep()->getAsType();
640
641     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
642     for (const auto &Base : RD->bases())
643       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
644         return true;
645     return S->isFunctionPrototypeScope();
646   }
647   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
648 }
649
650 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
651                                    SourceLocation IILoc,
652                                    Scope *S,
653                                    CXXScopeSpec *SS,
654                                    ParsedType &SuggestedType,
655                                    bool IsTemplateName) {
656   // Don't report typename errors for editor placeholders.
657   if (II->isEditorPlaceholder())
658     return;
659   // We don't have anything to suggest (yet).
660   SuggestedType = nullptr;
661
662   // There may have been a typo in the name of the type. Look up typo
663   // results, in case we have something that we can suggest.
664   if (TypoCorrection Corrected =
665           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
666                       llvm::make_unique<TypeNameValidatorCCC>(
667                           false, false, IsTemplateName, !IsTemplateName),
668                       CTK_ErrorRecovery)) {
669     // FIXME: Support error recovery for the template-name case.
670     bool CanRecover = !IsTemplateName;
671     if (Corrected.isKeyword()) {
672       // We corrected to a keyword.
673       diagnoseTypo(Corrected,
674                    PDiag(IsTemplateName ? diag::err_no_template_suggest
675                                         : diag::err_unknown_typename_suggest)
676                        << II);
677       II = Corrected.getCorrectionAsIdentifierInfo();
678     } else {
679       // We found a similarly-named type or interface; suggest that.
680       if (!SS || !SS->isSet()) {
681         diagnoseTypo(Corrected,
682                      PDiag(IsTemplateName ? diag::err_no_template_suggest
683                                           : diag::err_unknown_typename_suggest)
684                          << II, CanRecover);
685       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
686         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
687         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
688                                 II->getName().equals(CorrectedStr);
689         diagnoseTypo(Corrected,
690                      PDiag(IsTemplateName
691                                ? diag::err_no_member_template_suggest
692                                : diag::err_unknown_nested_typename_suggest)
693                          << II << DC << DroppedSpecifier << SS->getRange(),
694                      CanRecover);
695       } else {
696         llvm_unreachable("could not have corrected a typo here");
697       }
698
699       if (!CanRecover)
700         return;
701
702       CXXScopeSpec tmpSS;
703       if (Corrected.getCorrectionSpecifier())
704         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
705                           SourceRange(IILoc));
706       // FIXME: Support class template argument deduction here.
707       SuggestedType =
708           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
709                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
710                       /*IsCtorOrDtorName=*/false,
711                       /*NonTrivialTypeSourceInfo=*/true);
712     }
713     return;
714   }
715
716   if (getLangOpts().CPlusPlus && !IsTemplateName) {
717     // See if II is a class template that the user forgot to pass arguments to.
718     UnqualifiedId Name;
719     Name.setIdentifier(II, IILoc);
720     CXXScopeSpec EmptySS;
721     TemplateTy TemplateResult;
722     bool MemberOfUnknownSpecialization;
723     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
724                        Name, nullptr, true, TemplateResult,
725                        MemberOfUnknownSpecialization) == TNK_Type_template) {
726       TemplateName TplName = TemplateResult.get();
727       Diag(IILoc, diag::err_template_missing_args)
728         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
729       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
730         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
731           << TplDecl->getTemplateParameters()->getSourceRange();
732       }
733       return;
734     }
735   }
736
737   // FIXME: Should we move the logic that tries to recover from a missing tag
738   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
739
740   if (!SS || (!SS->isSet() && !SS->isInvalid()))
741     Diag(IILoc, IsTemplateName ? diag::err_no_template
742                                : diag::err_unknown_typename)
743         << II;
744   else if (DeclContext *DC = computeDeclContext(*SS, false))
745     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
746                                : diag::err_typename_nested_not_found)
747         << II << DC << SS->getRange();
748   else if (isDependentScopeSpecifier(*SS)) {
749     unsigned DiagID = diag::err_typename_missing;
750     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
751       DiagID = diag::ext_typename_missing;
752
753     Diag(SS->getRange().getBegin(), DiagID)
754       << SS->getScopeRep() << II->getName()
755       << SourceRange(SS->getRange().getBegin(), IILoc)
756       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
757     SuggestedType = ActOnTypenameType(S, SourceLocation(),
758                                       *SS, *II, IILoc).get();
759   } else {
760     assert(SS && SS->isInvalid() &&
761            "Invalid scope specifier has already been diagnosed");
762   }
763 }
764
765 /// \brief Determine whether the given result set contains either a type name
766 /// or
767 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
768   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
769                        NextToken.is(tok::less);
770
771   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
772     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
773       return true;
774
775     if (CheckTemplate && isa<TemplateDecl>(*I))
776       return true;
777   }
778
779   return false;
780 }
781
782 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
783                                     Scope *S, CXXScopeSpec &SS,
784                                     IdentifierInfo *&Name,
785                                     SourceLocation NameLoc) {
786   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
787   SemaRef.LookupParsedName(R, S, &SS);
788   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
789     StringRef FixItTagName;
790     switch (Tag->getTagKind()) {
791       case TTK_Class:
792         FixItTagName = "class ";
793         break;
794
795       case TTK_Enum:
796         FixItTagName = "enum ";
797         break;
798
799       case TTK_Struct:
800         FixItTagName = "struct ";
801         break;
802
803       case TTK_Interface:
804         FixItTagName = "__interface ";
805         break;
806
807       case TTK_Union:
808         FixItTagName = "union ";
809         break;
810     }
811
812     StringRef TagName = FixItTagName.drop_back();
813     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
814       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
815       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
816
817     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
818          I != IEnd; ++I)
819       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
820         << Name << TagName;
821
822     // Replace lookup results with just the tag decl.
823     Result.clear(Sema::LookupTagName);
824     SemaRef.LookupParsedName(Result, S, &SS);
825     return true;
826   }
827
828   return false;
829 }
830
831 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
832 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
833                                   QualType T, SourceLocation NameLoc) {
834   ASTContext &Context = S.Context;
835
836   TypeLocBuilder Builder;
837   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
838
839   T = S.getElaboratedType(ETK_None, SS, T);
840   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
841   ElabTL.setElaboratedKeywordLoc(SourceLocation());
842   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
843   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
844 }
845
846 Sema::NameClassification
847 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
848                    SourceLocation NameLoc, const Token &NextToken,
849                    bool IsAddressOfOperand,
850                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
851   DeclarationNameInfo NameInfo(Name, NameLoc);
852   ObjCMethodDecl *CurMethod = getCurMethodDecl();
853
854   if (NextToken.is(tok::coloncolon)) {
855     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
856     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
857   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
858              isCurrentClassName(*Name, S, &SS)) {
859     // Per [class.qual]p2, this names the constructors of SS, not the
860     // injected-class-name. We don't have a classification for that.
861     // There's not much point caching this result, since the parser
862     // will reject it later.
863     return NameClassification::Unknown();
864   }
865
866   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
867   LookupParsedName(Result, S, &SS, !CurMethod);
868
869   // For unqualified lookup in a class template in MSVC mode, look into
870   // dependent base classes where the primary class template is known.
871   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
872     if (ParsedType TypeInBase =
873             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
874       return TypeInBase;
875   }
876
877   // Perform lookup for Objective-C instance variables (including automatically
878   // synthesized instance variables), if we're in an Objective-C method.
879   // FIXME: This lookup really, really needs to be folded in to the normal
880   // unqualified lookup mechanism.
881   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
882     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
883     if (E.get() || E.isInvalid())
884       return E;
885   }
886
887   bool SecondTry = false;
888   bool IsFilteredTemplateName = false;
889
890 Corrected:
891   switch (Result.getResultKind()) {
892   case LookupResult::NotFound:
893     // If an unqualified-id is followed by a '(', then we have a function
894     // call.
895     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
896       // In C++, this is an ADL-only call.
897       // FIXME: Reference?
898       if (getLangOpts().CPlusPlus)
899         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
900
901       // C90 6.3.2.2:
902       //   If the expression that precedes the parenthesized argument list in a
903       //   function call consists solely of an identifier, and if no
904       //   declaration is visible for this identifier, the identifier is
905       //   implicitly declared exactly as if, in the innermost block containing
906       //   the function call, the declaration
907       //
908       //     extern int identifier ();
909       //
910       //   appeared.
911       //
912       // We also allow this in C99 as an extension.
913       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
914         Result.addDecl(D);
915         Result.resolveKind();
916         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
917       }
918     }
919
920     // In C, we first see whether there is a tag type by the same name, in
921     // which case it's likely that the user just forgot to write "enum",
922     // "struct", or "union".
923     if (!getLangOpts().CPlusPlus && !SecondTry &&
924         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
925       break;
926     }
927
928     // Perform typo correction to determine if there is another name that is
929     // close to this name.
930     if (!SecondTry && CCC) {
931       SecondTry = true;
932       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
933                                                  Result.getLookupKind(), S,
934                                                  &SS, std::move(CCC),
935                                                  CTK_ErrorRecovery)) {
936         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
937         unsigned QualifiedDiag = diag::err_no_member_suggest;
938
939         NamedDecl *FirstDecl = Corrected.getFoundDecl();
940         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
941         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
942             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
943           UnqualifiedDiag = diag::err_no_template_suggest;
944           QualifiedDiag = diag::err_no_member_template_suggest;
945         } else if (UnderlyingFirstDecl &&
946                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
947                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
948                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
949           UnqualifiedDiag = diag::err_unknown_typename_suggest;
950           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
951         }
952
953         if (SS.isEmpty()) {
954           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
955         } else {// FIXME: is this even reachable? Test it.
956           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
957           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
958                                   Name->getName().equals(CorrectedStr);
959           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
960                                     << Name << computeDeclContext(SS, false)
961                                     << DroppedSpecifier << SS.getRange());
962         }
963
964         // Update the name, so that the caller has the new name.
965         Name = Corrected.getCorrectionAsIdentifierInfo();
966
967         // Typo correction corrected to a keyword.
968         if (Corrected.isKeyword())
969           return Name;
970
971         // Also update the LookupResult...
972         // FIXME: This should probably go away at some point
973         Result.clear();
974         Result.setLookupName(Corrected.getCorrection());
975         if (FirstDecl)
976           Result.addDecl(FirstDecl);
977
978         // If we found an Objective-C instance variable, let
979         // LookupInObjCMethod build the appropriate expression to
980         // reference the ivar.
981         // FIXME: This is a gross hack.
982         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
983           Result.clear();
984           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
985           return E;
986         }
987
988         goto Corrected;
989       }
990     }
991
992     // We failed to correct; just fall through and let the parser deal with it.
993     Result.suppressDiagnostics();
994     return NameClassification::Unknown();
995
996   case LookupResult::NotFoundInCurrentInstantiation: {
997     // We performed name lookup into the current instantiation, and there were
998     // dependent bases, so we treat this result the same way as any other
999     // dependent nested-name-specifier.
1000
1001     // C++ [temp.res]p2:
1002     //   A name used in a template declaration or definition and that is
1003     //   dependent on a template-parameter is assumed not to name a type
1004     //   unless the applicable name lookup finds a type name or the name is
1005     //   qualified by the keyword typename.
1006     //
1007     // FIXME: If the next token is '<', we might want to ask the parser to
1008     // perform some heroics to see if we actually have a
1009     // template-argument-list, which would indicate a missing 'template'
1010     // keyword here.
1011     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1012                                       NameInfo, IsAddressOfOperand,
1013                                       /*TemplateArgs=*/nullptr);
1014   }
1015
1016   case LookupResult::Found:
1017   case LookupResult::FoundOverloaded:
1018   case LookupResult::FoundUnresolvedValue:
1019     break;
1020
1021   case LookupResult::Ambiguous:
1022     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1023         hasAnyAcceptableTemplateNames(Result)) {
1024       // C++ [temp.local]p3:
1025       //   A lookup that finds an injected-class-name (10.2) can result in an
1026       //   ambiguity in certain cases (for example, if it is found in more than
1027       //   one base class). If all of the injected-class-names that are found
1028       //   refer to specializations of the same class template, and if the name
1029       //   is followed by a template-argument-list, the reference refers to the
1030       //   class template itself and not a specialization thereof, and is not
1031       //   ambiguous.
1032       //
1033       // This filtering can make an ambiguous result into an unambiguous one,
1034       // so try again after filtering out template names.
1035       FilterAcceptableTemplateNames(Result);
1036       if (!Result.isAmbiguous()) {
1037         IsFilteredTemplateName = true;
1038         break;
1039       }
1040     }
1041
1042     // Diagnose the ambiguity and return an error.
1043     return NameClassification::Error();
1044   }
1045
1046   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1047       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1048     // C++ [temp.names]p3:
1049     //   After name lookup (3.4) finds that a name is a template-name or that
1050     //   an operator-function-id or a literal- operator-id refers to a set of
1051     //   overloaded functions any member of which is a function template if
1052     //   this is followed by a <, the < is always taken as the delimiter of a
1053     //   template-argument-list and never as the less-than operator.
1054     if (!IsFilteredTemplateName)
1055       FilterAcceptableTemplateNames(Result);
1056
1057     if (!Result.empty()) {
1058       bool IsFunctionTemplate;
1059       bool IsVarTemplate;
1060       TemplateName Template;
1061       if (Result.end() - Result.begin() > 1) {
1062         IsFunctionTemplate = true;
1063         Template = Context.getOverloadedTemplateName(Result.begin(),
1064                                                      Result.end());
1065       } else {
1066         TemplateDecl *TD
1067           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1068         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1069         IsVarTemplate = isa<VarTemplateDecl>(TD);
1070
1071         if (SS.isSet() && !SS.isInvalid())
1072           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1073                                                     /*TemplateKeyword=*/false,
1074                                                       TD);
1075         else
1076           Template = TemplateName(TD);
1077       }
1078
1079       if (IsFunctionTemplate) {
1080         // Function templates always go through overload resolution, at which
1081         // point we'll perform the various checks (e.g., accessibility) we need
1082         // to based on which function we selected.
1083         Result.suppressDiagnostics();
1084
1085         return NameClassification::FunctionTemplate(Template);
1086       }
1087
1088       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1089                            : NameClassification::TypeTemplate(Template);
1090     }
1091   }
1092
1093   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1094   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1095     DiagnoseUseOfDecl(Type, NameLoc);
1096     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1097     QualType T = Context.getTypeDeclType(Type);
1098     if (SS.isNotEmpty())
1099       return buildNestedType(*this, SS, T, NameLoc);
1100     return ParsedType::make(T);
1101   }
1102
1103   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1104   if (!Class) {
1105     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1106     if (ObjCCompatibleAliasDecl *Alias =
1107             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1108       Class = Alias->getClassInterface();
1109   }
1110
1111   if (Class) {
1112     DiagnoseUseOfDecl(Class, NameLoc);
1113
1114     if (NextToken.is(tok::period)) {
1115       // Interface. <something> is parsed as a property reference expression.
1116       // Just return "unknown" as a fall-through for now.
1117       Result.suppressDiagnostics();
1118       return NameClassification::Unknown();
1119     }
1120
1121     QualType T = Context.getObjCInterfaceType(Class);
1122     return ParsedType::make(T);
1123   }
1124
1125   // We can have a type template here if we're classifying a template argument.
1126   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1127       !isa<VarTemplateDecl>(FirstDecl))
1128     return NameClassification::TypeTemplate(
1129         TemplateName(cast<TemplateDecl>(FirstDecl)));
1130
1131   // Check for a tag type hidden by a non-type decl in a few cases where it
1132   // seems likely a type is wanted instead of the non-type that was found.
1133   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1134   if ((NextToken.is(tok::identifier) ||
1135        (NextIsOp &&
1136         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1137       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1138     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1139     DiagnoseUseOfDecl(Type, NameLoc);
1140     QualType T = Context.getTypeDeclType(Type);
1141     if (SS.isNotEmpty())
1142       return buildNestedType(*this, SS, T, NameLoc);
1143     return ParsedType::make(T);
1144   }
1145
1146   if (FirstDecl->isCXXClassMember())
1147     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1148                                            nullptr, S);
1149
1150   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1151   return BuildDeclarationNameExpr(SS, Result, ADL);
1152 }
1153
1154 Sema::TemplateNameKindForDiagnostics
1155 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1156   auto *TD = Name.getAsTemplateDecl();
1157   if (!TD)
1158     return TemplateNameKindForDiagnostics::DependentTemplate;
1159   if (isa<ClassTemplateDecl>(TD))
1160     return TemplateNameKindForDiagnostics::ClassTemplate;
1161   if (isa<FunctionTemplateDecl>(TD))
1162     return TemplateNameKindForDiagnostics::FunctionTemplate;
1163   if (isa<VarTemplateDecl>(TD))
1164     return TemplateNameKindForDiagnostics::VarTemplate;
1165   if (isa<TypeAliasTemplateDecl>(TD))
1166     return TemplateNameKindForDiagnostics::AliasTemplate;
1167   if (isa<TemplateTemplateParmDecl>(TD))
1168     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1169   return TemplateNameKindForDiagnostics::DependentTemplate;
1170 }
1171
1172 // Determines the context to return to after temporarily entering a
1173 // context.  This depends in an unnecessarily complicated way on the
1174 // exact ordering of callbacks from the parser.
1175 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1176
1177   // Functions defined inline within classes aren't parsed until we've
1178   // finished parsing the top-level class, so the top-level class is
1179   // the context we'll need to return to.
1180   // A Lambda call operator whose parent is a class must not be treated
1181   // as an inline member function.  A Lambda can be used legally
1182   // either as an in-class member initializer or a default argument.  These
1183   // are parsed once the class has been marked complete and so the containing
1184   // context would be the nested class (when the lambda is defined in one);
1185   // If the class is not complete, then the lambda is being used in an
1186   // ill-formed fashion (such as to specify the width of a bit-field, or
1187   // in an array-bound) - in which case we still want to return the
1188   // lexically containing DC (which could be a nested class).
1189   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1190     DC = DC->getLexicalParent();
1191
1192     // A function not defined within a class will always return to its
1193     // lexical context.
1194     if (!isa<CXXRecordDecl>(DC))
1195       return DC;
1196
1197     // A C++ inline method/friend is parsed *after* the topmost class
1198     // it was declared in is fully parsed ("complete");  the topmost
1199     // class is the context we need to return to.
1200     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1201       DC = RD;
1202
1203     // Return the declaration context of the topmost class the inline method is
1204     // declared in.
1205     return DC;
1206   }
1207
1208   return DC->getLexicalParent();
1209 }
1210
1211 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1212   assert(getContainingDC(DC) == CurContext &&
1213       "The next DeclContext should be lexically contained in the current one.");
1214   CurContext = DC;
1215   S->setEntity(DC);
1216 }
1217
1218 void Sema::PopDeclContext() {
1219   assert(CurContext && "DeclContext imbalance!");
1220
1221   CurContext = getContainingDC(CurContext);
1222   assert(CurContext && "Popped translation unit!");
1223 }
1224
1225 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1226                                                                     Decl *D) {
1227   // Unlike PushDeclContext, the context to which we return is not necessarily
1228   // the containing DC of TD, because the new context will be some pre-existing
1229   // TagDecl definition instead of a fresh one.
1230   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1231   CurContext = cast<TagDecl>(D)->getDefinition();
1232   assert(CurContext && "skipping definition of undefined tag");
1233   // Start lookups from the parent of the current context; we don't want to look
1234   // into the pre-existing complete definition.
1235   S->setEntity(CurContext->getLookupParent());
1236   return Result;
1237 }
1238
1239 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1240   CurContext = static_cast<decltype(CurContext)>(Context);
1241 }
1242
1243 /// EnterDeclaratorContext - Used when we must lookup names in the context
1244 /// of a declarator's nested name specifier.
1245 ///
1246 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1247   // C++0x [basic.lookup.unqual]p13:
1248   //   A name used in the definition of a static data member of class
1249   //   X (after the qualified-id of the static member) is looked up as
1250   //   if the name was used in a member function of X.
1251   // C++0x [basic.lookup.unqual]p14:
1252   //   If a variable member of a namespace is defined outside of the
1253   //   scope of its namespace then any name used in the definition of
1254   //   the variable member (after the declarator-id) is looked up as
1255   //   if the definition of the variable member occurred in its
1256   //   namespace.
1257   // Both of these imply that we should push a scope whose context
1258   // is the semantic context of the declaration.  We can't use
1259   // PushDeclContext here because that context is not necessarily
1260   // lexically contained in the current context.  Fortunately,
1261   // the containing scope should have the appropriate information.
1262
1263   assert(!S->getEntity() && "scope already has entity");
1264
1265 #ifndef NDEBUG
1266   Scope *Ancestor = S->getParent();
1267   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1268   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1269 #endif
1270
1271   CurContext = DC;
1272   S->setEntity(DC);
1273 }
1274
1275 void Sema::ExitDeclaratorContext(Scope *S) {
1276   assert(S->getEntity() == CurContext && "Context imbalance!");
1277
1278   // Switch back to the lexical context.  The safety of this is
1279   // enforced by an assert in EnterDeclaratorContext.
1280   Scope *Ancestor = S->getParent();
1281   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1282   CurContext = Ancestor->getEntity();
1283
1284   // We don't need to do anything with the scope, which is going to
1285   // disappear.
1286 }
1287
1288 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1289   // We assume that the caller has already called
1290   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1291   FunctionDecl *FD = D->getAsFunction();
1292   if (!FD)
1293     return;
1294
1295   // Same implementation as PushDeclContext, but enters the context
1296   // from the lexical parent, rather than the top-level class.
1297   assert(CurContext == FD->getLexicalParent() &&
1298     "The next DeclContext should be lexically contained in the current one.");
1299   CurContext = FD;
1300   S->setEntity(CurContext);
1301
1302   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1303     ParmVarDecl *Param = FD->getParamDecl(P);
1304     // If the parameter has an identifier, then add it to the scope
1305     if (Param->getIdentifier()) {
1306       S->AddDecl(Param);
1307       IdResolver.AddDecl(Param);
1308     }
1309   }
1310 }
1311
1312 void Sema::ActOnExitFunctionContext() {
1313   // Same implementation as PopDeclContext, but returns to the lexical parent,
1314   // rather than the top-level class.
1315   assert(CurContext && "DeclContext imbalance!");
1316   CurContext = CurContext->getLexicalParent();
1317   assert(CurContext && "Popped translation unit!");
1318 }
1319
1320 /// \brief Determine whether we allow overloading of the function
1321 /// PrevDecl with another declaration.
1322 ///
1323 /// This routine determines whether overloading is possible, not
1324 /// whether some new function is actually an overload. It will return
1325 /// true in C++ (where we can always provide overloads) or, as an
1326 /// extension, in C when the previous function is already an
1327 /// overloaded function declaration or has the "overloadable"
1328 /// attribute.
1329 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1330                                        ASTContext &Context,
1331                                        const FunctionDecl *New) {
1332   if (Context.getLangOpts().CPlusPlus)
1333     return true;
1334
1335   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1336     return true;
1337
1338   return Previous.getResultKind() == LookupResult::Found &&
1339          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1340           New->hasAttr<OverloadableAttr>());
1341 }
1342
1343 /// Add this decl to the scope shadowed decl chains.
1344 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1345   // Move up the scope chain until we find the nearest enclosing
1346   // non-transparent context. The declaration will be introduced into this
1347   // scope.
1348   while (S->getEntity() && S->getEntity()->isTransparentContext())
1349     S = S->getParent();
1350
1351   // Add scoped declarations into their context, so that they can be
1352   // found later. Declarations without a context won't be inserted
1353   // into any context.
1354   if (AddToContext)
1355     CurContext->addDecl(D);
1356
1357   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1358   // are function-local declarations.
1359   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1360       !D->getDeclContext()->getRedeclContext()->Equals(
1361         D->getLexicalDeclContext()->getRedeclContext()) &&
1362       !D->getLexicalDeclContext()->isFunctionOrMethod())
1363     return;
1364
1365   // Template instantiations should also not be pushed into scope.
1366   if (isa<FunctionDecl>(D) &&
1367       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1368     return;
1369
1370   // If this replaces anything in the current scope,
1371   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1372                                IEnd = IdResolver.end();
1373   for (; I != IEnd; ++I) {
1374     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1375       S->RemoveDecl(*I);
1376       IdResolver.RemoveDecl(*I);
1377
1378       // Should only need to replace one decl.
1379       break;
1380     }
1381   }
1382
1383   S->AddDecl(D);
1384
1385   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1386     // Implicitly-generated labels may end up getting generated in an order that
1387     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1388     // the label at the appropriate place in the identifier chain.
1389     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1390       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1391       if (IDC == CurContext) {
1392         if (!S->isDeclScope(*I))
1393           continue;
1394       } else if (IDC->Encloses(CurContext))
1395         break;
1396     }
1397
1398     IdResolver.InsertDeclAfter(I, D);
1399   } else {
1400     IdResolver.AddDecl(D);
1401   }
1402 }
1403
1404 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1405   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1406     TUScope->AddDecl(D);
1407 }
1408
1409 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1410                          bool AllowInlineNamespace) {
1411   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1412 }
1413
1414 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1415   DeclContext *TargetDC = DC->getPrimaryContext();
1416   do {
1417     if (DeclContext *ScopeDC = S->getEntity())
1418       if (ScopeDC->getPrimaryContext() == TargetDC)
1419         return S;
1420   } while ((S = S->getParent()));
1421
1422   return nullptr;
1423 }
1424
1425 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1426                                             DeclContext*,
1427                                             ASTContext&);
1428
1429 /// Filters out lookup results that don't fall within the given scope
1430 /// as determined by isDeclInScope.
1431 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1432                                 bool ConsiderLinkage,
1433                                 bool AllowInlineNamespace) {
1434   LookupResult::Filter F = R.makeFilter();
1435   while (F.hasNext()) {
1436     NamedDecl *D = F.next();
1437
1438     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1439       continue;
1440
1441     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1442       continue;
1443
1444     F.erase();
1445   }
1446
1447   F.done();
1448 }
1449
1450 static bool isUsingDecl(NamedDecl *D) {
1451   return isa<UsingShadowDecl>(D) ||
1452          isa<UnresolvedUsingTypenameDecl>(D) ||
1453          isa<UnresolvedUsingValueDecl>(D);
1454 }
1455
1456 /// Removes using shadow declarations from the lookup results.
1457 static void RemoveUsingDecls(LookupResult &R) {
1458   LookupResult::Filter F = R.makeFilter();
1459   while (F.hasNext())
1460     if (isUsingDecl(F.next()))
1461       F.erase();
1462
1463   F.done();
1464 }
1465
1466 /// \brief Check for this common pattern:
1467 /// @code
1468 /// class S {
1469 ///   S(const S&); // DO NOT IMPLEMENT
1470 ///   void operator=(const S&); // DO NOT IMPLEMENT
1471 /// };
1472 /// @endcode
1473 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1474   // FIXME: Should check for private access too but access is set after we get
1475   // the decl here.
1476   if (D->doesThisDeclarationHaveABody())
1477     return false;
1478
1479   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1480     return CD->isCopyConstructor();
1481   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1482     return Method->isCopyAssignmentOperator();
1483   return false;
1484 }
1485
1486 // We need this to handle
1487 //
1488 // typedef struct {
1489 //   void *foo() { return 0; }
1490 // } A;
1491 //
1492 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1493 // for example. If 'A', foo will have external linkage. If we have '*A',
1494 // foo will have no linkage. Since we can't know until we get to the end
1495 // of the typedef, this function finds out if D might have non-external linkage.
1496 // Callers should verify at the end of the TU if it D has external linkage or
1497 // not.
1498 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1499   const DeclContext *DC = D->getDeclContext();
1500   while (!DC->isTranslationUnit()) {
1501     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1502       if (!RD->hasNameForLinkage())
1503         return true;
1504     }
1505     DC = DC->getParent();
1506   }
1507
1508   return !D->isExternallyVisible();
1509 }
1510
1511 // FIXME: This needs to be refactored; some other isInMainFile users want
1512 // these semantics.
1513 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1514   if (S.TUKind != TU_Complete)
1515     return false;
1516   return S.SourceMgr.isInMainFile(Loc);
1517 }
1518
1519 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1520   assert(D);
1521
1522   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1523     return false;
1524
1525   // Ignore all entities declared within templates, and out-of-line definitions
1526   // of members of class templates.
1527   if (D->getDeclContext()->isDependentContext() ||
1528       D->getLexicalDeclContext()->isDependentContext())
1529     return false;
1530
1531   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1532     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1533       return false;
1534     // A non-out-of-line declaration of a member specialization was implicitly
1535     // instantiated; it's the out-of-line declaration that we're interested in.
1536     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1537         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1538       return false;
1539
1540     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1541       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1542         return false;
1543     } else {
1544       // 'static inline' functions are defined in headers; don't warn.
1545       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1546         return false;
1547     }
1548
1549     if (FD->doesThisDeclarationHaveABody() &&
1550         Context.DeclMustBeEmitted(FD))
1551       return false;
1552   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1553     // Constants and utility variables are defined in headers with internal
1554     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1555     // like "inline".)
1556     if (!isMainFileLoc(*this, VD->getLocation()))
1557       return false;
1558
1559     if (Context.DeclMustBeEmitted(VD))
1560       return false;
1561
1562     if (VD->isStaticDataMember() &&
1563         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1564       return false;
1565     if (VD->isStaticDataMember() &&
1566         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1567         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1568       return false;
1569
1570     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1571       return false;
1572   } else {
1573     return false;
1574   }
1575
1576   // Only warn for unused decls internal to the translation unit.
1577   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1578   // for inline functions defined in the main source file, for instance.
1579   return mightHaveNonExternalLinkage(D);
1580 }
1581
1582 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1583   if (!D)
1584     return;
1585
1586   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1587     const FunctionDecl *First = FD->getFirstDecl();
1588     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1589       return; // First should already be in the vector.
1590   }
1591
1592   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1593     const VarDecl *First = VD->getFirstDecl();
1594     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1595       return; // First should already be in the vector.
1596   }
1597
1598   if (ShouldWarnIfUnusedFileScopedDecl(D))
1599     UnusedFileScopedDecls.push_back(D);
1600 }
1601
1602 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1603   if (D->isInvalidDecl())
1604     return false;
1605
1606   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1607       D->hasAttr<ObjCPreciseLifetimeAttr>())
1608     return false;
1609
1610   if (isa<LabelDecl>(D))
1611     return true;
1612
1613   // Except for labels, we only care about unused decls that are local to
1614   // functions.
1615   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1616   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1617     // For dependent types, the diagnostic is deferred.
1618     WithinFunction =
1619         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1620   if (!WithinFunction)
1621     return false;
1622
1623   if (isa<TypedefNameDecl>(D))
1624     return true;
1625
1626   // White-list anything that isn't a local variable.
1627   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1628     return false;
1629
1630   // Types of valid local variables should be complete, so this should succeed.
1631   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1632
1633     // White-list anything with an __attribute__((unused)) type.
1634     const auto *Ty = VD->getType().getTypePtr();
1635
1636     // Only look at the outermost level of typedef.
1637     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1638       if (TT->getDecl()->hasAttr<UnusedAttr>())
1639         return false;
1640     }
1641
1642     // If we failed to complete the type for some reason, or if the type is
1643     // dependent, don't diagnose the variable.
1644     if (Ty->isIncompleteType() || Ty->isDependentType())
1645       return false;
1646
1647     // Look at the element type to ensure that the warning behaviour is
1648     // consistent for both scalars and arrays.
1649     Ty = Ty->getBaseElementTypeUnsafe();
1650
1651     if (const TagType *TT = Ty->getAs<TagType>()) {
1652       const TagDecl *Tag = TT->getDecl();
1653       if (Tag->hasAttr<UnusedAttr>())
1654         return false;
1655
1656       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1657         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1658           return false;
1659
1660         if (const Expr *Init = VD->getInit()) {
1661           if (const ExprWithCleanups *Cleanups =
1662                   dyn_cast<ExprWithCleanups>(Init))
1663             Init = Cleanups->getSubExpr();
1664           const CXXConstructExpr *Construct =
1665             dyn_cast<CXXConstructExpr>(Init);
1666           if (Construct && !Construct->isElidable()) {
1667             CXXConstructorDecl *CD = Construct->getConstructor();
1668             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1669               return false;
1670           }
1671         }
1672       }
1673     }
1674
1675     // TODO: __attribute__((unused)) templates?
1676   }
1677
1678   return true;
1679 }
1680
1681 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1682                                      FixItHint &Hint) {
1683   if (isa<LabelDecl>(D)) {
1684     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1685                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1686     if (AfterColon.isInvalid())
1687       return;
1688     Hint = FixItHint::CreateRemoval(CharSourceRange::
1689                                     getCharRange(D->getLocStart(), AfterColon));
1690   }
1691 }
1692
1693 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1694   if (D->getTypeForDecl()->isDependentType())
1695     return;
1696
1697   for (auto *TmpD : D->decls()) {
1698     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1699       DiagnoseUnusedDecl(T);
1700     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1701       DiagnoseUnusedNestedTypedefs(R);
1702   }
1703 }
1704
1705 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1706 /// unless they are marked attr(unused).
1707 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1708   if (!ShouldDiagnoseUnusedDecl(D))
1709     return;
1710
1711   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1712     // typedefs can be referenced later on, so the diagnostics are emitted
1713     // at end-of-translation-unit.
1714     UnusedLocalTypedefNameCandidates.insert(TD);
1715     return;
1716   }
1717
1718   FixItHint Hint;
1719   GenerateFixForUnusedDecl(D, Context, Hint);
1720
1721   unsigned DiagID;
1722   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1723     DiagID = diag::warn_unused_exception_param;
1724   else if (isa<LabelDecl>(D))
1725     DiagID = diag::warn_unused_label;
1726   else
1727     DiagID = diag::warn_unused_variable;
1728
1729   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1730 }
1731
1732 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1733   // Verify that we have no forward references left.  If so, there was a goto
1734   // or address of a label taken, but no definition of it.  Label fwd
1735   // definitions are indicated with a null substmt which is also not a resolved
1736   // MS inline assembly label name.
1737   bool Diagnose = false;
1738   if (L->isMSAsmLabel())
1739     Diagnose = !L->isResolvedMSAsmLabel();
1740   else
1741     Diagnose = L->getStmt() == nullptr;
1742   if (Diagnose)
1743     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1744 }
1745
1746 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1747   S->mergeNRVOIntoParent();
1748
1749   if (S->decl_empty()) return;
1750   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1751          "Scope shouldn't contain decls!");
1752
1753   for (auto *TmpD : S->decls()) {
1754     assert(TmpD && "This decl didn't get pushed??");
1755
1756     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1757     NamedDecl *D = cast<NamedDecl>(TmpD);
1758
1759     if (!D->getDeclName()) continue;
1760
1761     // Diagnose unused variables in this scope.
1762     if (!S->hasUnrecoverableErrorOccurred()) {
1763       DiagnoseUnusedDecl(D);
1764       if (const auto *RD = dyn_cast<RecordDecl>(D))
1765         DiagnoseUnusedNestedTypedefs(RD);
1766     }
1767
1768     // If this was a forward reference to a label, verify it was defined.
1769     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1770       CheckPoppedLabel(LD, *this);
1771
1772     // Remove this name from our lexical scope, and warn on it if we haven't
1773     // already.
1774     IdResolver.RemoveDecl(D);
1775     auto ShadowI = ShadowingDecls.find(D);
1776     if (ShadowI != ShadowingDecls.end()) {
1777       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1778         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1779             << D << FD << FD->getParent();
1780         Diag(FD->getLocation(), diag::note_previous_declaration);
1781       }
1782       ShadowingDecls.erase(ShadowI);
1783     }
1784   }
1785 }
1786
1787 /// \brief Look for an Objective-C class in the translation unit.
1788 ///
1789 /// \param Id The name of the Objective-C class we're looking for. If
1790 /// typo-correction fixes this name, the Id will be updated
1791 /// to the fixed name.
1792 ///
1793 /// \param IdLoc The location of the name in the translation unit.
1794 ///
1795 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1796 /// if there is no class with the given name.
1797 ///
1798 /// \returns The declaration of the named Objective-C class, or NULL if the
1799 /// class could not be found.
1800 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1801                                               SourceLocation IdLoc,
1802                                               bool DoTypoCorrection) {
1803   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1804   // creation from this context.
1805   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1806
1807   if (!IDecl && DoTypoCorrection) {
1808     // Perform typo correction at the given location, but only if we
1809     // find an Objective-C class name.
1810     if (TypoCorrection C = CorrectTypo(
1811             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1812             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1813             CTK_ErrorRecovery)) {
1814       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1815       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1816       Id = IDecl->getIdentifier();
1817     }
1818   }
1819   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1820   // This routine must always return a class definition, if any.
1821   if (Def && Def->getDefinition())
1822       Def = Def->getDefinition();
1823   return Def;
1824 }
1825
1826 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1827 /// from S, where a non-field would be declared. This routine copes
1828 /// with the difference between C and C++ scoping rules in structs and
1829 /// unions. For example, the following code is well-formed in C but
1830 /// ill-formed in C++:
1831 /// @code
1832 /// struct S6 {
1833 ///   enum { BAR } e;
1834 /// };
1835 ///
1836 /// void test_S6() {
1837 ///   struct S6 a;
1838 ///   a.e = BAR;
1839 /// }
1840 /// @endcode
1841 /// For the declaration of BAR, this routine will return a different
1842 /// scope. The scope S will be the scope of the unnamed enumeration
1843 /// within S6. In C++, this routine will return the scope associated
1844 /// with S6, because the enumeration's scope is a transparent
1845 /// context but structures can contain non-field names. In C, this
1846 /// routine will return the translation unit scope, since the
1847 /// enumeration's scope is a transparent context and structures cannot
1848 /// contain non-field names.
1849 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1850   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1851          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1852          (S->isClassScope() && !getLangOpts().CPlusPlus))
1853     S = S->getParent();
1854   return S;
1855 }
1856
1857 /// \brief Looks up the declaration of "struct objc_super" and
1858 /// saves it for later use in building builtin declaration of
1859 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1860 /// pre-existing declaration exists no action takes place.
1861 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1862                                         IdentifierInfo *II) {
1863   if (!II->isStr("objc_msgSendSuper"))
1864     return;
1865   ASTContext &Context = ThisSema.Context;
1866
1867   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1868                       SourceLocation(), Sema::LookupTagName);
1869   ThisSema.LookupName(Result, S);
1870   if (Result.getResultKind() == LookupResult::Found)
1871     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1872       Context.setObjCSuperType(Context.getTagDeclType(TD));
1873 }
1874
1875 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1876   switch (Error) {
1877   case ASTContext::GE_None:
1878     return "";
1879   case ASTContext::GE_Missing_stdio:
1880     return "stdio.h";
1881   case ASTContext::GE_Missing_setjmp:
1882     return "setjmp.h";
1883   case ASTContext::GE_Missing_ucontext:
1884     return "ucontext.h";
1885   }
1886   llvm_unreachable("unhandled error kind");
1887 }
1888
1889 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1890 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1891 /// if we're creating this built-in in anticipation of redeclaring the
1892 /// built-in.
1893 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1894                                      Scope *S, bool ForRedeclaration,
1895                                      SourceLocation Loc) {
1896   LookupPredefedObjCSuperType(*this, S, II);
1897
1898   ASTContext::GetBuiltinTypeError Error;
1899   QualType R = Context.GetBuiltinType(ID, Error);
1900   if (Error) {
1901     if (ForRedeclaration)
1902       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1903           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1904     return nullptr;
1905   }
1906
1907   if (!ForRedeclaration &&
1908       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1909        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1910     Diag(Loc, diag::ext_implicit_lib_function_decl)
1911         << Context.BuiltinInfo.getName(ID) << R;
1912     if (Context.BuiltinInfo.getHeaderName(ID) &&
1913         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1914       Diag(Loc, diag::note_include_header_or_declare)
1915           << Context.BuiltinInfo.getHeaderName(ID)
1916           << Context.BuiltinInfo.getName(ID);
1917   }
1918
1919   if (R.isNull())
1920     return nullptr;
1921
1922   DeclContext *Parent = Context.getTranslationUnitDecl();
1923   if (getLangOpts().CPlusPlus) {
1924     LinkageSpecDecl *CLinkageDecl =
1925         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1926                                 LinkageSpecDecl::lang_c, false);
1927     CLinkageDecl->setImplicit();
1928     Parent->addDecl(CLinkageDecl);
1929     Parent = CLinkageDecl;
1930   }
1931
1932   FunctionDecl *New = FunctionDecl::Create(Context,
1933                                            Parent,
1934                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1935                                            SC_Extern,
1936                                            false,
1937                                            R->isFunctionProtoType());
1938   New->setImplicit();
1939
1940   // Create Decl objects for each parameter, adding them to the
1941   // FunctionDecl.
1942   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1943     SmallVector<ParmVarDecl*, 16> Params;
1944     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1945       ParmVarDecl *parm =
1946           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1947                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1948                               SC_None, nullptr);
1949       parm->setScopeInfo(0, i);
1950       Params.push_back(parm);
1951     }
1952     New->setParams(Params);
1953   }
1954
1955   AddKnownFunctionAttributes(New);
1956   RegisterLocallyScopedExternCDecl(New, S);
1957
1958   // TUScope is the translation-unit scope to insert this function into.
1959   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1960   // relate Scopes to DeclContexts, and probably eliminate CurContext
1961   // entirely, but we're not there yet.
1962   DeclContext *SavedContext = CurContext;
1963   CurContext = Parent;
1964   PushOnScopeChains(New, TUScope);
1965   CurContext = SavedContext;
1966   return New;
1967 }
1968
1969 /// Typedef declarations don't have linkage, but they still denote the same
1970 /// entity if their types are the same.
1971 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1972 /// isSameEntity.
1973 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1974                                                      TypedefNameDecl *Decl,
1975                                                      LookupResult &Previous) {
1976   // This is only interesting when modules are enabled.
1977   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1978     return;
1979
1980   // Empty sets are uninteresting.
1981   if (Previous.empty())
1982     return;
1983
1984   LookupResult::Filter Filter = Previous.makeFilter();
1985   while (Filter.hasNext()) {
1986     NamedDecl *Old = Filter.next();
1987
1988     // Non-hidden declarations are never ignored.
1989     if (S.isVisible(Old))
1990       continue;
1991
1992     // Declarations of the same entity are not ignored, even if they have
1993     // different linkages.
1994     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1995       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1996                                 Decl->getUnderlyingType()))
1997         continue;
1998
1999       // If both declarations give a tag declaration a typedef name for linkage
2000       // purposes, then they declare the same entity.
2001       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2002           Decl->getAnonDeclWithTypedefName())
2003         continue;
2004     }
2005
2006     Filter.erase();
2007   }
2008
2009   Filter.done();
2010 }
2011
2012 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2013   QualType OldType;
2014   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2015     OldType = OldTypedef->getUnderlyingType();
2016   else
2017     OldType = Context.getTypeDeclType(Old);
2018   QualType NewType = New->getUnderlyingType();
2019
2020   if (NewType->isVariablyModifiedType()) {
2021     // Must not redefine a typedef with a variably-modified type.
2022     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2023     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2024       << Kind << NewType;
2025     if (Old->getLocation().isValid())
2026       notePreviousDefinition(Old, New->getLocation());
2027     New->setInvalidDecl();
2028     return true;
2029   }
2030
2031   if (OldType != NewType &&
2032       !OldType->isDependentType() &&
2033       !NewType->isDependentType() &&
2034       !Context.hasSameType(OldType, NewType)) {
2035     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2036     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2037       << Kind << NewType << OldType;
2038     if (Old->getLocation().isValid())
2039       notePreviousDefinition(Old, New->getLocation());
2040     New->setInvalidDecl();
2041     return true;
2042   }
2043   return false;
2044 }
2045
2046 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2047 /// same name and scope as a previous declaration 'Old'.  Figure out
2048 /// how to resolve this situation, merging decls or emitting
2049 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2050 ///
2051 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2052                                 LookupResult &OldDecls) {
2053   // If the new decl is known invalid already, don't bother doing any
2054   // merging checks.
2055   if (New->isInvalidDecl()) return;
2056
2057   // Allow multiple definitions for ObjC built-in typedefs.
2058   // FIXME: Verify the underlying types are equivalent!
2059   if (getLangOpts().ObjC1) {
2060     const IdentifierInfo *TypeID = New->getIdentifier();
2061     switch (TypeID->getLength()) {
2062     default: break;
2063     case 2:
2064       {
2065         if (!TypeID->isStr("id"))
2066           break;
2067         QualType T = New->getUnderlyingType();
2068         if (!T->isPointerType())
2069           break;
2070         if (!T->isVoidPointerType()) {
2071           QualType PT = T->getAs<PointerType>()->getPointeeType();
2072           if (!PT->isStructureType())
2073             break;
2074         }
2075         Context.setObjCIdRedefinitionType(T);
2076         // Install the built-in type for 'id', ignoring the current definition.
2077         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2078         return;
2079       }
2080     case 5:
2081       if (!TypeID->isStr("Class"))
2082         break;
2083       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2084       // Install the built-in type for 'Class', ignoring the current definition.
2085       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2086       return;
2087     case 3:
2088       if (!TypeID->isStr("SEL"))
2089         break;
2090       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2091       // Install the built-in type for 'SEL', ignoring the current definition.
2092       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2093       return;
2094     }
2095     // Fall through - the typedef name was not a builtin type.
2096   }
2097
2098   // Verify the old decl was also a type.
2099   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2100   if (!Old) {
2101     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2102       << New->getDeclName();
2103
2104     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2105     if (OldD->getLocation().isValid())
2106       notePreviousDefinition(OldD, New->getLocation());
2107
2108     return New->setInvalidDecl();
2109   }
2110
2111   // If the old declaration is invalid, just give up here.
2112   if (Old->isInvalidDecl())
2113     return New->setInvalidDecl();
2114
2115   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2116     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2117     auto *NewTag = New->getAnonDeclWithTypedefName();
2118     NamedDecl *Hidden = nullptr;
2119     if (OldTag && NewTag &&
2120         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2121         !hasVisibleDefinition(OldTag, &Hidden)) {
2122       // There is a definition of this tag, but it is not visible. Use it
2123       // instead of our tag.
2124       New->setTypeForDecl(OldTD->getTypeForDecl());
2125       if (OldTD->isModed())
2126         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2127                                     OldTD->getUnderlyingType());
2128       else
2129         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2130
2131       // Make the old tag definition visible.
2132       makeMergedDefinitionVisible(Hidden);
2133
2134       // If this was an unscoped enumeration, yank all of its enumerators
2135       // out of the scope.
2136       if (isa<EnumDecl>(NewTag)) {
2137         Scope *EnumScope = getNonFieldDeclScope(S);
2138         for (auto *D : NewTag->decls()) {
2139           auto *ED = cast<EnumConstantDecl>(D);
2140           assert(EnumScope->isDeclScope(ED));
2141           EnumScope->RemoveDecl(ED);
2142           IdResolver.RemoveDecl(ED);
2143           ED->getLexicalDeclContext()->removeDecl(ED);
2144         }
2145       }
2146     }
2147   }
2148
2149   // If the typedef types are not identical, reject them in all languages and
2150   // with any extensions enabled.
2151   if (isIncompatibleTypedef(Old, New))
2152     return;
2153
2154   // The types match.  Link up the redeclaration chain and merge attributes if
2155   // the old declaration was a typedef.
2156   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2157     New->setPreviousDecl(Typedef);
2158     mergeDeclAttributes(New, Old);
2159   }
2160
2161   if (getLangOpts().MicrosoftExt)
2162     return;
2163
2164   if (getLangOpts().CPlusPlus) {
2165     // C++ [dcl.typedef]p2:
2166     //   In a given non-class scope, a typedef specifier can be used to
2167     //   redefine the name of any type declared in that scope to refer
2168     //   to the type to which it already refers.
2169     if (!isa<CXXRecordDecl>(CurContext))
2170       return;
2171
2172     // C++0x [dcl.typedef]p4:
2173     //   In a given class scope, a typedef specifier can be used to redefine
2174     //   any class-name declared in that scope that is not also a typedef-name
2175     //   to refer to the type to which it already refers.
2176     //
2177     // This wording came in via DR424, which was a correction to the
2178     // wording in DR56, which accidentally banned code like:
2179     //
2180     //   struct S {
2181     //     typedef struct A { } A;
2182     //   };
2183     //
2184     // in the C++03 standard. We implement the C++0x semantics, which
2185     // allow the above but disallow
2186     //
2187     //   struct S {
2188     //     typedef int I;
2189     //     typedef int I;
2190     //   };
2191     //
2192     // since that was the intent of DR56.
2193     if (!isa<TypedefNameDecl>(Old))
2194       return;
2195
2196     Diag(New->getLocation(), diag::err_redefinition)
2197       << New->getDeclName();
2198     notePreviousDefinition(Old, New->getLocation());
2199     return New->setInvalidDecl();
2200   }
2201
2202   // Modules always permit redefinition of typedefs, as does C11.
2203   if (getLangOpts().Modules || getLangOpts().C11)
2204     return;
2205
2206   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2207   // is normally mapped to an error, but can be controlled with
2208   // -Wtypedef-redefinition.  If either the original or the redefinition is
2209   // in a system header, don't emit this for compatibility with GCC.
2210   if (getDiagnostics().getSuppressSystemWarnings() &&
2211       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2212       (Old->isImplicit() ||
2213        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2214        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2215     return;
2216
2217   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2218     << New->getDeclName();
2219   notePreviousDefinition(Old, New->getLocation());
2220 }
2221
2222 /// DeclhasAttr - returns true if decl Declaration already has the target
2223 /// attribute.
2224 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2225   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2226   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2227   for (const auto *i : D->attrs())
2228     if (i->getKind() == A->getKind()) {
2229       if (Ann) {
2230         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2231           return true;
2232         continue;
2233       }
2234       // FIXME: Don't hardcode this check
2235       if (OA && isa<OwnershipAttr>(i))
2236         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2237       return true;
2238     }
2239
2240   return false;
2241 }
2242
2243 static bool isAttributeTargetADefinition(Decl *D) {
2244   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2245     return VD->isThisDeclarationADefinition();
2246   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2247     return TD->isCompleteDefinition() || TD->isBeingDefined();
2248   return true;
2249 }
2250
2251 /// Merge alignment attributes from \p Old to \p New, taking into account the
2252 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2253 ///
2254 /// \return \c true if any attributes were added to \p New.
2255 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2256   // Look for alignas attributes on Old, and pick out whichever attribute
2257   // specifies the strictest alignment requirement.
2258   AlignedAttr *OldAlignasAttr = nullptr;
2259   AlignedAttr *OldStrictestAlignAttr = nullptr;
2260   unsigned OldAlign = 0;
2261   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2262     // FIXME: We have no way of representing inherited dependent alignments
2263     // in a case like:
2264     //   template<int A, int B> struct alignas(A) X;
2265     //   template<int A, int B> struct alignas(B) X {};
2266     // For now, we just ignore any alignas attributes which are not on the
2267     // definition in such a case.
2268     if (I->isAlignmentDependent())
2269       return false;
2270
2271     if (I->isAlignas())
2272       OldAlignasAttr = I;
2273
2274     unsigned Align = I->getAlignment(S.Context);
2275     if (Align > OldAlign) {
2276       OldAlign = Align;
2277       OldStrictestAlignAttr = I;
2278     }
2279   }
2280
2281   // Look for alignas attributes on New.
2282   AlignedAttr *NewAlignasAttr = nullptr;
2283   unsigned NewAlign = 0;
2284   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2285     if (I->isAlignmentDependent())
2286       return false;
2287
2288     if (I->isAlignas())
2289       NewAlignasAttr = I;
2290
2291     unsigned Align = I->getAlignment(S.Context);
2292     if (Align > NewAlign)
2293       NewAlign = Align;
2294   }
2295
2296   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2297     // Both declarations have 'alignas' attributes. We require them to match.
2298     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2299     // fall short. (If two declarations both have alignas, they must both match
2300     // every definition, and so must match each other if there is a definition.)
2301
2302     // If either declaration only contains 'alignas(0)' specifiers, then it
2303     // specifies the natural alignment for the type.
2304     if (OldAlign == 0 || NewAlign == 0) {
2305       QualType Ty;
2306       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2307         Ty = VD->getType();
2308       else
2309         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2310
2311       if (OldAlign == 0)
2312         OldAlign = S.Context.getTypeAlign(Ty);
2313       if (NewAlign == 0)
2314         NewAlign = S.Context.getTypeAlign(Ty);
2315     }
2316
2317     if (OldAlign != NewAlign) {
2318       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2319         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2320         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2321       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2322     }
2323   }
2324
2325   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2326     // C++11 [dcl.align]p6:
2327     //   if any declaration of an entity has an alignment-specifier,
2328     //   every defining declaration of that entity shall specify an
2329     //   equivalent alignment.
2330     // C11 6.7.5/7:
2331     //   If the definition of an object does not have an alignment
2332     //   specifier, any other declaration of that object shall also
2333     //   have no alignment specifier.
2334     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2335       << OldAlignasAttr;
2336     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2337       << OldAlignasAttr;
2338   }
2339
2340   bool AnyAdded = false;
2341
2342   // Ensure we have an attribute representing the strictest alignment.
2343   if (OldAlign > NewAlign) {
2344     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2345     Clone->setInherited(true);
2346     New->addAttr(Clone);
2347     AnyAdded = true;
2348   }
2349
2350   // Ensure we have an alignas attribute if the old declaration had one.
2351   if (OldAlignasAttr && !NewAlignasAttr &&
2352       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2353     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2354     Clone->setInherited(true);
2355     New->addAttr(Clone);
2356     AnyAdded = true;
2357   }
2358
2359   return AnyAdded;
2360 }
2361
2362 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2363                                const InheritableAttr *Attr,
2364                                Sema::AvailabilityMergeKind AMK) {
2365   // This function copies an attribute Attr from a previous declaration to the
2366   // new declaration D if the new declaration doesn't itself have that attribute
2367   // yet or if that attribute allows duplicates.
2368   // If you're adding a new attribute that requires logic different from
2369   // "use explicit attribute on decl if present, else use attribute from
2370   // previous decl", for example if the attribute needs to be consistent
2371   // between redeclarations, you need to call a custom merge function here.
2372   InheritableAttr *NewAttr = nullptr;
2373   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2374   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2375     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2376                                       AA->isImplicit(), AA->getIntroduced(),
2377                                       AA->getDeprecated(),
2378                                       AA->getObsoleted(), AA->getUnavailable(),
2379                                       AA->getMessage(), AA->getStrict(),
2380                                       AA->getReplacement(), AMK,
2381                                       AttrSpellingListIndex);
2382   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2383     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2384                                     AttrSpellingListIndex);
2385   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2386     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2387                                         AttrSpellingListIndex);
2388   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2389     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2390                                    AttrSpellingListIndex);
2391   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2392     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2393                                    AttrSpellingListIndex);
2394   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2395     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2396                                 FA->getFormatIdx(), FA->getFirstArg(),
2397                                 AttrSpellingListIndex);
2398   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2399     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2400                                  AttrSpellingListIndex);
2401   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2402     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2403                                        AttrSpellingListIndex,
2404                                        IA->getSemanticSpelling());
2405   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2406     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2407                                       &S.Context.Idents.get(AA->getSpelling()),
2408                                       AttrSpellingListIndex);
2409   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2410            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2411             isa<CUDAGlobalAttr>(Attr))) {
2412     // CUDA target attributes are part of function signature for
2413     // overloading purposes and must not be merged.
2414     return false;
2415   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2416     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2417   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2418     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2419   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2420     NewAttr = S.mergeInternalLinkageAttr(
2421         D, InternalLinkageA->getRange(),
2422         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2423         AttrSpellingListIndex);
2424   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2425     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2426                                 &S.Context.Idents.get(CommonA->getSpelling()),
2427                                 AttrSpellingListIndex);
2428   else if (isa<AlignedAttr>(Attr))
2429     // AlignedAttrs are handled separately, because we need to handle all
2430     // such attributes on a declaration at the same time.
2431     NewAttr = nullptr;
2432   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2433            (AMK == Sema::AMK_Override ||
2434             AMK == Sema::AMK_ProtocolImplementation))
2435     NewAttr = nullptr;
2436   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2437     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2438                               UA->getGuid());
2439   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2440     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2441
2442   if (NewAttr) {
2443     NewAttr->setInherited(true);
2444     D->addAttr(NewAttr);
2445     if (isa<MSInheritanceAttr>(NewAttr))
2446       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2447     return true;
2448   }
2449
2450   return false;
2451 }
2452
2453 static const NamedDecl *getDefinition(const Decl *D) {
2454   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2455     return TD->getDefinition();
2456   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2457     const VarDecl *Def = VD->getDefinition();
2458     if (Def)
2459       return Def;
2460     return VD->getActingDefinition();
2461   }
2462   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2463     return FD->getDefinition();
2464   return nullptr;
2465 }
2466
2467 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2468   for (const auto *Attribute : D->attrs())
2469     if (Attribute->getKind() == Kind)
2470       return true;
2471   return false;
2472 }
2473
2474 /// checkNewAttributesAfterDef - If we already have a definition, check that
2475 /// there are no new attributes in this declaration.
2476 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2477   if (!New->hasAttrs())
2478     return;
2479
2480   const NamedDecl *Def = getDefinition(Old);
2481   if (!Def || Def == New)
2482     return;
2483
2484   AttrVec &NewAttributes = New->getAttrs();
2485   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2486     const Attr *NewAttribute = NewAttributes[I];
2487
2488     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2489       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2490         Sema::SkipBodyInfo SkipBody;
2491         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2492
2493         // If we're skipping this definition, drop the "alias" attribute.
2494         if (SkipBody.ShouldSkip) {
2495           NewAttributes.erase(NewAttributes.begin() + I);
2496           --E;
2497           continue;
2498         }
2499       } else {
2500         VarDecl *VD = cast<VarDecl>(New);
2501         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2502                                 VarDecl::TentativeDefinition
2503                             ? diag::err_alias_after_tentative
2504                             : diag::err_redefinition;
2505         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2506         if (Diag == diag::err_redefinition)
2507           S.notePreviousDefinition(Def, VD->getLocation());
2508         else
2509           S.Diag(Def->getLocation(), diag::note_previous_definition);
2510         VD->setInvalidDecl();
2511       }
2512       ++I;
2513       continue;
2514     }
2515
2516     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2517       // Tentative definitions are only interesting for the alias check above.
2518       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2519         ++I;
2520         continue;
2521       }
2522     }
2523
2524     if (hasAttribute(Def, NewAttribute->getKind())) {
2525       ++I;
2526       continue; // regular attr merging will take care of validating this.
2527     }
2528
2529     if (isa<C11NoReturnAttr>(NewAttribute)) {
2530       // C's _Noreturn is allowed to be added to a function after it is defined.
2531       ++I;
2532       continue;
2533     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2534       if (AA->isAlignas()) {
2535         // C++11 [dcl.align]p6:
2536         //   if any declaration of an entity has an alignment-specifier,
2537         //   every defining declaration of that entity shall specify an
2538         //   equivalent alignment.
2539         // C11 6.7.5/7:
2540         //   If the definition of an object does not have an alignment
2541         //   specifier, any other declaration of that object shall also
2542         //   have no alignment specifier.
2543         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2544           << AA;
2545         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2546           << AA;
2547         NewAttributes.erase(NewAttributes.begin() + I);
2548         --E;
2549         continue;
2550       }
2551     }
2552
2553     S.Diag(NewAttribute->getLocation(),
2554            diag::warn_attribute_precede_definition);
2555     S.Diag(Def->getLocation(), diag::note_previous_definition);
2556     NewAttributes.erase(NewAttributes.begin() + I);
2557     --E;
2558   }
2559 }
2560
2561 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2562 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2563                                AvailabilityMergeKind AMK) {
2564   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2565     UsedAttr *NewAttr = OldAttr->clone(Context);
2566     NewAttr->setInherited(true);
2567     New->addAttr(NewAttr);
2568   }
2569
2570   if (!Old->hasAttrs() && !New->hasAttrs())
2571     return;
2572
2573   // Attributes declared post-definition are currently ignored.
2574   checkNewAttributesAfterDef(*this, New, Old);
2575
2576   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2577     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2578       if (OldA->getLabel() != NewA->getLabel()) {
2579         // This redeclaration changes __asm__ label.
2580         Diag(New->getLocation(), diag::err_different_asm_label);
2581         Diag(OldA->getLocation(), diag::note_previous_declaration);
2582       }
2583     } else if (Old->isUsed()) {
2584       // This redeclaration adds an __asm__ label to a declaration that has
2585       // already been ODR-used.
2586       Diag(New->getLocation(), diag::err_late_asm_label_name)
2587         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2588     }
2589   }
2590
2591   // Re-declaration cannot add abi_tag's.
2592   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2593     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2594       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2595         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2596                       NewTag) == OldAbiTagAttr->tags_end()) {
2597           Diag(NewAbiTagAttr->getLocation(),
2598                diag::err_new_abi_tag_on_redeclaration)
2599               << NewTag;
2600           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2601         }
2602       }
2603     } else {
2604       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2605       Diag(Old->getLocation(), diag::note_previous_declaration);
2606     }
2607   }
2608
2609   if (!Old->hasAttrs())
2610     return;
2611
2612   bool foundAny = New->hasAttrs();
2613
2614   // Ensure that any moving of objects within the allocated map is done before
2615   // we process them.
2616   if (!foundAny) New->setAttrs(AttrVec());
2617
2618   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2619     // Ignore deprecated/unavailable/availability attributes if requested.
2620     AvailabilityMergeKind LocalAMK = AMK_None;
2621     if (isa<DeprecatedAttr>(I) ||
2622         isa<UnavailableAttr>(I) ||
2623         isa<AvailabilityAttr>(I)) {
2624       switch (AMK) {
2625       case AMK_None:
2626         continue;
2627
2628       case AMK_Redeclaration:
2629       case AMK_Override:
2630       case AMK_ProtocolImplementation:
2631         LocalAMK = AMK;
2632         break;
2633       }
2634     }
2635
2636     // Already handled.
2637     if (isa<UsedAttr>(I))
2638       continue;
2639
2640     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2641       foundAny = true;
2642   }
2643
2644   if (mergeAlignedAttrs(*this, New, Old))
2645     foundAny = true;
2646
2647   if (!foundAny) New->dropAttrs();
2648 }
2649
2650 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2651 /// to the new one.
2652 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2653                                      const ParmVarDecl *oldDecl,
2654                                      Sema &S) {
2655   // C++11 [dcl.attr.depend]p2:
2656   //   The first declaration of a function shall specify the
2657   //   carries_dependency attribute for its declarator-id if any declaration
2658   //   of the function specifies the carries_dependency attribute.
2659   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2660   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2661     S.Diag(CDA->getLocation(),
2662            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2663     // Find the first declaration of the parameter.
2664     // FIXME: Should we build redeclaration chains for function parameters?
2665     const FunctionDecl *FirstFD =
2666       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2667     const ParmVarDecl *FirstVD =
2668       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2669     S.Diag(FirstVD->getLocation(),
2670            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2671   }
2672
2673   if (!oldDecl->hasAttrs())
2674     return;
2675
2676   bool foundAny = newDecl->hasAttrs();
2677
2678   // Ensure that any moving of objects within the allocated map is
2679   // done before we process them.
2680   if (!foundAny) newDecl->setAttrs(AttrVec());
2681
2682   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2683     if (!DeclHasAttr(newDecl, I)) {
2684       InheritableAttr *newAttr =
2685         cast<InheritableParamAttr>(I->clone(S.Context));
2686       newAttr->setInherited(true);
2687       newDecl->addAttr(newAttr);
2688       foundAny = true;
2689     }
2690   }
2691
2692   if (!foundAny) newDecl->dropAttrs();
2693 }
2694
2695 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2696                                 const ParmVarDecl *OldParam,
2697                                 Sema &S) {
2698   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2699     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2700       if (*Oldnullability != *Newnullability) {
2701         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2702           << DiagNullabilityKind(
2703                *Newnullability,
2704                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2705                 != 0))
2706           << DiagNullabilityKind(
2707                *Oldnullability,
2708                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2709                 != 0));
2710         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2711       }
2712     } else {
2713       QualType NewT = NewParam->getType();
2714       NewT = S.Context.getAttributedType(
2715                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2716                          NewT, NewT);
2717       NewParam->setType(NewT);
2718     }
2719   }
2720 }
2721
2722 namespace {
2723
2724 /// Used in MergeFunctionDecl to keep track of function parameters in
2725 /// C.
2726 struct GNUCompatibleParamWarning {
2727   ParmVarDecl *OldParm;
2728   ParmVarDecl *NewParm;
2729   QualType PromotedType;
2730 };
2731
2732 } // end anonymous namespace
2733
2734 /// getSpecialMember - get the special member enum for a method.
2735 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2736   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2737     if (Ctor->isDefaultConstructor())
2738       return Sema::CXXDefaultConstructor;
2739
2740     if (Ctor->isCopyConstructor())
2741       return Sema::CXXCopyConstructor;
2742
2743     if (Ctor->isMoveConstructor())
2744       return Sema::CXXMoveConstructor;
2745   } else if (isa<CXXDestructorDecl>(MD)) {
2746     return Sema::CXXDestructor;
2747   } else if (MD->isCopyAssignmentOperator()) {
2748     return Sema::CXXCopyAssignment;
2749   } else if (MD->isMoveAssignmentOperator()) {
2750     return Sema::CXXMoveAssignment;
2751   }
2752
2753   return Sema::CXXInvalid;
2754 }
2755
2756 // Determine whether the previous declaration was a definition, implicit
2757 // declaration, or a declaration.
2758 template <typename T>
2759 static std::pair<diag::kind, SourceLocation>
2760 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2761   diag::kind PrevDiag;
2762   SourceLocation OldLocation = Old->getLocation();
2763   if (Old->isThisDeclarationADefinition())
2764     PrevDiag = diag::note_previous_definition;
2765   else if (Old->isImplicit()) {
2766     PrevDiag = diag::note_previous_implicit_declaration;
2767     if (OldLocation.isInvalid())
2768       OldLocation = New->getLocation();
2769   } else
2770     PrevDiag = diag::note_previous_declaration;
2771   return std::make_pair(PrevDiag, OldLocation);
2772 }
2773
2774 /// canRedefineFunction - checks if a function can be redefined. Currently,
2775 /// only extern inline functions can be redefined, and even then only in
2776 /// GNU89 mode.
2777 static bool canRedefineFunction(const FunctionDecl *FD,
2778                                 const LangOptions& LangOpts) {
2779   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2780           !LangOpts.CPlusPlus &&
2781           FD->isInlineSpecified() &&
2782           FD->getStorageClass() == SC_Extern);
2783 }
2784
2785 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2786   const AttributedType *AT = T->getAs<AttributedType>();
2787   while (AT && !AT->isCallingConv())
2788     AT = AT->getModifiedType()->getAs<AttributedType>();
2789   return AT;
2790 }
2791
2792 template <typename T>
2793 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2794   const DeclContext *DC = Old->getDeclContext();
2795   if (DC->isRecord())
2796     return false;
2797
2798   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2799   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2800     return true;
2801   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2802     return true;
2803   return false;
2804 }
2805
2806 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2807 static bool isExternC(VarTemplateDecl *) { return false; }
2808
2809 /// \brief Check whether a redeclaration of an entity introduced by a
2810 /// using-declaration is valid, given that we know it's not an overload
2811 /// (nor a hidden tag declaration).
2812 template<typename ExpectedDecl>
2813 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2814                                    ExpectedDecl *New) {
2815   // C++11 [basic.scope.declarative]p4:
2816   //   Given a set of declarations in a single declarative region, each of
2817   //   which specifies the same unqualified name,
2818   //   -- they shall all refer to the same entity, or all refer to functions
2819   //      and function templates; or
2820   //   -- exactly one declaration shall declare a class name or enumeration
2821   //      name that is not a typedef name and the other declarations shall all
2822   //      refer to the same variable or enumerator, or all refer to functions
2823   //      and function templates; in this case the class name or enumeration
2824   //      name is hidden (3.3.10).
2825
2826   // C++11 [namespace.udecl]p14:
2827   //   If a function declaration in namespace scope or block scope has the
2828   //   same name and the same parameter-type-list as a function introduced
2829   //   by a using-declaration, and the declarations do not declare the same
2830   //   function, the program is ill-formed.
2831
2832   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2833   if (Old &&
2834       !Old->getDeclContext()->getRedeclContext()->Equals(
2835           New->getDeclContext()->getRedeclContext()) &&
2836       !(isExternC(Old) && isExternC(New)))
2837     Old = nullptr;
2838
2839   if (!Old) {
2840     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2841     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2842     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2843     return true;
2844   }
2845   return false;
2846 }
2847
2848 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2849                                             const FunctionDecl *B) {
2850   assert(A->getNumParams() == B->getNumParams());
2851
2852   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2853     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2854     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2855     if (AttrA == AttrB)
2856       return true;
2857     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2858   };
2859
2860   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2861 }
2862
2863 /// MergeFunctionDecl - We just parsed a function 'New' from
2864 /// declarator D which has the same name and scope as a previous
2865 /// declaration 'Old'.  Figure out how to resolve this situation,
2866 /// merging decls or emitting diagnostics as appropriate.
2867 ///
2868 /// In C++, New and Old must be declarations that are not
2869 /// overloaded. Use IsOverload to determine whether New and Old are
2870 /// overloaded, and to select the Old declaration that New should be
2871 /// merged with.
2872 ///
2873 /// Returns true if there was an error, false otherwise.
2874 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2875                              Scope *S, bool MergeTypeWithOld) {
2876   // Verify the old decl was also a function.
2877   FunctionDecl *Old = OldD->getAsFunction();
2878   if (!Old) {
2879     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2880       if (New->getFriendObjectKind()) {
2881         Diag(New->getLocation(), diag::err_using_decl_friend);
2882         Diag(Shadow->getTargetDecl()->getLocation(),
2883              diag::note_using_decl_target);
2884         Diag(Shadow->getUsingDecl()->getLocation(),
2885              diag::note_using_decl) << 0;
2886         return true;
2887       }
2888
2889       // Check whether the two declarations might declare the same function.
2890       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2891         return true;
2892       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2893     } else {
2894       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2895         << New->getDeclName();
2896       notePreviousDefinition(OldD, New->getLocation());
2897       return true;
2898     }
2899   }
2900
2901   // If the old declaration is invalid, just give up here.
2902   if (Old->isInvalidDecl())
2903     return true;
2904
2905   diag::kind PrevDiag;
2906   SourceLocation OldLocation;
2907   std::tie(PrevDiag, OldLocation) =
2908       getNoteDiagForInvalidRedeclaration(Old, New);
2909
2910   // Don't complain about this if we're in GNU89 mode and the old function
2911   // is an extern inline function.
2912   // Don't complain about specializations. They are not supposed to have
2913   // storage classes.
2914   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2915       New->getStorageClass() == SC_Static &&
2916       Old->hasExternalFormalLinkage() &&
2917       !New->getTemplateSpecializationInfo() &&
2918       !canRedefineFunction(Old, getLangOpts())) {
2919     if (getLangOpts().MicrosoftExt) {
2920       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2921       Diag(OldLocation, PrevDiag);
2922     } else {
2923       Diag(New->getLocation(), diag::err_static_non_static) << New;
2924       Diag(OldLocation, PrevDiag);
2925       return true;
2926     }
2927   }
2928
2929   if (New->hasAttr<InternalLinkageAttr>() &&
2930       !Old->hasAttr<InternalLinkageAttr>()) {
2931     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2932         << New->getDeclName();
2933     notePreviousDefinition(Old, New->getLocation());
2934     New->dropAttr<InternalLinkageAttr>();
2935   }
2936
2937   if (!getLangOpts().CPlusPlus) {
2938     bool OldOvl = Old->hasAttr<OverloadableAttr>();
2939     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
2940       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
2941         << New << OldOvl;
2942
2943       // Try our best to find a decl that actually has the overloadable
2944       // attribute for the note. In most cases (e.g. programs with only one
2945       // broken declaration/definition), this won't matter.
2946       //
2947       // FIXME: We could do this if we juggled some extra state in
2948       // OverloadableAttr, rather than just removing it.
2949       const Decl *DiagOld = Old;
2950       if (OldOvl) {
2951         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
2952           const auto *A = D->getAttr<OverloadableAttr>();
2953           return A && !A->isImplicit();
2954         });
2955         // If we've implicitly added *all* of the overloadable attrs to this
2956         // chain, emitting a "previous redecl" note is pointless.
2957         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
2958       }
2959
2960       if (DiagOld)
2961         Diag(DiagOld->getLocation(),
2962              diag::note_attribute_overloadable_prev_overload)
2963           << OldOvl;
2964
2965       if (OldOvl)
2966         New->addAttr(OverloadableAttr::CreateImplicit(Context));
2967       else
2968         New->dropAttr<OverloadableAttr>();
2969     }
2970   }
2971
2972   // If a function is first declared with a calling convention, but is later
2973   // declared or defined without one, all following decls assume the calling
2974   // convention of the first.
2975   //
2976   // It's OK if a function is first declared without a calling convention,
2977   // but is later declared or defined with the default calling convention.
2978   //
2979   // To test if either decl has an explicit calling convention, we look for
2980   // AttributedType sugar nodes on the type as written.  If they are missing or
2981   // were canonicalized away, we assume the calling convention was implicit.
2982   //
2983   // Note also that we DO NOT return at this point, because we still have
2984   // other tests to run.
2985   QualType OldQType = Context.getCanonicalType(Old->getType());
2986   QualType NewQType = Context.getCanonicalType(New->getType());
2987   const FunctionType *OldType = cast<FunctionType>(OldQType);
2988   const FunctionType *NewType = cast<FunctionType>(NewQType);
2989   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2990   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2991   bool RequiresAdjustment = false;
2992
2993   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2994     FunctionDecl *First = Old->getFirstDecl();
2995     const FunctionType *FT =
2996         First->getType().getCanonicalType()->castAs<FunctionType>();
2997     FunctionType::ExtInfo FI = FT->getExtInfo();
2998     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2999     if (!NewCCExplicit) {
3000       // Inherit the CC from the previous declaration if it was specified
3001       // there but not here.
3002       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3003       RequiresAdjustment = true;
3004     } else {
3005       // Calling conventions aren't compatible, so complain.
3006       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3007       Diag(New->getLocation(), diag::err_cconv_change)
3008         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3009         << !FirstCCExplicit
3010         << (!FirstCCExplicit ? "" :
3011             FunctionType::getNameForCallConv(FI.getCC()));
3012
3013       // Put the note on the first decl, since it is the one that matters.
3014       Diag(First->getLocation(), diag::note_previous_declaration);
3015       return true;
3016     }
3017   }
3018
3019   // FIXME: diagnose the other way around?
3020   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3021     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3022     RequiresAdjustment = true;
3023   }
3024
3025   // Merge regparm attribute.
3026   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3027       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3028     if (NewTypeInfo.getHasRegParm()) {
3029       Diag(New->getLocation(), diag::err_regparm_mismatch)
3030         << NewType->getRegParmType()
3031         << OldType->getRegParmType();
3032       Diag(OldLocation, diag::note_previous_declaration);
3033       return true;
3034     }
3035
3036     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3037     RequiresAdjustment = true;
3038   }
3039
3040   // Merge ns_returns_retained attribute.
3041   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3042     if (NewTypeInfo.getProducesResult()) {
3043       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3044           << "'ns_returns_retained'";
3045       Diag(OldLocation, diag::note_previous_declaration);
3046       return true;
3047     }
3048
3049     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3050     RequiresAdjustment = true;
3051   }
3052
3053   if (OldTypeInfo.getNoCallerSavedRegs() !=
3054       NewTypeInfo.getNoCallerSavedRegs()) {
3055     if (NewTypeInfo.getNoCallerSavedRegs()) {
3056       AnyX86NoCallerSavedRegistersAttr *Attr = 
3057         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3058       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3059       Diag(OldLocation, diag::note_previous_declaration);
3060       return true;
3061     }
3062
3063     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3064     RequiresAdjustment = true;
3065   }
3066
3067   if (RequiresAdjustment) {
3068     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3069     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3070     New->setType(QualType(AdjustedType, 0));
3071     NewQType = Context.getCanonicalType(New->getType());
3072     NewType = cast<FunctionType>(NewQType);
3073   }
3074
3075   // If this redeclaration makes the function inline, we may need to add it to
3076   // UndefinedButUsed.
3077   if (!Old->isInlined() && New->isInlined() &&
3078       !New->hasAttr<GNUInlineAttr>() &&
3079       !getLangOpts().GNUInline &&
3080       Old->isUsed(false) &&
3081       !Old->isDefined() && !New->isThisDeclarationADefinition())
3082     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3083                                            SourceLocation()));
3084
3085   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3086   // about it.
3087   if (New->hasAttr<GNUInlineAttr>() &&
3088       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3089     UndefinedButUsed.erase(Old->getCanonicalDecl());
3090   }
3091
3092   // If pass_object_size params don't match up perfectly, this isn't a valid
3093   // redeclaration.
3094   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3095       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3096     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3097         << New->getDeclName();
3098     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3099     return true;
3100   }
3101
3102   if (getLangOpts().CPlusPlus) {
3103     // C++1z [over.load]p2
3104     //   Certain function declarations cannot be overloaded:
3105     //     -- Function declarations that differ only in the return type,
3106     //        the exception specification, or both cannot be overloaded.
3107
3108     // Check the exception specifications match. This may recompute the type of
3109     // both Old and New if it resolved exception specifications, so grab the
3110     // types again after this. Because this updates the type, we do this before
3111     // any of the other checks below, which may update the "de facto" NewQType
3112     // but do not necessarily update the type of New.
3113     if (CheckEquivalentExceptionSpec(Old, New))
3114       return true;
3115     OldQType = Context.getCanonicalType(Old->getType());
3116     NewQType = Context.getCanonicalType(New->getType());
3117
3118     // Go back to the type source info to compare the declared return types,
3119     // per C++1y [dcl.type.auto]p13:
3120     //   Redeclarations or specializations of a function or function template
3121     //   with a declared return type that uses a placeholder type shall also
3122     //   use that placeholder, not a deduced type.
3123     QualType OldDeclaredReturnType =
3124         (Old->getTypeSourceInfo()
3125              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3126              : OldType)->getReturnType();
3127     QualType NewDeclaredReturnType =
3128         (New->getTypeSourceInfo()
3129              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3130              : NewType)->getReturnType();
3131     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3132         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3133           New->isLocalExternDecl())) {
3134       QualType ResQT;
3135       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3136           OldDeclaredReturnType->isObjCObjectPointerType())
3137         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3138       if (ResQT.isNull()) {
3139         if (New->isCXXClassMember() && New->isOutOfLine())
3140           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3141               << New << New->getReturnTypeSourceRange();
3142         else
3143           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3144               << New->getReturnTypeSourceRange();
3145         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3146                                     << Old->getReturnTypeSourceRange();
3147         return true;
3148       }
3149       else
3150         NewQType = ResQT;
3151     }
3152
3153     QualType OldReturnType = OldType->getReturnType();
3154     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3155     if (OldReturnType != NewReturnType) {
3156       // If this function has a deduced return type and has already been
3157       // defined, copy the deduced value from the old declaration.
3158       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3159       if (OldAT && OldAT->isDeduced()) {
3160         New->setType(
3161             SubstAutoType(New->getType(),
3162                           OldAT->isDependentType() ? Context.DependentTy
3163                                                    : OldAT->getDeducedType()));
3164         NewQType = Context.getCanonicalType(
3165             SubstAutoType(NewQType,
3166                           OldAT->isDependentType() ? Context.DependentTy
3167                                                    : OldAT->getDeducedType()));
3168       }
3169     }
3170
3171     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3172     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3173     if (OldMethod && NewMethod) {
3174       // Preserve triviality.
3175       NewMethod->setTrivial(OldMethod->isTrivial());
3176
3177       // MSVC allows explicit template specialization at class scope:
3178       // 2 CXXMethodDecls referring to the same function will be injected.
3179       // We don't want a redeclaration error.
3180       bool IsClassScopeExplicitSpecialization =
3181                               OldMethod->isFunctionTemplateSpecialization() &&
3182                               NewMethod->isFunctionTemplateSpecialization();
3183       bool isFriend = NewMethod->getFriendObjectKind();
3184
3185       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3186           !IsClassScopeExplicitSpecialization) {
3187         //    -- Member function declarations with the same name and the
3188         //       same parameter types cannot be overloaded if any of them
3189         //       is a static member function declaration.
3190         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3191           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3192           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3193           return true;
3194         }
3195
3196         // C++ [class.mem]p1:
3197         //   [...] A member shall not be declared twice in the
3198         //   member-specification, except that a nested class or member
3199         //   class template can be declared and then later defined.
3200         if (!inTemplateInstantiation()) {
3201           unsigned NewDiag;
3202           if (isa<CXXConstructorDecl>(OldMethod))
3203             NewDiag = diag::err_constructor_redeclared;
3204           else if (isa<CXXDestructorDecl>(NewMethod))
3205             NewDiag = diag::err_destructor_redeclared;
3206           else if (isa<CXXConversionDecl>(NewMethod))
3207             NewDiag = diag::err_conv_function_redeclared;
3208           else
3209             NewDiag = diag::err_member_redeclared;
3210
3211           Diag(New->getLocation(), NewDiag);
3212         } else {
3213           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3214             << New << New->getType();
3215         }
3216         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3217         return true;
3218
3219       // Complain if this is an explicit declaration of a special
3220       // member that was initially declared implicitly.
3221       //
3222       // As an exception, it's okay to befriend such methods in order
3223       // to permit the implicit constructor/destructor/operator calls.
3224       } else if (OldMethod->isImplicit()) {
3225         if (isFriend) {
3226           NewMethod->setImplicit();
3227         } else {
3228           Diag(NewMethod->getLocation(),
3229                diag::err_definition_of_implicitly_declared_member)
3230             << New << getSpecialMember(OldMethod);
3231           return true;
3232         }
3233       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3234         Diag(NewMethod->getLocation(),
3235              diag::err_definition_of_explicitly_defaulted_member)
3236           << getSpecialMember(OldMethod);
3237         return true;
3238       }
3239     }
3240
3241     // C++11 [dcl.attr.noreturn]p1:
3242     //   The first declaration of a function shall specify the noreturn
3243     //   attribute if any declaration of that function specifies the noreturn
3244     //   attribute.
3245     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3246     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3247       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3248       Diag(Old->getFirstDecl()->getLocation(),
3249            diag::note_noreturn_missing_first_decl);
3250     }
3251
3252     // C++11 [dcl.attr.depend]p2:
3253     //   The first declaration of a function shall specify the
3254     //   carries_dependency attribute for its declarator-id if any declaration
3255     //   of the function specifies the carries_dependency attribute.
3256     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3257     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3258       Diag(CDA->getLocation(),
3259            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3260       Diag(Old->getFirstDecl()->getLocation(),
3261            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3262     }
3263
3264     // (C++98 8.3.5p3):
3265     //   All declarations for a function shall agree exactly in both the
3266     //   return type and the parameter-type-list.
3267     // We also want to respect all the extended bits except noreturn.
3268
3269     // noreturn should now match unless the old type info didn't have it.
3270     QualType OldQTypeForComparison = OldQType;
3271     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3272       auto *OldType = OldQType->castAs<FunctionProtoType>();
3273       const FunctionType *OldTypeForComparison
3274         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3275       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3276       assert(OldQTypeForComparison.isCanonical());
3277     }
3278
3279     if (haveIncompatibleLanguageLinkages(Old, New)) {
3280       // As a special case, retain the language linkage from previous
3281       // declarations of a friend function as an extension.
3282       //
3283       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3284       // and is useful because there's otherwise no way to specify language
3285       // linkage within class scope.
3286       //
3287       // Check cautiously as the friend object kind isn't yet complete.
3288       if (New->getFriendObjectKind() != Decl::FOK_None) {
3289         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3290         Diag(OldLocation, PrevDiag);
3291       } else {
3292         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3293         Diag(OldLocation, PrevDiag);
3294         return true;
3295       }
3296     }
3297
3298     if (OldQTypeForComparison == NewQType)
3299       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3300
3301     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3302         New->isLocalExternDecl()) {
3303       // It's OK if we couldn't merge types for a local function declaraton
3304       // if either the old or new type is dependent. We'll merge the types
3305       // when we instantiate the function.
3306       return false;
3307     }
3308
3309     // Fall through for conflicting redeclarations and redefinitions.
3310   }
3311
3312   // C: Function types need to be compatible, not identical. This handles
3313   // duplicate function decls like "void f(int); void f(enum X);" properly.
3314   if (!getLangOpts().CPlusPlus &&
3315       Context.typesAreCompatible(OldQType, NewQType)) {
3316     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3317     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3318     const FunctionProtoType *OldProto = nullptr;
3319     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3320         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3321       // The old declaration provided a function prototype, but the
3322       // new declaration does not. Merge in the prototype.
3323       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3324       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3325       NewQType =
3326           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3327                                   OldProto->getExtProtoInfo());
3328       New->setType(NewQType);
3329       New->setHasInheritedPrototype();
3330
3331       // Synthesize parameters with the same types.
3332       SmallVector<ParmVarDecl*, 16> Params;
3333       for (const auto &ParamType : OldProto->param_types()) {
3334         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3335                                                  SourceLocation(), nullptr,
3336                                                  ParamType, /*TInfo=*/nullptr,
3337                                                  SC_None, nullptr);
3338         Param->setScopeInfo(0, Params.size());
3339         Param->setImplicit();
3340         Params.push_back(Param);
3341       }
3342
3343       New->setParams(Params);
3344     }
3345
3346     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3347   }
3348
3349   // GNU C permits a K&R definition to follow a prototype declaration
3350   // if the declared types of the parameters in the K&R definition
3351   // match the types in the prototype declaration, even when the
3352   // promoted types of the parameters from the K&R definition differ
3353   // from the types in the prototype. GCC then keeps the types from
3354   // the prototype.
3355   //
3356   // If a variadic prototype is followed by a non-variadic K&R definition,
3357   // the K&R definition becomes variadic.  This is sort of an edge case, but
3358   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3359   // C99 6.9.1p8.
3360   if (!getLangOpts().CPlusPlus &&
3361       Old->hasPrototype() && !New->hasPrototype() &&
3362       New->getType()->getAs<FunctionProtoType>() &&
3363       Old->getNumParams() == New->getNumParams()) {
3364     SmallVector<QualType, 16> ArgTypes;
3365     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3366     const FunctionProtoType *OldProto
3367       = Old->getType()->getAs<FunctionProtoType>();
3368     const FunctionProtoType *NewProto
3369       = New->getType()->getAs<FunctionProtoType>();
3370
3371     // Determine whether this is the GNU C extension.
3372     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3373                                                NewProto->getReturnType());
3374     bool LooseCompatible = !MergedReturn.isNull();
3375     for (unsigned Idx = 0, End = Old->getNumParams();
3376          LooseCompatible && Idx != End; ++Idx) {
3377       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3378       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3379       if (Context.typesAreCompatible(OldParm->getType(),
3380                                      NewProto->getParamType(Idx))) {
3381         ArgTypes.push_back(NewParm->getType());
3382       } else if (Context.typesAreCompatible(OldParm->getType(),
3383                                             NewParm->getType(),
3384                                             /*CompareUnqualified=*/true)) {
3385         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3386                                            NewProto->getParamType(Idx) };
3387         Warnings.push_back(Warn);
3388         ArgTypes.push_back(NewParm->getType());
3389       } else
3390         LooseCompatible = false;
3391     }
3392
3393     if (LooseCompatible) {
3394       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3395         Diag(Warnings[Warn].NewParm->getLocation(),
3396              diag::ext_param_promoted_not_compatible_with_prototype)
3397           << Warnings[Warn].PromotedType
3398           << Warnings[Warn].OldParm->getType();
3399         if (Warnings[Warn].OldParm->getLocation().isValid())
3400           Diag(Warnings[Warn].OldParm->getLocation(),
3401                diag::note_previous_declaration);
3402       }
3403
3404       if (MergeTypeWithOld)
3405         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3406                                              OldProto->getExtProtoInfo()));
3407       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3408     }
3409
3410     // Fall through to diagnose conflicting types.
3411   }
3412
3413   // A function that has already been declared has been redeclared or
3414   // defined with a different type; show an appropriate diagnostic.
3415
3416   // If the previous declaration was an implicitly-generated builtin
3417   // declaration, then at the very least we should use a specialized note.
3418   unsigned BuiltinID;
3419   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3420     // If it's actually a library-defined builtin function like 'malloc'
3421     // or 'printf', just warn about the incompatible redeclaration.
3422     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3423       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3424       Diag(OldLocation, diag::note_previous_builtin_declaration)
3425         << Old << Old->getType();
3426
3427       // If this is a global redeclaration, just forget hereafter
3428       // about the "builtin-ness" of the function.
3429       //
3430       // Doing this for local extern declarations is problematic.  If
3431       // the builtin declaration remains visible, a second invalid
3432       // local declaration will produce a hard error; if it doesn't
3433       // remain visible, a single bogus local redeclaration (which is
3434       // actually only a warning) could break all the downstream code.
3435       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3436         New->getIdentifier()->revertBuiltin();
3437
3438       return false;
3439     }
3440
3441     PrevDiag = diag::note_previous_builtin_declaration;
3442   }
3443
3444   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3445   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3446   return true;
3447 }
3448
3449 /// \brief Completes the merge of two function declarations that are
3450 /// known to be compatible.
3451 ///
3452 /// This routine handles the merging of attributes and other
3453 /// properties of function declarations from the old declaration to
3454 /// the new declaration, once we know that New is in fact a
3455 /// redeclaration of Old.
3456 ///
3457 /// \returns false
3458 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3459                                         Scope *S, bool MergeTypeWithOld) {
3460   // Merge the attributes
3461   mergeDeclAttributes(New, Old);
3462
3463   // Merge "pure" flag.
3464   if (Old->isPure())
3465     New->setPure();
3466
3467   // Merge "used" flag.
3468   if (Old->getMostRecentDecl()->isUsed(false))
3469     New->setIsUsed();
3470
3471   // Merge attributes from the parameters.  These can mismatch with K&R
3472   // declarations.
3473   if (New->getNumParams() == Old->getNumParams())
3474       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3475         ParmVarDecl *NewParam = New->getParamDecl(i);
3476         ParmVarDecl *OldParam = Old->getParamDecl(i);
3477         mergeParamDeclAttributes(NewParam, OldParam, *this);
3478         mergeParamDeclTypes(NewParam, OldParam, *this);
3479       }
3480
3481   if (getLangOpts().CPlusPlus)
3482     return MergeCXXFunctionDecl(New, Old, S);
3483
3484   // Merge the function types so the we get the composite types for the return
3485   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3486   // was visible.
3487   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3488   if (!Merged.isNull() && MergeTypeWithOld)
3489     New->setType(Merged);
3490
3491   return false;
3492 }
3493
3494 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3495                                 ObjCMethodDecl *oldMethod) {
3496   // Merge the attributes, including deprecated/unavailable
3497   AvailabilityMergeKind MergeKind =
3498     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3499       ? AMK_ProtocolImplementation
3500       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3501                                                        : AMK_Override;
3502
3503   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3504
3505   // Merge attributes from the parameters.
3506   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3507                                        oe = oldMethod->param_end();
3508   for (ObjCMethodDecl::param_iterator
3509          ni = newMethod->param_begin(), ne = newMethod->param_end();
3510        ni != ne && oi != oe; ++ni, ++oi)
3511     mergeParamDeclAttributes(*ni, *oi, *this);
3512
3513   CheckObjCMethodOverride(newMethod, oldMethod);
3514 }
3515
3516 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3517   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3518
3519   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3520          ? diag::err_redefinition_different_type
3521          : diag::err_redeclaration_different_type)
3522     << New->getDeclName() << New->getType() << Old->getType();
3523
3524   diag::kind PrevDiag;
3525   SourceLocation OldLocation;
3526   std::tie(PrevDiag, OldLocation)
3527     = getNoteDiagForInvalidRedeclaration(Old, New);
3528   S.Diag(OldLocation, PrevDiag);
3529   New->setInvalidDecl();
3530 }
3531
3532 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3533 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3534 /// emitting diagnostics as appropriate.
3535 ///
3536 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3537 /// to here in AddInitializerToDecl. We can't check them before the initializer
3538 /// is attached.
3539 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3540                              bool MergeTypeWithOld) {
3541   if (New->isInvalidDecl() || Old->isInvalidDecl())
3542     return;
3543
3544   QualType MergedT;
3545   if (getLangOpts().CPlusPlus) {
3546     if (New->getType()->isUndeducedType()) {
3547       // We don't know what the new type is until the initializer is attached.
3548       return;
3549     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3550       // These could still be something that needs exception specs checked.
3551       return MergeVarDeclExceptionSpecs(New, Old);
3552     }
3553     // C++ [basic.link]p10:
3554     //   [...] the types specified by all declarations referring to a given
3555     //   object or function shall be identical, except that declarations for an
3556     //   array object can specify array types that differ by the presence or
3557     //   absence of a major array bound (8.3.4).
3558     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3559       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3560       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3561
3562       // We are merging a variable declaration New into Old. If it has an array
3563       // bound, and that bound differs from Old's bound, we should diagnose the
3564       // mismatch.
3565       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3566         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3567              PrevVD = PrevVD->getPreviousDecl()) {
3568           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3569           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3570             continue;
3571
3572           if (!Context.hasSameType(NewArray, PrevVDTy))
3573             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3574         }
3575       }
3576
3577       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3578         if (Context.hasSameType(OldArray->getElementType(),
3579                                 NewArray->getElementType()))
3580           MergedT = New->getType();
3581       }
3582       // FIXME: Check visibility. New is hidden but has a complete type. If New
3583       // has no array bound, it should not inherit one from Old, if Old is not
3584       // visible.
3585       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3586         if (Context.hasSameType(OldArray->getElementType(),
3587                                 NewArray->getElementType()))
3588           MergedT = Old->getType();
3589       }
3590     }
3591     else if (New->getType()->isObjCObjectPointerType() &&
3592                Old->getType()->isObjCObjectPointerType()) {
3593       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3594                                               Old->getType());
3595     }
3596   } else {
3597     // C 6.2.7p2:
3598     //   All declarations that refer to the same object or function shall have
3599     //   compatible type.
3600     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3601   }
3602   if (MergedT.isNull()) {
3603     // It's OK if we couldn't merge types if either type is dependent, for a
3604     // block-scope variable. In other cases (static data members of class
3605     // templates, variable templates, ...), we require the types to be
3606     // equivalent.
3607     // FIXME: The C++ standard doesn't say anything about this.
3608     if ((New->getType()->isDependentType() ||
3609          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3610       // If the old type was dependent, we can't merge with it, so the new type
3611       // becomes dependent for now. We'll reproduce the original type when we
3612       // instantiate the TypeSourceInfo for the variable.
3613       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3614         New->setType(Context.DependentTy);
3615       return;
3616     }
3617     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3618   }
3619
3620   // Don't actually update the type on the new declaration if the old
3621   // declaration was an extern declaration in a different scope.
3622   if (MergeTypeWithOld)
3623     New->setType(MergedT);
3624 }
3625
3626 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3627                                   LookupResult &Previous) {
3628   // C11 6.2.7p4:
3629   //   For an identifier with internal or external linkage declared
3630   //   in a scope in which a prior declaration of that identifier is
3631   //   visible, if the prior declaration specifies internal or
3632   //   external linkage, the type of the identifier at the later
3633   //   declaration becomes the composite type.
3634   //
3635   // If the variable isn't visible, we do not merge with its type.
3636   if (Previous.isShadowed())
3637     return false;
3638
3639   if (S.getLangOpts().CPlusPlus) {
3640     // C++11 [dcl.array]p3:
3641     //   If there is a preceding declaration of the entity in the same
3642     //   scope in which the bound was specified, an omitted array bound
3643     //   is taken to be the same as in that earlier declaration.
3644     return NewVD->isPreviousDeclInSameBlockScope() ||
3645            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3646             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3647   } else {
3648     // If the old declaration was function-local, don't merge with its
3649     // type unless we're in the same function.
3650     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3651            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3652   }
3653 }
3654
3655 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3656 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3657 /// situation, merging decls or emitting diagnostics as appropriate.
3658 ///
3659 /// Tentative definition rules (C99 6.9.2p2) are checked by
3660 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3661 /// definitions here, since the initializer hasn't been attached.
3662 ///
3663 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3664   // If the new decl is already invalid, don't do any other checking.
3665   if (New->isInvalidDecl())
3666     return;
3667
3668   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3669     return;
3670
3671   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3672
3673   // Verify the old decl was also a variable or variable template.
3674   VarDecl *Old = nullptr;
3675   VarTemplateDecl *OldTemplate = nullptr;
3676   if (Previous.isSingleResult()) {
3677     if (NewTemplate) {
3678       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3679       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3680
3681       if (auto *Shadow =
3682               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3683         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3684           return New->setInvalidDecl();
3685     } else {
3686       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3687
3688       if (auto *Shadow =
3689               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3690         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3691           return New->setInvalidDecl();
3692     }
3693   }
3694   if (!Old) {
3695     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3696         << New->getDeclName();
3697     notePreviousDefinition(Previous.getRepresentativeDecl(),
3698                            New->getLocation());
3699     return New->setInvalidDecl();
3700   }
3701
3702   // Ensure the template parameters are compatible.
3703   if (NewTemplate &&
3704       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3705                                       OldTemplate->getTemplateParameters(),
3706                                       /*Complain=*/true, TPL_TemplateMatch))
3707     return New->setInvalidDecl();
3708
3709   // C++ [class.mem]p1:
3710   //   A member shall not be declared twice in the member-specification [...]
3711   //
3712   // Here, we need only consider static data members.
3713   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3714     Diag(New->getLocation(), diag::err_duplicate_member)
3715       << New->getIdentifier();
3716     Diag(Old->getLocation(), diag::note_previous_declaration);
3717     New->setInvalidDecl();
3718   }
3719
3720   mergeDeclAttributes(New, Old);
3721   // Warn if an already-declared variable is made a weak_import in a subsequent
3722   // declaration
3723   if (New->hasAttr<WeakImportAttr>() &&
3724       Old->getStorageClass() == SC_None &&
3725       !Old->hasAttr<WeakImportAttr>()) {
3726     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3727     notePreviousDefinition(Old, New->getLocation());
3728     // Remove weak_import attribute on new declaration.
3729     New->dropAttr<WeakImportAttr>();
3730   }
3731
3732   if (New->hasAttr<InternalLinkageAttr>() &&
3733       !Old->hasAttr<InternalLinkageAttr>()) {
3734     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3735         << New->getDeclName();
3736     notePreviousDefinition(Old, New->getLocation());
3737     New->dropAttr<InternalLinkageAttr>();
3738   }
3739
3740   // Merge the types.
3741   VarDecl *MostRecent = Old->getMostRecentDecl();
3742   if (MostRecent != Old) {
3743     MergeVarDeclTypes(New, MostRecent,
3744                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3745     if (New->isInvalidDecl())
3746       return;
3747   }
3748
3749   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3750   if (New->isInvalidDecl())
3751     return;
3752
3753   diag::kind PrevDiag;
3754   SourceLocation OldLocation;
3755   std::tie(PrevDiag, OldLocation) =
3756       getNoteDiagForInvalidRedeclaration(Old, New);
3757
3758   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3759   if (New->getStorageClass() == SC_Static &&
3760       !New->isStaticDataMember() &&
3761       Old->hasExternalFormalLinkage()) {
3762     if (getLangOpts().MicrosoftExt) {
3763       Diag(New->getLocation(), diag::ext_static_non_static)
3764           << New->getDeclName();
3765       Diag(OldLocation, PrevDiag);
3766     } else {
3767       Diag(New->getLocation(), diag::err_static_non_static)
3768           << New->getDeclName();
3769       Diag(OldLocation, PrevDiag);
3770       return New->setInvalidDecl();
3771     }
3772   }
3773   // C99 6.2.2p4:
3774   //   For an identifier declared with the storage-class specifier
3775   //   extern in a scope in which a prior declaration of that
3776   //   identifier is visible,23) if the prior declaration specifies
3777   //   internal or external linkage, the linkage of the identifier at
3778   //   the later declaration is the same as the linkage specified at
3779   //   the prior declaration. If no prior declaration is visible, or
3780   //   if the prior declaration specifies no linkage, then the
3781   //   identifier has external linkage.
3782   if (New->hasExternalStorage() && Old->hasLinkage())
3783     /* Okay */;
3784   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3785            !New->isStaticDataMember() &&
3786            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3787     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3788     Diag(OldLocation, PrevDiag);
3789     return New->setInvalidDecl();
3790   }
3791
3792   // Check if extern is followed by non-extern and vice-versa.
3793   if (New->hasExternalStorage() &&
3794       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3795     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3796     Diag(OldLocation, PrevDiag);
3797     return New->setInvalidDecl();
3798   }
3799   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3800       !New->hasExternalStorage()) {
3801     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3802     Diag(OldLocation, PrevDiag);
3803     return New->setInvalidDecl();
3804   }
3805
3806   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3807
3808   // FIXME: The test for external storage here seems wrong? We still
3809   // need to check for mismatches.
3810   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3811       // Don't complain about out-of-line definitions of static members.
3812       !(Old->getLexicalDeclContext()->isRecord() &&
3813         !New->getLexicalDeclContext()->isRecord())) {
3814     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3815     Diag(OldLocation, PrevDiag);
3816     return New->setInvalidDecl();
3817   }
3818
3819   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3820     if (VarDecl *Def = Old->getDefinition()) {
3821       // C++1z [dcl.fcn.spec]p4:
3822       //   If the definition of a variable appears in a translation unit before
3823       //   its first declaration as inline, the program is ill-formed.
3824       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3825       Diag(Def->getLocation(), diag::note_previous_definition);
3826     }
3827   }
3828
3829   // If this redeclaration makes the function inline, we may need to add it to
3830   // UndefinedButUsed.
3831   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3832       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3833     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3834                                            SourceLocation()));
3835
3836   if (New->getTLSKind() != Old->getTLSKind()) {
3837     if (!Old->getTLSKind()) {
3838       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3839       Diag(OldLocation, PrevDiag);
3840     } else if (!New->getTLSKind()) {
3841       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3842       Diag(OldLocation, PrevDiag);
3843     } else {
3844       // Do not allow redeclaration to change the variable between requiring
3845       // static and dynamic initialization.
3846       // FIXME: GCC allows this, but uses the TLS keyword on the first
3847       // declaration to determine the kind. Do we need to be compatible here?
3848       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3849         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3850       Diag(OldLocation, PrevDiag);
3851     }
3852   }
3853
3854   // C++ doesn't have tentative definitions, so go right ahead and check here.
3855   if (getLangOpts().CPlusPlus &&
3856       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3857     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3858         Old->getCanonicalDecl()->isConstexpr()) {
3859       // This definition won't be a definition any more once it's been merged.
3860       Diag(New->getLocation(),
3861            diag::warn_deprecated_redundant_constexpr_static_def);
3862     } else if (VarDecl *Def = Old->getDefinition()) {
3863       if (checkVarDeclRedefinition(Def, New))
3864         return;
3865     }
3866   }
3867
3868   if (haveIncompatibleLanguageLinkages(Old, New)) {
3869     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3870     Diag(OldLocation, PrevDiag);
3871     New->setInvalidDecl();
3872     return;
3873   }
3874
3875   // Merge "used" flag.
3876   if (Old->getMostRecentDecl()->isUsed(false))
3877     New->setIsUsed();
3878
3879   // Keep a chain of previous declarations.
3880   New->setPreviousDecl(Old);
3881   if (NewTemplate)
3882     NewTemplate->setPreviousDecl(OldTemplate);
3883
3884   // Inherit access appropriately.
3885   New->setAccess(Old->getAccess());
3886   if (NewTemplate)
3887     NewTemplate->setAccess(New->getAccess());
3888
3889   if (Old->isInline())
3890     New->setImplicitlyInline();
3891 }
3892
3893 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3894   SourceManager &SrcMgr = getSourceManager();
3895   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3896   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3897   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3898   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3899   auto &HSI = PP.getHeaderSearchInfo();
3900   StringRef HdrFilename =
3901       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3902
3903   auto noteFromModuleOrInclude = [&](Module *Mod,
3904                                      SourceLocation IncLoc) -> bool {
3905     // Redefinition errors with modules are common with non modular mapped
3906     // headers, example: a non-modular header H in module A that also gets
3907     // included directly in a TU. Pointing twice to the same header/definition
3908     // is confusing, try to get better diagnostics when modules is on.
3909     if (IncLoc.isValid()) {
3910       if (Mod) {
3911         Diag(IncLoc, diag::note_redefinition_modules_same_file)
3912             << HdrFilename.str() << Mod->getFullModuleName();
3913         if (!Mod->DefinitionLoc.isInvalid())
3914           Diag(Mod->DefinitionLoc, diag::note_defined_here)
3915               << Mod->getFullModuleName();
3916       } else {
3917         Diag(IncLoc, diag::note_redefinition_include_same_file)
3918             << HdrFilename.str();
3919       }
3920       return true;
3921     }
3922
3923     return false;
3924   };
3925
3926   // Is it the same file and same offset? Provide more information on why
3927   // this leads to a redefinition error.
3928   bool EmittedDiag = false;
3929   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
3930     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
3931     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
3932     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
3933     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
3934
3935     // If the header has no guards, emit a note suggesting one.
3936     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
3937       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
3938
3939     if (EmittedDiag)
3940       return;
3941   }
3942
3943   // Redefinition coming from different files or couldn't do better above.
3944   Diag(Old->getLocation(), diag::note_previous_definition);
3945 }
3946
3947 /// We've just determined that \p Old and \p New both appear to be definitions
3948 /// of the same variable. Either diagnose or fix the problem.
3949 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3950   if (!hasVisibleDefinition(Old) &&
3951       (New->getFormalLinkage() == InternalLinkage ||
3952        New->isInline() ||
3953        New->getDescribedVarTemplate() ||
3954        New->getNumTemplateParameterLists() ||
3955        New->getDeclContext()->isDependentContext())) {
3956     // The previous definition is hidden, and multiple definitions are
3957     // permitted (in separate TUs). Demote this to a declaration.
3958     New->demoteThisDefinitionToDeclaration();
3959
3960     // Make the canonical definition visible.
3961     if (auto *OldTD = Old->getDescribedVarTemplate())
3962       makeMergedDefinitionVisible(OldTD);
3963     makeMergedDefinitionVisible(Old);
3964     return false;
3965   } else {
3966     Diag(New->getLocation(), diag::err_redefinition) << New;
3967     notePreviousDefinition(Old, New->getLocation());
3968     New->setInvalidDecl();
3969     return true;
3970   }
3971 }
3972
3973 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3974 /// no declarator (e.g. "struct foo;") is parsed.
3975 Decl *
3976 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3977                                  RecordDecl *&AnonRecord) {
3978   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3979                                     AnonRecord);
3980 }
3981
3982 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3983 // disambiguate entities defined in different scopes.
3984 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3985 // compatibility.
3986 // We will pick our mangling number depending on which version of MSVC is being
3987 // targeted.
3988 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3989   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3990              ? S->getMSCurManglingNumber()
3991              : S->getMSLastManglingNumber();
3992 }
3993
3994 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3995   if (!Context.getLangOpts().CPlusPlus)
3996     return;
3997
3998   if (isa<CXXRecordDecl>(Tag->getParent())) {
3999     // If this tag is the direct child of a class, number it if
4000     // it is anonymous.
4001     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4002       return;
4003     MangleNumberingContext &MCtx =
4004         Context.getManglingNumberContext(Tag->getParent());
4005     Context.setManglingNumber(
4006         Tag, MCtx.getManglingNumber(
4007                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4008     return;
4009   }
4010
4011   // If this tag isn't a direct child of a class, number it if it is local.
4012   Decl *ManglingContextDecl;
4013   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4014           Tag->getDeclContext(), ManglingContextDecl)) {
4015     Context.setManglingNumber(
4016         Tag, MCtx->getManglingNumber(
4017                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4018   }
4019 }
4020
4021 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4022                                         TypedefNameDecl *NewTD) {
4023   if (TagFromDeclSpec->isInvalidDecl())
4024     return;
4025
4026   // Do nothing if the tag already has a name for linkage purposes.
4027   if (TagFromDeclSpec->hasNameForLinkage())
4028     return;
4029
4030   // A well-formed anonymous tag must always be a TUK_Definition.
4031   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4032
4033   // The type must match the tag exactly;  no qualifiers allowed.
4034   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4035                            Context.getTagDeclType(TagFromDeclSpec))) {
4036     if (getLangOpts().CPlusPlus)
4037       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4038     return;
4039   }
4040
4041   // If we've already computed linkage for the anonymous tag, then
4042   // adding a typedef name for the anonymous decl can change that
4043   // linkage, which might be a serious problem.  Diagnose this as
4044   // unsupported and ignore the typedef name.  TODO: we should
4045   // pursue this as a language defect and establish a formal rule
4046   // for how to handle it.
4047   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4048     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4049
4050     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4051     tagLoc = getLocForEndOfToken(tagLoc);
4052
4053     llvm::SmallString<40> textToInsert;
4054     textToInsert += ' ';
4055     textToInsert += NewTD->getIdentifier()->getName();
4056     Diag(tagLoc, diag::note_typedef_changes_linkage)
4057         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4058     return;
4059   }
4060
4061   // Otherwise, set this is the anon-decl typedef for the tag.
4062   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4063 }
4064
4065 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4066   switch (T) {
4067   case DeclSpec::TST_class:
4068     return 0;
4069   case DeclSpec::TST_struct:
4070     return 1;
4071   case DeclSpec::TST_interface:
4072     return 2;
4073   case DeclSpec::TST_union:
4074     return 3;
4075   case DeclSpec::TST_enum:
4076     return 4;
4077   default:
4078     llvm_unreachable("unexpected type specifier");
4079   }
4080 }
4081
4082 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4083 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4084 /// parameters to cope with template friend declarations.
4085 Decl *
4086 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4087                                  MultiTemplateParamsArg TemplateParams,
4088                                  bool IsExplicitInstantiation,
4089                                  RecordDecl *&AnonRecord) {
4090   Decl *TagD = nullptr;
4091   TagDecl *Tag = nullptr;
4092   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4093       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4094       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4095       DS.getTypeSpecType() == DeclSpec::TST_union ||
4096       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4097     TagD = DS.getRepAsDecl();
4098
4099     if (!TagD) // We probably had an error
4100       return nullptr;
4101
4102     // Note that the above type specs guarantee that the
4103     // type rep is a Decl, whereas in many of the others
4104     // it's a Type.
4105     if (isa<TagDecl>(TagD))
4106       Tag = cast<TagDecl>(TagD);
4107     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4108       Tag = CTD->getTemplatedDecl();
4109   }
4110
4111   if (Tag) {
4112     handleTagNumbering(Tag, S);
4113     Tag->setFreeStanding();
4114     if (Tag->isInvalidDecl())
4115       return Tag;
4116   }
4117
4118   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4119     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4120     // or incomplete types shall not be restrict-qualified."
4121     if (TypeQuals & DeclSpec::TQ_restrict)
4122       Diag(DS.getRestrictSpecLoc(),
4123            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4124            << DS.getSourceRange();
4125   }
4126
4127   if (DS.isInlineSpecified())
4128     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4129         << getLangOpts().CPlusPlus1z;
4130
4131   if (DS.isConstexprSpecified()) {
4132     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4133     // and definitions of functions and variables.
4134     if (Tag)
4135       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4136           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4137     else
4138       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4139     // Don't emit warnings after this error.
4140     return TagD;
4141   }
4142
4143   if (DS.isConceptSpecified()) {
4144     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4145     // either a function concept and its definition or a variable concept and
4146     // its initializer.
4147     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4148     return TagD;
4149   }
4150
4151   DiagnoseFunctionSpecifiers(DS);
4152
4153   if (DS.isFriendSpecified()) {
4154     // If we're dealing with a decl but not a TagDecl, assume that
4155     // whatever routines created it handled the friendship aspect.
4156     if (TagD && !Tag)
4157       return nullptr;
4158     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4159   }
4160
4161   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4162   bool IsExplicitSpecialization =
4163     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4164   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4165       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4166       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4167     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4168     // nested-name-specifier unless it is an explicit instantiation
4169     // or an explicit specialization.
4170     //
4171     // FIXME: We allow class template partial specializations here too, per the
4172     // obvious intent of DR1819.
4173     //
4174     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4175     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4176         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4177     return nullptr;
4178   }
4179
4180   // Track whether this decl-specifier declares anything.
4181   bool DeclaresAnything = true;
4182
4183   // Handle anonymous struct definitions.
4184   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4185     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4186         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4187       if (getLangOpts().CPlusPlus ||
4188           Record->getDeclContext()->isRecord()) {
4189         // If CurContext is a DeclContext that can contain statements,
4190         // RecursiveASTVisitor won't visit the decls that
4191         // BuildAnonymousStructOrUnion() will put into CurContext.
4192         // Also store them here so that they can be part of the
4193         // DeclStmt that gets created in this case.
4194         // FIXME: Also return the IndirectFieldDecls created by
4195         // BuildAnonymousStructOr union, for the same reason?
4196         if (CurContext->isFunctionOrMethod())
4197           AnonRecord = Record;
4198         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4199                                            Context.getPrintingPolicy());
4200       }
4201
4202       DeclaresAnything = false;
4203     }
4204   }
4205
4206   // C11 6.7.2.1p2:
4207   //   A struct-declaration that does not declare an anonymous structure or
4208   //   anonymous union shall contain a struct-declarator-list.
4209   //
4210   // This rule also existed in C89 and C99; the grammar for struct-declaration
4211   // did not permit a struct-declaration without a struct-declarator-list.
4212   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4213       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4214     // Check for Microsoft C extension: anonymous struct/union member.
4215     // Handle 2 kinds of anonymous struct/union:
4216     //   struct STRUCT;
4217     //   union UNION;
4218     // and
4219     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4220     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4221     if ((Tag && Tag->getDeclName()) ||
4222         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4223       RecordDecl *Record = nullptr;
4224       if (Tag)
4225         Record = dyn_cast<RecordDecl>(Tag);
4226       else if (const RecordType *RT =
4227                    DS.getRepAsType().get()->getAsStructureType())
4228         Record = RT->getDecl();
4229       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4230         Record = UT->getDecl();
4231
4232       if (Record && getLangOpts().MicrosoftExt) {
4233         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4234           << Record->isUnion() << DS.getSourceRange();
4235         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4236       }
4237
4238       DeclaresAnything = false;
4239     }
4240   }
4241
4242   // Skip all the checks below if we have a type error.
4243   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4244       (TagD && TagD->isInvalidDecl()))
4245     return TagD;
4246
4247   if (getLangOpts().CPlusPlus &&
4248       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4249     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4250       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4251           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4252         DeclaresAnything = false;
4253
4254   if (!DS.isMissingDeclaratorOk()) {
4255     // Customize diagnostic for a typedef missing a name.
4256     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4257       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4258         << DS.getSourceRange();
4259     else
4260       DeclaresAnything = false;
4261   }
4262
4263   if (DS.isModulePrivateSpecified() &&
4264       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4265     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4266       << Tag->getTagKind()
4267       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4268
4269   ActOnDocumentableDecl(TagD);
4270
4271   // C 6.7/2:
4272   //   A declaration [...] shall declare at least a declarator [...], a tag,
4273   //   or the members of an enumeration.
4274   // C++ [dcl.dcl]p3:
4275   //   [If there are no declarators], and except for the declaration of an
4276   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4277   //   names into the program, or shall redeclare a name introduced by a
4278   //   previous declaration.
4279   if (!DeclaresAnything) {
4280     // In C, we allow this as a (popular) extension / bug. Don't bother
4281     // producing further diagnostics for redundant qualifiers after this.
4282     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4283     return TagD;
4284   }
4285
4286   // C++ [dcl.stc]p1:
4287   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4288   //   init-declarator-list of the declaration shall not be empty.
4289   // C++ [dcl.fct.spec]p1:
4290   //   If a cv-qualifier appears in a decl-specifier-seq, the
4291   //   init-declarator-list of the declaration shall not be empty.
4292   //
4293   // Spurious qualifiers here appear to be valid in C.
4294   unsigned DiagID = diag::warn_standalone_specifier;
4295   if (getLangOpts().CPlusPlus)
4296     DiagID = diag::ext_standalone_specifier;
4297
4298   // Note that a linkage-specification sets a storage class, but
4299   // 'extern "C" struct foo;' is actually valid and not theoretically
4300   // useless.
4301   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4302     if (SCS == DeclSpec::SCS_mutable)
4303       // Since mutable is not a viable storage class specifier in C, there is
4304       // no reason to treat it as an extension. Instead, diagnose as an error.
4305       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4306     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4307       Diag(DS.getStorageClassSpecLoc(), DiagID)
4308         << DeclSpec::getSpecifierName(SCS);
4309   }
4310
4311   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4312     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4313       << DeclSpec::getSpecifierName(TSCS);
4314   if (DS.getTypeQualifiers()) {
4315     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4316       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4317     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4318       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4319     // Restrict is covered above.
4320     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4321       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4322     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4323       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4324   }
4325
4326   // Warn about ignored type attributes, for example:
4327   // __attribute__((aligned)) struct A;
4328   // Attributes should be placed after tag to apply to type declaration.
4329   if (!DS.getAttributes().empty()) {
4330     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4331     if (TypeSpecType == DeclSpec::TST_class ||
4332         TypeSpecType == DeclSpec::TST_struct ||
4333         TypeSpecType == DeclSpec::TST_interface ||
4334         TypeSpecType == DeclSpec::TST_union ||
4335         TypeSpecType == DeclSpec::TST_enum) {
4336       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4337            attrs = attrs->getNext())
4338         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4339             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4340     }
4341   }
4342
4343   return TagD;
4344 }
4345
4346 /// We are trying to inject an anonymous member into the given scope;
4347 /// check if there's an existing declaration that can't be overloaded.
4348 ///
4349 /// \return true if this is a forbidden redeclaration
4350 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4351                                          Scope *S,
4352                                          DeclContext *Owner,
4353                                          DeclarationName Name,
4354                                          SourceLocation NameLoc,
4355                                          bool IsUnion) {
4356   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4357                  Sema::ForRedeclaration);
4358   if (!SemaRef.LookupName(R, S)) return false;
4359
4360   // Pick a representative declaration.
4361   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4362   assert(PrevDecl && "Expected a non-null Decl");
4363
4364   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4365     return false;
4366
4367   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4368     << IsUnion << Name;
4369   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4370
4371   return true;
4372 }
4373
4374 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4375 /// anonymous struct or union AnonRecord into the owning context Owner
4376 /// and scope S. This routine will be invoked just after we realize
4377 /// that an unnamed union or struct is actually an anonymous union or
4378 /// struct, e.g.,
4379 ///
4380 /// @code
4381 /// union {
4382 ///   int i;
4383 ///   float f;
4384 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4385 ///    // f into the surrounding scope.x
4386 /// @endcode
4387 ///
4388 /// This routine is recursive, injecting the names of nested anonymous
4389 /// structs/unions into the owning context and scope as well.
4390 static bool
4391 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4392                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4393                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4394   bool Invalid = false;
4395
4396   // Look every FieldDecl and IndirectFieldDecl with a name.
4397   for (auto *D : AnonRecord->decls()) {
4398     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4399         cast<NamedDecl>(D)->getDeclName()) {
4400       ValueDecl *VD = cast<ValueDecl>(D);
4401       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4402                                        VD->getLocation(),
4403                                        AnonRecord->isUnion())) {
4404         // C++ [class.union]p2:
4405         //   The names of the members of an anonymous union shall be
4406         //   distinct from the names of any other entity in the
4407         //   scope in which the anonymous union is declared.
4408         Invalid = true;
4409       } else {
4410         // C++ [class.union]p2:
4411         //   For the purpose of name lookup, after the anonymous union
4412         //   definition, the members of the anonymous union are
4413         //   considered to have been defined in the scope in which the
4414         //   anonymous union is declared.
4415         unsigned OldChainingSize = Chaining.size();
4416         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4417           Chaining.append(IF->chain_begin(), IF->chain_end());
4418         else
4419           Chaining.push_back(VD);
4420
4421         assert(Chaining.size() >= 2);
4422         NamedDecl **NamedChain =
4423           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4424         for (unsigned i = 0; i < Chaining.size(); i++)
4425           NamedChain[i] = Chaining[i];
4426
4427         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4428             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4429             VD->getType(), {NamedChain, Chaining.size()});
4430
4431         for (const auto *Attr : VD->attrs())
4432           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4433
4434         IndirectField->setAccess(AS);
4435         IndirectField->setImplicit();
4436         SemaRef.PushOnScopeChains(IndirectField, S);
4437
4438         // That includes picking up the appropriate access specifier.
4439         if (AS != AS_none) IndirectField->setAccess(AS);
4440
4441         Chaining.resize(OldChainingSize);
4442       }
4443     }
4444   }
4445
4446   return Invalid;
4447 }
4448
4449 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4450 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4451 /// illegal input values are mapped to SC_None.
4452 static StorageClass
4453 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4454   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4455   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4456          "Parser allowed 'typedef' as storage class VarDecl.");
4457   switch (StorageClassSpec) {
4458   case DeclSpec::SCS_unspecified:    return SC_None;
4459   case DeclSpec::SCS_extern:
4460     if (DS.isExternInLinkageSpec())
4461       return SC_None;
4462     return SC_Extern;
4463   case DeclSpec::SCS_static:         return SC_Static;
4464   case DeclSpec::SCS_auto:           return SC_Auto;
4465   case DeclSpec::SCS_register:       return SC_Register;
4466   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4467     // Illegal SCSs map to None: error reporting is up to the caller.
4468   case DeclSpec::SCS_mutable:        // Fall through.
4469   case DeclSpec::SCS_typedef:        return SC_None;
4470   }
4471   llvm_unreachable("unknown storage class specifier");
4472 }
4473
4474 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4475   assert(Record->hasInClassInitializer());
4476
4477   for (const auto *I : Record->decls()) {
4478     const auto *FD = dyn_cast<FieldDecl>(I);
4479     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4480       FD = IFD->getAnonField();
4481     if (FD && FD->hasInClassInitializer())
4482       return FD->getLocation();
4483   }
4484
4485   llvm_unreachable("couldn't find in-class initializer");
4486 }
4487
4488 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4489                                       SourceLocation DefaultInitLoc) {
4490   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4491     return;
4492
4493   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4494   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4495 }
4496
4497 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4498                                       CXXRecordDecl *AnonUnion) {
4499   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4500     return;
4501
4502   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4503 }
4504
4505 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4506 /// anonymous structure or union. Anonymous unions are a C++ feature
4507 /// (C++ [class.union]) and a C11 feature; anonymous structures
4508 /// are a C11 feature and GNU C++ extension.
4509 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4510                                         AccessSpecifier AS,
4511                                         RecordDecl *Record,
4512                                         const PrintingPolicy &Policy) {
4513   DeclContext *Owner = Record->getDeclContext();
4514
4515   // Diagnose whether this anonymous struct/union is an extension.
4516   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4517     Diag(Record->getLocation(), diag::ext_anonymous_union);
4518   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4519     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4520   else if (!Record->isUnion() && !getLangOpts().C11)
4521     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4522
4523   // C and C++ require different kinds of checks for anonymous
4524   // structs/unions.
4525   bool Invalid = false;
4526   if (getLangOpts().CPlusPlus) {
4527     const char *PrevSpec = nullptr;
4528     unsigned DiagID;
4529     if (Record->isUnion()) {
4530       // C++ [class.union]p6:
4531       //   Anonymous unions declared in a named namespace or in the
4532       //   global namespace shall be declared static.
4533       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4534           (isa<TranslationUnitDecl>(Owner) ||
4535            (isa<NamespaceDecl>(Owner) &&
4536             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4537         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4538           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4539
4540         // Recover by adding 'static'.
4541         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4542                                PrevSpec, DiagID, Policy);
4543       }
4544       // C++ [class.union]p6:
4545       //   A storage class is not allowed in a declaration of an
4546       //   anonymous union in a class scope.
4547       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4548                isa<RecordDecl>(Owner)) {
4549         Diag(DS.getStorageClassSpecLoc(),
4550              diag::err_anonymous_union_with_storage_spec)
4551           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4552
4553         // Recover by removing the storage specifier.
4554         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4555                                SourceLocation(),
4556                                PrevSpec, DiagID, Context.getPrintingPolicy());
4557       }
4558     }
4559
4560     // Ignore const/volatile/restrict qualifiers.
4561     if (DS.getTypeQualifiers()) {
4562       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4563         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4564           << Record->isUnion() << "const"
4565           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4566       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4567         Diag(DS.getVolatileSpecLoc(),
4568              diag::ext_anonymous_struct_union_qualified)
4569           << Record->isUnion() << "volatile"
4570           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4571       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4572         Diag(DS.getRestrictSpecLoc(),
4573              diag::ext_anonymous_struct_union_qualified)
4574           << Record->isUnion() << "restrict"
4575           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4576       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4577         Diag(DS.getAtomicSpecLoc(),
4578              diag::ext_anonymous_struct_union_qualified)
4579           << Record->isUnion() << "_Atomic"
4580           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4581       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4582         Diag(DS.getUnalignedSpecLoc(),
4583              diag::ext_anonymous_struct_union_qualified)
4584           << Record->isUnion() << "__unaligned"
4585           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4586
4587       DS.ClearTypeQualifiers();
4588     }
4589
4590     // C++ [class.union]p2:
4591     //   The member-specification of an anonymous union shall only
4592     //   define non-static data members. [Note: nested types and
4593     //   functions cannot be declared within an anonymous union. ]
4594     for (auto *Mem : Record->decls()) {
4595       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4596         // C++ [class.union]p3:
4597         //   An anonymous union shall not have private or protected
4598         //   members (clause 11).
4599         assert(FD->getAccess() != AS_none);
4600         if (FD->getAccess() != AS_public) {
4601           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4602             << Record->isUnion() << (FD->getAccess() == AS_protected);
4603           Invalid = true;
4604         }
4605
4606         // C++ [class.union]p1
4607         //   An object of a class with a non-trivial constructor, a non-trivial
4608         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4609         //   assignment operator cannot be a member of a union, nor can an
4610         //   array of such objects.
4611         if (CheckNontrivialField(FD))
4612           Invalid = true;
4613       } else if (Mem->isImplicit()) {
4614         // Any implicit members are fine.
4615       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4616         // This is a type that showed up in an
4617         // elaborated-type-specifier inside the anonymous struct or
4618         // union, but which actually declares a type outside of the
4619         // anonymous struct or union. It's okay.
4620       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4621         if (!MemRecord->isAnonymousStructOrUnion() &&
4622             MemRecord->getDeclName()) {
4623           // Visual C++ allows type definition in anonymous struct or union.
4624           if (getLangOpts().MicrosoftExt)
4625             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4626               << Record->isUnion();
4627           else {
4628             // This is a nested type declaration.
4629             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4630               << Record->isUnion();
4631             Invalid = true;
4632           }
4633         } else {
4634           // This is an anonymous type definition within another anonymous type.
4635           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4636           // not part of standard C++.
4637           Diag(MemRecord->getLocation(),
4638                diag::ext_anonymous_record_with_anonymous_type)
4639             << Record->isUnion();
4640         }
4641       } else if (isa<AccessSpecDecl>(Mem)) {
4642         // Any access specifier is fine.
4643       } else if (isa<StaticAssertDecl>(Mem)) {
4644         // In C++1z, static_assert declarations are also fine.
4645       } else {
4646         // We have something that isn't a non-static data
4647         // member. Complain about it.
4648         unsigned DK = diag::err_anonymous_record_bad_member;
4649         if (isa<TypeDecl>(Mem))
4650           DK = diag::err_anonymous_record_with_type;
4651         else if (isa<FunctionDecl>(Mem))
4652           DK = diag::err_anonymous_record_with_function;
4653         else if (isa<VarDecl>(Mem))
4654           DK = diag::err_anonymous_record_with_static;
4655
4656         // Visual C++ allows type definition in anonymous struct or union.
4657         if (getLangOpts().MicrosoftExt &&
4658             DK == diag::err_anonymous_record_with_type)
4659           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4660             << Record->isUnion();
4661         else {
4662           Diag(Mem->getLocation(), DK) << Record->isUnion();
4663           Invalid = true;
4664         }
4665       }
4666     }
4667
4668     // C++11 [class.union]p8 (DR1460):
4669     //   At most one variant member of a union may have a
4670     //   brace-or-equal-initializer.
4671     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4672         Owner->isRecord())
4673       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4674                                 cast<CXXRecordDecl>(Record));
4675   }
4676
4677   if (!Record->isUnion() && !Owner->isRecord()) {
4678     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4679       << getLangOpts().CPlusPlus;
4680     Invalid = true;
4681   }
4682
4683   // Mock up a declarator.
4684   Declarator Dc(DS, Declarator::MemberContext);
4685   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4686   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4687
4688   // Create a declaration for this anonymous struct/union.
4689   NamedDecl *Anon = nullptr;
4690   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4691     Anon = FieldDecl::Create(Context, OwningClass,
4692                              DS.getLocStart(),
4693                              Record->getLocation(),
4694                              /*IdentifierInfo=*/nullptr,
4695                              Context.getTypeDeclType(Record),
4696                              TInfo,
4697                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4698                              /*InitStyle=*/ICIS_NoInit);
4699     Anon->setAccess(AS);
4700     if (getLangOpts().CPlusPlus)
4701       FieldCollector->Add(cast<FieldDecl>(Anon));
4702   } else {
4703     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4704     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4705     if (SCSpec == DeclSpec::SCS_mutable) {
4706       // mutable can only appear on non-static class members, so it's always
4707       // an error here
4708       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4709       Invalid = true;
4710       SC = SC_None;
4711     }
4712
4713     Anon = VarDecl::Create(Context, Owner,
4714                            DS.getLocStart(),
4715                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4716                            Context.getTypeDeclType(Record),
4717                            TInfo, SC);
4718
4719     // Default-initialize the implicit variable. This initialization will be
4720     // trivial in almost all cases, except if a union member has an in-class
4721     // initializer:
4722     //   union { int n = 0; };
4723     ActOnUninitializedDecl(Anon);
4724   }
4725   Anon->setImplicit();
4726
4727   // Mark this as an anonymous struct/union type.
4728   Record->setAnonymousStructOrUnion(true);
4729
4730   // Add the anonymous struct/union object to the current
4731   // context. We'll be referencing this object when we refer to one of
4732   // its members.
4733   Owner->addDecl(Anon);
4734
4735   // Inject the members of the anonymous struct/union into the owning
4736   // context and into the identifier resolver chain for name lookup
4737   // purposes.
4738   SmallVector<NamedDecl*, 2> Chain;
4739   Chain.push_back(Anon);
4740
4741   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4742     Invalid = true;
4743
4744   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4745     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4746       Decl *ManglingContextDecl;
4747       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4748               NewVD->getDeclContext(), ManglingContextDecl)) {
4749         Context.setManglingNumber(
4750             NewVD, MCtx->getManglingNumber(
4751                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4752         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4753       }
4754     }
4755   }
4756
4757   if (Invalid)
4758     Anon->setInvalidDecl();
4759
4760   return Anon;
4761 }
4762
4763 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4764 /// Microsoft C anonymous structure.
4765 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4766 /// Example:
4767 ///
4768 /// struct A { int a; };
4769 /// struct B { struct A; int b; };
4770 ///
4771 /// void foo() {
4772 ///   B var;
4773 ///   var.a = 3;
4774 /// }
4775 ///
4776 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4777                                            RecordDecl *Record) {
4778   assert(Record && "expected a record!");
4779
4780   // Mock up a declarator.
4781   Declarator Dc(DS, Declarator::TypeNameContext);
4782   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4783   assert(TInfo && "couldn't build declarator info for anonymous struct");
4784
4785   auto *ParentDecl = cast<RecordDecl>(CurContext);
4786   QualType RecTy = Context.getTypeDeclType(Record);
4787
4788   // Create a declaration for this anonymous struct.
4789   NamedDecl *Anon = FieldDecl::Create(Context,
4790                              ParentDecl,
4791                              DS.getLocStart(),
4792                              DS.getLocStart(),
4793                              /*IdentifierInfo=*/nullptr,
4794                              RecTy,
4795                              TInfo,
4796                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4797                              /*InitStyle=*/ICIS_NoInit);
4798   Anon->setImplicit();
4799
4800   // Add the anonymous struct object to the current context.
4801   CurContext->addDecl(Anon);
4802
4803   // Inject the members of the anonymous struct into the current
4804   // context and into the identifier resolver chain for name lookup
4805   // purposes.
4806   SmallVector<NamedDecl*, 2> Chain;
4807   Chain.push_back(Anon);
4808
4809   RecordDecl *RecordDef = Record->getDefinition();
4810   if (RequireCompleteType(Anon->getLocation(), RecTy,
4811                           diag::err_field_incomplete) ||
4812       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4813                                           AS_none, Chain)) {
4814     Anon->setInvalidDecl();
4815     ParentDecl->setInvalidDecl();
4816   }
4817
4818   return Anon;
4819 }
4820
4821 /// GetNameForDeclarator - Determine the full declaration name for the
4822 /// given Declarator.
4823 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4824   return GetNameFromUnqualifiedId(D.getName());
4825 }
4826
4827 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4828 DeclarationNameInfo
4829 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4830   DeclarationNameInfo NameInfo;
4831   NameInfo.setLoc(Name.StartLocation);
4832
4833   switch (Name.getKind()) {
4834
4835   case UnqualifiedId::IK_ImplicitSelfParam:
4836   case UnqualifiedId::IK_Identifier:
4837     NameInfo.setName(Name.Identifier);
4838     NameInfo.setLoc(Name.StartLocation);
4839     return NameInfo;
4840
4841   case UnqualifiedId::IK_DeductionGuideName: {
4842     // C++ [temp.deduct.guide]p3:
4843     //   The simple-template-id shall name a class template specialization.
4844     //   The template-name shall be the same identifier as the template-name
4845     //   of the simple-template-id.
4846     // These together intend to imply that the template-name shall name a
4847     // class template.
4848     // FIXME: template<typename T> struct X {};
4849     //        template<typename T> using Y = X<T>;
4850     //        Y(int) -> Y<int>;
4851     //   satisfies these rules but does not name a class template.
4852     TemplateName TN = Name.TemplateName.get().get();
4853     auto *Template = TN.getAsTemplateDecl();
4854     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4855       Diag(Name.StartLocation,
4856            diag::err_deduction_guide_name_not_class_template)
4857         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4858       if (Template)
4859         Diag(Template->getLocation(), diag::note_template_decl_here);
4860       return DeclarationNameInfo();
4861     }
4862
4863     NameInfo.setName(
4864         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4865     NameInfo.setLoc(Name.StartLocation);
4866     return NameInfo;
4867   }
4868
4869   case UnqualifiedId::IK_OperatorFunctionId:
4870     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4871                                            Name.OperatorFunctionId.Operator));
4872     NameInfo.setLoc(Name.StartLocation);
4873     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4874       = Name.OperatorFunctionId.SymbolLocations[0];
4875     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4876       = Name.EndLocation.getRawEncoding();
4877     return NameInfo;
4878
4879   case UnqualifiedId::IK_LiteralOperatorId:
4880     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4881                                                            Name.Identifier));
4882     NameInfo.setLoc(Name.StartLocation);
4883     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4884     return NameInfo;
4885
4886   case UnqualifiedId::IK_ConversionFunctionId: {
4887     TypeSourceInfo *TInfo;
4888     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4889     if (Ty.isNull())
4890       return DeclarationNameInfo();
4891     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4892                                                Context.getCanonicalType(Ty)));
4893     NameInfo.setLoc(Name.StartLocation);
4894     NameInfo.setNamedTypeInfo(TInfo);
4895     return NameInfo;
4896   }
4897
4898   case UnqualifiedId::IK_ConstructorName: {
4899     TypeSourceInfo *TInfo;
4900     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4901     if (Ty.isNull())
4902       return DeclarationNameInfo();
4903     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4904                                               Context.getCanonicalType(Ty)));
4905     NameInfo.setLoc(Name.StartLocation);
4906     NameInfo.setNamedTypeInfo(TInfo);
4907     return NameInfo;
4908   }
4909
4910   case UnqualifiedId::IK_ConstructorTemplateId: {
4911     // In well-formed code, we can only have a constructor
4912     // template-id that refers to the current context, so go there
4913     // to find the actual type being constructed.
4914     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4915     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4916       return DeclarationNameInfo();
4917
4918     // Determine the type of the class being constructed.
4919     QualType CurClassType = Context.getTypeDeclType(CurClass);
4920
4921     // FIXME: Check two things: that the template-id names the same type as
4922     // CurClassType, and that the template-id does not occur when the name
4923     // was qualified.
4924
4925     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4926                                     Context.getCanonicalType(CurClassType)));
4927     NameInfo.setLoc(Name.StartLocation);
4928     // FIXME: should we retrieve TypeSourceInfo?
4929     NameInfo.setNamedTypeInfo(nullptr);
4930     return NameInfo;
4931   }
4932
4933   case UnqualifiedId::IK_DestructorName: {
4934     TypeSourceInfo *TInfo;
4935     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4936     if (Ty.isNull())
4937       return DeclarationNameInfo();
4938     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4939                                               Context.getCanonicalType(Ty)));
4940     NameInfo.setLoc(Name.StartLocation);
4941     NameInfo.setNamedTypeInfo(TInfo);
4942     return NameInfo;
4943   }
4944
4945   case UnqualifiedId::IK_TemplateId: {
4946     TemplateName TName = Name.TemplateId->Template.get();
4947     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4948     return Context.getNameForTemplate(TName, TNameLoc);
4949   }
4950
4951   } // switch (Name.getKind())
4952
4953   llvm_unreachable("Unknown name kind");
4954 }
4955
4956 static QualType getCoreType(QualType Ty) {
4957   do {
4958     if (Ty->isPointerType() || Ty->isReferenceType())
4959       Ty = Ty->getPointeeType();
4960     else if (Ty->isArrayType())
4961       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4962     else
4963       return Ty.withoutLocalFastQualifiers();
4964   } while (true);
4965 }
4966
4967 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4968 /// and Definition have "nearly" matching parameters. This heuristic is
4969 /// used to improve diagnostics in the case where an out-of-line function
4970 /// definition doesn't match any declaration within the class or namespace.
4971 /// Also sets Params to the list of indices to the parameters that differ
4972 /// between the declaration and the definition. If hasSimilarParameters
4973 /// returns true and Params is empty, then all of the parameters match.
4974 static bool hasSimilarParameters(ASTContext &Context,
4975                                      FunctionDecl *Declaration,
4976                                      FunctionDecl *Definition,
4977                                      SmallVectorImpl<unsigned> &Params) {
4978   Params.clear();
4979   if (Declaration->param_size() != Definition->param_size())
4980     return false;
4981   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4982     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4983     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4984
4985     // The parameter types are identical
4986     if (Context.hasSameType(DefParamTy, DeclParamTy))
4987       continue;
4988
4989     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4990     QualType DefParamBaseTy = getCoreType(DefParamTy);
4991     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4992     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4993
4994     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4995         (DeclTyName && DeclTyName == DefTyName))
4996       Params.push_back(Idx);
4997     else  // The two parameters aren't even close
4998       return false;
4999   }
5000
5001   return true;
5002 }
5003
5004 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5005 /// declarator needs to be rebuilt in the current instantiation.
5006 /// Any bits of declarator which appear before the name are valid for
5007 /// consideration here.  That's specifically the type in the decl spec
5008 /// and the base type in any member-pointer chunks.
5009 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5010                                                     DeclarationName Name) {
5011   // The types we specifically need to rebuild are:
5012   //   - typenames, typeofs, and decltypes
5013   //   - types which will become injected class names
5014   // Of course, we also need to rebuild any type referencing such a
5015   // type.  It's safest to just say "dependent", but we call out a
5016   // few cases here.
5017
5018   DeclSpec &DS = D.getMutableDeclSpec();
5019   switch (DS.getTypeSpecType()) {
5020   case DeclSpec::TST_typename:
5021   case DeclSpec::TST_typeofType:
5022   case DeclSpec::TST_underlyingType:
5023   case DeclSpec::TST_atomic: {
5024     // Grab the type from the parser.
5025     TypeSourceInfo *TSI = nullptr;
5026     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5027     if (T.isNull() || !T->isDependentType()) break;
5028
5029     // Make sure there's a type source info.  This isn't really much
5030     // of a waste; most dependent types should have type source info
5031     // attached already.
5032     if (!TSI)
5033       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5034
5035     // Rebuild the type in the current instantiation.
5036     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5037     if (!TSI) return true;
5038
5039     // Store the new type back in the decl spec.
5040     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5041     DS.UpdateTypeRep(LocType);
5042     break;
5043   }
5044
5045   case DeclSpec::TST_decltype:
5046   case DeclSpec::TST_typeofExpr: {
5047     Expr *E = DS.getRepAsExpr();
5048     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5049     if (Result.isInvalid()) return true;
5050     DS.UpdateExprRep(Result.get());
5051     break;
5052   }
5053
5054   default:
5055     // Nothing to do for these decl specs.
5056     break;
5057   }
5058
5059   // It doesn't matter what order we do this in.
5060   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5061     DeclaratorChunk &Chunk = D.getTypeObject(I);
5062
5063     // The only type information in the declarator which can come
5064     // before the declaration name is the base type of a member
5065     // pointer.
5066     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5067       continue;
5068
5069     // Rebuild the scope specifier in-place.
5070     CXXScopeSpec &SS = Chunk.Mem.Scope();
5071     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5072       return true;
5073   }
5074
5075   return false;
5076 }
5077
5078 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5079   D.setFunctionDefinitionKind(FDK_Declaration);
5080   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5081
5082   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5083       Dcl && Dcl->getDeclContext()->isFileContext())
5084     Dcl->setTopLevelDeclInObjCContainer();
5085
5086   if (getLangOpts().OpenCL)
5087     setCurrentOpenCLExtensionForDecl(Dcl);
5088
5089   return Dcl;
5090 }
5091
5092 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5093 ///   If T is the name of a class, then each of the following shall have a
5094 ///   name different from T:
5095 ///     - every static data member of class T;
5096 ///     - every member function of class T
5097 ///     - every member of class T that is itself a type;
5098 /// \returns true if the declaration name violates these rules.
5099 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5100                                    DeclarationNameInfo NameInfo) {
5101   DeclarationName Name = NameInfo.getName();
5102
5103   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5104   while (Record && Record->isAnonymousStructOrUnion())
5105     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5106   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5107     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5108     return true;
5109   }
5110
5111   return false;
5112 }
5113
5114 /// \brief Diagnose a declaration whose declarator-id has the given
5115 /// nested-name-specifier.
5116 ///
5117 /// \param SS The nested-name-specifier of the declarator-id.
5118 ///
5119 /// \param DC The declaration context to which the nested-name-specifier
5120 /// resolves.
5121 ///
5122 /// \param Name The name of the entity being declared.
5123 ///
5124 /// \param Loc The location of the name of the entity being declared.
5125 ///
5126 /// \returns true if we cannot safely recover from this error, false otherwise.
5127 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5128                                         DeclarationName Name,
5129                                         SourceLocation Loc) {
5130   DeclContext *Cur = CurContext;
5131   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5132     Cur = Cur->getParent();
5133
5134   // If the user provided a superfluous scope specifier that refers back to the
5135   // class in which the entity is already declared, diagnose and ignore it.
5136   //
5137   // class X {
5138   //   void X::f();
5139   // };
5140   //
5141   // Note, it was once ill-formed to give redundant qualification in all
5142   // contexts, but that rule was removed by DR482.
5143   if (Cur->Equals(DC)) {
5144     if (Cur->isRecord()) {
5145       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5146                                       : diag::err_member_extra_qualification)
5147         << Name << FixItHint::CreateRemoval(SS.getRange());
5148       SS.clear();
5149     } else {
5150       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5151     }
5152     return false;
5153   }
5154
5155   // Check whether the qualifying scope encloses the scope of the original
5156   // declaration.
5157   if (!Cur->Encloses(DC)) {
5158     if (Cur->isRecord())
5159       Diag(Loc, diag::err_member_qualification)
5160         << Name << SS.getRange();
5161     else if (isa<TranslationUnitDecl>(DC))
5162       Diag(Loc, diag::err_invalid_declarator_global_scope)
5163         << Name << SS.getRange();
5164     else if (isa<FunctionDecl>(Cur))
5165       Diag(Loc, diag::err_invalid_declarator_in_function)
5166         << Name << SS.getRange();
5167     else if (isa<BlockDecl>(Cur))
5168       Diag(Loc, diag::err_invalid_declarator_in_block)
5169         << Name << SS.getRange();
5170     else
5171       Diag(Loc, diag::err_invalid_declarator_scope)
5172       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5173
5174     return true;
5175   }
5176
5177   if (Cur->isRecord()) {
5178     // Cannot qualify members within a class.
5179     Diag(Loc, diag::err_member_qualification)
5180       << Name << SS.getRange();
5181     SS.clear();
5182
5183     // C++ constructors and destructors with incorrect scopes can break
5184     // our AST invariants by having the wrong underlying types. If
5185     // that's the case, then drop this declaration entirely.
5186     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5187          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5188         !Context.hasSameType(Name.getCXXNameType(),
5189                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5190       return true;
5191
5192     return false;
5193   }
5194
5195   // C++11 [dcl.meaning]p1:
5196   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5197   //   not begin with a decltype-specifer"
5198   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5199   while (SpecLoc.getPrefix())
5200     SpecLoc = SpecLoc.getPrefix();
5201   if (dyn_cast_or_null<DecltypeType>(
5202         SpecLoc.getNestedNameSpecifier()->getAsType()))
5203     Diag(Loc, diag::err_decltype_in_declarator)
5204       << SpecLoc.getTypeLoc().getSourceRange();
5205
5206   return false;
5207 }
5208
5209 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5210                                   MultiTemplateParamsArg TemplateParamLists) {
5211   // TODO: consider using NameInfo for diagnostic.
5212   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5213   DeclarationName Name = NameInfo.getName();
5214
5215   // All of these full declarators require an identifier.  If it doesn't have
5216   // one, the ParsedFreeStandingDeclSpec action should be used.
5217   if (D.isDecompositionDeclarator()) {
5218     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5219   } else if (!Name) {
5220     if (!D.isInvalidType())  // Reject this if we think it is valid.
5221       Diag(D.getDeclSpec().getLocStart(),
5222            diag::err_declarator_need_ident)
5223         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5224     return nullptr;
5225   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5226     return nullptr;
5227
5228   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5229   // we find one that is.
5230   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5231          (S->getFlags() & Scope::TemplateParamScope) != 0)
5232     S = S->getParent();
5233
5234   DeclContext *DC = CurContext;
5235   if (D.getCXXScopeSpec().isInvalid())
5236     D.setInvalidType();
5237   else if (D.getCXXScopeSpec().isSet()) {
5238     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5239                                         UPPC_DeclarationQualifier))
5240       return nullptr;
5241
5242     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5243     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5244     if (!DC || isa<EnumDecl>(DC)) {
5245       // If we could not compute the declaration context, it's because the
5246       // declaration context is dependent but does not refer to a class,
5247       // class template, or class template partial specialization. Complain
5248       // and return early, to avoid the coming semantic disaster.
5249       Diag(D.getIdentifierLoc(),
5250            diag::err_template_qualified_declarator_no_match)
5251         << D.getCXXScopeSpec().getScopeRep()
5252         << D.getCXXScopeSpec().getRange();
5253       return nullptr;
5254     }
5255     bool IsDependentContext = DC->isDependentContext();
5256
5257     if (!IsDependentContext &&
5258         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5259       return nullptr;
5260
5261     // If a class is incomplete, do not parse entities inside it.
5262     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5263       Diag(D.getIdentifierLoc(),
5264            diag::err_member_def_undefined_record)
5265         << Name << DC << D.getCXXScopeSpec().getRange();
5266       return nullptr;
5267     }
5268     if (!D.getDeclSpec().isFriendSpecified()) {
5269       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5270                                       Name, D.getIdentifierLoc())) {
5271         if (DC->isRecord())
5272           return nullptr;
5273
5274         D.setInvalidType();
5275       }
5276     }
5277
5278     // Check whether we need to rebuild the type of the given
5279     // declaration in the current instantiation.
5280     if (EnteringContext && IsDependentContext &&
5281         TemplateParamLists.size() != 0) {
5282       ContextRAII SavedContext(*this, DC);
5283       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5284         D.setInvalidType();
5285     }
5286   }
5287
5288   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5289   QualType R = TInfo->getType();
5290
5291   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5292     // If this is a typedef, we'll end up spewing multiple diagnostics.
5293     // Just return early; it's safer. If this is a function, let the
5294     // "constructor cannot have a return type" diagnostic handle it.
5295     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5296       return nullptr;
5297
5298   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5299                                       UPPC_DeclarationType))
5300     D.setInvalidType();
5301
5302   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5303                         ForRedeclaration);
5304
5305   // See if this is a redefinition of a variable in the same scope.
5306   if (!D.getCXXScopeSpec().isSet()) {
5307     bool IsLinkageLookup = false;
5308     bool CreateBuiltins = false;
5309
5310     // If the declaration we're planning to build will be a function
5311     // or object with linkage, then look for another declaration with
5312     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5313     //
5314     // If the declaration we're planning to build will be declared with
5315     // external linkage in the translation unit, create any builtin with
5316     // the same name.
5317     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5318       /* Do nothing*/;
5319     else if (CurContext->isFunctionOrMethod() &&
5320              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5321               R->isFunctionType())) {
5322       IsLinkageLookup = true;
5323       CreateBuiltins =
5324           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5325     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5326                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5327       CreateBuiltins = true;
5328
5329     if (IsLinkageLookup)
5330       Previous.clear(LookupRedeclarationWithLinkage);
5331
5332     LookupName(Previous, S, CreateBuiltins);
5333   } else { // Something like "int foo::x;"
5334     LookupQualifiedName(Previous, DC);
5335
5336     // C++ [dcl.meaning]p1:
5337     //   When the declarator-id is qualified, the declaration shall refer to a
5338     //  previously declared member of the class or namespace to which the
5339     //  qualifier refers (or, in the case of a namespace, of an element of the
5340     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5341     //  thereof; [...]
5342     //
5343     // Note that we already checked the context above, and that we do not have
5344     // enough information to make sure that Previous contains the declaration
5345     // we want to match. For example, given:
5346     //
5347     //   class X {
5348     //     void f();
5349     //     void f(float);
5350     //   };
5351     //
5352     //   void X::f(int) { } // ill-formed
5353     //
5354     // In this case, Previous will point to the overload set
5355     // containing the two f's declared in X, but neither of them
5356     // matches.
5357
5358     // C++ [dcl.meaning]p1:
5359     //   [...] the member shall not merely have been introduced by a
5360     //   using-declaration in the scope of the class or namespace nominated by
5361     //   the nested-name-specifier of the declarator-id.
5362     RemoveUsingDecls(Previous);
5363   }
5364
5365   if (Previous.isSingleResult() &&
5366       Previous.getFoundDecl()->isTemplateParameter()) {
5367     // Maybe we will complain about the shadowed template parameter.
5368     if (!D.isInvalidType())
5369       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5370                                       Previous.getFoundDecl());
5371
5372     // Just pretend that we didn't see the previous declaration.
5373     Previous.clear();
5374   }
5375
5376   // In C++, the previous declaration we find might be a tag type
5377   // (class or enum). In this case, the new declaration will hide the
5378   // tag type. Note that this does does not apply if we're declaring a
5379   // typedef (C++ [dcl.typedef]p4).
5380   if (Previous.isSingleTagDecl() &&
5381       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5382     Previous.clear();
5383
5384   // Check that there are no default arguments other than in the parameters
5385   // of a function declaration (C++ only).
5386   if (getLangOpts().CPlusPlus)
5387     CheckExtraCXXDefaultArguments(D);
5388
5389   if (D.getDeclSpec().isConceptSpecified()) {
5390     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5391     // applied only to the definition of a function template or variable
5392     // template, declared in namespace scope
5393     if (!TemplateParamLists.size()) {
5394       Diag(D.getDeclSpec().getConceptSpecLoc(),
5395            diag:: err_concept_wrong_decl_kind);
5396       return nullptr;
5397     }
5398
5399     if (!DC->getRedeclContext()->isFileContext()) {
5400       Diag(D.getIdentifierLoc(),
5401            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5402       return nullptr;
5403     }
5404   }
5405
5406   NamedDecl *New;
5407
5408   bool AddToScope = true;
5409   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5410     if (TemplateParamLists.size()) {
5411       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5412       return nullptr;
5413     }
5414
5415     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5416   } else if (R->isFunctionType()) {
5417     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5418                                   TemplateParamLists,
5419                                   AddToScope);
5420   } else {
5421     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5422                                   AddToScope);
5423   }
5424
5425   if (!New)
5426     return nullptr;
5427
5428   // If this has an identifier and is not a function template specialization,
5429   // add it to the scope stack.
5430   if (New->getDeclName() && AddToScope) {
5431     // Only make a locally-scoped extern declaration visible if it is the first
5432     // declaration of this entity. Qualified lookup for such an entity should
5433     // only find this declaration if there is no visible declaration of it.
5434     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5435     PushOnScopeChains(New, S, AddToContext);
5436     if (!AddToContext)
5437       CurContext->addHiddenDecl(New);
5438   }
5439
5440   if (isInOpenMPDeclareTargetContext())
5441     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5442
5443   return New;
5444 }
5445
5446 /// Helper method to turn variable array types into constant array
5447 /// types in certain situations which would otherwise be errors (for
5448 /// GCC compatibility).
5449 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5450                                                     ASTContext &Context,
5451                                                     bool &SizeIsNegative,
5452                                                     llvm::APSInt &Oversized) {
5453   // This method tries to turn a variable array into a constant
5454   // array even when the size isn't an ICE.  This is necessary
5455   // for compatibility with code that depends on gcc's buggy
5456   // constant expression folding, like struct {char x[(int)(char*)2];}
5457   SizeIsNegative = false;
5458   Oversized = 0;
5459
5460   if (T->isDependentType())
5461     return QualType();
5462
5463   QualifierCollector Qs;
5464   const Type *Ty = Qs.strip(T);
5465
5466   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5467     QualType Pointee = PTy->getPointeeType();
5468     QualType FixedType =
5469         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5470                                             Oversized);
5471     if (FixedType.isNull()) return FixedType;
5472     FixedType = Context.getPointerType(FixedType);
5473     return Qs.apply(Context, FixedType);
5474   }
5475   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5476     QualType Inner = PTy->getInnerType();
5477     QualType FixedType =
5478         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5479                                             Oversized);
5480     if (FixedType.isNull()) return FixedType;
5481     FixedType = Context.getParenType(FixedType);
5482     return Qs.apply(Context, FixedType);
5483   }
5484
5485   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5486   if (!VLATy)
5487     return QualType();
5488   // FIXME: We should probably handle this case
5489   if (VLATy->getElementType()->isVariablyModifiedType())
5490     return QualType();
5491
5492   llvm::APSInt Res;
5493   if (!VLATy->getSizeExpr() ||
5494       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5495     return QualType();
5496
5497   // Check whether the array size is negative.
5498   if (Res.isSigned() && Res.isNegative()) {
5499     SizeIsNegative = true;
5500     return QualType();
5501   }
5502
5503   // Check whether the array is too large to be addressed.
5504   unsigned ActiveSizeBits
5505     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5506                                               Res);
5507   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5508     Oversized = Res;
5509     return QualType();
5510   }
5511
5512   return Context.getConstantArrayType(VLATy->getElementType(),
5513                                       Res, ArrayType::Normal, 0);
5514 }
5515
5516 static void
5517 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5518   SrcTL = SrcTL.getUnqualifiedLoc();
5519   DstTL = DstTL.getUnqualifiedLoc();
5520   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5521     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5522     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5523                                       DstPTL.getPointeeLoc());
5524     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5525     return;
5526   }
5527   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5528     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5529     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5530                                       DstPTL.getInnerLoc());
5531     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5532     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5533     return;
5534   }
5535   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5536   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5537   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5538   TypeLoc DstElemTL = DstATL.getElementLoc();
5539   DstElemTL.initializeFullCopy(SrcElemTL);
5540   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5541   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5542   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5543 }
5544
5545 /// Helper method to turn variable array types into constant array
5546 /// types in certain situations which would otherwise be errors (for
5547 /// GCC compatibility).
5548 static TypeSourceInfo*
5549 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5550                                               ASTContext &Context,
5551                                               bool &SizeIsNegative,
5552                                               llvm::APSInt &Oversized) {
5553   QualType FixedTy
5554     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5555                                           SizeIsNegative, Oversized);
5556   if (FixedTy.isNull())
5557     return nullptr;
5558   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5559   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5560                                     FixedTInfo->getTypeLoc());
5561   return FixedTInfo;
5562 }
5563
5564 /// \brief Register the given locally-scoped extern "C" declaration so
5565 /// that it can be found later for redeclarations. We include any extern "C"
5566 /// declaration that is not visible in the translation unit here, not just
5567 /// function-scope declarations.
5568 void
5569 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5570   if (!getLangOpts().CPlusPlus &&
5571       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5572     // Don't need to track declarations in the TU in C.
5573     return;
5574
5575   // Note that we have a locally-scoped external with this name.
5576   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5577 }
5578
5579 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5580   // FIXME: We can have multiple results via __attribute__((overloadable)).
5581   auto Result = Context.getExternCContextDecl()->lookup(Name);
5582   return Result.empty() ? nullptr : *Result.begin();
5583 }
5584
5585 /// \brief Diagnose function specifiers on a declaration of an identifier that
5586 /// does not identify a function.
5587 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5588   // FIXME: We should probably indicate the identifier in question to avoid
5589   // confusion for constructs like "virtual int a(), b;"
5590   if (DS.isVirtualSpecified())
5591     Diag(DS.getVirtualSpecLoc(),
5592          diag::err_virtual_non_function);
5593
5594   if (DS.isExplicitSpecified())
5595     Diag(DS.getExplicitSpecLoc(),
5596          diag::err_explicit_non_function);
5597
5598   if (DS.isNoreturnSpecified())
5599     Diag(DS.getNoreturnSpecLoc(),
5600          diag::err_noreturn_non_function);
5601 }
5602
5603 NamedDecl*
5604 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5605                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5606   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5607   if (D.getCXXScopeSpec().isSet()) {
5608     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5609       << D.getCXXScopeSpec().getRange();
5610     D.setInvalidType();
5611     // Pretend we didn't see the scope specifier.
5612     DC = CurContext;
5613     Previous.clear();
5614   }
5615
5616   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5617
5618   if (D.getDeclSpec().isInlineSpecified())
5619     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5620         << getLangOpts().CPlusPlus1z;
5621   if (D.getDeclSpec().isConstexprSpecified())
5622     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5623       << 1;
5624   if (D.getDeclSpec().isConceptSpecified())
5625     Diag(D.getDeclSpec().getConceptSpecLoc(),
5626          diag::err_concept_wrong_decl_kind);
5627
5628   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5629     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5630       Diag(D.getName().StartLocation,
5631            diag::err_deduction_guide_invalid_specifier)
5632           << "typedef";
5633     else
5634       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5635           << D.getName().getSourceRange();
5636     return nullptr;
5637   }
5638
5639   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5640   if (!NewTD) return nullptr;
5641
5642   // Handle attributes prior to checking for duplicates in MergeVarDecl
5643   ProcessDeclAttributes(S, NewTD, D);
5644
5645   CheckTypedefForVariablyModifiedType(S, NewTD);
5646
5647   bool Redeclaration = D.isRedeclaration();
5648   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5649   D.setRedeclaration(Redeclaration);
5650   return ND;
5651 }
5652
5653 void
5654 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5655   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5656   // then it shall have block scope.
5657   // Note that variably modified types must be fixed before merging the decl so
5658   // that redeclarations will match.
5659   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5660   QualType T = TInfo->getType();
5661   if (T->isVariablyModifiedType()) {
5662     getCurFunction()->setHasBranchProtectedScope();
5663
5664     if (S->getFnParent() == nullptr) {
5665       bool SizeIsNegative;
5666       llvm::APSInt Oversized;
5667       TypeSourceInfo *FixedTInfo =
5668         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5669                                                       SizeIsNegative,
5670                                                       Oversized);
5671       if (FixedTInfo) {
5672         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5673         NewTD->setTypeSourceInfo(FixedTInfo);
5674       } else {
5675         if (SizeIsNegative)
5676           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5677         else if (T->isVariableArrayType())
5678           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5679         else if (Oversized.getBoolValue())
5680           Diag(NewTD->getLocation(), diag::err_array_too_large)
5681             << Oversized.toString(10);
5682         else
5683           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5684         NewTD->setInvalidDecl();
5685       }
5686     }
5687   }
5688 }
5689
5690 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5691 /// declares a typedef-name, either using the 'typedef' type specifier or via
5692 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5693 NamedDecl*
5694 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5695                            LookupResult &Previous, bool &Redeclaration) {
5696
5697   // Find the shadowed declaration before filtering for scope.
5698   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5699
5700   // Merge the decl with the existing one if appropriate. If the decl is
5701   // in an outer scope, it isn't the same thing.
5702   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5703                        /*AllowInlineNamespace*/false);
5704   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5705   if (!Previous.empty()) {
5706     Redeclaration = true;
5707     MergeTypedefNameDecl(S, NewTD, Previous);
5708   }
5709
5710   if (ShadowedDecl && !Redeclaration)
5711     CheckShadow(NewTD, ShadowedDecl, Previous);
5712
5713   // If this is the C FILE type, notify the AST context.
5714   if (IdentifierInfo *II = NewTD->getIdentifier())
5715     if (!NewTD->isInvalidDecl() &&
5716         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5717       if (II->isStr("FILE"))
5718         Context.setFILEDecl(NewTD);
5719       else if (II->isStr("jmp_buf"))
5720         Context.setjmp_bufDecl(NewTD);
5721       else if (II->isStr("sigjmp_buf"))
5722         Context.setsigjmp_bufDecl(NewTD);
5723       else if (II->isStr("ucontext_t"))
5724         Context.setucontext_tDecl(NewTD);
5725     }
5726
5727   return NewTD;
5728 }
5729
5730 /// \brief Determines whether the given declaration is an out-of-scope
5731 /// previous declaration.
5732 ///
5733 /// This routine should be invoked when name lookup has found a
5734 /// previous declaration (PrevDecl) that is not in the scope where a
5735 /// new declaration by the same name is being introduced. If the new
5736 /// declaration occurs in a local scope, previous declarations with
5737 /// linkage may still be considered previous declarations (C99
5738 /// 6.2.2p4-5, C++ [basic.link]p6).
5739 ///
5740 /// \param PrevDecl the previous declaration found by name
5741 /// lookup
5742 ///
5743 /// \param DC the context in which the new declaration is being
5744 /// declared.
5745 ///
5746 /// \returns true if PrevDecl is an out-of-scope previous declaration
5747 /// for a new delcaration with the same name.
5748 static bool
5749 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5750                                 ASTContext &Context) {
5751   if (!PrevDecl)
5752     return false;
5753
5754   if (!PrevDecl->hasLinkage())
5755     return false;
5756
5757   if (Context.getLangOpts().CPlusPlus) {
5758     // C++ [basic.link]p6:
5759     //   If there is a visible declaration of an entity with linkage
5760     //   having the same name and type, ignoring entities declared
5761     //   outside the innermost enclosing namespace scope, the block
5762     //   scope declaration declares that same entity and receives the
5763     //   linkage of the previous declaration.
5764     DeclContext *OuterContext = DC->getRedeclContext();
5765     if (!OuterContext->isFunctionOrMethod())
5766       // This rule only applies to block-scope declarations.
5767       return false;
5768
5769     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5770     if (PrevOuterContext->isRecord())
5771       // We found a member function: ignore it.
5772       return false;
5773
5774     // Find the innermost enclosing namespace for the new and
5775     // previous declarations.
5776     OuterContext = OuterContext->getEnclosingNamespaceContext();
5777     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5778
5779     // The previous declaration is in a different namespace, so it
5780     // isn't the same function.
5781     if (!OuterContext->Equals(PrevOuterContext))
5782       return false;
5783   }
5784
5785   return true;
5786 }
5787
5788 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5789   CXXScopeSpec &SS = D.getCXXScopeSpec();
5790   if (!SS.isSet()) return;
5791   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5792 }
5793
5794 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5795   QualType type = decl->getType();
5796   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5797   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5798     // Various kinds of declaration aren't allowed to be __autoreleasing.
5799     unsigned kind = -1U;
5800     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5801       if (var->hasAttr<BlocksAttr>())
5802         kind = 0; // __block
5803       else if (!var->hasLocalStorage())
5804         kind = 1; // global
5805     } else if (isa<ObjCIvarDecl>(decl)) {
5806       kind = 3; // ivar
5807     } else if (isa<FieldDecl>(decl)) {
5808       kind = 2; // field
5809     }
5810
5811     if (kind != -1U) {
5812       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5813         << kind;
5814     }
5815   } else if (lifetime == Qualifiers::OCL_None) {
5816     // Try to infer lifetime.
5817     if (!type->isObjCLifetimeType())
5818       return false;
5819
5820     lifetime = type->getObjCARCImplicitLifetime();
5821     type = Context.getLifetimeQualifiedType(type, lifetime);
5822     decl->setType(type);
5823   }
5824
5825   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5826     // Thread-local variables cannot have lifetime.
5827     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5828         var->getTLSKind()) {
5829       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5830         << var->getType();
5831       return true;
5832     }
5833   }
5834
5835   return false;
5836 }
5837
5838 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5839   // Ensure that an auto decl is deduced otherwise the checks below might cache
5840   // the wrong linkage.
5841   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5842
5843   // 'weak' only applies to declarations with external linkage.
5844   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5845     if (!ND.isExternallyVisible()) {
5846       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5847       ND.dropAttr<WeakAttr>();
5848     }
5849   }
5850   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5851     if (ND.isExternallyVisible()) {
5852       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5853       ND.dropAttr<WeakRefAttr>();
5854       ND.dropAttr<AliasAttr>();
5855     }
5856   }
5857
5858   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5859     if (VD->hasInit()) {
5860       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5861         assert(VD->isThisDeclarationADefinition() &&
5862                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5863         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5864         VD->dropAttr<AliasAttr>();
5865       }
5866     }
5867   }
5868
5869   // 'selectany' only applies to externally visible variable declarations.
5870   // It does not apply to functions.
5871   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5872     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5873       S.Diag(Attr->getLocation(),
5874              diag::err_attribute_selectany_non_extern_data);
5875       ND.dropAttr<SelectAnyAttr>();
5876     }
5877   }
5878
5879   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5880     // dll attributes require external linkage. Static locals may have external
5881     // linkage but still cannot be explicitly imported or exported.
5882     auto *VD = dyn_cast<VarDecl>(&ND);
5883     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5884       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5885         << &ND << Attr;
5886       ND.setInvalidDecl();
5887     }
5888   }
5889
5890   // Virtual functions cannot be marked as 'notail'.
5891   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5892     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5893       if (MD->isVirtual()) {
5894         S.Diag(ND.getLocation(),
5895                diag::err_invalid_attribute_on_virtual_function)
5896             << Attr;
5897         ND.dropAttr<NotTailCalledAttr>();
5898       }
5899 }
5900
5901 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5902                                            NamedDecl *NewDecl,
5903                                            bool IsSpecialization,
5904                                            bool IsDefinition) {
5905   if (OldDecl->isInvalidDecl())
5906     return;
5907
5908   bool IsTemplate = false;
5909   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5910     OldDecl = OldTD->getTemplatedDecl();
5911     IsTemplate = true;
5912     if (!IsSpecialization)
5913       IsDefinition = false;
5914   }
5915   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5916     NewDecl = NewTD->getTemplatedDecl();
5917     IsTemplate = true;
5918   }
5919
5920   if (!OldDecl || !NewDecl)
5921     return;
5922
5923   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5924   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5925   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5926   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5927
5928   // dllimport and dllexport are inheritable attributes so we have to exclude
5929   // inherited attribute instances.
5930   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5931                     (NewExportAttr && !NewExportAttr->isInherited());
5932
5933   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5934   // the only exception being explicit specializations.
5935   // Implicitly generated declarations are also excluded for now because there
5936   // is no other way to switch these to use dllimport or dllexport.
5937   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5938
5939   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5940     // Allow with a warning for free functions and global variables.
5941     bool JustWarn = false;
5942     if (!OldDecl->isCXXClassMember()) {
5943       auto *VD = dyn_cast<VarDecl>(OldDecl);
5944       if (VD && !VD->getDescribedVarTemplate())
5945         JustWarn = true;
5946       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5947       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5948         JustWarn = true;
5949     }
5950
5951     // We cannot change a declaration that's been used because IR has already
5952     // been emitted. Dllimported functions will still work though (modulo
5953     // address equality) as they can use the thunk.
5954     if (OldDecl->isUsed())
5955       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5956         JustWarn = false;
5957
5958     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5959                                : diag::err_attribute_dll_redeclaration;
5960     S.Diag(NewDecl->getLocation(), DiagID)
5961         << NewDecl
5962         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5963     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5964     if (!JustWarn) {
5965       NewDecl->setInvalidDecl();
5966       return;
5967     }
5968   }
5969
5970   // A redeclaration is not allowed to drop a dllimport attribute, the only
5971   // exceptions being inline function definitions (except for function
5972   // templates), local extern declarations, qualified friend declarations or
5973   // special MSVC extension: in the last case, the declaration is treated as if
5974   // it were marked dllexport.
5975   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5976   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5977   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5978     // Ignore static data because out-of-line definitions are diagnosed
5979     // separately.
5980     IsStaticDataMember = VD->isStaticDataMember();
5981     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5982                    VarDecl::DeclarationOnly;
5983   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5984     IsInline = FD->isInlined();
5985     IsQualifiedFriend = FD->getQualifier() &&
5986                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5987   }
5988
5989   if (OldImportAttr && !HasNewAttr &&
5990       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5991       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5992     if (IsMicrosoft && IsDefinition) {
5993       S.Diag(NewDecl->getLocation(),
5994              diag::warn_redeclaration_without_import_attribute)
5995           << NewDecl;
5996       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5997       NewDecl->dropAttr<DLLImportAttr>();
5998       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5999           NewImportAttr->getRange(), S.Context,
6000           NewImportAttr->getSpellingListIndex()));
6001     } else {
6002       S.Diag(NewDecl->getLocation(),
6003              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6004           << NewDecl << OldImportAttr;
6005       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6006       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6007       OldDecl->dropAttr<DLLImportAttr>();
6008       NewDecl->dropAttr<DLLImportAttr>();
6009     }
6010   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6011     // In MinGW, seeing a function declared inline drops the dllimport attribute.
6012     OldDecl->dropAttr<DLLImportAttr>();
6013     NewDecl->dropAttr<DLLImportAttr>();
6014     S.Diag(NewDecl->getLocation(),
6015            diag::warn_dllimport_dropped_from_inline_function)
6016         << NewDecl << OldImportAttr;
6017   }
6018 }
6019
6020 /// Given that we are within the definition of the given function,
6021 /// will that definition behave like C99's 'inline', where the
6022 /// definition is discarded except for optimization purposes?
6023 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6024   // Try to avoid calling GetGVALinkageForFunction.
6025
6026   // All cases of this require the 'inline' keyword.
6027   if (!FD->isInlined()) return false;
6028
6029   // This is only possible in C++ with the gnu_inline attribute.
6030   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6031     return false;
6032
6033   // Okay, go ahead and call the relatively-more-expensive function.
6034   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6035 }
6036
6037 /// Determine whether a variable is extern "C" prior to attaching
6038 /// an initializer. We can't just call isExternC() here, because that
6039 /// will also compute and cache whether the declaration is externally
6040 /// visible, which might change when we attach the initializer.
6041 ///
6042 /// This can only be used if the declaration is known to not be a
6043 /// redeclaration of an internal linkage declaration.
6044 ///
6045 /// For instance:
6046 ///
6047 ///   auto x = []{};
6048 ///
6049 /// Attaching the initializer here makes this declaration not externally
6050 /// visible, because its type has internal linkage.
6051 ///
6052 /// FIXME: This is a hack.
6053 template<typename T>
6054 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6055   if (S.getLangOpts().CPlusPlus) {
6056     // In C++, the overloadable attribute negates the effects of extern "C".
6057     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6058       return false;
6059
6060     // So do CUDA's host/device attributes.
6061     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6062                                  D->template hasAttr<CUDAHostAttr>()))
6063       return false;
6064   }
6065   return D->isExternC();
6066 }
6067
6068 static bool shouldConsiderLinkage(const VarDecl *VD) {
6069   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6070   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6071     return VD->hasExternalStorage();
6072   if (DC->isFileContext())
6073     return true;
6074   if (DC->isRecord())
6075     return false;
6076   llvm_unreachable("Unexpected context");
6077 }
6078
6079 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6080   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6081   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6082       isa<OMPDeclareReductionDecl>(DC))
6083     return true;
6084   if (DC->isRecord())
6085     return false;
6086   llvm_unreachable("Unexpected context");
6087 }
6088
6089 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6090                           AttributeList::Kind Kind) {
6091   for (const AttributeList *L = AttrList; L; L = L->getNext())
6092     if (L->getKind() == Kind)
6093       return true;
6094   return false;
6095 }
6096
6097 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6098                           AttributeList::Kind Kind) {
6099   // Check decl attributes on the DeclSpec.
6100   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6101     return true;
6102
6103   // Walk the declarator structure, checking decl attributes that were in a type
6104   // position to the decl itself.
6105   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6106     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6107       return true;
6108   }
6109
6110   // Finally, check attributes on the decl itself.
6111   return hasParsedAttr(S, PD.getAttributes(), Kind);
6112 }
6113
6114 /// Adjust the \c DeclContext for a function or variable that might be a
6115 /// function-local external declaration.
6116 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6117   if (!DC->isFunctionOrMethod())
6118     return false;
6119
6120   // If this is a local extern function or variable declared within a function
6121   // template, don't add it into the enclosing namespace scope until it is
6122   // instantiated; it might have a dependent type right now.
6123   if (DC->isDependentContext())
6124     return true;
6125
6126   // C++11 [basic.link]p7:
6127   //   When a block scope declaration of an entity with linkage is not found to
6128   //   refer to some other declaration, then that entity is a member of the
6129   //   innermost enclosing namespace.
6130   //
6131   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6132   // semantically-enclosing namespace, not a lexically-enclosing one.
6133   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6134     DC = DC->getParent();
6135   return true;
6136 }
6137
6138 /// \brief Returns true if given declaration has external C language linkage.
6139 static bool isDeclExternC(const Decl *D) {
6140   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6141     return FD->isExternC();
6142   if (const auto *VD = dyn_cast<VarDecl>(D))
6143     return VD->isExternC();
6144
6145   llvm_unreachable("Unknown type of decl!");
6146 }
6147
6148 NamedDecl *Sema::ActOnVariableDeclarator(
6149     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6150     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6151     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6152   QualType R = TInfo->getType();
6153   DeclarationName Name = GetNameForDeclarator(D).getName();
6154
6155   IdentifierInfo *II = Name.getAsIdentifierInfo();
6156
6157   if (D.isDecompositionDeclarator()) {
6158     AddToScope = false;
6159     // Take the name of the first declarator as our name for diagnostic
6160     // purposes.
6161     auto &Decomp = D.getDecompositionDeclarator();
6162     if (!Decomp.bindings().empty()) {
6163       II = Decomp.bindings()[0].Name;
6164       Name = II;
6165     }
6166   } else if (!II) {
6167     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6168     return nullptr;
6169   }
6170
6171   if (getLangOpts().OpenCL) {
6172     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6173     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6174     // argument.
6175     if (R->isImageType() || R->isPipeType()) {
6176       Diag(D.getIdentifierLoc(),
6177            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6178           << R;
6179       D.setInvalidType();
6180       return nullptr;
6181     }
6182
6183     // OpenCL v1.2 s6.9.r:
6184     // The event type cannot be used to declare a program scope variable.
6185     // OpenCL v2.0 s6.9.q:
6186     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6187     if (NULL == S->getParent()) {
6188       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6189         Diag(D.getIdentifierLoc(),
6190              diag::err_invalid_type_for_program_scope_var) << R;
6191         D.setInvalidType();
6192         return nullptr;
6193       }
6194     }
6195
6196     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6197     QualType NR = R;
6198     while (NR->isPointerType()) {
6199       if (NR->isFunctionPointerType()) {
6200         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6201         D.setInvalidType();
6202         break;
6203       }
6204       NR = NR->getPointeeType();
6205     }
6206
6207     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6208       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6209       // half array type (unless the cl_khr_fp16 extension is enabled).
6210       if (Context.getBaseElementType(R)->isHalfType()) {
6211         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6212         D.setInvalidType();
6213       }
6214     }
6215
6216     if (R->isSamplerT()) {
6217       // OpenCL v1.2 s6.9.b p4:
6218       // The sampler type cannot be used with the __local and __global address
6219       // space qualifiers.
6220       if (R.getAddressSpace() == LangAS::opencl_local ||
6221           R.getAddressSpace() == LangAS::opencl_global) {
6222         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6223       }
6224
6225       // OpenCL v1.2 s6.12.14.1:
6226       // A global sampler must be declared with either the constant address
6227       // space qualifier or with the const qualifier.
6228       if (DC->isTranslationUnit() &&
6229           !(R.getAddressSpace() == LangAS::opencl_constant ||
6230           R.isConstQualified())) {
6231         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6232         D.setInvalidType();
6233       }
6234     }
6235
6236     // OpenCL v1.2 s6.9.r:
6237     // The event type cannot be used with the __local, __constant and __global
6238     // address space qualifiers.
6239     if (R->isEventT()) {
6240       if (R.getAddressSpace()) {
6241         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6242         D.setInvalidType();
6243       }
6244     }
6245   }
6246
6247   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6248   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6249
6250   // dllimport globals without explicit storage class are treated as extern. We
6251   // have to change the storage class this early to get the right DeclContext.
6252   if (SC == SC_None && !DC->isRecord() &&
6253       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6254       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6255     SC = SC_Extern;
6256
6257   DeclContext *OriginalDC = DC;
6258   bool IsLocalExternDecl = SC == SC_Extern &&
6259                            adjustContextForLocalExternDecl(DC);
6260
6261   if (SCSpec == DeclSpec::SCS_mutable) {
6262     // mutable can only appear on non-static class members, so it's always
6263     // an error here
6264     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6265     D.setInvalidType();
6266     SC = SC_None;
6267   }
6268
6269   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6270       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6271                               D.getDeclSpec().getStorageClassSpecLoc())) {
6272     // In C++11, the 'register' storage class specifier is deprecated.
6273     // Suppress the warning in system macros, it's used in macros in some
6274     // popular C system headers, such as in glibc's htonl() macro.
6275     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6276          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6277                                    : diag::warn_deprecated_register)
6278       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6279   }
6280
6281   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6282
6283   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6284     // C99 6.9p2: The storage-class specifiers auto and register shall not
6285     // appear in the declaration specifiers in an external declaration.
6286     // Global Register+Asm is a GNU extension we support.
6287     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6288       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6289       D.setInvalidType();
6290     }
6291   }
6292
6293   bool IsMemberSpecialization = false;
6294   bool IsVariableTemplateSpecialization = false;
6295   bool IsPartialSpecialization = false;
6296   bool IsVariableTemplate = false;
6297   VarDecl *NewVD = nullptr;
6298   VarTemplateDecl *NewTemplate = nullptr;
6299   TemplateParameterList *TemplateParams = nullptr;
6300   if (!getLangOpts().CPlusPlus) {
6301     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6302                             D.getIdentifierLoc(), II,
6303                             R, TInfo, SC);
6304
6305     if (R->getContainedDeducedType())
6306       ParsingInitForAutoVars.insert(NewVD);
6307
6308     if (D.isInvalidType())
6309       NewVD->setInvalidDecl();
6310   } else {
6311     bool Invalid = false;
6312
6313     if (DC->isRecord() && !CurContext->isRecord()) {
6314       // This is an out-of-line definition of a static data member.
6315       switch (SC) {
6316       case SC_None:
6317         break;
6318       case SC_Static:
6319         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6320              diag::err_static_out_of_line)
6321           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6322         break;
6323       case SC_Auto:
6324       case SC_Register:
6325       case SC_Extern:
6326         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6327         // to names of variables declared in a block or to function parameters.
6328         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6329         // of class members
6330
6331         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6332              diag::err_storage_class_for_static_member)
6333           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6334         break;
6335       case SC_PrivateExtern:
6336         llvm_unreachable("C storage class in c++!");
6337       }
6338     }
6339
6340     if (SC == SC_Static && CurContext->isRecord()) {
6341       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6342         if (RD->isLocalClass())
6343           Diag(D.getIdentifierLoc(),
6344                diag::err_static_data_member_not_allowed_in_local_class)
6345             << Name << RD->getDeclName();
6346
6347         // C++98 [class.union]p1: If a union contains a static data member,
6348         // the program is ill-formed. C++11 drops this restriction.
6349         if (RD->isUnion())
6350           Diag(D.getIdentifierLoc(),
6351                getLangOpts().CPlusPlus11
6352                  ? diag::warn_cxx98_compat_static_data_member_in_union
6353                  : diag::ext_static_data_member_in_union) << Name;
6354         // We conservatively disallow static data members in anonymous structs.
6355         else if (!RD->getDeclName())
6356           Diag(D.getIdentifierLoc(),
6357                diag::err_static_data_member_not_allowed_in_anon_struct)
6358             << Name << RD->isUnion();
6359       }
6360     }
6361
6362     // Match up the template parameter lists with the scope specifier, then
6363     // determine whether we have a template or a template specialization.
6364     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6365         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6366         D.getCXXScopeSpec(),
6367         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6368             ? D.getName().TemplateId
6369             : nullptr,
6370         TemplateParamLists,
6371         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6372
6373     if (TemplateParams) {
6374       if (!TemplateParams->size() &&
6375           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6376         // There is an extraneous 'template<>' for this variable. Complain
6377         // about it, but allow the declaration of the variable.
6378         Diag(TemplateParams->getTemplateLoc(),
6379              diag::err_template_variable_noparams)
6380           << II
6381           << SourceRange(TemplateParams->getTemplateLoc(),
6382                          TemplateParams->getRAngleLoc());
6383         TemplateParams = nullptr;
6384       } else {
6385         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6386           // This is an explicit specialization or a partial specialization.
6387           // FIXME: Check that we can declare a specialization here.
6388           IsVariableTemplateSpecialization = true;
6389           IsPartialSpecialization = TemplateParams->size() > 0;
6390         } else { // if (TemplateParams->size() > 0)
6391           // This is a template declaration.
6392           IsVariableTemplate = true;
6393
6394           // Check that we can declare a template here.
6395           if (CheckTemplateDeclScope(S, TemplateParams))
6396             return nullptr;
6397
6398           // Only C++1y supports variable templates (N3651).
6399           Diag(D.getIdentifierLoc(),
6400                getLangOpts().CPlusPlus14
6401                    ? diag::warn_cxx11_compat_variable_template
6402                    : diag::ext_variable_template);
6403         }
6404       }
6405     } else {
6406       assert(
6407           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6408           "should have a 'template<>' for this decl");
6409     }
6410
6411     if (IsVariableTemplateSpecialization) {
6412       SourceLocation TemplateKWLoc =
6413           TemplateParamLists.size() > 0
6414               ? TemplateParamLists[0]->getTemplateLoc()
6415               : SourceLocation();
6416       DeclResult Res = ActOnVarTemplateSpecialization(
6417           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6418           IsPartialSpecialization);
6419       if (Res.isInvalid())
6420         return nullptr;
6421       NewVD = cast<VarDecl>(Res.get());
6422       AddToScope = false;
6423     } else if (D.isDecompositionDeclarator()) {
6424       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6425                                         D.getIdentifierLoc(), R, TInfo, SC,
6426                                         Bindings);
6427     } else
6428       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6429                               D.getIdentifierLoc(), II, R, TInfo, SC);
6430
6431     // If this is supposed to be a variable template, create it as such.
6432     if (IsVariableTemplate) {
6433       NewTemplate =
6434           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6435                                   TemplateParams, NewVD);
6436       NewVD->setDescribedVarTemplate(NewTemplate);
6437     }
6438
6439     // If this decl has an auto type in need of deduction, make a note of the
6440     // Decl so we can diagnose uses of it in its own initializer.
6441     if (R->getContainedDeducedType())
6442       ParsingInitForAutoVars.insert(NewVD);
6443
6444     if (D.isInvalidType() || Invalid) {
6445       NewVD->setInvalidDecl();
6446       if (NewTemplate)
6447         NewTemplate->setInvalidDecl();
6448     }
6449
6450     SetNestedNameSpecifier(NewVD, D);
6451
6452     // If we have any template parameter lists that don't directly belong to
6453     // the variable (matching the scope specifier), store them.
6454     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6455     if (TemplateParamLists.size() > VDTemplateParamLists)
6456       NewVD->setTemplateParameterListsInfo(
6457           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6458
6459     if (D.getDeclSpec().isConstexprSpecified()) {
6460       NewVD->setConstexpr(true);
6461       // C++1z [dcl.spec.constexpr]p1:
6462       //   A static data member declared with the constexpr specifier is
6463       //   implicitly an inline variable.
6464       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6465         NewVD->setImplicitlyInline();
6466     }
6467
6468     if (D.getDeclSpec().isConceptSpecified()) {
6469       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6470         VTD->setConcept();
6471
6472       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6473       // be declared with the thread_local, inline, friend, or constexpr
6474       // specifiers, [...]
6475       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6476         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6477              diag::err_concept_decl_invalid_specifiers)
6478             << 0 << 0;
6479         NewVD->setInvalidDecl(true);
6480       }
6481
6482       if (D.getDeclSpec().isConstexprSpecified()) {
6483         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6484              diag::err_concept_decl_invalid_specifiers)
6485             << 0 << 3;
6486         NewVD->setInvalidDecl(true);
6487       }
6488
6489       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6490       // applied only to the definition of a function template or variable
6491       // template, declared in namespace scope.
6492       if (IsVariableTemplateSpecialization) {
6493         Diag(D.getDeclSpec().getConceptSpecLoc(),
6494              diag::err_concept_specified_specialization)
6495             << (IsPartialSpecialization ? 2 : 1);
6496       }
6497
6498       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6499       // following restrictions:
6500       // - The declared type shall have the type bool.
6501       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6502           !NewVD->isInvalidDecl()) {
6503         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6504         NewVD->setInvalidDecl(true);
6505       }
6506     }
6507   }
6508
6509   if (D.getDeclSpec().isInlineSpecified()) {
6510     if (!getLangOpts().CPlusPlus) {
6511       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6512           << 0;
6513     } else if (CurContext->isFunctionOrMethod()) {
6514       // 'inline' is not allowed on block scope variable declaration.
6515       Diag(D.getDeclSpec().getInlineSpecLoc(),
6516            diag::err_inline_declaration_block_scope) << Name
6517         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6518     } else {
6519       Diag(D.getDeclSpec().getInlineSpecLoc(),
6520            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6521                                      : diag::ext_inline_variable);
6522       NewVD->setInlineSpecified();
6523     }
6524   }
6525
6526   // Set the lexical context. If the declarator has a C++ scope specifier, the
6527   // lexical context will be different from the semantic context.
6528   NewVD->setLexicalDeclContext(CurContext);
6529   if (NewTemplate)
6530     NewTemplate->setLexicalDeclContext(CurContext);
6531
6532   if (IsLocalExternDecl) {
6533     if (D.isDecompositionDeclarator())
6534       for (auto *B : Bindings)
6535         B->setLocalExternDecl();
6536     else
6537       NewVD->setLocalExternDecl();
6538   }
6539
6540   bool EmitTLSUnsupportedError = false;
6541   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6542     // C++11 [dcl.stc]p4:
6543     //   When thread_local is applied to a variable of block scope the
6544     //   storage-class-specifier static is implied if it does not appear
6545     //   explicitly.
6546     // Core issue: 'static' is not implied if the variable is declared
6547     //   'extern'.
6548     if (NewVD->hasLocalStorage() &&
6549         (SCSpec != DeclSpec::SCS_unspecified ||
6550          TSCS != DeclSpec::TSCS_thread_local ||
6551          !DC->isFunctionOrMethod()))
6552       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6553            diag::err_thread_non_global)
6554         << DeclSpec::getSpecifierName(TSCS);
6555     else if (!Context.getTargetInfo().isTLSSupported()) {
6556       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6557         // Postpone error emission until we've collected attributes required to
6558         // figure out whether it's a host or device variable and whether the
6559         // error should be ignored.
6560         EmitTLSUnsupportedError = true;
6561         // We still need to mark the variable as TLS so it shows up in AST with
6562         // proper storage class for other tools to use even if we're not going
6563         // to emit any code for it.
6564         NewVD->setTSCSpec(TSCS);
6565       } else
6566         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6567              diag::err_thread_unsupported);
6568     } else
6569       NewVD->setTSCSpec(TSCS);
6570   }
6571
6572   // C99 6.7.4p3
6573   //   An inline definition of a function with external linkage shall
6574   //   not contain a definition of a modifiable object with static or
6575   //   thread storage duration...
6576   // We only apply this when the function is required to be defined
6577   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6578   // that a local variable with thread storage duration still has to
6579   // be marked 'static'.  Also note that it's possible to get these
6580   // semantics in C++ using __attribute__((gnu_inline)).
6581   if (SC == SC_Static && S->getFnParent() != nullptr &&
6582       !NewVD->getType().isConstQualified()) {
6583     FunctionDecl *CurFD = getCurFunctionDecl();
6584     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6585       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6586            diag::warn_static_local_in_extern_inline);
6587       MaybeSuggestAddingStaticToDecl(CurFD);
6588     }
6589   }
6590
6591   if (D.getDeclSpec().isModulePrivateSpecified()) {
6592     if (IsVariableTemplateSpecialization)
6593       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6594           << (IsPartialSpecialization ? 1 : 0)
6595           << FixItHint::CreateRemoval(
6596                  D.getDeclSpec().getModulePrivateSpecLoc());
6597     else if (IsMemberSpecialization)
6598       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6599         << 2
6600         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6601     else if (NewVD->hasLocalStorage())
6602       Diag(NewVD->getLocation(), diag::err_module_private_local)
6603         << 0 << NewVD->getDeclName()
6604         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6605         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6606     else {
6607       NewVD->setModulePrivate();
6608       if (NewTemplate)
6609         NewTemplate->setModulePrivate();
6610       for (auto *B : Bindings)
6611         B->setModulePrivate();
6612     }
6613   }
6614
6615   // Handle attributes prior to checking for duplicates in MergeVarDecl
6616   ProcessDeclAttributes(S, NewVD, D);
6617
6618   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6619     if (EmitTLSUnsupportedError &&
6620         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6621          (getLangOpts().OpenMPIsDevice &&
6622           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6623       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6624            diag::err_thread_unsupported);
6625     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6626     // storage [duration]."
6627     if (SC == SC_None && S->getFnParent() != nullptr &&
6628         (NewVD->hasAttr<CUDASharedAttr>() ||
6629          NewVD->hasAttr<CUDAConstantAttr>())) {
6630       NewVD->setStorageClass(SC_Static);
6631     }
6632   }
6633
6634   // Ensure that dllimport globals without explicit storage class are treated as
6635   // extern. The storage class is set above using parsed attributes. Now we can
6636   // check the VarDecl itself.
6637   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6638          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6639          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6640
6641   // In auto-retain/release, infer strong retension for variables of
6642   // retainable type.
6643   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6644     NewVD->setInvalidDecl();
6645
6646   // Handle GNU asm-label extension (encoded as an attribute).
6647   if (Expr *E = (Expr*)D.getAsmLabel()) {
6648     // The parser guarantees this is a string.
6649     StringLiteral *SE = cast<StringLiteral>(E);
6650     StringRef Label = SE->getString();
6651     if (S->getFnParent() != nullptr) {
6652       switch (SC) {
6653       case SC_None:
6654       case SC_Auto:
6655         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6656         break;
6657       case SC_Register:
6658         // Local Named register
6659         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6660             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6661           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6662         break;
6663       case SC_Static:
6664       case SC_Extern:
6665       case SC_PrivateExtern:
6666         break;
6667       }
6668     } else if (SC == SC_Register) {
6669       // Global Named register
6670       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6671         const auto &TI = Context.getTargetInfo();
6672         bool HasSizeMismatch;
6673
6674         if (!TI.isValidGCCRegisterName(Label))
6675           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6676         else if (!TI.validateGlobalRegisterVariable(Label,
6677                                                     Context.getTypeSize(R),
6678                                                     HasSizeMismatch))
6679           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6680         else if (HasSizeMismatch)
6681           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6682       }
6683
6684       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6685         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6686         NewVD->setInvalidDecl(true);
6687       }
6688     }
6689
6690     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6691                                                 Context, Label, 0));
6692   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6693     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6694       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6695     if (I != ExtnameUndeclaredIdentifiers.end()) {
6696       if (isDeclExternC(NewVD)) {
6697         NewVD->addAttr(I->second);
6698         ExtnameUndeclaredIdentifiers.erase(I);
6699       } else
6700         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6701             << /*Variable*/1 << NewVD;
6702     }
6703   }
6704
6705   // Find the shadowed declaration before filtering for scope.
6706   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6707                                 ? getShadowedDeclaration(NewVD, Previous)
6708                                 : nullptr;
6709
6710   // Don't consider existing declarations that are in a different
6711   // scope and are out-of-semantic-context declarations (if the new
6712   // declaration has linkage).
6713   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6714                        D.getCXXScopeSpec().isNotEmpty() ||
6715                        IsMemberSpecialization ||
6716                        IsVariableTemplateSpecialization);
6717
6718   // Check whether the previous declaration is in the same block scope. This
6719   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6720   if (getLangOpts().CPlusPlus &&
6721       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6722     NewVD->setPreviousDeclInSameBlockScope(
6723         Previous.isSingleResult() && !Previous.isShadowed() &&
6724         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6725
6726   if (!getLangOpts().CPlusPlus) {
6727     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6728   } else {
6729     // If this is an explicit specialization of a static data member, check it.
6730     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6731         CheckMemberSpecialization(NewVD, Previous))
6732       NewVD->setInvalidDecl();
6733
6734     // Merge the decl with the existing one if appropriate.
6735     if (!Previous.empty()) {
6736       if (Previous.isSingleResult() &&
6737           isa<FieldDecl>(Previous.getFoundDecl()) &&
6738           D.getCXXScopeSpec().isSet()) {
6739         // The user tried to define a non-static data member
6740         // out-of-line (C++ [dcl.meaning]p1).
6741         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6742           << D.getCXXScopeSpec().getRange();
6743         Previous.clear();
6744         NewVD->setInvalidDecl();
6745       }
6746     } else if (D.getCXXScopeSpec().isSet()) {
6747       // No previous declaration in the qualifying scope.
6748       Diag(D.getIdentifierLoc(), diag::err_no_member)
6749         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6750         << D.getCXXScopeSpec().getRange();
6751       NewVD->setInvalidDecl();
6752     }
6753
6754     if (!IsVariableTemplateSpecialization)
6755       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6756
6757     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6758     // an explicit specialization (14.8.3) or a partial specialization of a
6759     // concept definition.
6760     if (IsVariableTemplateSpecialization &&
6761         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6762         Previous.isSingleResult()) {
6763       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6764       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6765         if (VarTmpl->isConcept()) {
6766           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6767               << 1                            /*variable*/
6768               << (IsPartialSpecialization ? 2 /*partially specialized*/
6769                                           : 1 /*explicitly specialized*/);
6770           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6771           NewVD->setInvalidDecl();
6772         }
6773       }
6774     }
6775
6776     if (NewTemplate) {
6777       VarTemplateDecl *PrevVarTemplate =
6778           NewVD->getPreviousDecl()
6779               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6780               : nullptr;
6781
6782       // Check the template parameter list of this declaration, possibly
6783       // merging in the template parameter list from the previous variable
6784       // template declaration.
6785       if (CheckTemplateParameterList(
6786               TemplateParams,
6787               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6788                               : nullptr,
6789               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6790                DC->isDependentContext())
6791                   ? TPC_ClassTemplateMember
6792                   : TPC_VarTemplate))
6793         NewVD->setInvalidDecl();
6794
6795       // If we are providing an explicit specialization of a static variable
6796       // template, make a note of that.
6797       if (PrevVarTemplate &&
6798           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6799         PrevVarTemplate->setMemberSpecialization();
6800     }
6801   }
6802
6803   // Diagnose shadowed variables iff this isn't a redeclaration.
6804   if (ShadowedDecl && !D.isRedeclaration())
6805     CheckShadow(NewVD, ShadowedDecl, Previous);
6806
6807   ProcessPragmaWeak(S, NewVD);
6808
6809   // If this is the first declaration of an extern C variable, update
6810   // the map of such variables.
6811   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6812       isIncompleteDeclExternC(*this, NewVD))
6813     RegisterLocallyScopedExternCDecl(NewVD, S);
6814
6815   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6816     Decl *ManglingContextDecl;
6817     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6818             NewVD->getDeclContext(), ManglingContextDecl)) {
6819       Context.setManglingNumber(
6820           NewVD, MCtx->getManglingNumber(
6821                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6822       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6823     }
6824   }
6825
6826   // Special handling of variable named 'main'.
6827   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6828       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6829       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6830
6831     // C++ [basic.start.main]p3
6832     // A program that declares a variable main at global scope is ill-formed.
6833     if (getLangOpts().CPlusPlus)
6834       Diag(D.getLocStart(), diag::err_main_global_variable);
6835
6836     // In C, and external-linkage variable named main results in undefined
6837     // behavior.
6838     else if (NewVD->hasExternalFormalLinkage())
6839       Diag(D.getLocStart(), diag::warn_main_redefined);
6840   }
6841
6842   if (D.isRedeclaration() && !Previous.empty()) {
6843     checkDLLAttributeRedeclaration(
6844         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6845         IsMemberSpecialization, D.isFunctionDefinition());
6846   }
6847
6848   if (NewTemplate) {
6849     if (NewVD->isInvalidDecl())
6850       NewTemplate->setInvalidDecl();
6851     ActOnDocumentableDecl(NewTemplate);
6852     return NewTemplate;
6853   }
6854
6855   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6856     CompleteMemberSpecialization(NewVD, Previous);
6857
6858   return NewVD;
6859 }
6860
6861 /// Enum describing the %select options in diag::warn_decl_shadow.
6862 enum ShadowedDeclKind {
6863   SDK_Local,
6864   SDK_Global,
6865   SDK_StaticMember,
6866   SDK_Field,
6867   SDK_Typedef,
6868   SDK_Using
6869 };
6870
6871 /// Determine what kind of declaration we're shadowing.
6872 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6873                                                 const DeclContext *OldDC) {
6874   if (isa<TypeAliasDecl>(ShadowedDecl))
6875     return SDK_Using;
6876   else if (isa<TypedefDecl>(ShadowedDecl))
6877     return SDK_Typedef;
6878   else if (isa<RecordDecl>(OldDC))
6879     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6880
6881   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6882 }
6883
6884 /// Return the location of the capture if the given lambda captures the given
6885 /// variable \p VD, or an invalid source location otherwise.
6886 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6887                                          const VarDecl *VD) {
6888   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6889     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6890       return Capture.getLocation();
6891   }
6892   return SourceLocation();
6893 }
6894
6895 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6896                                      const LookupResult &R) {
6897   // Only diagnose if we're shadowing an unambiguous field or variable.
6898   if (R.getResultKind() != LookupResult::Found)
6899     return false;
6900
6901   // Return false if warning is ignored.
6902   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6903 }
6904
6905 /// \brief Return the declaration shadowed by the given variable \p D, or null
6906 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6907 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6908                                         const LookupResult &R) {
6909   if (!shouldWarnIfShadowedDecl(Diags, R))
6910     return nullptr;
6911
6912   // Don't diagnose declarations at file scope.
6913   if (D->hasGlobalStorage())
6914     return nullptr;
6915
6916   NamedDecl *ShadowedDecl = R.getFoundDecl();
6917   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6918              ? ShadowedDecl
6919              : nullptr;
6920 }
6921
6922 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6923 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6924 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6925                                         const LookupResult &R) {
6926   // Don't warn if typedef declaration is part of a class
6927   if (D->getDeclContext()->isRecord())
6928     return nullptr;
6929   
6930   if (!shouldWarnIfShadowedDecl(Diags, R))
6931     return nullptr;
6932
6933   NamedDecl *ShadowedDecl = R.getFoundDecl();
6934   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6935 }
6936
6937 /// \brief Diagnose variable or built-in function shadowing.  Implements
6938 /// -Wshadow.
6939 ///
6940 /// This method is called whenever a VarDecl is added to a "useful"
6941 /// scope.
6942 ///
6943 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6944 /// \param R the lookup of the name
6945 ///
6946 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6947                        const LookupResult &R) {
6948   DeclContext *NewDC = D->getDeclContext();
6949
6950   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6951     // Fields are not shadowed by variables in C++ static methods.
6952     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6953       if (MD->isStatic())
6954         return;
6955
6956     // Fields shadowed by constructor parameters are a special case. Usually
6957     // the constructor initializes the field with the parameter.
6958     if (isa<CXXConstructorDecl>(NewDC))
6959       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6960         // Remember that this was shadowed so we can either warn about its
6961         // modification or its existence depending on warning settings.
6962         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6963         return;
6964       }
6965   }
6966
6967   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6968     if (shadowedVar->isExternC()) {
6969       // For shadowing external vars, make sure that we point to the global
6970       // declaration, not a locally scoped extern declaration.
6971       for (auto I : shadowedVar->redecls())
6972         if (I->isFileVarDecl()) {
6973           ShadowedDecl = I;
6974           break;
6975         }
6976     }
6977
6978   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
6979
6980   unsigned WarningDiag = diag::warn_decl_shadow;
6981   SourceLocation CaptureLoc;
6982   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6983       isa<CXXMethodDecl>(NewDC)) {
6984     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6985       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6986         if (RD->getLambdaCaptureDefault() == LCD_None) {
6987           // Try to avoid warnings for lambdas with an explicit capture list.
6988           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6989           // Warn only when the lambda captures the shadowed decl explicitly.
6990           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6991           if (CaptureLoc.isInvalid())
6992             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6993         } else {
6994           // Remember that this was shadowed so we can avoid the warning if the
6995           // shadowed decl isn't captured and the warning settings allow it.
6996           cast<LambdaScopeInfo>(getCurFunction())
6997               ->ShadowingDecls.push_back(
6998                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6999           return;
7000         }
7001       }
7002
7003       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7004         // A variable can't shadow a local variable in an enclosing scope, if
7005         // they are separated by a non-capturing declaration context.
7006         for (DeclContext *ParentDC = NewDC;
7007              ParentDC && !ParentDC->Equals(OldDC);
7008              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7009           // Only block literals, captured statements, and lambda expressions
7010           // can capture; other scopes don't.
7011           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7012               !isLambdaCallOperator(ParentDC)) {
7013             return;
7014           }
7015         }
7016       }
7017     }
7018   }
7019
7020   // Only warn about certain kinds of shadowing for class members.
7021   if (NewDC && NewDC->isRecord()) {
7022     // In particular, don't warn about shadowing non-class members.
7023     if (!OldDC->isRecord())
7024       return;
7025
7026     // TODO: should we warn about static data members shadowing
7027     // static data members from base classes?
7028
7029     // TODO: don't diagnose for inaccessible shadowed members.
7030     // This is hard to do perfectly because we might friend the
7031     // shadowing context, but that's just a false negative.
7032   }
7033
7034
7035   DeclarationName Name = R.getLookupName();
7036
7037   // Emit warning and note.
7038   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7039     return;
7040   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7041   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7042   if (!CaptureLoc.isInvalid())
7043     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7044         << Name << /*explicitly*/ 1;
7045   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7046 }
7047
7048 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7049 /// when these variables are captured by the lambda.
7050 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7051   for (const auto &Shadow : LSI->ShadowingDecls) {
7052     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7053     // Try to avoid the warning when the shadowed decl isn't captured.
7054     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7055     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7056     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7057                                        ? diag::warn_decl_shadow_uncaptured_local
7058                                        : diag::warn_decl_shadow)
7059         << Shadow.VD->getDeclName()
7060         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7061     if (!CaptureLoc.isInvalid())
7062       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7063           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7064     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7065   }
7066 }
7067
7068 /// \brief Check -Wshadow without the advantage of a previous lookup.
7069 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7070   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7071     return;
7072
7073   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7074                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
7075   LookupName(R, S);
7076   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7077     CheckShadow(D, ShadowedDecl, R);
7078 }
7079
7080 /// Check if 'E', which is an expression that is about to be modified, refers
7081 /// to a constructor parameter that shadows a field.
7082 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7083   // Quickly ignore expressions that can't be shadowing ctor parameters.
7084   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7085     return;
7086   E = E->IgnoreParenImpCasts();
7087   auto *DRE = dyn_cast<DeclRefExpr>(E);
7088   if (!DRE)
7089     return;
7090   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7091   auto I = ShadowingDecls.find(D);
7092   if (I == ShadowingDecls.end())
7093     return;
7094   const NamedDecl *ShadowedDecl = I->second;
7095   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7096   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7097   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7098   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7099
7100   // Avoid issuing multiple warnings about the same decl.
7101   ShadowingDecls.erase(I);
7102 }
7103
7104 /// Check for conflict between this global or extern "C" declaration and
7105 /// previous global or extern "C" declarations. This is only used in C++.
7106 template<typename T>
7107 static bool checkGlobalOrExternCConflict(
7108     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7109   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7110   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7111
7112   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7113     // The common case: this global doesn't conflict with any extern "C"
7114     // declaration.
7115     return false;
7116   }
7117
7118   if (Prev) {
7119     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7120       // Both the old and new declarations have C language linkage. This is a
7121       // redeclaration.
7122       Previous.clear();
7123       Previous.addDecl(Prev);
7124       return true;
7125     }
7126
7127     // This is a global, non-extern "C" declaration, and there is a previous
7128     // non-global extern "C" declaration. Diagnose if this is a variable
7129     // declaration.
7130     if (!isa<VarDecl>(ND))
7131       return false;
7132   } else {
7133     // The declaration is extern "C". Check for any declaration in the
7134     // translation unit which might conflict.
7135     if (IsGlobal) {
7136       // We have already performed the lookup into the translation unit.
7137       IsGlobal = false;
7138       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7139            I != E; ++I) {
7140         if (isa<VarDecl>(*I)) {
7141           Prev = *I;
7142           break;
7143         }
7144       }
7145     } else {
7146       DeclContext::lookup_result R =
7147           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7148       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7149            I != E; ++I) {
7150         if (isa<VarDecl>(*I)) {
7151           Prev = *I;
7152           break;
7153         }
7154         // FIXME: If we have any other entity with this name in global scope,
7155         // the declaration is ill-formed, but that is a defect: it breaks the
7156         // 'stat' hack, for instance. Only variables can have mangled name
7157         // clashes with extern "C" declarations, so only they deserve a
7158         // diagnostic.
7159       }
7160     }
7161
7162     if (!Prev)
7163       return false;
7164   }
7165
7166   // Use the first declaration's location to ensure we point at something which
7167   // is lexically inside an extern "C" linkage-spec.
7168   assert(Prev && "should have found a previous declaration to diagnose");
7169   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7170     Prev = FD->getFirstDecl();
7171   else
7172     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7173
7174   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7175     << IsGlobal << ND;
7176   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7177     << IsGlobal;
7178   return false;
7179 }
7180
7181 /// Apply special rules for handling extern "C" declarations. Returns \c true
7182 /// if we have found that this is a redeclaration of some prior entity.
7183 ///
7184 /// Per C++ [dcl.link]p6:
7185 ///   Two declarations [for a function or variable] with C language linkage
7186 ///   with the same name that appear in different scopes refer to the same
7187 ///   [entity]. An entity with C language linkage shall not be declared with
7188 ///   the same name as an entity in global scope.
7189 template<typename T>
7190 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7191                                                   LookupResult &Previous) {
7192   if (!S.getLangOpts().CPlusPlus) {
7193     // In C, when declaring a global variable, look for a corresponding 'extern'
7194     // variable declared in function scope. We don't need this in C++, because
7195     // we find local extern decls in the surrounding file-scope DeclContext.
7196     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7197       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7198         Previous.clear();
7199         Previous.addDecl(Prev);
7200         return true;
7201       }
7202     }
7203     return false;
7204   }
7205
7206   // A declaration in the translation unit can conflict with an extern "C"
7207   // declaration.
7208   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7209     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7210
7211   // An extern "C" declaration can conflict with a declaration in the
7212   // translation unit or can be a redeclaration of an extern "C" declaration
7213   // in another scope.
7214   if (isIncompleteDeclExternC(S,ND))
7215     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7216
7217   // Neither global nor extern "C": nothing to do.
7218   return false;
7219 }
7220
7221 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7222   // If the decl is already known invalid, don't check it.
7223   if (NewVD->isInvalidDecl())
7224     return;
7225
7226   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7227   QualType T = TInfo->getType();
7228
7229   // Defer checking an 'auto' type until its initializer is attached.
7230   if (T->isUndeducedType())
7231     return;
7232
7233   if (NewVD->hasAttrs())
7234     CheckAlignasUnderalignment(NewVD);
7235
7236   if (T->isObjCObjectType()) {
7237     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7238       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7239     T = Context.getObjCObjectPointerType(T);
7240     NewVD->setType(T);
7241   }
7242
7243   // Emit an error if an address space was applied to decl with local storage.
7244   // This includes arrays of objects with address space qualifiers, but not
7245   // automatic variables that point to other address spaces.
7246   // ISO/IEC TR 18037 S5.1.2
7247   if (!getLangOpts().OpenCL
7248       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7249     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7250     NewVD->setInvalidDecl();
7251     return;
7252   }
7253
7254   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7255   // scope.
7256   if (getLangOpts().OpenCLVersion == 120 &&
7257       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7258       NewVD->isStaticLocal()) {
7259     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7260     NewVD->setInvalidDecl();
7261     return;
7262   }
7263
7264   if (getLangOpts().OpenCL) {
7265     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7266     if (NewVD->hasAttr<BlocksAttr>()) {
7267       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7268       return;
7269     }
7270
7271     if (T->isBlockPointerType()) {
7272       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7273       // can't use 'extern' storage class.
7274       if (!T.isConstQualified()) {
7275         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7276             << 0 /*const*/;
7277         NewVD->setInvalidDecl();
7278         return;
7279       }
7280       if (NewVD->hasExternalStorage()) {
7281         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7282         NewVD->setInvalidDecl();
7283         return;
7284       }
7285     }
7286     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7287     // __constant address space.
7288     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7289     // variables inside a function can also be declared in the global
7290     // address space.
7291     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7292         NewVD->hasExternalStorage()) {
7293       if (!T->isSamplerT() &&
7294           !(T.getAddressSpace() == LangAS::opencl_constant ||
7295             (T.getAddressSpace() == LangAS::opencl_global &&
7296              getLangOpts().OpenCLVersion == 200))) {
7297         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7298         if (getLangOpts().OpenCLVersion == 200)
7299           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7300               << Scope << "global or constant";
7301         else
7302           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7303               << Scope << "constant";
7304         NewVD->setInvalidDecl();
7305         return;
7306       }
7307     } else {
7308       if (T.getAddressSpace() == LangAS::opencl_global) {
7309         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7310             << 1 /*is any function*/ << "global";
7311         NewVD->setInvalidDecl();
7312         return;
7313       }
7314       if (T.getAddressSpace() == LangAS::opencl_constant ||
7315           T.getAddressSpace() == LangAS::opencl_local) {
7316         FunctionDecl *FD = getCurFunctionDecl();
7317         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7318         // in functions.
7319         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7320           if (T.getAddressSpace() == LangAS::opencl_constant)
7321             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7322                 << 0 /*non-kernel only*/ << "constant";
7323           else
7324             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7325                 << 0 /*non-kernel only*/ << "local";
7326           NewVD->setInvalidDecl();
7327           return;
7328         }
7329         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7330         // in the outermost scope of a kernel function.
7331         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7332           if (!getCurScope()->isFunctionScope()) {
7333             if (T.getAddressSpace() == LangAS::opencl_constant)
7334               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7335                   << "constant";
7336             else
7337               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7338                   << "local";
7339             NewVD->setInvalidDecl();
7340             return;
7341           }
7342         }
7343       } else if (T.getAddressSpace() != LangAS::Default) {
7344         // Do not allow other address spaces on automatic variable.
7345         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7346         NewVD->setInvalidDecl();
7347         return;
7348       }
7349     }
7350   }
7351
7352   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7353       && !NewVD->hasAttr<BlocksAttr>()) {
7354     if (getLangOpts().getGC() != LangOptions::NonGC)
7355       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7356     else {
7357       assert(!getLangOpts().ObjCAutoRefCount);
7358       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7359     }
7360   }
7361
7362   bool isVM = T->isVariablyModifiedType();
7363   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7364       NewVD->hasAttr<BlocksAttr>())
7365     getCurFunction()->setHasBranchProtectedScope();
7366
7367   if ((isVM && NewVD->hasLinkage()) ||
7368       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7369     bool SizeIsNegative;
7370     llvm::APSInt Oversized;
7371     TypeSourceInfo *FixedTInfo =
7372       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7373                                                     SizeIsNegative, Oversized);
7374     if (!FixedTInfo && T->isVariableArrayType()) {
7375       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7376       // FIXME: This won't give the correct result for
7377       // int a[10][n];
7378       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7379
7380       if (NewVD->isFileVarDecl())
7381         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7382         << SizeRange;
7383       else if (NewVD->isStaticLocal())
7384         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7385         << SizeRange;
7386       else
7387         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7388         << SizeRange;
7389       NewVD->setInvalidDecl();
7390       return;
7391     }
7392
7393     if (!FixedTInfo) {
7394       if (NewVD->isFileVarDecl())
7395         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7396       else
7397         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7398       NewVD->setInvalidDecl();
7399       return;
7400     }
7401
7402     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7403     NewVD->setType(FixedTInfo->getType());
7404     NewVD->setTypeSourceInfo(FixedTInfo);
7405   }
7406
7407   if (T->isVoidType()) {
7408     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7409     //                    of objects and functions.
7410     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7411       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7412         << T;
7413       NewVD->setInvalidDecl();
7414       return;
7415     }
7416   }
7417
7418   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7419     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7420     NewVD->setInvalidDecl();
7421     return;
7422   }
7423
7424   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7425     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7426     NewVD->setInvalidDecl();
7427     return;
7428   }
7429
7430   if (NewVD->isConstexpr() && !T->isDependentType() &&
7431       RequireLiteralType(NewVD->getLocation(), T,
7432                          diag::err_constexpr_var_non_literal)) {
7433     NewVD->setInvalidDecl();
7434     return;
7435   }
7436 }
7437
7438 /// \brief Perform semantic checking on a newly-created variable
7439 /// declaration.
7440 ///
7441 /// This routine performs all of the type-checking required for a
7442 /// variable declaration once it has been built. It is used both to
7443 /// check variables after they have been parsed and their declarators
7444 /// have been translated into a declaration, and to check variables
7445 /// that have been instantiated from a template.
7446 ///
7447 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7448 ///
7449 /// Returns true if the variable declaration is a redeclaration.
7450 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7451   CheckVariableDeclarationType(NewVD);
7452
7453   // If the decl is already known invalid, don't check it.
7454   if (NewVD->isInvalidDecl())
7455     return false;
7456
7457   // If we did not find anything by this name, look for a non-visible
7458   // extern "C" declaration with the same name.
7459   if (Previous.empty() &&
7460       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7461     Previous.setShadowed();
7462
7463   if (!Previous.empty()) {
7464     MergeVarDecl(NewVD, Previous);
7465     return true;
7466   }
7467   return false;
7468 }
7469
7470 namespace {
7471 struct FindOverriddenMethod {
7472   Sema *S;
7473   CXXMethodDecl *Method;
7474
7475   /// Member lookup function that determines whether a given C++
7476   /// method overrides a method in a base class, to be used with
7477   /// CXXRecordDecl::lookupInBases().
7478   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7479     RecordDecl *BaseRecord =
7480         Specifier->getType()->getAs<RecordType>()->getDecl();
7481
7482     DeclarationName Name = Method->getDeclName();
7483
7484     // FIXME: Do we care about other names here too?
7485     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7486       // We really want to find the base class destructor here.
7487       QualType T = S->Context.getTypeDeclType(BaseRecord);
7488       CanQualType CT = S->Context.getCanonicalType(T);
7489
7490       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7491     }
7492
7493     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7494          Path.Decls = Path.Decls.slice(1)) {
7495       NamedDecl *D = Path.Decls.front();
7496       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7497         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7498           return true;
7499       }
7500     }
7501
7502     return false;
7503   }
7504 };
7505
7506 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7507 } // end anonymous namespace
7508
7509 /// \brief Report an error regarding overriding, along with any relevant
7510 /// overriden methods.
7511 ///
7512 /// \param DiagID the primary error to report.
7513 /// \param MD the overriding method.
7514 /// \param OEK which overrides to include as notes.
7515 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7516                             OverrideErrorKind OEK = OEK_All) {
7517   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7518   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7519                                       E = MD->end_overridden_methods();
7520        I != E; ++I) {
7521     // This check (& the OEK parameter) could be replaced by a predicate, but
7522     // without lambdas that would be overkill. This is still nicer than writing
7523     // out the diag loop 3 times.
7524     if ((OEK == OEK_All) ||
7525         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7526         (OEK == OEK_Deleted && (*I)->isDeleted()))
7527       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7528   }
7529 }
7530
7531 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7532 /// and if so, check that it's a valid override and remember it.
7533 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7534   // Look for methods in base classes that this method might override.
7535   CXXBasePaths Paths;
7536   FindOverriddenMethod FOM;
7537   FOM.Method = MD;
7538   FOM.S = this;
7539   bool hasDeletedOverridenMethods = false;
7540   bool hasNonDeletedOverridenMethods = false;
7541   bool AddedAny = false;
7542   if (DC->lookupInBases(FOM, Paths)) {
7543     for (auto *I : Paths.found_decls()) {
7544       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7545         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7546         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7547             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7548             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7549             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7550           hasDeletedOverridenMethods |= OldMD->isDeleted();
7551           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7552           AddedAny = true;
7553         }
7554       }
7555     }
7556   }
7557
7558   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7559     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7560   }
7561   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7562     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7563   }
7564
7565   return AddedAny;
7566 }
7567
7568 namespace {
7569   // Struct for holding all of the extra arguments needed by
7570   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7571   struct ActOnFDArgs {
7572     Scope *S;
7573     Declarator &D;
7574     MultiTemplateParamsArg TemplateParamLists;
7575     bool AddToScope;
7576   };
7577 } // end anonymous namespace
7578
7579 namespace {
7580
7581 // Callback to only accept typo corrections that have a non-zero edit distance.
7582 // Also only accept corrections that have the same parent decl.
7583 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7584  public:
7585   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7586                             CXXRecordDecl *Parent)
7587       : Context(Context), OriginalFD(TypoFD),
7588         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7589
7590   bool ValidateCandidate(const TypoCorrection &candidate) override {
7591     if (candidate.getEditDistance() == 0)
7592       return false;
7593
7594     SmallVector<unsigned, 1> MismatchedParams;
7595     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7596                                           CDeclEnd = candidate.end();
7597          CDecl != CDeclEnd; ++CDecl) {
7598       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7599
7600       if (FD && !FD->hasBody() &&
7601           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7602         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7603           CXXRecordDecl *Parent = MD->getParent();
7604           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7605             return true;
7606         } else if (!ExpectedParent) {
7607           return true;
7608         }
7609       }
7610     }
7611
7612     return false;
7613   }
7614
7615  private:
7616   ASTContext &Context;
7617   FunctionDecl *OriginalFD;
7618   CXXRecordDecl *ExpectedParent;
7619 };
7620
7621 } // end anonymous namespace
7622
7623 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7624   TypoCorrectedFunctionDefinitions.insert(F);
7625 }
7626
7627 /// \brief Generate diagnostics for an invalid function redeclaration.
7628 ///
7629 /// This routine handles generating the diagnostic messages for an invalid
7630 /// function redeclaration, including finding possible similar declarations
7631 /// or performing typo correction if there are no previous declarations with
7632 /// the same name.
7633 ///
7634 /// Returns a NamedDecl iff typo correction was performed and substituting in
7635 /// the new declaration name does not cause new errors.
7636 static NamedDecl *DiagnoseInvalidRedeclaration(
7637     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7638     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7639   DeclarationName Name = NewFD->getDeclName();
7640   DeclContext *NewDC = NewFD->getDeclContext();
7641   SmallVector<unsigned, 1> MismatchedParams;
7642   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7643   TypoCorrection Correction;
7644   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7645   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7646                                    : diag::err_member_decl_does_not_match;
7647   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7648                     IsLocalFriend ? Sema::LookupLocalFriendName
7649                                   : Sema::LookupOrdinaryName,
7650                     Sema::ForRedeclaration);
7651
7652   NewFD->setInvalidDecl();
7653   if (IsLocalFriend)
7654     SemaRef.LookupName(Prev, S);
7655   else
7656     SemaRef.LookupQualifiedName(Prev, NewDC);
7657   assert(!Prev.isAmbiguous() &&
7658          "Cannot have an ambiguity in previous-declaration lookup");
7659   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7660   if (!Prev.empty()) {
7661     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7662          Func != FuncEnd; ++Func) {
7663       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7664       if (FD &&
7665           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7666         // Add 1 to the index so that 0 can mean the mismatch didn't
7667         // involve a parameter
7668         unsigned ParamNum =
7669             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7670         NearMatches.push_back(std::make_pair(FD, ParamNum));
7671       }
7672     }
7673   // If the qualified name lookup yielded nothing, try typo correction
7674   } else if ((Correction = SemaRef.CorrectTypo(
7675                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7676                   &ExtraArgs.D.getCXXScopeSpec(),
7677                   llvm::make_unique<DifferentNameValidatorCCC>(
7678                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7679                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7680     // Set up everything for the call to ActOnFunctionDeclarator
7681     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7682                               ExtraArgs.D.getIdentifierLoc());
7683     Previous.clear();
7684     Previous.setLookupName(Correction.getCorrection());
7685     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7686                                     CDeclEnd = Correction.end();
7687          CDecl != CDeclEnd; ++CDecl) {
7688       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7689       if (FD && !FD->hasBody() &&
7690           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7691         Previous.addDecl(FD);
7692       }
7693     }
7694     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7695
7696     NamedDecl *Result;
7697     // Retry building the function declaration with the new previous
7698     // declarations, and with errors suppressed.
7699     {
7700       // Trap errors.
7701       Sema::SFINAETrap Trap(SemaRef);
7702
7703       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7704       // pieces need to verify the typo-corrected C++ declaration and hopefully
7705       // eliminate the need for the parameter pack ExtraArgs.
7706       Result = SemaRef.ActOnFunctionDeclarator(
7707           ExtraArgs.S, ExtraArgs.D,
7708           Correction.getCorrectionDecl()->getDeclContext(),
7709           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7710           ExtraArgs.AddToScope);
7711
7712       if (Trap.hasErrorOccurred())
7713         Result = nullptr;
7714     }
7715
7716     if (Result) {
7717       // Determine which correction we picked.
7718       Decl *Canonical = Result->getCanonicalDecl();
7719       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7720            I != E; ++I)
7721         if ((*I)->getCanonicalDecl() == Canonical)
7722           Correction.setCorrectionDecl(*I);
7723
7724       // Let Sema know about the correction.
7725       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7726       SemaRef.diagnoseTypo(
7727           Correction,
7728           SemaRef.PDiag(IsLocalFriend
7729                           ? diag::err_no_matching_local_friend_suggest
7730                           : diag::err_member_decl_does_not_match_suggest)
7731             << Name << NewDC << IsDefinition);
7732       return Result;
7733     }
7734
7735     // Pretend the typo correction never occurred
7736     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7737                               ExtraArgs.D.getIdentifierLoc());
7738     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7739     Previous.clear();
7740     Previous.setLookupName(Name);
7741   }
7742
7743   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7744       << Name << NewDC << IsDefinition << NewFD->getLocation();
7745
7746   bool NewFDisConst = false;
7747   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7748     NewFDisConst = NewMD->isConst();
7749
7750   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7751        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7752        NearMatch != NearMatchEnd; ++NearMatch) {
7753     FunctionDecl *FD = NearMatch->first;
7754     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7755     bool FDisConst = MD && MD->isConst();
7756     bool IsMember = MD || !IsLocalFriend;
7757
7758     // FIXME: These notes are poorly worded for the local friend case.
7759     if (unsigned Idx = NearMatch->second) {
7760       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7761       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7762       if (Loc.isInvalid()) Loc = FD->getLocation();
7763       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7764                                  : diag::note_local_decl_close_param_match)
7765         << Idx << FDParam->getType()
7766         << NewFD->getParamDecl(Idx - 1)->getType();
7767     } else if (FDisConst != NewFDisConst) {
7768       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7769           << NewFDisConst << FD->getSourceRange().getEnd();
7770     } else
7771       SemaRef.Diag(FD->getLocation(),
7772                    IsMember ? diag::note_member_def_close_match
7773                             : diag::note_local_decl_close_match);
7774   }
7775   return nullptr;
7776 }
7777
7778 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7779   switch (D.getDeclSpec().getStorageClassSpec()) {
7780   default: llvm_unreachable("Unknown storage class!");
7781   case DeclSpec::SCS_auto:
7782   case DeclSpec::SCS_register:
7783   case DeclSpec::SCS_mutable:
7784     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7785                  diag::err_typecheck_sclass_func);
7786     D.getMutableDeclSpec().ClearStorageClassSpecs();
7787     D.setInvalidType();
7788     break;
7789   case DeclSpec::SCS_unspecified: break;
7790   case DeclSpec::SCS_extern:
7791     if (D.getDeclSpec().isExternInLinkageSpec())
7792       return SC_None;
7793     return SC_Extern;
7794   case DeclSpec::SCS_static: {
7795     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7796       // C99 6.7.1p5:
7797       //   The declaration of an identifier for a function that has
7798       //   block scope shall have no explicit storage-class specifier
7799       //   other than extern
7800       // See also (C++ [dcl.stc]p4).
7801       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7802                    diag::err_static_block_func);
7803       break;
7804     } else
7805       return SC_Static;
7806   }
7807   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7808   }
7809
7810   // No explicit storage class has already been returned
7811   return SC_None;
7812 }
7813
7814 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7815                                            DeclContext *DC, QualType &R,
7816                                            TypeSourceInfo *TInfo,
7817                                            StorageClass SC,
7818                                            bool &IsVirtualOkay) {
7819   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7820   DeclarationName Name = NameInfo.getName();
7821
7822   FunctionDecl *NewFD = nullptr;
7823   bool isInline = D.getDeclSpec().isInlineSpecified();
7824
7825   if (!SemaRef.getLangOpts().CPlusPlus) {
7826     // Determine whether the function was written with a
7827     // prototype. This true when:
7828     //   - there is a prototype in the declarator, or
7829     //   - the type R of the function is some kind of typedef or other non-
7830     //     attributed reference to a type name (which eventually refers to a
7831     //     function type).
7832     bool HasPrototype =
7833       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7834       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7835
7836     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7837                                  D.getLocStart(), NameInfo, R,
7838                                  TInfo, SC, isInline,
7839                                  HasPrototype, false);
7840     if (D.isInvalidType())
7841       NewFD->setInvalidDecl();
7842
7843     return NewFD;
7844   }
7845
7846   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7847   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7848
7849   // Check that the return type is not an abstract class type.
7850   // For record types, this is done by the AbstractClassUsageDiagnoser once
7851   // the class has been completely parsed.
7852   if (!DC->isRecord() &&
7853       SemaRef.RequireNonAbstractType(
7854           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7855           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7856     D.setInvalidType();
7857
7858   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7859     // This is a C++ constructor declaration.
7860     assert(DC->isRecord() &&
7861            "Constructors can only be declared in a member context");
7862
7863     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7864     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7865                                       D.getLocStart(), NameInfo,
7866                                       R, TInfo, isExplicit, isInline,
7867                                       /*isImplicitlyDeclared=*/false,
7868                                       isConstexpr);
7869
7870   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7871     // This is a C++ destructor declaration.
7872     if (DC->isRecord()) {
7873       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7874       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7875       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7876                                         SemaRef.Context, Record,
7877                                         D.getLocStart(),
7878                                         NameInfo, R, TInfo, isInline,
7879                                         /*isImplicitlyDeclared=*/false);
7880
7881       // If the class is complete, then we now create the implicit exception
7882       // specification. If the class is incomplete or dependent, we can't do
7883       // it yet.
7884       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7885           Record->getDefinition() && !Record->isBeingDefined() &&
7886           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7887         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7888       }
7889
7890       IsVirtualOkay = true;
7891       return NewDD;
7892
7893     } else {
7894       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7895       D.setInvalidType();
7896
7897       // Create a FunctionDecl to satisfy the function definition parsing
7898       // code path.
7899       return FunctionDecl::Create(SemaRef.Context, DC,
7900                                   D.getLocStart(),
7901                                   D.getIdentifierLoc(), Name, R, TInfo,
7902                                   SC, isInline,
7903                                   /*hasPrototype=*/true, isConstexpr);
7904     }
7905
7906   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7907     if (!DC->isRecord()) {
7908       SemaRef.Diag(D.getIdentifierLoc(),
7909            diag::err_conv_function_not_member);
7910       return nullptr;
7911     }
7912
7913     SemaRef.CheckConversionDeclarator(D, R, SC);
7914     IsVirtualOkay = true;
7915     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7916                                      D.getLocStart(), NameInfo,
7917                                      R, TInfo, isInline, isExplicit,
7918                                      isConstexpr, SourceLocation());
7919
7920   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7921     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7922
7923     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7924                                          isExplicit, NameInfo, R, TInfo,
7925                                          D.getLocEnd());
7926   } else if (DC->isRecord()) {
7927     // If the name of the function is the same as the name of the record,
7928     // then this must be an invalid constructor that has a return type.
7929     // (The parser checks for a return type and makes the declarator a
7930     // constructor if it has no return type).
7931     if (Name.getAsIdentifierInfo() &&
7932         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7933       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7934         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7935         << SourceRange(D.getIdentifierLoc());
7936       return nullptr;
7937     }
7938
7939     // This is a C++ method declaration.
7940     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7941                                                cast<CXXRecordDecl>(DC),
7942                                                D.getLocStart(), NameInfo, R,
7943                                                TInfo, SC, isInline,
7944                                                isConstexpr, SourceLocation());
7945     IsVirtualOkay = !Ret->isStatic();
7946     return Ret;
7947   } else {
7948     bool isFriend =
7949         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7950     if (!isFriend && SemaRef.CurContext->isRecord())
7951       return nullptr;
7952
7953     // Determine whether the function was written with a
7954     // prototype. This true when:
7955     //   - we're in C++ (where every function has a prototype),
7956     return FunctionDecl::Create(SemaRef.Context, DC,
7957                                 D.getLocStart(),
7958                                 NameInfo, R, TInfo, SC, isInline,
7959                                 true/*HasPrototype*/, isConstexpr);
7960   }
7961 }
7962
7963 enum OpenCLParamType {
7964   ValidKernelParam,
7965   PtrPtrKernelParam,
7966   PtrKernelParam,
7967   InvalidAddrSpacePtrKernelParam,
7968   InvalidKernelParam,
7969   RecordKernelParam
7970 };
7971
7972 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7973   if (PT->isPointerType()) {
7974     QualType PointeeType = PT->getPointeeType();
7975     if (PointeeType->isPointerType())
7976       return PtrPtrKernelParam;
7977     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7978         PointeeType.getAddressSpace() == 0)
7979       return InvalidAddrSpacePtrKernelParam;
7980     return PtrKernelParam;
7981   }
7982
7983   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7984   // be used as builtin types.
7985
7986   if (PT->isImageType())
7987     return PtrKernelParam;
7988
7989   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
7990     return InvalidKernelParam;
7991
7992   // OpenCL extension spec v1.2 s9.5:
7993   // This extension adds support for half scalar and vector types as built-in
7994   // types that can be used for arithmetic operations, conversions etc.
7995   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7996     return InvalidKernelParam;
7997
7998   if (PT->isRecordType())
7999     return RecordKernelParam;
8000
8001   return ValidKernelParam;
8002 }
8003
8004 static void checkIsValidOpenCLKernelParameter(
8005   Sema &S,
8006   Declarator &D,
8007   ParmVarDecl *Param,
8008   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8009   QualType PT = Param->getType();
8010
8011   // Cache the valid types we encounter to avoid rechecking structs that are
8012   // used again
8013   if (ValidTypes.count(PT.getTypePtr()))
8014     return;
8015
8016   switch (getOpenCLKernelParameterType(S, PT)) {
8017   case PtrPtrKernelParam:
8018     // OpenCL v1.2 s6.9.a:
8019     // A kernel function argument cannot be declared as a
8020     // pointer to a pointer type.
8021     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8022     D.setInvalidType();
8023     return;
8024
8025   case InvalidAddrSpacePtrKernelParam:
8026     // OpenCL v1.0 s6.5:
8027     // __kernel function arguments declared to be a pointer of a type can point
8028     // to one of the following address spaces only : __global, __local or
8029     // __constant.
8030     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8031     D.setInvalidType();
8032     return;
8033
8034     // OpenCL v1.2 s6.9.k:
8035     // Arguments to kernel functions in a program cannot be declared with the
8036     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8037     // uintptr_t or a struct and/or union that contain fields declared to be
8038     // one of these built-in scalar types.
8039
8040   case InvalidKernelParam:
8041     // OpenCL v1.2 s6.8 n:
8042     // A kernel function argument cannot be declared
8043     // of event_t type.
8044     // Do not diagnose half type since it is diagnosed as invalid argument
8045     // type for any function elsewhere.
8046     if (!PT->isHalfType())
8047       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8048     D.setInvalidType();
8049     return;
8050
8051   case PtrKernelParam:
8052   case ValidKernelParam:
8053     ValidTypes.insert(PT.getTypePtr());
8054     return;
8055
8056   case RecordKernelParam:
8057     break;
8058   }
8059
8060   // Track nested structs we will inspect
8061   SmallVector<const Decl *, 4> VisitStack;
8062
8063   // Track where we are in the nested structs. Items will migrate from
8064   // VisitStack to HistoryStack as we do the DFS for bad field.
8065   SmallVector<const FieldDecl *, 4> HistoryStack;
8066   HistoryStack.push_back(nullptr);
8067
8068   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8069   VisitStack.push_back(PD);
8070
8071   assert(VisitStack.back() && "First decl null?");
8072
8073   do {
8074     const Decl *Next = VisitStack.pop_back_val();
8075     if (!Next) {
8076       assert(!HistoryStack.empty());
8077       // Found a marker, we have gone up a level
8078       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8079         ValidTypes.insert(Hist->getType().getTypePtr());
8080
8081       continue;
8082     }
8083
8084     // Adds everything except the original parameter declaration (which is not a
8085     // field itself) to the history stack.
8086     const RecordDecl *RD;
8087     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8088       HistoryStack.push_back(Field);
8089       RD = Field->getType()->castAs<RecordType>()->getDecl();
8090     } else {
8091       RD = cast<RecordDecl>(Next);
8092     }
8093
8094     // Add a null marker so we know when we've gone back up a level
8095     VisitStack.push_back(nullptr);
8096
8097     for (const auto *FD : RD->fields()) {
8098       QualType QT = FD->getType();
8099
8100       if (ValidTypes.count(QT.getTypePtr()))
8101         continue;
8102
8103       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8104       if (ParamType == ValidKernelParam)
8105         continue;
8106
8107       if (ParamType == RecordKernelParam) {
8108         VisitStack.push_back(FD);
8109         continue;
8110       }
8111
8112       // OpenCL v1.2 s6.9.p:
8113       // Arguments to kernel functions that are declared to be a struct or union
8114       // do not allow OpenCL objects to be passed as elements of the struct or
8115       // union.
8116       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8117           ParamType == InvalidAddrSpacePtrKernelParam) {
8118         S.Diag(Param->getLocation(),
8119                diag::err_record_with_pointers_kernel_param)
8120           << PT->isUnionType()
8121           << PT;
8122       } else {
8123         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8124       }
8125
8126       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8127         << PD->getDeclName();
8128
8129       // We have an error, now let's go back up through history and show where
8130       // the offending field came from
8131       for (ArrayRef<const FieldDecl *>::const_iterator
8132                I = HistoryStack.begin() + 1,
8133                E = HistoryStack.end();
8134            I != E; ++I) {
8135         const FieldDecl *OuterField = *I;
8136         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8137           << OuterField->getType();
8138       }
8139
8140       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8141         << QT->isPointerType()
8142         << QT;
8143       D.setInvalidType();
8144       return;
8145     }
8146   } while (!VisitStack.empty());
8147 }
8148
8149 /// Find the DeclContext in which a tag is implicitly declared if we see an
8150 /// elaborated type specifier in the specified context, and lookup finds
8151 /// nothing.
8152 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8153   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8154     DC = DC->getParent();
8155   return DC;
8156 }
8157
8158 /// Find the Scope in which a tag is implicitly declared if we see an
8159 /// elaborated type specifier in the specified context, and lookup finds
8160 /// nothing.
8161 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8162   while (S->isClassScope() ||
8163          (LangOpts.CPlusPlus &&
8164           S->isFunctionPrototypeScope()) ||
8165          ((S->getFlags() & Scope::DeclScope) == 0) ||
8166          (S->getEntity() && S->getEntity()->isTransparentContext()))
8167     S = S->getParent();
8168   return S;
8169 }
8170
8171 NamedDecl*
8172 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8173                               TypeSourceInfo *TInfo, LookupResult &Previous,
8174                               MultiTemplateParamsArg TemplateParamLists,
8175                               bool &AddToScope) {
8176   QualType R = TInfo->getType();
8177
8178   assert(R.getTypePtr()->isFunctionType());
8179
8180   // TODO: consider using NameInfo for diagnostic.
8181   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8182   DeclarationName Name = NameInfo.getName();
8183   StorageClass SC = getFunctionStorageClass(*this, D);
8184
8185   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8186     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8187          diag::err_invalid_thread)
8188       << DeclSpec::getSpecifierName(TSCS);
8189
8190   if (D.isFirstDeclarationOfMember())
8191     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8192                            D.getIdentifierLoc());
8193
8194   bool isFriend = false;
8195   FunctionTemplateDecl *FunctionTemplate = nullptr;
8196   bool isMemberSpecialization = false;
8197   bool isFunctionTemplateSpecialization = false;
8198
8199   bool isDependentClassScopeExplicitSpecialization = false;
8200   bool HasExplicitTemplateArgs = false;
8201   TemplateArgumentListInfo TemplateArgs;
8202
8203   bool isVirtualOkay = false;
8204
8205   DeclContext *OriginalDC = DC;
8206   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8207
8208   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8209                                               isVirtualOkay);
8210   if (!NewFD) return nullptr;
8211
8212   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8213     NewFD->setTopLevelDeclInObjCContainer();
8214
8215   // Set the lexical context. If this is a function-scope declaration, or has a
8216   // C++ scope specifier, or is the object of a friend declaration, the lexical
8217   // context will be different from the semantic context.
8218   NewFD->setLexicalDeclContext(CurContext);
8219
8220   if (IsLocalExternDecl)
8221     NewFD->setLocalExternDecl();
8222
8223   if (getLangOpts().CPlusPlus) {
8224     bool isInline = D.getDeclSpec().isInlineSpecified();
8225     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8226     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8227     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8228     bool isConcept = D.getDeclSpec().isConceptSpecified();
8229     isFriend = D.getDeclSpec().isFriendSpecified();
8230     if (isFriend && !isInline && D.isFunctionDefinition()) {
8231       // C++ [class.friend]p5
8232       //   A function can be defined in a friend declaration of a
8233       //   class . . . . Such a function is implicitly inline.
8234       NewFD->setImplicitlyInline();
8235     }
8236
8237     // If this is a method defined in an __interface, and is not a constructor
8238     // or an overloaded operator, then set the pure flag (isVirtual will already
8239     // return true).
8240     if (const CXXRecordDecl *Parent =
8241           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8242       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8243         NewFD->setPure(true);
8244
8245       // C++ [class.union]p2
8246       //   A union can have member functions, but not virtual functions.
8247       if (isVirtual && Parent->isUnion())
8248         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8249     }
8250
8251     SetNestedNameSpecifier(NewFD, D);
8252     isMemberSpecialization = false;
8253     isFunctionTemplateSpecialization = false;
8254     if (D.isInvalidType())
8255       NewFD->setInvalidDecl();
8256
8257     // Match up the template parameter lists with the scope specifier, then
8258     // determine whether we have a template or a template specialization.
8259     bool Invalid = false;
8260     if (TemplateParameterList *TemplateParams =
8261             MatchTemplateParametersToScopeSpecifier(
8262                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8263                 D.getCXXScopeSpec(),
8264                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8265                     ? D.getName().TemplateId
8266                     : nullptr,
8267                 TemplateParamLists, isFriend, isMemberSpecialization,
8268                 Invalid)) {
8269       if (TemplateParams->size() > 0) {
8270         // This is a function template
8271
8272         // Check that we can declare a template here.
8273         if (CheckTemplateDeclScope(S, TemplateParams))
8274           NewFD->setInvalidDecl();
8275
8276         // A destructor cannot be a template.
8277         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8278           Diag(NewFD->getLocation(), diag::err_destructor_template);
8279           NewFD->setInvalidDecl();
8280         }
8281
8282         // If we're adding a template to a dependent context, we may need to
8283         // rebuilding some of the types used within the template parameter list,
8284         // now that we know what the current instantiation is.
8285         if (DC->isDependentContext()) {
8286           ContextRAII SavedContext(*this, DC);
8287           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8288             Invalid = true;
8289         }
8290
8291         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8292                                                         NewFD->getLocation(),
8293                                                         Name, TemplateParams,
8294                                                         NewFD);
8295         FunctionTemplate->setLexicalDeclContext(CurContext);
8296         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8297
8298         // For source fidelity, store the other template param lists.
8299         if (TemplateParamLists.size() > 1) {
8300           NewFD->setTemplateParameterListsInfo(Context,
8301                                                TemplateParamLists.drop_back(1));
8302         }
8303       } else {
8304         // This is a function template specialization.
8305         isFunctionTemplateSpecialization = true;
8306         // For source fidelity, store all the template param lists.
8307         if (TemplateParamLists.size() > 0)
8308           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8309
8310         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8311         if (isFriend) {
8312           // We want to remove the "template<>", found here.
8313           SourceRange RemoveRange = TemplateParams->getSourceRange();
8314
8315           // If we remove the template<> and the name is not a
8316           // template-id, we're actually silently creating a problem:
8317           // the friend declaration will refer to an untemplated decl,
8318           // and clearly the user wants a template specialization.  So
8319           // we need to insert '<>' after the name.
8320           SourceLocation InsertLoc;
8321           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8322             InsertLoc = D.getName().getSourceRange().getEnd();
8323             InsertLoc = getLocForEndOfToken(InsertLoc);
8324           }
8325
8326           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8327             << Name << RemoveRange
8328             << FixItHint::CreateRemoval(RemoveRange)
8329             << FixItHint::CreateInsertion(InsertLoc, "<>");
8330         }
8331       }
8332     }
8333     else {
8334       // All template param lists were matched against the scope specifier:
8335       // this is NOT (an explicit specialization of) a template.
8336       if (TemplateParamLists.size() > 0)
8337         // For source fidelity, store all the template param lists.
8338         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8339     }
8340
8341     if (Invalid) {
8342       NewFD->setInvalidDecl();
8343       if (FunctionTemplate)
8344         FunctionTemplate->setInvalidDecl();
8345     }
8346
8347     // C++ [dcl.fct.spec]p5:
8348     //   The virtual specifier shall only be used in declarations of
8349     //   nonstatic class member functions that appear within a
8350     //   member-specification of a class declaration; see 10.3.
8351     //
8352     if (isVirtual && !NewFD->isInvalidDecl()) {
8353       if (!isVirtualOkay) {
8354         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8355              diag::err_virtual_non_function);
8356       } else if (!CurContext->isRecord()) {
8357         // 'virtual' was specified outside of the class.
8358         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8359              diag::err_virtual_out_of_class)
8360           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8361       } else if (NewFD->getDescribedFunctionTemplate()) {
8362         // C++ [temp.mem]p3:
8363         //  A member function template shall not be virtual.
8364         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8365              diag::err_virtual_member_function_template)
8366           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8367       } else {
8368         // Okay: Add virtual to the method.
8369         NewFD->setVirtualAsWritten(true);
8370       }
8371
8372       if (getLangOpts().CPlusPlus14 &&
8373           NewFD->getReturnType()->isUndeducedType())
8374         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8375     }
8376
8377     if (getLangOpts().CPlusPlus14 &&
8378         (NewFD->isDependentContext() ||
8379          (isFriend && CurContext->isDependentContext())) &&
8380         NewFD->getReturnType()->isUndeducedType()) {
8381       // If the function template is referenced directly (for instance, as a
8382       // member of the current instantiation), pretend it has a dependent type.
8383       // This is not really justified by the standard, but is the only sane
8384       // thing to do.
8385       // FIXME: For a friend function, we have not marked the function as being
8386       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8387       const FunctionProtoType *FPT =
8388           NewFD->getType()->castAs<FunctionProtoType>();
8389       QualType Result =
8390           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8391       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8392                                              FPT->getExtProtoInfo()));
8393     }
8394
8395     // C++ [dcl.fct.spec]p3:
8396     //  The inline specifier shall not appear on a block scope function
8397     //  declaration.
8398     if (isInline && !NewFD->isInvalidDecl()) {
8399       if (CurContext->isFunctionOrMethod()) {
8400         // 'inline' is not allowed on block scope function declaration.
8401         Diag(D.getDeclSpec().getInlineSpecLoc(),
8402              diag::err_inline_declaration_block_scope) << Name
8403           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8404       }
8405     }
8406
8407     // C++ [dcl.fct.spec]p6:
8408     //  The explicit specifier shall be used only in the declaration of a
8409     //  constructor or conversion function within its class definition;
8410     //  see 12.3.1 and 12.3.2.
8411     if (isExplicit && !NewFD->isInvalidDecl() &&
8412         !isa<CXXDeductionGuideDecl>(NewFD)) {
8413       if (!CurContext->isRecord()) {
8414         // 'explicit' was specified outside of the class.
8415         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8416              diag::err_explicit_out_of_class)
8417           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8418       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8419                  !isa<CXXConversionDecl>(NewFD)) {
8420         // 'explicit' was specified on a function that wasn't a constructor
8421         // or conversion function.
8422         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8423              diag::err_explicit_non_ctor_or_conv_function)
8424           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8425       }
8426     }
8427
8428     if (isConstexpr) {
8429       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8430       // are implicitly inline.
8431       NewFD->setImplicitlyInline();
8432
8433       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8434       // be either constructors or to return a literal type. Therefore,
8435       // destructors cannot be declared constexpr.
8436       if (isa<CXXDestructorDecl>(NewFD))
8437         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8438     }
8439
8440     if (isConcept) {
8441       // This is a function concept.
8442       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8443         FTD->setConcept();
8444
8445       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8446       // applied only to the definition of a function template [...]
8447       if (!D.isFunctionDefinition()) {
8448         Diag(D.getDeclSpec().getConceptSpecLoc(),
8449              diag::err_function_concept_not_defined);
8450         NewFD->setInvalidDecl();
8451       }
8452
8453       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8454       // have no exception-specification and is treated as if it were specified
8455       // with noexcept(true) (15.4). [...]
8456       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8457         if (FPT->hasExceptionSpec()) {
8458           SourceRange Range;
8459           if (D.isFunctionDeclarator())
8460             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8461           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8462               << FixItHint::CreateRemoval(Range);
8463           NewFD->setInvalidDecl();
8464         } else {
8465           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8466         }
8467
8468         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8469         // following restrictions:
8470         // - The declared return type shall have the type bool.
8471         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8472           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8473           NewFD->setInvalidDecl();
8474         }
8475
8476         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8477         // following restrictions:
8478         // - The declaration's parameter list shall be equivalent to an empty
8479         //   parameter list.
8480         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8481           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8482       }
8483
8484       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8485       // implicity defined to be a constexpr declaration (implicitly inline)
8486       NewFD->setImplicitlyInline();
8487
8488       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8489       // be declared with the thread_local, inline, friend, or constexpr
8490       // specifiers, [...]
8491       if (isInline) {
8492         Diag(D.getDeclSpec().getInlineSpecLoc(),
8493              diag::err_concept_decl_invalid_specifiers)
8494             << 1 << 1;
8495         NewFD->setInvalidDecl(true);
8496       }
8497
8498       if (isFriend) {
8499         Diag(D.getDeclSpec().getFriendSpecLoc(),
8500              diag::err_concept_decl_invalid_specifiers)
8501             << 1 << 2;
8502         NewFD->setInvalidDecl(true);
8503       }
8504
8505       if (isConstexpr) {
8506         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8507              diag::err_concept_decl_invalid_specifiers)
8508             << 1 << 3;
8509         NewFD->setInvalidDecl(true);
8510       }
8511
8512       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8513       // applied only to the definition of a function template or variable
8514       // template, declared in namespace scope.
8515       if (isFunctionTemplateSpecialization) {
8516         Diag(D.getDeclSpec().getConceptSpecLoc(),
8517              diag::err_concept_specified_specialization) << 1;
8518         NewFD->setInvalidDecl(true);
8519         return NewFD;
8520       }
8521     }
8522
8523     // If __module_private__ was specified, mark the function accordingly.
8524     if (D.getDeclSpec().isModulePrivateSpecified()) {
8525       if (isFunctionTemplateSpecialization) {
8526         SourceLocation ModulePrivateLoc
8527           = D.getDeclSpec().getModulePrivateSpecLoc();
8528         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8529           << 0
8530           << FixItHint::CreateRemoval(ModulePrivateLoc);
8531       } else {
8532         NewFD->setModulePrivate();
8533         if (FunctionTemplate)
8534           FunctionTemplate->setModulePrivate();
8535       }
8536     }
8537
8538     if (isFriend) {
8539       if (FunctionTemplate) {
8540         FunctionTemplate->setObjectOfFriendDecl();
8541         FunctionTemplate->setAccess(AS_public);
8542       }
8543       NewFD->setObjectOfFriendDecl();
8544       NewFD->setAccess(AS_public);
8545     }
8546
8547     // If a function is defined as defaulted or deleted, mark it as such now.
8548     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8549     // definition kind to FDK_Definition.
8550     switch (D.getFunctionDefinitionKind()) {
8551       case FDK_Declaration:
8552       case FDK_Definition:
8553         break;
8554
8555       case FDK_Defaulted:
8556         NewFD->setDefaulted();
8557         break;
8558
8559       case FDK_Deleted:
8560         NewFD->setDeletedAsWritten();
8561         break;
8562     }
8563
8564     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8565         D.isFunctionDefinition()) {
8566       // C++ [class.mfct]p2:
8567       //   A member function may be defined (8.4) in its class definition, in
8568       //   which case it is an inline member function (7.1.2)
8569       NewFD->setImplicitlyInline();
8570     }
8571
8572     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8573         !CurContext->isRecord()) {
8574       // C++ [class.static]p1:
8575       //   A data or function member of a class may be declared static
8576       //   in a class definition, in which case it is a static member of
8577       //   the class.
8578
8579       // Complain about the 'static' specifier if it's on an out-of-line
8580       // member function definition.
8581       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8582            diag::err_static_out_of_line)
8583         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8584     }
8585
8586     // C++11 [except.spec]p15:
8587     //   A deallocation function with no exception-specification is treated
8588     //   as if it were specified with noexcept(true).
8589     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8590     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8591          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8592         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8593       NewFD->setType(Context.getFunctionType(
8594           FPT->getReturnType(), FPT->getParamTypes(),
8595           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8596   }
8597
8598   // Filter out previous declarations that don't match the scope.
8599   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8600                        D.getCXXScopeSpec().isNotEmpty() ||
8601                        isMemberSpecialization ||
8602                        isFunctionTemplateSpecialization);
8603
8604   // Handle GNU asm-label extension (encoded as an attribute).
8605   if (Expr *E = (Expr*) D.getAsmLabel()) {
8606     // The parser guarantees this is a string.
8607     StringLiteral *SE = cast<StringLiteral>(E);
8608     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8609                                                 SE->getString(), 0));
8610   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8611     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8612       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8613     if (I != ExtnameUndeclaredIdentifiers.end()) {
8614       if (isDeclExternC(NewFD)) {
8615         NewFD->addAttr(I->second);
8616         ExtnameUndeclaredIdentifiers.erase(I);
8617       } else
8618         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8619             << /*Variable*/0 << NewFD;
8620     }
8621   }
8622
8623   // Copy the parameter declarations from the declarator D to the function
8624   // declaration NewFD, if they are available.  First scavenge them into Params.
8625   SmallVector<ParmVarDecl*, 16> Params;
8626   unsigned FTIIdx;
8627   if (D.isFunctionDeclarator(FTIIdx)) {
8628     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8629
8630     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8631     // function that takes no arguments, not a function that takes a
8632     // single void argument.
8633     // We let through "const void" here because Sema::GetTypeForDeclarator
8634     // already checks for that case.
8635     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8636       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8637         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8638         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8639         Param->setDeclContext(NewFD);
8640         Params.push_back(Param);
8641
8642         if (Param->isInvalidDecl())
8643           NewFD->setInvalidDecl();
8644       }
8645     }
8646
8647     if (!getLangOpts().CPlusPlus) {
8648       // In C, find all the tag declarations from the prototype and move them
8649       // into the function DeclContext. Remove them from the surrounding tag
8650       // injection context of the function, which is typically but not always
8651       // the TU.
8652       DeclContext *PrototypeTagContext =
8653           getTagInjectionContext(NewFD->getLexicalDeclContext());
8654       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8655         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8656
8657         // We don't want to reparent enumerators. Look at their parent enum
8658         // instead.
8659         if (!TD) {
8660           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8661             TD = cast<EnumDecl>(ECD->getDeclContext());
8662         }
8663         if (!TD)
8664           continue;
8665         DeclContext *TagDC = TD->getLexicalDeclContext();
8666         if (!TagDC->containsDecl(TD))
8667           continue;
8668         TagDC->removeDecl(TD);
8669         TD->setDeclContext(NewFD);
8670         NewFD->addDecl(TD);
8671
8672         // Preserve the lexical DeclContext if it is not the surrounding tag
8673         // injection context of the FD. In this example, the semantic context of
8674         // E will be f and the lexical context will be S, while both the
8675         // semantic and lexical contexts of S will be f:
8676         //   void f(struct S { enum E { a } f; } s);
8677         if (TagDC != PrototypeTagContext)
8678           TD->setLexicalDeclContext(TagDC);
8679       }
8680     }
8681   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8682     // When we're declaring a function with a typedef, typeof, etc as in the
8683     // following example, we'll need to synthesize (unnamed)
8684     // parameters for use in the declaration.
8685     //
8686     // @code
8687     // typedef void fn(int);
8688     // fn f;
8689     // @endcode
8690
8691     // Synthesize a parameter for each argument type.
8692     for (const auto &AI : FT->param_types()) {
8693       ParmVarDecl *Param =
8694           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8695       Param->setScopeInfo(0, Params.size());
8696       Params.push_back(Param);
8697     }
8698   } else {
8699     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8700            "Should not need args for typedef of non-prototype fn");
8701   }
8702
8703   // Finally, we know we have the right number of parameters, install them.
8704   NewFD->setParams(Params);
8705
8706   if (D.getDeclSpec().isNoreturnSpecified())
8707     NewFD->addAttr(
8708         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8709                                        Context, 0));
8710
8711   // Functions returning a variably modified type violate C99 6.7.5.2p2
8712   // because all functions have linkage.
8713   if (!NewFD->isInvalidDecl() &&
8714       NewFD->getReturnType()->isVariablyModifiedType()) {
8715     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8716     NewFD->setInvalidDecl();
8717   }
8718
8719   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8720   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8721       !NewFD->hasAttr<SectionAttr>()) {
8722     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8723                                                  PragmaClangTextSection.SectionName,
8724                                                  PragmaClangTextSection.PragmaLocation));
8725   }
8726
8727   // Apply an implicit SectionAttr if #pragma code_seg is active.
8728   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8729       !NewFD->hasAttr<SectionAttr>()) {
8730     NewFD->addAttr(
8731         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8732                                     CodeSegStack.CurrentValue->getString(),
8733                                     CodeSegStack.CurrentPragmaLocation));
8734     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8735                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8736                          ASTContext::PSF_Read,
8737                      NewFD))
8738       NewFD->dropAttr<SectionAttr>();
8739   }
8740
8741   // Handle attributes.
8742   ProcessDeclAttributes(S, NewFD, D);
8743
8744   if (getLangOpts().OpenCL) {
8745     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8746     // type declaration will generate a compilation error.
8747     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8748     if (AddressSpace == LangAS::opencl_local ||
8749         AddressSpace == LangAS::opencl_global ||
8750         AddressSpace == LangAS::opencl_constant) {
8751       Diag(NewFD->getLocation(),
8752            diag::err_opencl_return_value_with_address_space);
8753       NewFD->setInvalidDecl();
8754     }
8755   }
8756
8757   if (!getLangOpts().CPlusPlus) {
8758     // Perform semantic checking on the function declaration.
8759     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8760       CheckMain(NewFD, D.getDeclSpec());
8761
8762     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8763       CheckMSVCRTEntryPoint(NewFD);
8764
8765     if (!NewFD->isInvalidDecl())
8766       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8767                                                   isMemberSpecialization));
8768     else if (!Previous.empty())
8769       // Recover gracefully from an invalid redeclaration.
8770       D.setRedeclaration(true);
8771     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8772             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8773            "previous declaration set still overloaded");
8774
8775     // Diagnose no-prototype function declarations with calling conventions that
8776     // don't support variadic calls. Only do this in C and do it after merging
8777     // possibly prototyped redeclarations.
8778     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8779     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8780       CallingConv CC = FT->getExtInfo().getCC();
8781       if (!supportsVariadicCall(CC)) {
8782         // Windows system headers sometimes accidentally use stdcall without
8783         // (void) parameters, so we relax this to a warning.
8784         int DiagID =
8785             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8786         Diag(NewFD->getLocation(), DiagID)
8787             << FunctionType::getNameForCallConv(CC);
8788       }
8789     }
8790   } else {
8791     // C++11 [replacement.functions]p3:
8792     //  The program's definitions shall not be specified as inline.
8793     //
8794     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8795     //
8796     // Suppress the diagnostic if the function is __attribute__((used)), since
8797     // that forces an external definition to be emitted.
8798     if (D.getDeclSpec().isInlineSpecified() &&
8799         NewFD->isReplaceableGlobalAllocationFunction() &&
8800         !NewFD->hasAttr<UsedAttr>())
8801       Diag(D.getDeclSpec().getInlineSpecLoc(),
8802            diag::ext_operator_new_delete_declared_inline)
8803         << NewFD->getDeclName();
8804
8805     // If the declarator is a template-id, translate the parser's template
8806     // argument list into our AST format.
8807     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8808       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8809       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8810       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8811       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8812                                          TemplateId->NumArgs);
8813       translateTemplateArguments(TemplateArgsPtr,
8814                                  TemplateArgs);
8815
8816       HasExplicitTemplateArgs = true;
8817
8818       if (NewFD->isInvalidDecl()) {
8819         HasExplicitTemplateArgs = false;
8820       } else if (FunctionTemplate) {
8821         // Function template with explicit template arguments.
8822         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8823           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8824
8825         HasExplicitTemplateArgs = false;
8826       } else {
8827         assert((isFunctionTemplateSpecialization ||
8828                 D.getDeclSpec().isFriendSpecified()) &&
8829                "should have a 'template<>' for this decl");
8830         // "friend void foo<>(int);" is an implicit specialization decl.
8831         isFunctionTemplateSpecialization = true;
8832       }
8833     } else if (isFriend && isFunctionTemplateSpecialization) {
8834       // This combination is only possible in a recovery case;  the user
8835       // wrote something like:
8836       //   template <> friend void foo(int);
8837       // which we're recovering from as if the user had written:
8838       //   friend void foo<>(int);
8839       // Go ahead and fake up a template id.
8840       HasExplicitTemplateArgs = true;
8841       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8842       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8843     }
8844
8845     // We do not add HD attributes to specializations here because
8846     // they may have different constexpr-ness compared to their
8847     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8848     // may end up with different effective targets. Instead, a
8849     // specialization inherits its target attributes from its template
8850     // in the CheckFunctionTemplateSpecialization() call below.
8851     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8852       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8853
8854     // If it's a friend (and only if it's a friend), it's possible
8855     // that either the specialized function type or the specialized
8856     // template is dependent, and therefore matching will fail.  In
8857     // this case, don't check the specialization yet.
8858     bool InstantiationDependent = false;
8859     if (isFunctionTemplateSpecialization && isFriend &&
8860         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8861          TemplateSpecializationType::anyDependentTemplateArguments(
8862             TemplateArgs,
8863             InstantiationDependent))) {
8864       assert(HasExplicitTemplateArgs &&
8865              "friend function specialization without template args");
8866       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8867                                                        Previous))
8868         NewFD->setInvalidDecl();
8869     } else if (isFunctionTemplateSpecialization) {
8870       if (CurContext->isDependentContext() && CurContext->isRecord()
8871           && !isFriend) {
8872         isDependentClassScopeExplicitSpecialization = true;
8873         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8874           diag::ext_function_specialization_in_class :
8875           diag::err_function_specialization_in_class)
8876           << NewFD->getDeclName();
8877       } else if (CheckFunctionTemplateSpecialization(NewFD,
8878                                   (HasExplicitTemplateArgs ? &TemplateArgs
8879                                                            : nullptr),
8880                                                      Previous))
8881         NewFD->setInvalidDecl();
8882
8883       // C++ [dcl.stc]p1:
8884       //   A storage-class-specifier shall not be specified in an explicit
8885       //   specialization (14.7.3)
8886       FunctionTemplateSpecializationInfo *Info =
8887           NewFD->getTemplateSpecializationInfo();
8888       if (Info && SC != SC_None) {
8889         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8890           Diag(NewFD->getLocation(),
8891                diag::err_explicit_specialization_inconsistent_storage_class)
8892             << SC
8893             << FixItHint::CreateRemoval(
8894                                       D.getDeclSpec().getStorageClassSpecLoc());
8895
8896         else
8897           Diag(NewFD->getLocation(),
8898                diag::ext_explicit_specialization_storage_class)
8899             << FixItHint::CreateRemoval(
8900                                       D.getDeclSpec().getStorageClassSpecLoc());
8901       }
8902     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8903       if (CheckMemberSpecialization(NewFD, Previous))
8904           NewFD->setInvalidDecl();
8905     }
8906
8907     // Perform semantic checking on the function declaration.
8908     if (!isDependentClassScopeExplicitSpecialization) {
8909       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8910         CheckMain(NewFD, D.getDeclSpec());
8911
8912       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8913         CheckMSVCRTEntryPoint(NewFD);
8914
8915       if (!NewFD->isInvalidDecl())
8916         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8917                                                     isMemberSpecialization));
8918       else if (!Previous.empty())
8919         // Recover gracefully from an invalid redeclaration.
8920         D.setRedeclaration(true);
8921     }
8922
8923     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8924             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8925            "previous declaration set still overloaded");
8926
8927     NamedDecl *PrincipalDecl = (FunctionTemplate
8928                                 ? cast<NamedDecl>(FunctionTemplate)
8929                                 : NewFD);
8930
8931     if (isFriend && NewFD->getPreviousDecl()) {
8932       AccessSpecifier Access = AS_public;
8933       if (!NewFD->isInvalidDecl())
8934         Access = NewFD->getPreviousDecl()->getAccess();
8935
8936       NewFD->setAccess(Access);
8937       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8938     }
8939
8940     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8941         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8942       PrincipalDecl->setNonMemberOperator();
8943
8944     // If we have a function template, check the template parameter
8945     // list. This will check and merge default template arguments.
8946     if (FunctionTemplate) {
8947       FunctionTemplateDecl *PrevTemplate =
8948                                      FunctionTemplate->getPreviousDecl();
8949       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8950                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8951                                     : nullptr,
8952                             D.getDeclSpec().isFriendSpecified()
8953                               ? (D.isFunctionDefinition()
8954                                    ? TPC_FriendFunctionTemplateDefinition
8955                                    : TPC_FriendFunctionTemplate)
8956                               : (D.getCXXScopeSpec().isSet() &&
8957                                  DC && DC->isRecord() &&
8958                                  DC->isDependentContext())
8959                                   ? TPC_ClassTemplateMember
8960                                   : TPC_FunctionTemplate);
8961     }
8962
8963     if (NewFD->isInvalidDecl()) {
8964       // Ignore all the rest of this.
8965     } else if (!D.isRedeclaration()) {
8966       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8967                                        AddToScope };
8968       // Fake up an access specifier if it's supposed to be a class member.
8969       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8970         NewFD->setAccess(AS_public);
8971
8972       // Qualified decls generally require a previous declaration.
8973       if (D.getCXXScopeSpec().isSet()) {
8974         // ...with the major exception of templated-scope or
8975         // dependent-scope friend declarations.
8976
8977         // TODO: we currently also suppress this check in dependent
8978         // contexts because (1) the parameter depth will be off when
8979         // matching friend templates and (2) we might actually be
8980         // selecting a friend based on a dependent factor.  But there
8981         // are situations where these conditions don't apply and we
8982         // can actually do this check immediately.
8983         if (isFriend &&
8984             (TemplateParamLists.size() ||
8985              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8986              CurContext->isDependentContext())) {
8987           // ignore these
8988         } else {
8989           // The user tried to provide an out-of-line definition for a
8990           // function that is a member of a class or namespace, but there
8991           // was no such member function declared (C++ [class.mfct]p2,
8992           // C++ [namespace.memdef]p2). For example:
8993           //
8994           // class X {
8995           //   void f() const;
8996           // };
8997           //
8998           // void X::f() { } // ill-formed
8999           //
9000           // Complain about this problem, and attempt to suggest close
9001           // matches (e.g., those that differ only in cv-qualifiers and
9002           // whether the parameter types are references).
9003
9004           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9005                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9006             AddToScope = ExtraArgs.AddToScope;
9007             return Result;
9008           }
9009         }
9010
9011         // Unqualified local friend declarations are required to resolve
9012         // to something.
9013       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9014         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9015                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9016           AddToScope = ExtraArgs.AddToScope;
9017           return Result;
9018         }
9019       }
9020     } else if (!D.isFunctionDefinition() &&
9021                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9022                !isFriend && !isFunctionTemplateSpecialization &&
9023                !isMemberSpecialization) {
9024       // An out-of-line member function declaration must also be a
9025       // definition (C++ [class.mfct]p2).
9026       // Note that this is not the case for explicit specializations of
9027       // function templates or member functions of class templates, per
9028       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9029       // extension for compatibility with old SWIG code which likes to
9030       // generate them.
9031       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9032         << D.getCXXScopeSpec().getRange();
9033     }
9034   }
9035
9036   ProcessPragmaWeak(S, NewFD);
9037   checkAttributesAfterMerging(*this, *NewFD);
9038
9039   AddKnownFunctionAttributes(NewFD);
9040
9041   if (NewFD->hasAttr<OverloadableAttr>() &&
9042       !NewFD->getType()->getAs<FunctionProtoType>()) {
9043     Diag(NewFD->getLocation(),
9044          diag::err_attribute_overloadable_no_prototype)
9045       << NewFD;
9046
9047     // Turn this into a variadic function with no parameters.
9048     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9049     FunctionProtoType::ExtProtoInfo EPI(
9050         Context.getDefaultCallingConvention(true, false));
9051     EPI.Variadic = true;
9052     EPI.ExtInfo = FT->getExtInfo();
9053
9054     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9055     NewFD->setType(R);
9056   }
9057
9058   // If there's a #pragma GCC visibility in scope, and this isn't a class
9059   // member, set the visibility of this function.
9060   if (!DC->isRecord() && NewFD->isExternallyVisible())
9061     AddPushedVisibilityAttribute(NewFD);
9062
9063   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9064   // marking the function.
9065   AddCFAuditedAttribute(NewFD);
9066
9067   // If this is a function definition, check if we have to apply optnone due to
9068   // a pragma.
9069   if(D.isFunctionDefinition())
9070     AddRangeBasedOptnone(NewFD);
9071
9072   // If this is the first declaration of an extern C variable, update
9073   // the map of such variables.
9074   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9075       isIncompleteDeclExternC(*this, NewFD))
9076     RegisterLocallyScopedExternCDecl(NewFD, S);
9077
9078   // Set this FunctionDecl's range up to the right paren.
9079   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9080
9081   if (D.isRedeclaration() && !Previous.empty()) {
9082     checkDLLAttributeRedeclaration(
9083         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9084         isMemberSpecialization || isFunctionTemplateSpecialization,
9085         D.isFunctionDefinition());
9086   }
9087
9088   if (getLangOpts().CUDA) {
9089     IdentifierInfo *II = NewFD->getIdentifier();
9090     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9091         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9092       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9093         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9094
9095       Context.setcudaConfigureCallDecl(NewFD);
9096     }
9097
9098     // Variadic functions, other than a *declaration* of printf, are not allowed
9099     // in device-side CUDA code, unless someone passed
9100     // -fcuda-allow-variadic-functions.
9101     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9102         (NewFD->hasAttr<CUDADeviceAttr>() ||
9103          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9104         !(II && II->isStr("printf") && NewFD->isExternC() &&
9105           !D.isFunctionDefinition())) {
9106       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9107     }
9108   }
9109
9110   MarkUnusedFileScopedDecl(NewFD);
9111
9112   if (getLangOpts().CPlusPlus) {
9113     if (FunctionTemplate) {
9114       if (NewFD->isInvalidDecl())
9115         FunctionTemplate->setInvalidDecl();
9116       return FunctionTemplate;
9117     }
9118
9119     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9120       CompleteMemberSpecialization(NewFD, Previous);
9121   }
9122
9123   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9124     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9125     if ((getLangOpts().OpenCLVersion >= 120)
9126         && (SC == SC_Static)) {
9127       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9128       D.setInvalidType();
9129     }
9130
9131     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9132     if (!NewFD->getReturnType()->isVoidType()) {
9133       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9134       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9135           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9136                                 : FixItHint());
9137       D.setInvalidType();
9138     }
9139
9140     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9141     for (auto Param : NewFD->parameters())
9142       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9143   }
9144   for (const ParmVarDecl *Param : NewFD->parameters()) {
9145     QualType PT = Param->getType();
9146
9147     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9148     // types.
9149     if (getLangOpts().OpenCLVersion >= 200) {
9150       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9151         QualType ElemTy = PipeTy->getElementType();
9152           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9153             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9154             D.setInvalidType();
9155           }
9156       }
9157     }
9158   }
9159
9160   // Here we have an function template explicit specialization at class scope.
9161   // The actually specialization will be postponed to template instatiation
9162   // time via the ClassScopeFunctionSpecializationDecl node.
9163   if (isDependentClassScopeExplicitSpecialization) {
9164     ClassScopeFunctionSpecializationDecl *NewSpec =
9165                          ClassScopeFunctionSpecializationDecl::Create(
9166                                 Context, CurContext, SourceLocation(),
9167                                 cast<CXXMethodDecl>(NewFD),
9168                                 HasExplicitTemplateArgs, TemplateArgs);
9169     CurContext->addDecl(NewSpec);
9170     AddToScope = false;
9171   }
9172
9173   return NewFD;
9174 }
9175
9176 /// \brief Checks if the new declaration declared in dependent context must be
9177 /// put in the same redeclaration chain as the specified declaration.
9178 ///
9179 /// \param D Declaration that is checked.
9180 /// \param PrevDecl Previous declaration found with proper lookup method for the
9181 ///                 same declaration name.
9182 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9183 ///          belongs to.
9184 ///
9185 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9186   // Any declarations should be put into redeclaration chains except for
9187   // friend declaration in a dependent context that names a function in
9188   // namespace scope.
9189   //
9190   // This allows to compile code like:
9191   //
9192   //       void func();
9193   //       template<typename T> class C1 { friend void func() { } };
9194   //       template<typename T> class C2 { friend void func() { } };
9195   //
9196   // This code snippet is a valid code unless both templates are instantiated.
9197   return !(D->getLexicalDeclContext()->isDependentContext() &&
9198            D->getDeclContext()->isFileContext() &&
9199            D->getFriendObjectKind() != Decl::FOK_None);
9200 }
9201
9202 /// \brief Perform semantic checking of a new function declaration.
9203 ///
9204 /// Performs semantic analysis of the new function declaration
9205 /// NewFD. This routine performs all semantic checking that does not
9206 /// require the actual declarator involved in the declaration, and is
9207 /// used both for the declaration of functions as they are parsed
9208 /// (called via ActOnDeclarator) and for the declaration of functions
9209 /// that have been instantiated via C++ template instantiation (called
9210 /// via InstantiateDecl).
9211 ///
9212 /// \param IsMemberSpecialization whether this new function declaration is
9213 /// a member specialization (that replaces any definition provided by the
9214 /// previous declaration).
9215 ///
9216 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9217 ///
9218 /// \returns true if the function declaration is a redeclaration.
9219 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9220                                     LookupResult &Previous,
9221                                     bool IsMemberSpecialization) {
9222   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9223          "Variably modified return types are not handled here");
9224
9225   // Determine whether the type of this function should be merged with
9226   // a previous visible declaration. This never happens for functions in C++,
9227   // and always happens in C if the previous declaration was visible.
9228   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9229                                !Previous.isShadowed();
9230
9231   bool Redeclaration = false;
9232   NamedDecl *OldDecl = nullptr;
9233   bool MayNeedOverloadableChecks = false;
9234
9235   // Merge or overload the declaration with an existing declaration of
9236   // the same name, if appropriate.
9237   if (!Previous.empty()) {
9238     // Determine whether NewFD is an overload of PrevDecl or
9239     // a declaration that requires merging. If it's an overload,
9240     // there's no more work to do here; we'll just add the new
9241     // function to the scope.
9242     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9243       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9244       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9245         Redeclaration = true;
9246         OldDecl = Candidate;
9247       }
9248     } else {
9249       MayNeedOverloadableChecks = true;
9250       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9251                             /*NewIsUsingDecl*/ false)) {
9252       case Ovl_Match:
9253         Redeclaration = true;
9254         break;
9255
9256       case Ovl_NonFunction:
9257         Redeclaration = true;
9258         break;
9259
9260       case Ovl_Overload:
9261         Redeclaration = false;
9262         break;
9263       }
9264     }
9265   }
9266
9267   // Check for a previous extern "C" declaration with this name.
9268   if (!Redeclaration &&
9269       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9270     if (!Previous.empty()) {
9271       // This is an extern "C" declaration with the same name as a previous
9272       // declaration, and thus redeclares that entity...
9273       Redeclaration = true;
9274       OldDecl = Previous.getFoundDecl();
9275       MergeTypeWithPrevious = false;
9276
9277       // ... except in the presence of __attribute__((overloadable)).
9278       if (OldDecl->hasAttr<OverloadableAttr>() ||
9279           NewFD->hasAttr<OverloadableAttr>()) {
9280         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9281           MayNeedOverloadableChecks = true;
9282           Redeclaration = false;
9283           OldDecl = nullptr;
9284         }
9285       }
9286     }
9287   }
9288
9289   // C++11 [dcl.constexpr]p8:
9290   //   A constexpr specifier for a non-static member function that is not
9291   //   a constructor declares that member function to be const.
9292   //
9293   // This needs to be delayed until we know whether this is an out-of-line
9294   // definition of a static member function.
9295   //
9296   // This rule is not present in C++1y, so we produce a backwards
9297   // compatibility warning whenever it happens in C++11.
9298   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9299   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9300       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9301       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9302     CXXMethodDecl *OldMD = nullptr;
9303     if (OldDecl)
9304       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9305     if (!OldMD || !OldMD->isStatic()) {
9306       const FunctionProtoType *FPT =
9307         MD->getType()->castAs<FunctionProtoType>();
9308       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9309       EPI.TypeQuals |= Qualifiers::Const;
9310       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9311                                           FPT->getParamTypes(), EPI));
9312
9313       // Warn that we did this, if we're not performing template instantiation.
9314       // In that case, we'll have warned already when the template was defined.
9315       if (!inTemplateInstantiation()) {
9316         SourceLocation AddConstLoc;
9317         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9318                 .IgnoreParens().getAs<FunctionTypeLoc>())
9319           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9320
9321         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9322           << FixItHint::CreateInsertion(AddConstLoc, " const");
9323       }
9324     }
9325   }
9326
9327   if (Redeclaration) {
9328     // NewFD and OldDecl represent declarations that need to be
9329     // merged.
9330     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9331       NewFD->setInvalidDecl();
9332       return Redeclaration;
9333     }
9334
9335     Previous.clear();
9336     Previous.addDecl(OldDecl);
9337
9338     if (FunctionTemplateDecl *OldTemplateDecl
9339                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9340       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9341       FunctionTemplateDecl *NewTemplateDecl
9342         = NewFD->getDescribedFunctionTemplate();
9343       assert(NewTemplateDecl && "Template/non-template mismatch");
9344       if (CXXMethodDecl *Method
9345             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9346         Method->setAccess(OldTemplateDecl->getAccess());
9347         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9348       }
9349
9350       // If this is an explicit specialization of a member that is a function
9351       // template, mark it as a member specialization.
9352       if (IsMemberSpecialization &&
9353           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9354         NewTemplateDecl->setMemberSpecialization();
9355         assert(OldTemplateDecl->isMemberSpecialization());
9356         // Explicit specializations of a member template do not inherit deleted
9357         // status from the parent member template that they are specializing.
9358         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9359           FunctionDecl *const OldTemplatedDecl =
9360               OldTemplateDecl->getTemplatedDecl();
9361           // FIXME: This assert will not hold in the presence of modules.
9362           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9363           // FIXME: We need an update record for this AST mutation.
9364           OldTemplatedDecl->setDeletedAsWritten(false);
9365         }
9366       }
9367
9368     } else {
9369       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9370         // This needs to happen first so that 'inline' propagates.
9371         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9372         if (isa<CXXMethodDecl>(NewFD))
9373           NewFD->setAccess(OldDecl->getAccess());
9374       }
9375     }
9376   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9377              !NewFD->getAttr<OverloadableAttr>()) {
9378     assert((Previous.empty() ||
9379             llvm::any_of(Previous,
9380                          [](const NamedDecl *ND) {
9381                            return ND->hasAttr<OverloadableAttr>();
9382                          })) &&
9383            "Non-redecls shouldn't happen without overloadable present");
9384
9385     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9386       const auto *FD = dyn_cast<FunctionDecl>(ND);
9387       return FD && !FD->hasAttr<OverloadableAttr>();
9388     });
9389
9390     if (OtherUnmarkedIter != Previous.end()) {
9391       Diag(NewFD->getLocation(),
9392            diag::err_attribute_overloadable_multiple_unmarked_overloads);
9393       Diag((*OtherUnmarkedIter)->getLocation(),
9394            diag::note_attribute_overloadable_prev_overload)
9395           << false;
9396
9397       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9398     }
9399   }
9400
9401   // Semantic checking for this function declaration (in isolation).
9402
9403   if (getLangOpts().CPlusPlus) {
9404     // C++-specific checks.
9405     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9406       CheckConstructor(Constructor);
9407     } else if (CXXDestructorDecl *Destructor =
9408                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9409       CXXRecordDecl *Record = Destructor->getParent();
9410       QualType ClassType = Context.getTypeDeclType(Record);
9411
9412       // FIXME: Shouldn't we be able to perform this check even when the class
9413       // type is dependent? Both gcc and edg can handle that.
9414       if (!ClassType->isDependentType()) {
9415         DeclarationName Name
9416           = Context.DeclarationNames.getCXXDestructorName(
9417                                         Context.getCanonicalType(ClassType));
9418         if (NewFD->getDeclName() != Name) {
9419           Diag(NewFD->getLocation(), diag::err_destructor_name);
9420           NewFD->setInvalidDecl();
9421           return Redeclaration;
9422         }
9423       }
9424     } else if (CXXConversionDecl *Conversion
9425                = dyn_cast<CXXConversionDecl>(NewFD)) {
9426       ActOnConversionDeclarator(Conversion);
9427     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9428       if (auto *TD = Guide->getDescribedFunctionTemplate())
9429         CheckDeductionGuideTemplate(TD);
9430
9431       // A deduction guide is not on the list of entities that can be
9432       // explicitly specialized.
9433       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9434         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9435             << /*explicit specialization*/ 1;
9436     }
9437
9438     // Find any virtual functions that this function overrides.
9439     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9440       if (!Method->isFunctionTemplateSpecialization() &&
9441           !Method->getDescribedFunctionTemplate() &&
9442           Method->isCanonicalDecl()) {
9443         if (AddOverriddenMethods(Method->getParent(), Method)) {
9444           // If the function was marked as "static", we have a problem.
9445           if (NewFD->getStorageClass() == SC_Static) {
9446             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9447           }
9448         }
9449       }
9450
9451       if (Method->isStatic())
9452         checkThisInStaticMemberFunctionType(Method);
9453     }
9454
9455     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9456     if (NewFD->isOverloadedOperator() &&
9457         CheckOverloadedOperatorDeclaration(NewFD)) {
9458       NewFD->setInvalidDecl();
9459       return Redeclaration;
9460     }
9461
9462     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9463     if (NewFD->getLiteralIdentifier() &&
9464         CheckLiteralOperatorDeclaration(NewFD)) {
9465       NewFD->setInvalidDecl();
9466       return Redeclaration;
9467     }
9468
9469     // In C++, check default arguments now that we have merged decls. Unless
9470     // the lexical context is the class, because in this case this is done
9471     // during delayed parsing anyway.
9472     if (!CurContext->isRecord())
9473       CheckCXXDefaultArguments(NewFD);
9474
9475     // If this function declares a builtin function, check the type of this
9476     // declaration against the expected type for the builtin.
9477     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9478       ASTContext::GetBuiltinTypeError Error;
9479       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9480       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9481       // If the type of the builtin differs only in its exception
9482       // specification, that's OK.
9483       // FIXME: If the types do differ in this way, it would be better to
9484       // retain the 'noexcept' form of the type.
9485       if (!T.isNull() &&
9486           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9487                                                             NewFD->getType()))
9488         // The type of this function differs from the type of the builtin,
9489         // so forget about the builtin entirely.
9490         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9491     }
9492
9493     // If this function is declared as being extern "C", then check to see if
9494     // the function returns a UDT (class, struct, or union type) that is not C
9495     // compatible, and if it does, warn the user.
9496     // But, issue any diagnostic on the first declaration only.
9497     if (Previous.empty() && NewFD->isExternC()) {
9498       QualType R = NewFD->getReturnType();
9499       if (R->isIncompleteType() && !R->isVoidType())
9500         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9501             << NewFD << R;
9502       else if (!R.isPODType(Context) && !R->isVoidType() &&
9503                !R->isObjCObjectPointerType())
9504         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9505     }
9506
9507     // C++1z [dcl.fct]p6:
9508     //   [...] whether the function has a non-throwing exception-specification
9509     //   [is] part of the function type
9510     //
9511     // This results in an ABI break between C++14 and C++17 for functions whose
9512     // declared type includes an exception-specification in a parameter or
9513     // return type. (Exception specifications on the function itself are OK in
9514     // most cases, and exception specifications are not permitted in most other
9515     // contexts where they could make it into a mangling.)
9516     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9517       auto HasNoexcept = [&](QualType T) -> bool {
9518         // Strip off declarator chunks that could be between us and a function
9519         // type. We don't need to look far, exception specifications are very
9520         // restricted prior to C++17.
9521         if (auto *RT = T->getAs<ReferenceType>())
9522           T = RT->getPointeeType();
9523         else if (T->isAnyPointerType())
9524           T = T->getPointeeType();
9525         else if (auto *MPT = T->getAs<MemberPointerType>())
9526           T = MPT->getPointeeType();
9527         if (auto *FPT = T->getAs<FunctionProtoType>())
9528           if (FPT->isNothrow(Context))
9529             return true;
9530         return false;
9531       };
9532
9533       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9534       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9535       for (QualType T : FPT->param_types())
9536         AnyNoexcept |= HasNoexcept(T);
9537       if (AnyNoexcept)
9538         Diag(NewFD->getLocation(),
9539              diag::warn_cxx1z_compat_exception_spec_in_signature)
9540             << NewFD;
9541     }
9542
9543     if (!Redeclaration && LangOpts.CUDA)
9544       checkCUDATargetOverload(NewFD, Previous);
9545   }
9546   return Redeclaration;
9547 }
9548
9549 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9550   // C++11 [basic.start.main]p3:
9551   //   A program that [...] declares main to be inline, static or
9552   //   constexpr is ill-formed.
9553   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9554   //   appear in a declaration of main.
9555   // static main is not an error under C99, but we should warn about it.
9556   // We accept _Noreturn main as an extension.
9557   if (FD->getStorageClass() == SC_Static)
9558     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9559          ? diag::err_static_main : diag::warn_static_main)
9560       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9561   if (FD->isInlineSpecified())
9562     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9563       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9564   if (DS.isNoreturnSpecified()) {
9565     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9566     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9567     Diag(NoreturnLoc, diag::ext_noreturn_main);
9568     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9569       << FixItHint::CreateRemoval(NoreturnRange);
9570   }
9571   if (FD->isConstexpr()) {
9572     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9573       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9574     FD->setConstexpr(false);
9575   }
9576
9577   if (getLangOpts().OpenCL) {
9578     Diag(FD->getLocation(), diag::err_opencl_no_main)
9579         << FD->hasAttr<OpenCLKernelAttr>();
9580     FD->setInvalidDecl();
9581     return;
9582   }
9583
9584   QualType T = FD->getType();
9585   assert(T->isFunctionType() && "function decl is not of function type");
9586   const FunctionType* FT = T->castAs<FunctionType>();
9587
9588   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9589     // In C with GNU extensions we allow main() to have non-integer return
9590     // type, but we should warn about the extension, and we disable the
9591     // implicit-return-zero rule.
9592
9593     // GCC in C mode accepts qualified 'int'.
9594     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9595       FD->setHasImplicitReturnZero(true);
9596     else {
9597       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9598       SourceRange RTRange = FD->getReturnTypeSourceRange();
9599       if (RTRange.isValid())
9600         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9601             << FixItHint::CreateReplacement(RTRange, "int");
9602     }
9603   } else {
9604     // In C and C++, main magically returns 0 if you fall off the end;
9605     // set the flag which tells us that.
9606     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9607
9608     // All the standards say that main() should return 'int'.
9609     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9610       FD->setHasImplicitReturnZero(true);
9611     else {
9612       // Otherwise, this is just a flat-out error.
9613       SourceRange RTRange = FD->getReturnTypeSourceRange();
9614       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9615           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9616                                 : FixItHint());
9617       FD->setInvalidDecl(true);
9618     }
9619   }
9620
9621   // Treat protoless main() as nullary.
9622   if (isa<FunctionNoProtoType>(FT)) return;
9623
9624   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9625   unsigned nparams = FTP->getNumParams();
9626   assert(FD->getNumParams() == nparams);
9627
9628   bool HasExtraParameters = (nparams > 3);
9629
9630   if (FTP->isVariadic()) {
9631     Diag(FD->getLocation(), diag::ext_variadic_main);
9632     // FIXME: if we had information about the location of the ellipsis, we
9633     // could add a FixIt hint to remove it as a parameter.
9634   }
9635
9636   // Darwin passes an undocumented fourth argument of type char**.  If
9637   // other platforms start sprouting these, the logic below will start
9638   // getting shifty.
9639   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9640     HasExtraParameters = false;
9641
9642   if (HasExtraParameters) {
9643     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9644     FD->setInvalidDecl(true);
9645     nparams = 3;
9646   }
9647
9648   // FIXME: a lot of the following diagnostics would be improved
9649   // if we had some location information about types.
9650
9651   QualType CharPP =
9652     Context.getPointerType(Context.getPointerType(Context.CharTy));
9653   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9654
9655   for (unsigned i = 0; i < nparams; ++i) {
9656     QualType AT = FTP->getParamType(i);
9657
9658     bool mismatch = true;
9659
9660     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9661       mismatch = false;
9662     else if (Expected[i] == CharPP) {
9663       // As an extension, the following forms are okay:
9664       //   char const **
9665       //   char const * const *
9666       //   char * const *
9667
9668       QualifierCollector qs;
9669       const PointerType* PT;
9670       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9671           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9672           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9673                               Context.CharTy)) {
9674         qs.removeConst();
9675         mismatch = !qs.empty();
9676       }
9677     }
9678
9679     if (mismatch) {
9680       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9681       // TODO: suggest replacing given type with expected type
9682       FD->setInvalidDecl(true);
9683     }
9684   }
9685
9686   if (nparams == 1 && !FD->isInvalidDecl()) {
9687     Diag(FD->getLocation(), diag::warn_main_one_arg);
9688   }
9689
9690   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9691     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9692     FD->setInvalidDecl();
9693   }
9694 }
9695
9696 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9697   QualType T = FD->getType();
9698   assert(T->isFunctionType() && "function decl is not of function type");
9699   const FunctionType *FT = T->castAs<FunctionType>();
9700
9701   // Set an implicit return of 'zero' if the function can return some integral,
9702   // enumeration, pointer or nullptr type.
9703   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9704       FT->getReturnType()->isAnyPointerType() ||
9705       FT->getReturnType()->isNullPtrType())
9706     // DllMain is exempt because a return value of zero means it failed.
9707     if (FD->getName() != "DllMain")
9708       FD->setHasImplicitReturnZero(true);
9709
9710   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9711     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9712     FD->setInvalidDecl();
9713   }
9714 }
9715
9716 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9717   // FIXME: Need strict checking.  In C89, we need to check for
9718   // any assignment, increment, decrement, function-calls, or
9719   // commas outside of a sizeof.  In C99, it's the same list,
9720   // except that the aforementioned are allowed in unevaluated
9721   // expressions.  Everything else falls under the
9722   // "may accept other forms of constant expressions" exception.
9723   // (We never end up here for C++, so the constant expression
9724   // rules there don't matter.)
9725   const Expr *Culprit;
9726   if (Init->isConstantInitializer(Context, false, &Culprit))
9727     return false;
9728   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9729     << Culprit->getSourceRange();
9730   return true;
9731 }
9732
9733 namespace {
9734   // Visits an initialization expression to see if OrigDecl is evaluated in
9735   // its own initialization and throws a warning if it does.
9736   class SelfReferenceChecker
9737       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9738     Sema &S;
9739     Decl *OrigDecl;
9740     bool isRecordType;
9741     bool isPODType;
9742     bool isReferenceType;
9743
9744     bool isInitList;
9745     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9746
9747   public:
9748     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9749
9750     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9751                                                     S(S), OrigDecl(OrigDecl) {
9752       isPODType = false;
9753       isRecordType = false;
9754       isReferenceType = false;
9755       isInitList = false;
9756       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9757         isPODType = VD->getType().isPODType(S.Context);
9758         isRecordType = VD->getType()->isRecordType();
9759         isReferenceType = VD->getType()->isReferenceType();
9760       }
9761     }
9762
9763     // For most expressions, just call the visitor.  For initializer lists,
9764     // track the index of the field being initialized since fields are
9765     // initialized in order allowing use of previously initialized fields.
9766     void CheckExpr(Expr *E) {
9767       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9768       if (!InitList) {
9769         Visit(E);
9770         return;
9771       }
9772
9773       // Track and increment the index here.
9774       isInitList = true;
9775       InitFieldIndex.push_back(0);
9776       for (auto Child : InitList->children()) {
9777         CheckExpr(cast<Expr>(Child));
9778         ++InitFieldIndex.back();
9779       }
9780       InitFieldIndex.pop_back();
9781     }
9782
9783     // Returns true if MemberExpr is checked and no further checking is needed.
9784     // Returns false if additional checking is required.
9785     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9786       llvm::SmallVector<FieldDecl*, 4> Fields;
9787       Expr *Base = E;
9788       bool ReferenceField = false;
9789
9790       // Get the field memebers used.
9791       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9792         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9793         if (!FD)
9794           return false;
9795         Fields.push_back(FD);
9796         if (FD->getType()->isReferenceType())
9797           ReferenceField = true;
9798         Base = ME->getBase()->IgnoreParenImpCasts();
9799       }
9800
9801       // Keep checking only if the base Decl is the same.
9802       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9803       if (!DRE || DRE->getDecl() != OrigDecl)
9804         return false;
9805
9806       // A reference field can be bound to an unininitialized field.
9807       if (CheckReference && !ReferenceField)
9808         return true;
9809
9810       // Convert FieldDecls to their index number.
9811       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9812       for (const FieldDecl *I : llvm::reverse(Fields))
9813         UsedFieldIndex.push_back(I->getFieldIndex());
9814
9815       // See if a warning is needed by checking the first difference in index
9816       // numbers.  If field being used has index less than the field being
9817       // initialized, then the use is safe.
9818       for (auto UsedIter = UsedFieldIndex.begin(),
9819                 UsedEnd = UsedFieldIndex.end(),
9820                 OrigIter = InitFieldIndex.begin(),
9821                 OrigEnd = InitFieldIndex.end();
9822            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9823         if (*UsedIter < *OrigIter)
9824           return true;
9825         if (*UsedIter > *OrigIter)
9826           break;
9827       }
9828
9829       // TODO: Add a different warning which will print the field names.
9830       HandleDeclRefExpr(DRE);
9831       return true;
9832     }
9833
9834     // For most expressions, the cast is directly above the DeclRefExpr.
9835     // For conditional operators, the cast can be outside the conditional
9836     // operator if both expressions are DeclRefExpr's.
9837     void HandleValue(Expr *E) {
9838       E = E->IgnoreParens();
9839       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9840         HandleDeclRefExpr(DRE);
9841         return;
9842       }
9843
9844       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9845         Visit(CO->getCond());
9846         HandleValue(CO->getTrueExpr());
9847         HandleValue(CO->getFalseExpr());
9848         return;
9849       }
9850
9851       if (BinaryConditionalOperator *BCO =
9852               dyn_cast<BinaryConditionalOperator>(E)) {
9853         Visit(BCO->getCond());
9854         HandleValue(BCO->getFalseExpr());
9855         return;
9856       }
9857
9858       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9859         HandleValue(OVE->getSourceExpr());
9860         return;
9861       }
9862
9863       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9864         if (BO->getOpcode() == BO_Comma) {
9865           Visit(BO->getLHS());
9866           HandleValue(BO->getRHS());
9867           return;
9868         }
9869       }
9870
9871       if (isa<MemberExpr>(E)) {
9872         if (isInitList) {
9873           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9874                                       false /*CheckReference*/))
9875             return;
9876         }
9877
9878         Expr *Base = E->IgnoreParenImpCasts();
9879         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9880           // Check for static member variables and don't warn on them.
9881           if (!isa<FieldDecl>(ME->getMemberDecl()))
9882             return;
9883           Base = ME->getBase()->IgnoreParenImpCasts();
9884         }
9885         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9886           HandleDeclRefExpr(DRE);
9887         return;
9888       }
9889
9890       Visit(E);
9891     }
9892
9893     // Reference types not handled in HandleValue are handled here since all
9894     // uses of references are bad, not just r-value uses.
9895     void VisitDeclRefExpr(DeclRefExpr *E) {
9896       if (isReferenceType)
9897         HandleDeclRefExpr(E);
9898     }
9899
9900     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9901       if (E->getCastKind() == CK_LValueToRValue) {
9902         HandleValue(E->getSubExpr());
9903         return;
9904       }
9905
9906       Inherited::VisitImplicitCastExpr(E);
9907     }
9908
9909     void VisitMemberExpr(MemberExpr *E) {
9910       if (isInitList) {
9911         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9912           return;
9913       }
9914
9915       // Don't warn on arrays since they can be treated as pointers.
9916       if (E->getType()->canDecayToPointerType()) return;
9917
9918       // Warn when a non-static method call is followed by non-static member
9919       // field accesses, which is followed by a DeclRefExpr.
9920       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9921       bool Warn = (MD && !MD->isStatic());
9922       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9923       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9924         if (!isa<FieldDecl>(ME->getMemberDecl()))
9925           Warn = false;
9926         Base = ME->getBase()->IgnoreParenImpCasts();
9927       }
9928
9929       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9930         if (Warn)
9931           HandleDeclRefExpr(DRE);
9932         return;
9933       }
9934
9935       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9936       // Visit that expression.
9937       Visit(Base);
9938     }
9939
9940     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9941       Expr *Callee = E->getCallee();
9942
9943       if (isa<UnresolvedLookupExpr>(Callee))
9944         return Inherited::VisitCXXOperatorCallExpr(E);
9945
9946       Visit(Callee);
9947       for (auto Arg: E->arguments())
9948         HandleValue(Arg->IgnoreParenImpCasts());
9949     }
9950
9951     void VisitUnaryOperator(UnaryOperator *E) {
9952       // For POD record types, addresses of its own members are well-defined.
9953       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9954           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9955         if (!isPODType)
9956           HandleValue(E->getSubExpr());
9957         return;
9958       }
9959
9960       if (E->isIncrementDecrementOp()) {
9961         HandleValue(E->getSubExpr());
9962         return;
9963       }
9964
9965       Inherited::VisitUnaryOperator(E);
9966     }
9967
9968     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9969
9970     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9971       if (E->getConstructor()->isCopyConstructor()) {
9972         Expr *ArgExpr = E->getArg(0);
9973         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9974           if (ILE->getNumInits() == 1)
9975             ArgExpr = ILE->getInit(0);
9976         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9977           if (ICE->getCastKind() == CK_NoOp)
9978             ArgExpr = ICE->getSubExpr();
9979         HandleValue(ArgExpr);
9980         return;
9981       }
9982       Inherited::VisitCXXConstructExpr(E);
9983     }
9984
9985     void VisitCallExpr(CallExpr *E) {
9986       // Treat std::move as a use.
9987       if (E->getNumArgs() == 1) {
9988         if (FunctionDecl *FD = E->getDirectCallee()) {
9989           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9990               FD->getIdentifier()->isStr("move")) {
9991             HandleValue(E->getArg(0));
9992             return;
9993           }
9994         }
9995       }
9996
9997       Inherited::VisitCallExpr(E);
9998     }
9999
10000     void VisitBinaryOperator(BinaryOperator *E) {
10001       if (E->isCompoundAssignmentOp()) {
10002         HandleValue(E->getLHS());
10003         Visit(E->getRHS());
10004         return;
10005       }
10006
10007       Inherited::VisitBinaryOperator(E);
10008     }
10009
10010     // A custom visitor for BinaryConditionalOperator is needed because the
10011     // regular visitor would check the condition and true expression separately
10012     // but both point to the same place giving duplicate diagnostics.
10013     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10014       Visit(E->getCond());
10015       Visit(E->getFalseExpr());
10016     }
10017
10018     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10019       Decl* ReferenceDecl = DRE->getDecl();
10020       if (OrigDecl != ReferenceDecl) return;
10021       unsigned diag;
10022       if (isReferenceType) {
10023         diag = diag::warn_uninit_self_reference_in_reference_init;
10024       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10025         diag = diag::warn_static_self_reference_in_init;
10026       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10027                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10028                  DRE->getDecl()->getType()->isRecordType()) {
10029         diag = diag::warn_uninit_self_reference_in_init;
10030       } else {
10031         // Local variables will be handled by the CFG analysis.
10032         return;
10033       }
10034
10035       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10036                             S.PDiag(diag)
10037                               << DRE->getNameInfo().getName()
10038                               << OrigDecl->getLocation()
10039                               << DRE->getSourceRange());
10040     }
10041   };
10042
10043   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10044   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10045                                  bool DirectInit) {
10046     // Parameters arguments are occassionially constructed with itself,
10047     // for instance, in recursive functions.  Skip them.
10048     if (isa<ParmVarDecl>(OrigDecl))
10049       return;
10050
10051     E = E->IgnoreParens();
10052
10053     // Skip checking T a = a where T is not a record or reference type.
10054     // Doing so is a way to silence uninitialized warnings.
10055     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10056       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10057         if (ICE->getCastKind() == CK_LValueToRValue)
10058           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10059             if (DRE->getDecl() == OrigDecl)
10060               return;
10061
10062     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10063   }
10064 } // end anonymous namespace
10065
10066 namespace {
10067   // Simple wrapper to add the name of a variable or (if no variable is
10068   // available) a DeclarationName into a diagnostic.
10069   struct VarDeclOrName {
10070     VarDecl *VDecl;
10071     DeclarationName Name;
10072
10073     friend const Sema::SemaDiagnosticBuilder &
10074     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10075       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10076     }
10077   };
10078 } // end anonymous namespace
10079
10080 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10081                                             DeclarationName Name, QualType Type,
10082                                             TypeSourceInfo *TSI,
10083                                             SourceRange Range, bool DirectInit,
10084                                             Expr *Init) {
10085   bool IsInitCapture = !VDecl;
10086   assert((!VDecl || !VDecl->isInitCapture()) &&
10087          "init captures are expected to be deduced prior to initialization");
10088
10089   VarDeclOrName VN{VDecl, Name};
10090
10091   DeducedType *Deduced = Type->getContainedDeducedType();
10092   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10093
10094   // C++11 [dcl.spec.auto]p3
10095   if (!Init) {
10096     assert(VDecl && "no init for init capture deduction?");
10097     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10098       << VDecl->getDeclName() << Type;
10099     return QualType();
10100   }
10101
10102   ArrayRef<Expr*> DeduceInits = Init;
10103   if (DirectInit) {
10104     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10105       DeduceInits = PL->exprs();
10106   }
10107
10108   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10109     assert(VDecl && "non-auto type for init capture deduction?");
10110     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10111     InitializationKind Kind = InitializationKind::CreateForInit(
10112         VDecl->getLocation(), DirectInit, Init);
10113     // FIXME: Initialization should not be taking a mutable list of inits. 
10114     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10115     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10116                                                        InitsCopy);
10117   }
10118
10119   if (DirectInit) {
10120     if (auto *IL = dyn_cast<InitListExpr>(Init))
10121       DeduceInits = IL->inits();
10122   }
10123
10124   // Deduction only works if we have exactly one source expression.
10125   if (DeduceInits.empty()) {
10126     // It isn't possible to write this directly, but it is possible to
10127     // end up in this situation with "auto x(some_pack...);"
10128     Diag(Init->getLocStart(), IsInitCapture
10129                                   ? diag::err_init_capture_no_expression
10130                                   : diag::err_auto_var_init_no_expression)
10131         << VN << Type << Range;
10132     return QualType();
10133   }
10134
10135   if (DeduceInits.size() > 1) {
10136     Diag(DeduceInits[1]->getLocStart(),
10137          IsInitCapture ? diag::err_init_capture_multiple_expressions
10138                        : diag::err_auto_var_init_multiple_expressions)
10139         << VN << Type << Range;
10140     return QualType();
10141   }
10142
10143   Expr *DeduceInit = DeduceInits[0];
10144   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10145     Diag(Init->getLocStart(), IsInitCapture
10146                                   ? diag::err_init_capture_paren_braces
10147                                   : diag::err_auto_var_init_paren_braces)
10148         << isa<InitListExpr>(Init) << VN << Type << Range;
10149     return QualType();
10150   }
10151
10152   // Expressions default to 'id' when we're in a debugger.
10153   bool DefaultedAnyToId = false;
10154   if (getLangOpts().DebuggerCastResultToId &&
10155       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10156     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10157     if (Result.isInvalid()) {
10158       return QualType();
10159     }
10160     Init = Result.get();
10161     DefaultedAnyToId = true;
10162   }
10163
10164   // C++ [dcl.decomp]p1:
10165   //   If the assignment-expression [...] has array type A and no ref-qualifier
10166   //   is present, e has type cv A
10167   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10168       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10169       DeduceInit->getType()->isConstantArrayType())
10170     return Context.getQualifiedType(DeduceInit->getType(),
10171                                     Type.getQualifiers());
10172
10173   QualType DeducedType;
10174   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10175     if (!IsInitCapture)
10176       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10177     else if (isa<InitListExpr>(Init))
10178       Diag(Range.getBegin(),
10179            diag::err_init_capture_deduction_failure_from_init_list)
10180           << VN
10181           << (DeduceInit->getType().isNull() ? TSI->getType()
10182                                              : DeduceInit->getType())
10183           << DeduceInit->getSourceRange();
10184     else
10185       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10186           << VN << TSI->getType()
10187           << (DeduceInit->getType().isNull() ? TSI->getType()
10188                                              : DeduceInit->getType())
10189           << DeduceInit->getSourceRange();
10190   }
10191
10192   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10193   // 'id' instead of a specific object type prevents most of our usual
10194   // checks.
10195   // We only want to warn outside of template instantiations, though:
10196   // inside a template, the 'id' could have come from a parameter.
10197   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10198       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10199     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10200     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10201   }
10202
10203   return DeducedType;
10204 }
10205
10206 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10207                                          Expr *Init) {
10208   QualType DeducedType = deduceVarTypeFromInitializer(
10209       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10210       VDecl->getSourceRange(), DirectInit, Init);
10211   if (DeducedType.isNull()) {
10212     VDecl->setInvalidDecl();
10213     return true;
10214   }
10215
10216   VDecl->setType(DeducedType);
10217   assert(VDecl->isLinkageValid());
10218
10219   // In ARC, infer lifetime.
10220   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10221     VDecl->setInvalidDecl();
10222
10223   // If this is a redeclaration, check that the type we just deduced matches
10224   // the previously declared type.
10225   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10226     // We never need to merge the type, because we cannot form an incomplete
10227     // array of auto, nor deduce such a type.
10228     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10229   }
10230
10231   // Check the deduced type is valid for a variable declaration.
10232   CheckVariableDeclarationType(VDecl);
10233   return VDecl->isInvalidDecl();
10234 }
10235
10236 /// AddInitializerToDecl - Adds the initializer Init to the
10237 /// declaration dcl. If DirectInit is true, this is C++ direct
10238 /// initialization rather than copy initialization.
10239 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10240   // If there is no declaration, there was an error parsing it.  Just ignore
10241   // the initializer.
10242   if (!RealDecl || RealDecl->isInvalidDecl()) {
10243     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10244     return;
10245   }
10246
10247   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10248     // Pure-specifiers are handled in ActOnPureSpecifier.
10249     Diag(Method->getLocation(), diag::err_member_function_initialization)
10250       << Method->getDeclName() << Init->getSourceRange();
10251     Method->setInvalidDecl();
10252     return;
10253   }
10254
10255   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10256   if (!VDecl) {
10257     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10258     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10259     RealDecl->setInvalidDecl();
10260     return;
10261   }
10262
10263   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10264   if (VDecl->getType()->isUndeducedType()) {
10265     // Attempt typo correction early so that the type of the init expression can
10266     // be deduced based on the chosen correction if the original init contains a
10267     // TypoExpr.
10268     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10269     if (!Res.isUsable()) {
10270       RealDecl->setInvalidDecl();
10271       return;
10272     }
10273     Init = Res.get();
10274
10275     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10276       return;
10277   }
10278
10279   // dllimport cannot be used on variable definitions.
10280   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10281     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10282     VDecl->setInvalidDecl();
10283     return;
10284   }
10285
10286   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10287     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10288     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10289     VDecl->setInvalidDecl();
10290     return;
10291   }
10292
10293   if (!VDecl->getType()->isDependentType()) {
10294     // A definition must end up with a complete type, which means it must be
10295     // complete with the restriction that an array type might be completed by
10296     // the initializer; note that later code assumes this restriction.
10297     QualType BaseDeclType = VDecl->getType();
10298     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10299       BaseDeclType = Array->getElementType();
10300     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10301                             diag::err_typecheck_decl_incomplete_type)) {
10302       RealDecl->setInvalidDecl();
10303       return;
10304     }
10305
10306     // The variable can not have an abstract class type.
10307     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10308                                diag::err_abstract_type_in_decl,
10309                                AbstractVariableType))
10310       VDecl->setInvalidDecl();
10311   }
10312
10313   // If adding the initializer will turn this declaration into a definition,
10314   // and we already have a definition for this variable, diagnose or otherwise
10315   // handle the situation.
10316   VarDecl *Def;
10317   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10318       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10319       !VDecl->isThisDeclarationADemotedDefinition() &&
10320       checkVarDeclRedefinition(Def, VDecl))
10321     return;
10322
10323   if (getLangOpts().CPlusPlus) {
10324     // C++ [class.static.data]p4
10325     //   If a static data member is of const integral or const
10326     //   enumeration type, its declaration in the class definition can
10327     //   specify a constant-initializer which shall be an integral
10328     //   constant expression (5.19). In that case, the member can appear
10329     //   in integral constant expressions. The member shall still be
10330     //   defined in a namespace scope if it is used in the program and the
10331     //   namespace scope definition shall not contain an initializer.
10332     //
10333     // We already performed a redefinition check above, but for static
10334     // data members we also need to check whether there was an in-class
10335     // declaration with an initializer.
10336     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10337       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10338           << VDecl->getDeclName();
10339       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10340            diag::note_previous_initializer)
10341           << 0;
10342       return;
10343     }
10344
10345     if (VDecl->hasLocalStorage())
10346       getCurFunction()->setHasBranchProtectedScope();
10347
10348     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10349       VDecl->setInvalidDecl();
10350       return;
10351     }
10352   }
10353
10354   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10355   // a kernel function cannot be initialized."
10356   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10357     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10358     VDecl->setInvalidDecl();
10359     return;
10360   }
10361
10362   // Get the decls type and save a reference for later, since
10363   // CheckInitializerTypes may change it.
10364   QualType DclT = VDecl->getType(), SavT = DclT;
10365
10366   // Expressions default to 'id' when we're in a debugger
10367   // and we are assigning it to a variable of Objective-C pointer type.
10368   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10369       Init->getType() == Context.UnknownAnyTy) {
10370     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10371     if (Result.isInvalid()) {
10372       VDecl->setInvalidDecl();
10373       return;
10374     }
10375     Init = Result.get();
10376   }
10377
10378   // Perform the initialization.
10379   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10380   if (!VDecl->isInvalidDecl()) {
10381     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10382     InitializationKind Kind = InitializationKind::CreateForInit(
10383         VDecl->getLocation(), DirectInit, Init);
10384
10385     MultiExprArg Args = Init;
10386     if (CXXDirectInit)
10387       Args = MultiExprArg(CXXDirectInit->getExprs(),
10388                           CXXDirectInit->getNumExprs());
10389
10390     // Try to correct any TypoExprs in the initialization arguments.
10391     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10392       ExprResult Res = CorrectDelayedTyposInExpr(
10393           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10394             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10395             return Init.Failed() ? ExprError() : E;
10396           });
10397       if (Res.isInvalid()) {
10398         VDecl->setInvalidDecl();
10399       } else if (Res.get() != Args[Idx]) {
10400         Args[Idx] = Res.get();
10401       }
10402     }
10403     if (VDecl->isInvalidDecl())
10404       return;
10405
10406     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10407                                    /*TopLevelOfInitList=*/false,
10408                                    /*TreatUnavailableAsInvalid=*/false);
10409     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10410     if (Result.isInvalid()) {
10411       VDecl->setInvalidDecl();
10412       return;
10413     }
10414
10415     Init = Result.getAs<Expr>();
10416   }
10417
10418   // Check for self-references within variable initializers.
10419   // Variables declared within a function/method body (except for references)
10420   // are handled by a dataflow analysis.
10421   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10422       VDecl->getType()->isReferenceType()) {
10423     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10424   }
10425
10426   // If the type changed, it means we had an incomplete type that was
10427   // completed by the initializer. For example:
10428   //   int ary[] = { 1, 3, 5 };
10429   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10430   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10431     VDecl->setType(DclT);
10432
10433   if (!VDecl->isInvalidDecl()) {
10434     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10435
10436     if (VDecl->hasAttr<BlocksAttr>())
10437       checkRetainCycles(VDecl, Init);
10438
10439     // It is safe to assign a weak reference into a strong variable.
10440     // Although this code can still have problems:
10441     //   id x = self.weakProp;
10442     //   id y = self.weakProp;
10443     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10444     // paths through the function. This should be revisited if
10445     // -Wrepeated-use-of-weak is made flow-sensitive.
10446     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10447          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10448         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10449                          Init->getLocStart()))
10450       getCurFunction()->markSafeWeakUse(Init);
10451   }
10452
10453   // The initialization is usually a full-expression.
10454   //
10455   // FIXME: If this is a braced initialization of an aggregate, it is not
10456   // an expression, and each individual field initializer is a separate
10457   // full-expression. For instance, in:
10458   //
10459   //   struct Temp { ~Temp(); };
10460   //   struct S { S(Temp); };
10461   //   struct T { S a, b; } t = { Temp(), Temp() }
10462   //
10463   // we should destroy the first Temp before constructing the second.
10464   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10465                                           false,
10466                                           VDecl->isConstexpr());
10467   if (Result.isInvalid()) {
10468     VDecl->setInvalidDecl();
10469     return;
10470   }
10471   Init = Result.get();
10472
10473   // Attach the initializer to the decl.
10474   VDecl->setInit(Init);
10475
10476   if (VDecl->isLocalVarDecl()) {
10477     // Don't check the initializer if the declaration is malformed.
10478     if (VDecl->isInvalidDecl()) {
10479       // do nothing
10480
10481     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10482     // This is true even in OpenCL C++.
10483     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10484       CheckForConstantInitializer(Init, DclT);
10485
10486     // Otherwise, C++ does not restrict the initializer.
10487     } else if (getLangOpts().CPlusPlus) {
10488       // do nothing
10489
10490     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10491     // static storage duration shall be constant expressions or string literals.
10492     } else if (VDecl->getStorageClass() == SC_Static) {
10493       CheckForConstantInitializer(Init, DclT);
10494
10495     // C89 is stricter than C99 for aggregate initializers.
10496     // C89 6.5.7p3: All the expressions [...] in an initializer list
10497     // for an object that has aggregate or union type shall be
10498     // constant expressions.
10499     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10500                isa<InitListExpr>(Init)) {
10501       const Expr *Culprit;
10502       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10503         Diag(Culprit->getExprLoc(),
10504              diag::ext_aggregate_init_not_constant)
10505           << Culprit->getSourceRange();
10506       }
10507     }
10508   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10509              VDecl->getLexicalDeclContext()->isRecord()) {
10510     // This is an in-class initialization for a static data member, e.g.,
10511     //
10512     // struct S {
10513     //   static const int value = 17;
10514     // };
10515
10516     // C++ [class.mem]p4:
10517     //   A member-declarator can contain a constant-initializer only
10518     //   if it declares a static member (9.4) of const integral or
10519     //   const enumeration type, see 9.4.2.
10520     //
10521     // C++11 [class.static.data]p3:
10522     //   If a non-volatile non-inline const static data member is of integral
10523     //   or enumeration type, its declaration in the class definition can
10524     //   specify a brace-or-equal-initializer in which every initializer-clause
10525     //   that is an assignment-expression is a constant expression. A static
10526     //   data member of literal type can be declared in the class definition
10527     //   with the constexpr specifier; if so, its declaration shall specify a
10528     //   brace-or-equal-initializer in which every initializer-clause that is
10529     //   an assignment-expression is a constant expression.
10530
10531     // Do nothing on dependent types.
10532     if (DclT->isDependentType()) {
10533
10534     // Allow any 'static constexpr' members, whether or not they are of literal
10535     // type. We separately check that every constexpr variable is of literal
10536     // type.
10537     } else if (VDecl->isConstexpr()) {
10538
10539     // Require constness.
10540     } else if (!DclT.isConstQualified()) {
10541       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10542         << Init->getSourceRange();
10543       VDecl->setInvalidDecl();
10544
10545     // We allow integer constant expressions in all cases.
10546     } else if (DclT->isIntegralOrEnumerationType()) {
10547       // Check whether the expression is a constant expression.
10548       SourceLocation Loc;
10549       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10550         // In C++11, a non-constexpr const static data member with an
10551         // in-class initializer cannot be volatile.
10552         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10553       else if (Init->isValueDependent())
10554         ; // Nothing to check.
10555       else if (Init->isIntegerConstantExpr(Context, &Loc))
10556         ; // Ok, it's an ICE!
10557       else if (Init->isEvaluatable(Context)) {
10558         // If we can constant fold the initializer through heroics, accept it,
10559         // but report this as a use of an extension for -pedantic.
10560         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10561           << Init->getSourceRange();
10562       } else {
10563         // Otherwise, this is some crazy unknown case.  Report the issue at the
10564         // location provided by the isIntegerConstantExpr failed check.
10565         Diag(Loc, diag::err_in_class_initializer_non_constant)
10566           << Init->getSourceRange();
10567         VDecl->setInvalidDecl();
10568       }
10569
10570     // We allow foldable floating-point constants as an extension.
10571     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10572       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10573       // it anyway and provide a fixit to add the 'constexpr'.
10574       if (getLangOpts().CPlusPlus11) {
10575         Diag(VDecl->getLocation(),
10576              diag::ext_in_class_initializer_float_type_cxx11)
10577             << DclT << Init->getSourceRange();
10578         Diag(VDecl->getLocStart(),
10579              diag::note_in_class_initializer_float_type_cxx11)
10580             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10581       } else {
10582         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10583           << DclT << Init->getSourceRange();
10584
10585         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10586           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10587             << Init->getSourceRange();
10588           VDecl->setInvalidDecl();
10589         }
10590       }
10591
10592     // Suggest adding 'constexpr' in C++11 for literal types.
10593     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10594       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10595         << DclT << Init->getSourceRange()
10596         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10597       VDecl->setConstexpr(true);
10598
10599     } else {
10600       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10601         << DclT << Init->getSourceRange();
10602       VDecl->setInvalidDecl();
10603     }
10604   } else if (VDecl->isFileVarDecl()) {
10605     // In C, extern is typically used to avoid tentative definitions when
10606     // declaring variables in headers, but adding an intializer makes it a
10607     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10608     // In C++, extern is often used to give implictly static const variables
10609     // external linkage, so don't warn in that case. If selectany is present,
10610     // this might be header code intended for C and C++ inclusion, so apply the
10611     // C++ rules.
10612     if (VDecl->getStorageClass() == SC_Extern &&
10613         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10614          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10615         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10616         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10617       Diag(VDecl->getLocation(), diag::warn_extern_init);
10618
10619     // C99 6.7.8p4. All file scoped initializers need to be constant.
10620     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10621       CheckForConstantInitializer(Init, DclT);
10622   }
10623
10624   // We will represent direct-initialization similarly to copy-initialization:
10625   //    int x(1);  -as-> int x = 1;
10626   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10627   //
10628   // Clients that want to distinguish between the two forms, can check for
10629   // direct initializer using VarDecl::getInitStyle().
10630   // A major benefit is that clients that don't particularly care about which
10631   // exactly form was it (like the CodeGen) can handle both cases without
10632   // special case code.
10633
10634   // C++ 8.5p11:
10635   // The form of initialization (using parentheses or '=') is generally
10636   // insignificant, but does matter when the entity being initialized has a
10637   // class type.
10638   if (CXXDirectInit) {
10639     assert(DirectInit && "Call-style initializer must be direct init.");
10640     VDecl->setInitStyle(VarDecl::CallInit);
10641   } else if (DirectInit) {
10642     // This must be list-initialization. No other way is direct-initialization.
10643     VDecl->setInitStyle(VarDecl::ListInit);
10644   }
10645
10646   CheckCompleteVariableDeclaration(VDecl);
10647 }
10648
10649 /// ActOnInitializerError - Given that there was an error parsing an
10650 /// initializer for the given declaration, try to return to some form
10651 /// of sanity.
10652 void Sema::ActOnInitializerError(Decl *D) {
10653   // Our main concern here is re-establishing invariants like "a
10654   // variable's type is either dependent or complete".
10655   if (!D || D->isInvalidDecl()) return;
10656
10657   VarDecl *VD = dyn_cast<VarDecl>(D);
10658   if (!VD) return;
10659
10660   // Bindings are not usable if we can't make sense of the initializer.
10661   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10662     for (auto *BD : DD->bindings())
10663       BD->setInvalidDecl();
10664
10665   // Auto types are meaningless if we can't make sense of the initializer.
10666   if (ParsingInitForAutoVars.count(D)) {
10667     D->setInvalidDecl();
10668     return;
10669   }
10670
10671   QualType Ty = VD->getType();
10672   if (Ty->isDependentType()) return;
10673
10674   // Require a complete type.
10675   if (RequireCompleteType(VD->getLocation(),
10676                           Context.getBaseElementType(Ty),
10677                           diag::err_typecheck_decl_incomplete_type)) {
10678     VD->setInvalidDecl();
10679     return;
10680   }
10681
10682   // Require a non-abstract type.
10683   if (RequireNonAbstractType(VD->getLocation(), Ty,
10684                              diag::err_abstract_type_in_decl,
10685                              AbstractVariableType)) {
10686     VD->setInvalidDecl();
10687     return;
10688   }
10689
10690   // Don't bother complaining about constructors or destructors,
10691   // though.
10692 }
10693
10694 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10695   // If there is no declaration, there was an error parsing it. Just ignore it.
10696   if (!RealDecl)
10697     return;
10698
10699   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10700     QualType Type = Var->getType();
10701
10702     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10703     if (isa<DecompositionDecl>(RealDecl)) {
10704       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10705       Var->setInvalidDecl();
10706       return;
10707     }
10708
10709     if (Type->isUndeducedType() &&
10710         DeduceVariableDeclarationType(Var, false, nullptr))
10711       return;
10712
10713     // C++11 [class.static.data]p3: A static data member can be declared with
10714     // the constexpr specifier; if so, its declaration shall specify
10715     // a brace-or-equal-initializer.
10716     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10717     // the definition of a variable [...] or the declaration of a static data
10718     // member.
10719     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10720         !Var->isThisDeclarationADemotedDefinition()) {
10721       if (Var->isStaticDataMember()) {
10722         // C++1z removes the relevant rule; the in-class declaration is always
10723         // a definition there.
10724         if (!getLangOpts().CPlusPlus1z) {
10725           Diag(Var->getLocation(),
10726                diag::err_constexpr_static_mem_var_requires_init)
10727             << Var->getDeclName();
10728           Var->setInvalidDecl();
10729           return;
10730         }
10731       } else {
10732         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10733         Var->setInvalidDecl();
10734         return;
10735       }
10736     }
10737
10738     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10739     // definition having the concept specifier is called a variable concept. A
10740     // concept definition refers to [...] a variable concept and its initializer.
10741     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10742       if (VTD->isConcept()) {
10743         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10744         Var->setInvalidDecl();
10745         return;
10746       }
10747     }
10748
10749     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10750     // be initialized.
10751     if (!Var->isInvalidDecl() &&
10752         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10753         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10754       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10755       Var->setInvalidDecl();
10756       return;
10757     }
10758
10759     switch (Var->isThisDeclarationADefinition()) {
10760     case VarDecl::Definition:
10761       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10762         break;
10763
10764       // We have an out-of-line definition of a static data member
10765       // that has an in-class initializer, so we type-check this like
10766       // a declaration.
10767       //
10768       // Fall through
10769
10770     case VarDecl::DeclarationOnly:
10771       // It's only a declaration.
10772
10773       // Block scope. C99 6.7p7: If an identifier for an object is
10774       // declared with no linkage (C99 6.2.2p6), the type for the
10775       // object shall be complete.
10776       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10777           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10778           RequireCompleteType(Var->getLocation(), Type,
10779                               diag::err_typecheck_decl_incomplete_type))
10780         Var->setInvalidDecl();
10781
10782       // Make sure that the type is not abstract.
10783       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10784           RequireNonAbstractType(Var->getLocation(), Type,
10785                                  diag::err_abstract_type_in_decl,
10786                                  AbstractVariableType))
10787         Var->setInvalidDecl();
10788       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10789           Var->getStorageClass() == SC_PrivateExtern) {
10790         Diag(Var->getLocation(), diag::warn_private_extern);
10791         Diag(Var->getLocation(), diag::note_private_extern);
10792       }
10793
10794       return;
10795
10796     case VarDecl::TentativeDefinition:
10797       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10798       // object that has file scope without an initializer, and without a
10799       // storage-class specifier or with the storage-class specifier "static",
10800       // constitutes a tentative definition. Note: A tentative definition with
10801       // external linkage is valid (C99 6.2.2p5).
10802       if (!Var->isInvalidDecl()) {
10803         if (const IncompleteArrayType *ArrayT
10804                                     = Context.getAsIncompleteArrayType(Type)) {
10805           if (RequireCompleteType(Var->getLocation(),
10806                                   ArrayT->getElementType(),
10807                                   diag::err_illegal_decl_array_incomplete_type))
10808             Var->setInvalidDecl();
10809         } else if (Var->getStorageClass() == SC_Static) {
10810           // C99 6.9.2p3: If the declaration of an identifier for an object is
10811           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10812           // declared type shall not be an incomplete type.
10813           // NOTE: code such as the following
10814           //     static struct s;
10815           //     struct s { int a; };
10816           // is accepted by gcc. Hence here we issue a warning instead of
10817           // an error and we do not invalidate the static declaration.
10818           // NOTE: to avoid multiple warnings, only check the first declaration.
10819           if (Var->isFirstDecl())
10820             RequireCompleteType(Var->getLocation(), Type,
10821                                 diag::ext_typecheck_decl_incomplete_type);
10822         }
10823       }
10824
10825       // Record the tentative definition; we're done.
10826       if (!Var->isInvalidDecl())
10827         TentativeDefinitions.push_back(Var);
10828       return;
10829     }
10830
10831     // Provide a specific diagnostic for uninitialized variable
10832     // definitions with incomplete array type.
10833     if (Type->isIncompleteArrayType()) {
10834       Diag(Var->getLocation(),
10835            diag::err_typecheck_incomplete_array_needs_initializer);
10836       Var->setInvalidDecl();
10837       return;
10838     }
10839
10840     // Provide a specific diagnostic for uninitialized variable
10841     // definitions with reference type.
10842     if (Type->isReferenceType()) {
10843       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10844         << Var->getDeclName()
10845         << SourceRange(Var->getLocation(), Var->getLocation());
10846       Var->setInvalidDecl();
10847       return;
10848     }
10849
10850     // Do not attempt to type-check the default initializer for a
10851     // variable with dependent type.
10852     if (Type->isDependentType())
10853       return;
10854
10855     if (Var->isInvalidDecl())
10856       return;
10857
10858     if (!Var->hasAttr<AliasAttr>()) {
10859       if (RequireCompleteType(Var->getLocation(),
10860                               Context.getBaseElementType(Type),
10861                               diag::err_typecheck_decl_incomplete_type)) {
10862         Var->setInvalidDecl();
10863         return;
10864       }
10865     } else {
10866       return;
10867     }
10868
10869     // The variable can not have an abstract class type.
10870     if (RequireNonAbstractType(Var->getLocation(), Type,
10871                                diag::err_abstract_type_in_decl,
10872                                AbstractVariableType)) {
10873       Var->setInvalidDecl();
10874       return;
10875     }
10876
10877     // Check for jumps past the implicit initializer.  C++0x
10878     // clarifies that this applies to a "variable with automatic
10879     // storage duration", not a "local variable".
10880     // C++11 [stmt.dcl]p3
10881     //   A program that jumps from a point where a variable with automatic
10882     //   storage duration is not in scope to a point where it is in scope is
10883     //   ill-formed unless the variable has scalar type, class type with a
10884     //   trivial default constructor and a trivial destructor, a cv-qualified
10885     //   version of one of these types, or an array of one of the preceding
10886     //   types and is declared without an initializer.
10887     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10888       if (const RecordType *Record
10889             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10890         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10891         // Mark the function for further checking even if the looser rules of
10892         // C++11 do not require such checks, so that we can diagnose
10893         // incompatibilities with C++98.
10894         if (!CXXRecord->isPOD())
10895           getCurFunction()->setHasBranchProtectedScope();
10896       }
10897     }
10898
10899     // C++03 [dcl.init]p9:
10900     //   If no initializer is specified for an object, and the
10901     //   object is of (possibly cv-qualified) non-POD class type (or
10902     //   array thereof), the object shall be default-initialized; if
10903     //   the object is of const-qualified type, the underlying class
10904     //   type shall have a user-declared default
10905     //   constructor. Otherwise, if no initializer is specified for
10906     //   a non- static object, the object and its subobjects, if
10907     //   any, have an indeterminate initial value); if the object
10908     //   or any of its subobjects are of const-qualified type, the
10909     //   program is ill-formed.
10910     // C++0x [dcl.init]p11:
10911     //   If no initializer is specified for an object, the object is
10912     //   default-initialized; [...].
10913     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10914     InitializationKind Kind
10915       = InitializationKind::CreateDefault(Var->getLocation());
10916
10917     InitializationSequence InitSeq(*this, Entity, Kind, None);
10918     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10919     if (Init.isInvalid())
10920       Var->setInvalidDecl();
10921     else if (Init.get()) {
10922       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10923       // This is important for template substitution.
10924       Var->setInitStyle(VarDecl::CallInit);
10925     }
10926
10927     CheckCompleteVariableDeclaration(Var);
10928   }
10929 }
10930
10931 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10932   // If there is no declaration, there was an error parsing it. Ignore it.
10933   if (!D)
10934     return;
10935
10936   VarDecl *VD = dyn_cast<VarDecl>(D);
10937   if (!VD) {
10938     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10939     D->setInvalidDecl();
10940     return;
10941   }
10942
10943   VD->setCXXForRangeDecl(true);
10944
10945   // for-range-declaration cannot be given a storage class specifier.
10946   int Error = -1;
10947   switch (VD->getStorageClass()) {
10948   case SC_None:
10949     break;
10950   case SC_Extern:
10951     Error = 0;
10952     break;
10953   case SC_Static:
10954     Error = 1;
10955     break;
10956   case SC_PrivateExtern:
10957     Error = 2;
10958     break;
10959   case SC_Auto:
10960     Error = 3;
10961     break;
10962   case SC_Register:
10963     Error = 4;
10964     break;
10965   }
10966   if (Error != -1) {
10967     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10968       << VD->getDeclName() << Error;
10969     D->setInvalidDecl();
10970   }
10971 }
10972
10973 StmtResult
10974 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10975                                  IdentifierInfo *Ident,
10976                                  ParsedAttributes &Attrs,
10977                                  SourceLocation AttrEnd) {
10978   // C++1y [stmt.iter]p1:
10979   //   A range-based for statement of the form
10980   //      for ( for-range-identifier : for-range-initializer ) statement
10981   //   is equivalent to
10982   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10983   DeclSpec DS(Attrs.getPool().getFactory());
10984
10985   const char *PrevSpec;
10986   unsigned DiagID;
10987   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10988                      getPrintingPolicy());
10989
10990   Declarator D(DS, Declarator::ForContext);
10991   D.SetIdentifier(Ident, IdentLoc);
10992   D.takeAttributes(Attrs, AttrEnd);
10993
10994   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10995   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10996                 EmptyAttrs, IdentLoc);
10997   Decl *Var = ActOnDeclarator(S, D);
10998   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10999   FinalizeDeclaration(Var);
11000   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11001                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11002 }
11003
11004 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11005   if (var->isInvalidDecl()) return;
11006
11007   if (getLangOpts().OpenCL) {
11008     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11009     // initialiser
11010     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11011         !var->hasInit()) {
11012       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11013           << 1 /*Init*/;
11014       var->setInvalidDecl();
11015       return;
11016     }
11017   }
11018
11019   // In Objective-C, don't allow jumps past the implicit initialization of a
11020   // local retaining variable.
11021   if (getLangOpts().ObjC1 &&
11022       var->hasLocalStorage()) {
11023     switch (var->getType().getObjCLifetime()) {
11024     case Qualifiers::OCL_None:
11025     case Qualifiers::OCL_ExplicitNone:
11026     case Qualifiers::OCL_Autoreleasing:
11027       break;
11028
11029     case Qualifiers::OCL_Weak:
11030     case Qualifiers::OCL_Strong:
11031       getCurFunction()->setHasBranchProtectedScope();
11032       break;
11033     }
11034   }
11035
11036   // Warn about externally-visible variables being defined without a
11037   // prior declaration.  We only want to do this for global
11038   // declarations, but we also specifically need to avoid doing it for
11039   // class members because the linkage of an anonymous class can
11040   // change if it's later given a typedef name.
11041   if (var->isThisDeclarationADefinition() &&
11042       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11043       var->isExternallyVisible() && var->hasLinkage() &&
11044       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11045                                   var->getLocation())) {
11046     // Find a previous declaration that's not a definition.
11047     VarDecl *prev = var->getPreviousDecl();
11048     while (prev && prev->isThisDeclarationADefinition())
11049       prev = prev->getPreviousDecl();
11050
11051     if (!prev)
11052       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11053   }
11054
11055   // Cache the result of checking for constant initialization.
11056   Optional<bool> CacheHasConstInit;
11057   const Expr *CacheCulprit;
11058   auto checkConstInit = [&]() mutable {
11059     if (!CacheHasConstInit)
11060       CacheHasConstInit = var->getInit()->isConstantInitializer(
11061             Context, var->getType()->isReferenceType(), &CacheCulprit);
11062     return *CacheHasConstInit;
11063   };
11064
11065   if (var->getTLSKind() == VarDecl::TLS_Static) {
11066     if (var->getType().isDestructedType()) {
11067       // GNU C++98 edits for __thread, [basic.start.term]p3:
11068       //   The type of an object with thread storage duration shall not
11069       //   have a non-trivial destructor.
11070       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11071       if (getLangOpts().CPlusPlus11)
11072         Diag(var->getLocation(), diag::note_use_thread_local);
11073     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11074       if (!checkConstInit()) {
11075         // GNU C++98 edits for __thread, [basic.start.init]p4:
11076         //   An object of thread storage duration shall not require dynamic
11077         //   initialization.
11078         // FIXME: Need strict checking here.
11079         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11080           << CacheCulprit->getSourceRange();
11081         if (getLangOpts().CPlusPlus11)
11082           Diag(var->getLocation(), diag::note_use_thread_local);
11083       }
11084     }
11085   }
11086
11087   // Apply section attributes and pragmas to global variables.
11088   bool GlobalStorage = var->hasGlobalStorage();
11089   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11090       !inTemplateInstantiation()) {
11091     PragmaStack<StringLiteral *> *Stack = nullptr;
11092     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11093     if (var->getType().isConstQualified())
11094       Stack = &ConstSegStack;
11095     else if (!var->getInit()) {
11096       Stack = &BSSSegStack;
11097       SectionFlags |= ASTContext::PSF_Write;
11098     } else {
11099       Stack = &DataSegStack;
11100       SectionFlags |= ASTContext::PSF_Write;
11101     }
11102     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11103       var->addAttr(SectionAttr::CreateImplicit(
11104           Context, SectionAttr::Declspec_allocate,
11105           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11106     }
11107     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11108       if (UnifySection(SA->getName(), SectionFlags, var))
11109         var->dropAttr<SectionAttr>();
11110
11111     // Apply the init_seg attribute if this has an initializer.  If the
11112     // initializer turns out to not be dynamic, we'll end up ignoring this
11113     // attribute.
11114     if (CurInitSeg && var->getInit())
11115       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11116                                                CurInitSegLoc));
11117   }
11118
11119   // All the following checks are C++ only.
11120   if (!getLangOpts().CPlusPlus) {
11121       // If this variable must be emitted, add it as an initializer for the
11122       // current module.
11123      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11124        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11125      return;
11126   }
11127
11128   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11129     CheckCompleteDecompositionDeclaration(DD);
11130
11131   QualType type = var->getType();
11132   if (type->isDependentType()) return;
11133
11134   // __block variables might require us to capture a copy-initializer.
11135   if (var->hasAttr<BlocksAttr>()) {
11136     // It's currently invalid to ever have a __block variable with an
11137     // array type; should we diagnose that here?
11138
11139     // Regardless, we don't want to ignore array nesting when
11140     // constructing this copy.
11141     if (type->isStructureOrClassType()) {
11142       EnterExpressionEvaluationContext scope(
11143           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11144       SourceLocation poi = var->getLocation();
11145       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11146       ExprResult result
11147         = PerformMoveOrCopyInitialization(
11148             InitializedEntity::InitializeBlock(poi, type, false),
11149             var, var->getType(), varRef, /*AllowNRVO=*/true);
11150       if (!result.isInvalid()) {
11151         result = MaybeCreateExprWithCleanups(result);
11152         Expr *init = result.getAs<Expr>();
11153         Context.setBlockVarCopyInits(var, init);
11154       }
11155     }
11156   }
11157
11158   Expr *Init = var->getInit();
11159   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11160   QualType baseType = Context.getBaseElementType(type);
11161
11162   if (Init && !Init->isValueDependent()) {
11163     if (var->isConstexpr()) {
11164       SmallVector<PartialDiagnosticAt, 8> Notes;
11165       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11166         SourceLocation DiagLoc = var->getLocation();
11167         // If the note doesn't add any useful information other than a source
11168         // location, fold it into the primary diagnostic.
11169         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11170               diag::note_invalid_subexpr_in_const_expr) {
11171           DiagLoc = Notes[0].first;
11172           Notes.clear();
11173         }
11174         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11175           << var << Init->getSourceRange();
11176         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11177           Diag(Notes[I].first, Notes[I].second);
11178       }
11179     } else if (var->isUsableInConstantExpressions(Context)) {
11180       // Check whether the initializer of a const variable of integral or
11181       // enumeration type is an ICE now, since we can't tell whether it was
11182       // initialized by a constant expression if we check later.
11183       var->checkInitIsICE();
11184     }
11185
11186     // Don't emit further diagnostics about constexpr globals since they
11187     // were just diagnosed.
11188     if (!var->isConstexpr() && GlobalStorage &&
11189             var->hasAttr<RequireConstantInitAttr>()) {
11190       // FIXME: Need strict checking in C++03 here.
11191       bool DiagErr = getLangOpts().CPlusPlus11
11192           ? !var->checkInitIsICE() : !checkConstInit();
11193       if (DiagErr) {
11194         auto attr = var->getAttr<RequireConstantInitAttr>();
11195         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11196           << Init->getSourceRange();
11197         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11198           << attr->getRange();
11199         if (getLangOpts().CPlusPlus11) {
11200           APValue Value;
11201           SmallVector<PartialDiagnosticAt, 8> Notes;
11202           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11203           for (auto &it : Notes)
11204             Diag(it.first, it.second);
11205         } else {
11206           Diag(CacheCulprit->getExprLoc(),
11207                diag::note_invalid_subexpr_in_const_expr)
11208               << CacheCulprit->getSourceRange();
11209         }
11210       }
11211     }
11212     else if (!var->isConstexpr() && IsGlobal &&
11213              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11214                                     var->getLocation())) {
11215       // Warn about globals which don't have a constant initializer.  Don't
11216       // warn about globals with a non-trivial destructor because we already
11217       // warned about them.
11218       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11219       if (!(RD && !RD->hasTrivialDestructor())) {
11220         if (!checkConstInit())
11221           Diag(var->getLocation(), diag::warn_global_constructor)
11222             << Init->getSourceRange();
11223       }
11224     }
11225   }
11226
11227   // Require the destructor.
11228   if (const RecordType *recordType = baseType->getAs<RecordType>())
11229     FinalizeVarWithDestructor(var, recordType);
11230
11231   // If this variable must be emitted, add it as an initializer for the current
11232   // module.
11233   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11234     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11235 }
11236
11237 /// \brief Determines if a variable's alignment is dependent.
11238 static bool hasDependentAlignment(VarDecl *VD) {
11239   if (VD->getType()->isDependentType())
11240     return true;
11241   for (auto *I : VD->specific_attrs<AlignedAttr>())
11242     if (I->isAlignmentDependent())
11243       return true;
11244   return false;
11245 }
11246
11247 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11248 /// any semantic actions necessary after any initializer has been attached.
11249 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11250   // Note that we are no longer parsing the initializer for this declaration.
11251   ParsingInitForAutoVars.erase(ThisDecl);
11252
11253   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11254   if (!VD)
11255     return;
11256
11257   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11258   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11259       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11260     if (PragmaClangBSSSection.Valid)
11261       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11262                                                             PragmaClangBSSSection.SectionName,
11263                                                             PragmaClangBSSSection.PragmaLocation));
11264     if (PragmaClangDataSection.Valid)
11265       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11266                                                              PragmaClangDataSection.SectionName,
11267                                                              PragmaClangDataSection.PragmaLocation));
11268     if (PragmaClangRodataSection.Valid)
11269       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11270                                                                PragmaClangRodataSection.SectionName,
11271                                                                PragmaClangRodataSection.PragmaLocation));
11272   }
11273
11274   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11275     for (auto *BD : DD->bindings()) {
11276       FinalizeDeclaration(BD);
11277     }
11278   }
11279
11280   checkAttributesAfterMerging(*this, *VD);
11281
11282   // Perform TLS alignment check here after attributes attached to the variable
11283   // which may affect the alignment have been processed. Only perform the check
11284   // if the target has a maximum TLS alignment (zero means no constraints).
11285   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11286     // Protect the check so that it's not performed on dependent types and
11287     // dependent alignments (we can't determine the alignment in that case).
11288     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11289         !VD->isInvalidDecl()) {
11290       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11291       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11292         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11293           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11294           << (unsigned)MaxAlignChars.getQuantity();
11295       }
11296     }
11297   }
11298
11299   if (VD->isStaticLocal()) {
11300     if (FunctionDecl *FD =
11301             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11302       // Static locals inherit dll attributes from their function.
11303       if (Attr *A = getDLLAttr(FD)) {
11304         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11305         NewAttr->setInherited(true);
11306         VD->addAttr(NewAttr);
11307       }
11308       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11309       // function, only __shared__ variables may be declared with
11310       // static storage class.
11311       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11312           CUDADiagIfDeviceCode(VD->getLocation(),
11313                                diag::err_device_static_local_var)
11314               << CurrentCUDATarget())
11315         VD->setInvalidDecl();
11316     }
11317   }
11318
11319   // Perform check for initializers of device-side global variables.
11320   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11321   // 7.5). We must also apply the same checks to all __shared__
11322   // variables whether they are local or not. CUDA also allows
11323   // constant initializers for __constant__ and __device__ variables.
11324   if (getLangOpts().CUDA) {
11325     const Expr *Init = VD->getInit();
11326     if (Init && VD->hasGlobalStorage()) {
11327       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11328           VD->hasAttr<CUDASharedAttr>()) {
11329         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11330         bool AllowedInit = false;
11331         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11332           AllowedInit =
11333               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11334         // We'll allow constant initializers even if it's a non-empty
11335         // constructor according to CUDA rules. This deviates from NVCC,
11336         // but allows us to handle things like constexpr constructors.
11337         if (!AllowedInit &&
11338             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11339           AllowedInit = VD->getInit()->isConstantInitializer(
11340               Context, VD->getType()->isReferenceType());
11341
11342         // Also make sure that destructor, if there is one, is empty.
11343         if (AllowedInit)
11344           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11345             AllowedInit =
11346                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11347
11348         if (!AllowedInit) {
11349           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11350                                       ? diag::err_shared_var_init
11351                                       : diag::err_dynamic_var_init)
11352               << Init->getSourceRange();
11353           VD->setInvalidDecl();
11354         }
11355       } else {
11356         // This is a host-side global variable.  Check that the initializer is
11357         // callable from the host side.
11358         const FunctionDecl *InitFn = nullptr;
11359         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11360           InitFn = CE->getConstructor();
11361         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11362           InitFn = CE->getDirectCallee();
11363         }
11364         if (InitFn) {
11365           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11366           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11367             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11368                 << InitFnTarget << InitFn;
11369             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11370             VD->setInvalidDecl();
11371           }
11372         }
11373       }
11374     }
11375   }
11376
11377   // Grab the dllimport or dllexport attribute off of the VarDecl.
11378   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11379
11380   // Imported static data members cannot be defined out-of-line.
11381   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11382     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11383         VD->isThisDeclarationADefinition()) {
11384       // We allow definitions of dllimport class template static data members
11385       // with a warning.
11386       CXXRecordDecl *Context =
11387         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11388       bool IsClassTemplateMember =
11389           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11390           Context->getDescribedClassTemplate();
11391
11392       Diag(VD->getLocation(),
11393            IsClassTemplateMember
11394                ? diag::warn_attribute_dllimport_static_field_definition
11395                : diag::err_attribute_dllimport_static_field_definition);
11396       Diag(IA->getLocation(), diag::note_attribute);
11397       if (!IsClassTemplateMember)
11398         VD->setInvalidDecl();
11399     }
11400   }
11401
11402   // dllimport/dllexport variables cannot be thread local, their TLS index
11403   // isn't exported with the variable.
11404   if (DLLAttr && VD->getTLSKind()) {
11405     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11406     if (F && getDLLAttr(F)) {
11407       assert(VD->isStaticLocal());
11408       // But if this is a static local in a dlimport/dllexport function, the
11409       // function will never be inlined, which means the var would never be
11410       // imported, so having it marked import/export is safe.
11411     } else {
11412       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11413                                                                     << DLLAttr;
11414       VD->setInvalidDecl();
11415     }
11416   }
11417
11418   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11419     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11420       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11421       VD->dropAttr<UsedAttr>();
11422     }
11423   }
11424
11425   const DeclContext *DC = VD->getDeclContext();
11426   // If there's a #pragma GCC visibility in scope, and this isn't a class
11427   // member, set the visibility of this variable.
11428   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11429     AddPushedVisibilityAttribute(VD);
11430
11431   // FIXME: Warn on unused var template partial specializations.
11432   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11433     MarkUnusedFileScopedDecl(VD);
11434
11435   // Now we have parsed the initializer and can update the table of magic
11436   // tag values.
11437   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11438       !VD->getType()->isIntegralOrEnumerationType())
11439     return;
11440
11441   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11442     const Expr *MagicValueExpr = VD->getInit();
11443     if (!MagicValueExpr) {
11444       continue;
11445     }
11446     llvm::APSInt MagicValueInt;
11447     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11448       Diag(I->getRange().getBegin(),
11449            diag::err_type_tag_for_datatype_not_ice)
11450         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11451       continue;
11452     }
11453     if (MagicValueInt.getActiveBits() > 64) {
11454       Diag(I->getRange().getBegin(),
11455            diag::err_type_tag_for_datatype_too_large)
11456         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11457       continue;
11458     }
11459     uint64_t MagicValue = MagicValueInt.getZExtValue();
11460     RegisterTypeTagForDatatype(I->getArgumentKind(),
11461                                MagicValue,
11462                                I->getMatchingCType(),
11463                                I->getLayoutCompatible(),
11464                                I->getMustBeNull());
11465   }
11466 }
11467
11468 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11469   auto *VD = dyn_cast<VarDecl>(DD);
11470   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11471 }
11472
11473 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11474                                                    ArrayRef<Decl *> Group) {
11475   SmallVector<Decl*, 8> Decls;
11476
11477   if (DS.isTypeSpecOwned())
11478     Decls.push_back(DS.getRepAsDecl());
11479
11480   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11481   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11482   bool DiagnosedMultipleDecomps = false;
11483   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11484   bool DiagnosedNonDeducedAuto = false;
11485
11486   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11487     if (Decl *D = Group[i]) {
11488       // For declarators, there are some additional syntactic-ish checks we need
11489       // to perform.
11490       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11491         if (!FirstDeclaratorInGroup)
11492           FirstDeclaratorInGroup = DD;
11493         if (!FirstDecompDeclaratorInGroup)
11494           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11495         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11496             !hasDeducedAuto(DD))
11497           FirstNonDeducedAutoInGroup = DD;
11498
11499         if (FirstDeclaratorInGroup != DD) {
11500           // A decomposition declaration cannot be combined with any other
11501           // declaration in the same group.
11502           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11503             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11504                  diag::err_decomp_decl_not_alone)
11505                 << FirstDeclaratorInGroup->getSourceRange()
11506                 << DD->getSourceRange();
11507             DiagnosedMultipleDecomps = true;
11508           }
11509
11510           // A declarator that uses 'auto' in any way other than to declare a
11511           // variable with a deduced type cannot be combined with any other
11512           // declarator in the same group.
11513           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11514             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11515                  diag::err_auto_non_deduced_not_alone)
11516                 << FirstNonDeducedAutoInGroup->getType()
11517                        ->hasAutoForTrailingReturnType()
11518                 << FirstDeclaratorInGroup->getSourceRange()
11519                 << DD->getSourceRange();
11520             DiagnosedNonDeducedAuto = true;
11521           }
11522         }
11523       }
11524
11525       Decls.push_back(D);
11526     }
11527   }
11528
11529   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11530     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11531       handleTagNumbering(Tag, S);
11532       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11533           getLangOpts().CPlusPlus)
11534         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11535     }
11536   }
11537
11538   return BuildDeclaratorGroup(Decls);
11539 }
11540
11541 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11542 /// group, performing any necessary semantic checking.
11543 Sema::DeclGroupPtrTy
11544 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11545   // C++14 [dcl.spec.auto]p7: (DR1347)
11546   //   If the type that replaces the placeholder type is not the same in each
11547   //   deduction, the program is ill-formed.
11548   if (Group.size() > 1) {
11549     QualType Deduced;
11550     VarDecl *DeducedDecl = nullptr;
11551     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11552       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11553       if (!D || D->isInvalidDecl())
11554         break;
11555       DeducedType *DT = D->getType()->getContainedDeducedType();
11556       if (!DT || DT->getDeducedType().isNull())
11557         continue;
11558       if (Deduced.isNull()) {
11559         Deduced = DT->getDeducedType();
11560         DeducedDecl = D;
11561       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11562         auto *AT = dyn_cast<AutoType>(DT);
11563         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11564              diag::err_auto_different_deductions)
11565           << (AT ? (unsigned)AT->getKeyword() : 3)
11566           << Deduced << DeducedDecl->getDeclName()
11567           << DT->getDeducedType() << D->getDeclName()
11568           << DeducedDecl->getInit()->getSourceRange()
11569           << D->getInit()->getSourceRange();
11570         D->setInvalidDecl();
11571         break;
11572       }
11573     }
11574   }
11575
11576   ActOnDocumentableDecls(Group);
11577
11578   return DeclGroupPtrTy::make(
11579       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11580 }
11581
11582 void Sema::ActOnDocumentableDecl(Decl *D) {
11583   ActOnDocumentableDecls(D);
11584 }
11585
11586 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11587   // Don't parse the comment if Doxygen diagnostics are ignored.
11588   if (Group.empty() || !Group[0])
11589     return;
11590
11591   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11592                       Group[0]->getLocation()) &&
11593       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11594                       Group[0]->getLocation()))
11595     return;
11596
11597   if (Group.size() >= 2) {
11598     // This is a decl group.  Normally it will contain only declarations
11599     // produced from declarator list.  But in case we have any definitions or
11600     // additional declaration references:
11601     //   'typedef struct S {} S;'
11602     //   'typedef struct S *S;'
11603     //   'struct S *pS;'
11604     // FinalizeDeclaratorGroup adds these as separate declarations.
11605     Decl *MaybeTagDecl = Group[0];
11606     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11607       Group = Group.slice(1);
11608     }
11609   }
11610
11611   // See if there are any new comments that are not attached to a decl.
11612   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11613   if (!Comments.empty() &&
11614       !Comments.back()->isAttached()) {
11615     // There is at least one comment that not attached to a decl.
11616     // Maybe it should be attached to one of these decls?
11617     //
11618     // Note that this way we pick up not only comments that precede the
11619     // declaration, but also comments that *follow* the declaration -- thanks to
11620     // the lookahead in the lexer: we've consumed the semicolon and looked
11621     // ahead through comments.
11622     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11623       Context.getCommentForDecl(Group[i], &PP);
11624   }
11625 }
11626
11627 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11628 /// to introduce parameters into function prototype scope.
11629 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11630   const DeclSpec &DS = D.getDeclSpec();
11631
11632   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11633
11634   // C++03 [dcl.stc]p2 also permits 'auto'.
11635   StorageClass SC = SC_None;
11636   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11637     SC = SC_Register;
11638   } else if (getLangOpts().CPlusPlus &&
11639              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11640     SC = SC_Auto;
11641   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11642     Diag(DS.getStorageClassSpecLoc(),
11643          diag::err_invalid_storage_class_in_func_decl);
11644     D.getMutableDeclSpec().ClearStorageClassSpecs();
11645   }
11646
11647   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11648     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11649       << DeclSpec::getSpecifierName(TSCS);
11650   if (DS.isInlineSpecified())
11651     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11652         << getLangOpts().CPlusPlus1z;
11653   if (DS.isConstexprSpecified())
11654     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11655       << 0;
11656   if (DS.isConceptSpecified())
11657     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11658
11659   DiagnoseFunctionSpecifiers(DS);
11660
11661   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11662   QualType parmDeclType = TInfo->getType();
11663
11664   if (getLangOpts().CPlusPlus) {
11665     // Check that there are no default arguments inside the type of this
11666     // parameter.
11667     CheckExtraCXXDefaultArguments(D);
11668
11669     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11670     if (D.getCXXScopeSpec().isSet()) {
11671       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11672         << D.getCXXScopeSpec().getRange();
11673       D.getCXXScopeSpec().clear();
11674     }
11675   }
11676
11677   // Ensure we have a valid name
11678   IdentifierInfo *II = nullptr;
11679   if (D.hasName()) {
11680     II = D.getIdentifier();
11681     if (!II) {
11682       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11683         << GetNameForDeclarator(D).getName();
11684       D.setInvalidType(true);
11685     }
11686   }
11687
11688   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11689   if (II) {
11690     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11691                    ForRedeclaration);
11692     LookupName(R, S);
11693     if (R.isSingleResult()) {
11694       NamedDecl *PrevDecl = R.getFoundDecl();
11695       if (PrevDecl->isTemplateParameter()) {
11696         // Maybe we will complain about the shadowed template parameter.
11697         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11698         // Just pretend that we didn't see the previous declaration.
11699         PrevDecl = nullptr;
11700       } else if (S->isDeclScope(PrevDecl)) {
11701         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11702         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11703
11704         // Recover by removing the name
11705         II = nullptr;
11706         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11707         D.setInvalidType(true);
11708       }
11709     }
11710   }
11711
11712   // Temporarily put parameter variables in the translation unit, not
11713   // the enclosing context.  This prevents them from accidentally
11714   // looking like class members in C++.
11715   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11716                                     D.getLocStart(),
11717                                     D.getIdentifierLoc(), II,
11718                                     parmDeclType, TInfo,
11719                                     SC);
11720
11721   if (D.isInvalidType())
11722     New->setInvalidDecl();
11723
11724   assert(S->isFunctionPrototypeScope());
11725   assert(S->getFunctionPrototypeDepth() >= 1);
11726   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11727                     S->getNextFunctionPrototypeIndex());
11728
11729   // Add the parameter declaration into this scope.
11730   S->AddDecl(New);
11731   if (II)
11732     IdResolver.AddDecl(New);
11733
11734   ProcessDeclAttributes(S, New, D);
11735
11736   if (D.getDeclSpec().isModulePrivateSpecified())
11737     Diag(New->getLocation(), diag::err_module_private_local)
11738       << 1 << New->getDeclName()
11739       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11740       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11741
11742   if (New->hasAttr<BlocksAttr>()) {
11743     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11744   }
11745   return New;
11746 }
11747
11748 /// \brief Synthesizes a variable for a parameter arising from a
11749 /// typedef.
11750 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11751                                               SourceLocation Loc,
11752                                               QualType T) {
11753   /* FIXME: setting StartLoc == Loc.
11754      Would it be worth to modify callers so as to provide proper source
11755      location for the unnamed parameters, embedding the parameter's type? */
11756   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11757                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11758                                            SC_None, nullptr);
11759   Param->setImplicit();
11760   return Param;
11761 }
11762
11763 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11764   // Don't diagnose unused-parameter errors in template instantiations; we
11765   // will already have done so in the template itself.
11766   if (inTemplateInstantiation())
11767     return;
11768
11769   for (const ParmVarDecl *Parameter : Parameters) {
11770     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11771         !Parameter->hasAttr<UnusedAttr>()) {
11772       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11773         << Parameter->getDeclName();
11774     }
11775   }
11776 }
11777
11778 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11779     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11780   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11781     return;
11782
11783   // Warn if the return value is pass-by-value and larger than the specified
11784   // threshold.
11785   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11786     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11787     if (Size > LangOpts.NumLargeByValueCopy)
11788       Diag(D->getLocation(), diag::warn_return_value_size)
11789           << D->getDeclName() << Size;
11790   }
11791
11792   // Warn if any parameter is pass-by-value and larger than the specified
11793   // threshold.
11794   for (const ParmVarDecl *Parameter : Parameters) {
11795     QualType T = Parameter->getType();
11796     if (T->isDependentType() || !T.isPODType(Context))
11797       continue;
11798     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11799     if (Size > LangOpts.NumLargeByValueCopy)
11800       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11801           << Parameter->getDeclName() << Size;
11802   }
11803 }
11804
11805 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11806                                   SourceLocation NameLoc, IdentifierInfo *Name,
11807                                   QualType T, TypeSourceInfo *TSInfo,
11808                                   StorageClass SC) {
11809   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11810   if (getLangOpts().ObjCAutoRefCount &&
11811       T.getObjCLifetime() == Qualifiers::OCL_None &&
11812       T->isObjCLifetimeType()) {
11813
11814     Qualifiers::ObjCLifetime lifetime;
11815
11816     // Special cases for arrays:
11817     //   - if it's const, use __unsafe_unretained
11818     //   - otherwise, it's an error
11819     if (T->isArrayType()) {
11820       if (!T.isConstQualified()) {
11821         DelayedDiagnostics.add(
11822             sema::DelayedDiagnostic::makeForbiddenType(
11823             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11824       }
11825       lifetime = Qualifiers::OCL_ExplicitNone;
11826     } else {
11827       lifetime = T->getObjCARCImplicitLifetime();
11828     }
11829     T = Context.getLifetimeQualifiedType(T, lifetime);
11830   }
11831
11832   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11833                                          Context.getAdjustedParameterType(T),
11834                                          TSInfo, SC, nullptr);
11835
11836   // Parameters can not be abstract class types.
11837   // For record types, this is done by the AbstractClassUsageDiagnoser once
11838   // the class has been completely parsed.
11839   if (!CurContext->isRecord() &&
11840       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11841                              AbstractParamType))
11842     New->setInvalidDecl();
11843
11844   // Parameter declarators cannot be interface types. All ObjC objects are
11845   // passed by reference.
11846   if (T->isObjCObjectType()) {
11847     SourceLocation TypeEndLoc =
11848         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11849     Diag(NameLoc,
11850          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11851       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11852     T = Context.getObjCObjectPointerType(T);
11853     New->setType(T);
11854   }
11855
11856   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11857   // duration shall not be qualified by an address-space qualifier."
11858   // Since all parameters have automatic store duration, they can not have
11859   // an address space.
11860   if (T.getAddressSpace() != 0) {
11861     // OpenCL allows function arguments declared to be an array of a type
11862     // to be qualified with an address space.
11863     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11864       Diag(NameLoc, diag::err_arg_with_address_space);
11865       New->setInvalidDecl();
11866     }
11867   }
11868
11869   return New;
11870 }
11871
11872 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11873                                            SourceLocation LocAfterDecls) {
11874   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11875
11876   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11877   // for a K&R function.
11878   if (!FTI.hasPrototype) {
11879     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11880       --i;
11881       if (FTI.Params[i].Param == nullptr) {
11882         SmallString<256> Code;
11883         llvm::raw_svector_ostream(Code)
11884             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11885         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11886             << FTI.Params[i].Ident
11887             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11888
11889         // Implicitly declare the argument as type 'int' for lack of a better
11890         // type.
11891         AttributeFactory attrs;
11892         DeclSpec DS(attrs);
11893         const char* PrevSpec; // unused
11894         unsigned DiagID; // unused
11895         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11896                            DiagID, Context.getPrintingPolicy());
11897         // Use the identifier location for the type source range.
11898         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11899         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11900         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11901         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11902         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11903       }
11904     }
11905   }
11906 }
11907
11908 Decl *
11909 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11910                               MultiTemplateParamsArg TemplateParameterLists,
11911                               SkipBodyInfo *SkipBody) {
11912   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11913   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11914   Scope *ParentScope = FnBodyScope->getParent();
11915
11916   D.setFunctionDefinitionKind(FDK_Definition);
11917   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11918   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11919 }
11920
11921 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11922   Consumer.HandleInlineFunctionDefinition(D);
11923 }
11924
11925 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11926                              const FunctionDecl*& PossibleZeroParamPrototype) {
11927   // Don't warn about invalid declarations.
11928   if (FD->isInvalidDecl())
11929     return false;
11930
11931   // Or declarations that aren't global.
11932   if (!FD->isGlobal())
11933     return false;
11934
11935   // Don't warn about C++ member functions.
11936   if (isa<CXXMethodDecl>(FD))
11937     return false;
11938
11939   // Don't warn about 'main'.
11940   if (FD->isMain())
11941     return false;
11942
11943   // Don't warn about inline functions.
11944   if (FD->isInlined())
11945     return false;
11946
11947   // Don't warn about function templates.
11948   if (FD->getDescribedFunctionTemplate())
11949     return false;
11950
11951   // Don't warn about function template specializations.
11952   if (FD->isFunctionTemplateSpecialization())
11953     return false;
11954
11955   // Don't warn for OpenCL kernels.
11956   if (FD->hasAttr<OpenCLKernelAttr>())
11957     return false;
11958
11959   // Don't warn on explicitly deleted functions.
11960   if (FD->isDeleted())
11961     return false;
11962
11963   bool MissingPrototype = true;
11964   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11965        Prev; Prev = Prev->getPreviousDecl()) {
11966     // Ignore any declarations that occur in function or method
11967     // scope, because they aren't visible from the header.
11968     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11969       continue;
11970
11971     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11972     if (FD->getNumParams() == 0)
11973       PossibleZeroParamPrototype = Prev;
11974     break;
11975   }
11976
11977   return MissingPrototype;
11978 }
11979
11980 void
11981 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11982                                    const FunctionDecl *EffectiveDefinition,
11983                                    SkipBodyInfo *SkipBody) {
11984   const FunctionDecl *Definition = EffectiveDefinition;
11985   if (!Definition)
11986     if (!FD->isDefined(Definition))
11987       return;
11988
11989   if (canRedefineFunction(Definition, getLangOpts()))
11990     return;
11991
11992   // Don't emit an error when this is redefinition of a typo-corrected
11993   // definition.
11994   if (TypoCorrectedFunctionDefinitions.count(Definition))
11995     return;
11996
11997   // If we don't have a visible definition of the function, and it's inline or
11998   // a template, skip the new definition.
11999   if (SkipBody && !hasVisibleDefinition(Definition) &&
12000       (Definition->getFormalLinkage() == InternalLinkage ||
12001        Definition->isInlined() ||
12002        Definition->getDescribedFunctionTemplate() ||
12003        Definition->getNumTemplateParameterLists())) {
12004     SkipBody->ShouldSkip = true;
12005     if (auto *TD = Definition->getDescribedFunctionTemplate())
12006       makeMergedDefinitionVisible(TD);
12007     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12008     return;
12009   }
12010
12011   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12012       Definition->getStorageClass() == SC_Extern)
12013     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12014         << FD->getDeclName() << getLangOpts().CPlusPlus;
12015   else
12016     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12017
12018   Diag(Definition->getLocation(), diag::note_previous_definition);
12019   FD->setInvalidDecl();
12020 }
12021
12022 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12023                                    Sema &S) {
12024   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12025
12026   LambdaScopeInfo *LSI = S.PushLambdaScope();
12027   LSI->CallOperator = CallOperator;
12028   LSI->Lambda = LambdaClass;
12029   LSI->ReturnType = CallOperator->getReturnType();
12030   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12031
12032   if (LCD == LCD_None)
12033     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12034   else if (LCD == LCD_ByCopy)
12035     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12036   else if (LCD == LCD_ByRef)
12037     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12038   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12039
12040   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12041   LSI->Mutable = !CallOperator->isConst();
12042
12043   // Add the captures to the LSI so they can be noted as already
12044   // captured within tryCaptureVar.
12045   auto I = LambdaClass->field_begin();
12046   for (const auto &C : LambdaClass->captures()) {
12047     if (C.capturesVariable()) {
12048       VarDecl *VD = C.getCapturedVar();
12049       if (VD->isInitCapture())
12050         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12051       QualType CaptureType = VD->getType();
12052       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12053       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12054           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12055           /*EllipsisLoc*/C.isPackExpansion()
12056                          ? C.getEllipsisLoc() : SourceLocation(),
12057           CaptureType, /*Expr*/ nullptr);
12058
12059     } else if (C.capturesThis()) {
12060       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12061                               /*Expr*/ nullptr,
12062                               C.getCaptureKind() == LCK_StarThis);
12063     } else {
12064       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12065     }
12066     ++I;
12067   }
12068 }
12069
12070 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12071                                     SkipBodyInfo *SkipBody) {
12072   if (!D)
12073     return D;
12074   FunctionDecl *FD = nullptr;
12075
12076   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12077     FD = FunTmpl->getTemplatedDecl();
12078   else
12079     FD = cast<FunctionDecl>(D);
12080
12081   // Check for defining attributes before the check for redefinition.
12082   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12083     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12084     FD->dropAttr<AliasAttr>();
12085     FD->setInvalidDecl();
12086   }
12087   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12088     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12089     FD->dropAttr<IFuncAttr>();
12090     FD->setInvalidDecl();
12091   }
12092
12093   // See if this is a redefinition. If 'will have body' is already set, then
12094   // these checks were already performed when it was set.
12095   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12096     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12097
12098     // If we're skipping the body, we're done. Don't enter the scope.
12099     if (SkipBody && SkipBody->ShouldSkip)
12100       return D;
12101   }
12102
12103   // Mark this function as "will have a body eventually".  This lets users to
12104   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12105   // this function.
12106   FD->setWillHaveBody();
12107
12108   // If we are instantiating a generic lambda call operator, push
12109   // a LambdaScopeInfo onto the function stack.  But use the information
12110   // that's already been calculated (ActOnLambdaExpr) to prime the current
12111   // LambdaScopeInfo.
12112   // When the template operator is being specialized, the LambdaScopeInfo,
12113   // has to be properly restored so that tryCaptureVariable doesn't try
12114   // and capture any new variables. In addition when calculating potential
12115   // captures during transformation of nested lambdas, it is necessary to
12116   // have the LSI properly restored.
12117   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12118     assert(inTemplateInstantiation() &&
12119            "There should be an active template instantiation on the stack "
12120            "when instantiating a generic lambda!");
12121     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12122   } else {
12123     // Enter a new function scope
12124     PushFunctionScope();
12125   }
12126
12127   // Builtin functions cannot be defined.
12128   if (unsigned BuiltinID = FD->getBuiltinID()) {
12129     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12130         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12131       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12132       FD->setInvalidDecl();
12133     }
12134   }
12135
12136   // The return type of a function definition must be complete
12137   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12138   QualType ResultType = FD->getReturnType();
12139   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12140       !FD->isInvalidDecl() &&
12141       RequireCompleteType(FD->getLocation(), ResultType,
12142                           diag::err_func_def_incomplete_result))
12143     FD->setInvalidDecl();
12144
12145   if (FnBodyScope)
12146     PushDeclContext(FnBodyScope, FD);
12147
12148   // Check the validity of our function parameters
12149   CheckParmsForFunctionDef(FD->parameters(),
12150                            /*CheckParameterNames=*/true);
12151
12152   // Add non-parameter declarations already in the function to the current
12153   // scope.
12154   if (FnBodyScope) {
12155     for (Decl *NPD : FD->decls()) {
12156       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12157       if (!NonParmDecl)
12158         continue;
12159       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12160              "parameters should not be in newly created FD yet");
12161
12162       // If the decl has a name, make it accessible in the current scope.
12163       if (NonParmDecl->getDeclName())
12164         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12165
12166       // Similarly, dive into enums and fish their constants out, making them
12167       // accessible in this scope.
12168       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12169         for (auto *EI : ED->enumerators())
12170           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12171       }
12172     }
12173   }
12174
12175   // Introduce our parameters into the function scope
12176   for (auto Param : FD->parameters()) {
12177     Param->setOwningFunction(FD);
12178
12179     // If this has an identifier, add it to the scope stack.
12180     if (Param->getIdentifier() && FnBodyScope) {
12181       CheckShadow(FnBodyScope, Param);
12182
12183       PushOnScopeChains(Param, FnBodyScope);
12184     }
12185   }
12186
12187   // Ensure that the function's exception specification is instantiated.
12188   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12189     ResolveExceptionSpec(D->getLocation(), FPT);
12190
12191   // dllimport cannot be applied to non-inline function definitions.
12192   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12193       !FD->isTemplateInstantiation()) {
12194     assert(!FD->hasAttr<DLLExportAttr>());
12195     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12196     FD->setInvalidDecl();
12197     return D;
12198   }
12199   // We want to attach documentation to original Decl (which might be
12200   // a function template).
12201   ActOnDocumentableDecl(D);
12202   if (getCurLexicalContext()->isObjCContainer() &&
12203       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12204       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12205     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12206
12207   return D;
12208 }
12209
12210 /// \brief Given the set of return statements within a function body,
12211 /// compute the variables that are subject to the named return value
12212 /// optimization.
12213 ///
12214 /// Each of the variables that is subject to the named return value
12215 /// optimization will be marked as NRVO variables in the AST, and any
12216 /// return statement that has a marked NRVO variable as its NRVO candidate can
12217 /// use the named return value optimization.
12218 ///
12219 /// This function applies a very simplistic algorithm for NRVO: if every return
12220 /// statement in the scope of a variable has the same NRVO candidate, that
12221 /// candidate is an NRVO variable.
12222 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12223   ReturnStmt **Returns = Scope->Returns.data();
12224
12225   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12226     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12227       if (!NRVOCandidate->isNRVOVariable())
12228         Returns[I]->setNRVOCandidate(nullptr);
12229     }
12230   }
12231 }
12232
12233 bool Sema::canDelayFunctionBody(const Declarator &D) {
12234   // We can't delay parsing the body of a constexpr function template (yet).
12235   if (D.getDeclSpec().isConstexprSpecified())
12236     return false;
12237
12238   // We can't delay parsing the body of a function template with a deduced
12239   // return type (yet).
12240   if (D.getDeclSpec().hasAutoTypeSpec()) {
12241     // If the placeholder introduces a non-deduced trailing return type,
12242     // we can still delay parsing it.
12243     if (D.getNumTypeObjects()) {
12244       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12245       if (Outer.Kind == DeclaratorChunk::Function &&
12246           Outer.Fun.hasTrailingReturnType()) {
12247         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12248         return Ty.isNull() || !Ty->isUndeducedType();
12249       }
12250     }
12251     return false;
12252   }
12253
12254   return true;
12255 }
12256
12257 bool Sema::canSkipFunctionBody(Decl *D) {
12258   // We cannot skip the body of a function (or function template) which is
12259   // constexpr, since we may need to evaluate its body in order to parse the
12260   // rest of the file.
12261   // We cannot skip the body of a function with an undeduced return type,
12262   // because any callers of that function need to know the type.
12263   if (const FunctionDecl *FD = D->getAsFunction())
12264     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12265       return false;
12266   return Consumer.shouldSkipFunctionBody(D);
12267 }
12268
12269 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12270   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12271     FD->setHasSkippedBody();
12272   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12273     MD->setHasSkippedBody();
12274   return Decl;
12275 }
12276
12277 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12278   return ActOnFinishFunctionBody(D, BodyArg, false);
12279 }
12280
12281 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12282                                     bool IsInstantiation) {
12283   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12284
12285   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12286   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12287
12288   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12289     CheckCompletedCoroutineBody(FD, Body);
12290
12291   if (FD) {
12292     FD->setBody(Body);
12293     FD->setWillHaveBody(false);
12294
12295     if (getLangOpts().CPlusPlus14) {
12296       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12297           FD->getReturnType()->isUndeducedType()) {
12298         // If the function has a deduced result type but contains no 'return'
12299         // statements, the result type as written must be exactly 'auto', and
12300         // the deduced result type is 'void'.
12301         if (!FD->getReturnType()->getAs<AutoType>()) {
12302           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12303               << FD->getReturnType();
12304           FD->setInvalidDecl();
12305         } else {
12306           // Substitute 'void' for the 'auto' in the type.
12307           TypeLoc ResultType = getReturnTypeLoc(FD);
12308           Context.adjustDeducedFunctionResultType(
12309               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12310         }
12311       }
12312     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12313       // In C++11, we don't use 'auto' deduction rules for lambda call
12314       // operators because we don't support return type deduction.
12315       auto *LSI = getCurLambda();
12316       if (LSI->HasImplicitReturnType) {
12317         deduceClosureReturnType(*LSI);
12318
12319         // C++11 [expr.prim.lambda]p4:
12320         //   [...] if there are no return statements in the compound-statement
12321         //   [the deduced type is] the type void
12322         QualType RetType =
12323             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12324
12325         // Update the return type to the deduced type.
12326         const FunctionProtoType *Proto =
12327             FD->getType()->getAs<FunctionProtoType>();
12328         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12329                                             Proto->getExtProtoInfo()));
12330       }
12331     }
12332
12333     // The only way to be included in UndefinedButUsed is if there is an
12334     // ODR use before the definition. Avoid the expensive map lookup if this
12335     // is the first declaration.
12336     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12337       if (!FD->isExternallyVisible())
12338         UndefinedButUsed.erase(FD);
12339       else if (FD->isInlined() &&
12340                !LangOpts.GNUInline &&
12341                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12342         UndefinedButUsed.erase(FD);
12343     }
12344
12345     // If the function implicitly returns zero (like 'main') or is naked,
12346     // don't complain about missing return statements.
12347     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12348       WP.disableCheckFallThrough();
12349
12350     // MSVC permits the use of pure specifier (=0) on function definition,
12351     // defined at class scope, warn about this non-standard construct.
12352     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12353       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12354
12355     if (!FD->isInvalidDecl()) {
12356       // Don't diagnose unused parameters of defaulted or deleted functions.
12357       if (!FD->isDeleted() && !FD->isDefaulted())
12358         DiagnoseUnusedParameters(FD->parameters());
12359       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12360                                              FD->getReturnType(), FD);
12361
12362       // If this is a structor, we need a vtable.
12363       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12364         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12365       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12366         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12367
12368       // Try to apply the named return value optimization. We have to check
12369       // if we can do this here because lambdas keep return statements around
12370       // to deduce an implicit return type.
12371       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12372           !FD->isDependentContext())
12373         computeNRVO(Body, getCurFunction());
12374     }
12375
12376     // GNU warning -Wmissing-prototypes:
12377     //   Warn if a global function is defined without a previous
12378     //   prototype declaration. This warning is issued even if the
12379     //   definition itself provides a prototype. The aim is to detect
12380     //   global functions that fail to be declared in header files.
12381     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12382     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12383       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12384
12385       if (PossibleZeroParamPrototype) {
12386         // We found a declaration that is not a prototype,
12387         // but that could be a zero-parameter prototype
12388         if (TypeSourceInfo *TI =
12389                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12390           TypeLoc TL = TI->getTypeLoc();
12391           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12392             Diag(PossibleZeroParamPrototype->getLocation(),
12393                  diag::note_declaration_not_a_prototype)
12394                 << PossibleZeroParamPrototype
12395                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12396         }
12397       }
12398
12399       // GNU warning -Wstrict-prototypes
12400       //   Warn if K&R function is defined without a previous declaration.
12401       //   This warning is issued only if the definition itself does not provide
12402       //   a prototype. Only K&R definitions do not provide a prototype.
12403       //   An empty list in a function declarator that is part of a definition
12404       //   of that function specifies that the function has no parameters
12405       //   (C99 6.7.5.3p14)
12406       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12407           !LangOpts.CPlusPlus) {
12408         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12409         TypeLoc TL = TI->getTypeLoc();
12410         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12411         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12412       }
12413     }
12414
12415     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12416       const CXXMethodDecl *KeyFunction;
12417       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12418           MD->isVirtual() &&
12419           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12420           MD == KeyFunction->getCanonicalDecl()) {
12421         // Update the key-function state if necessary for this ABI.
12422         if (FD->isInlined() &&
12423             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12424           Context.setNonKeyFunction(MD);
12425
12426           // If the newly-chosen key function is already defined, then we
12427           // need to mark the vtable as used retroactively.
12428           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12429           const FunctionDecl *Definition;
12430           if (KeyFunction && KeyFunction->isDefined(Definition))
12431             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12432         } else {
12433           // We just defined they key function; mark the vtable as used.
12434           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12435         }
12436       }
12437     }
12438
12439     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12440            "Function parsing confused");
12441   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12442     assert(MD == getCurMethodDecl() && "Method parsing confused");
12443     MD->setBody(Body);
12444     if (!MD->isInvalidDecl()) {
12445       DiagnoseUnusedParameters(MD->parameters());
12446       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12447                                              MD->getReturnType(), MD);
12448
12449       if (Body)
12450         computeNRVO(Body, getCurFunction());
12451     }
12452     if (getCurFunction()->ObjCShouldCallSuper) {
12453       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12454         << MD->getSelector().getAsString();
12455       getCurFunction()->ObjCShouldCallSuper = false;
12456     }
12457     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12458       const ObjCMethodDecl *InitMethod = nullptr;
12459       bool isDesignated =
12460           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12461       assert(isDesignated && InitMethod);
12462       (void)isDesignated;
12463
12464       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12465         auto IFace = MD->getClassInterface();
12466         if (!IFace)
12467           return false;
12468         auto SuperD = IFace->getSuperClass();
12469         if (!SuperD)
12470           return false;
12471         return SuperD->getIdentifier() ==
12472             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12473       };
12474       // Don't issue this warning for unavailable inits or direct subclasses
12475       // of NSObject.
12476       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12477         Diag(MD->getLocation(),
12478              diag::warn_objc_designated_init_missing_super_call);
12479         Diag(InitMethod->getLocation(),
12480              diag::note_objc_designated_init_marked_here);
12481       }
12482       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12483     }
12484     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12485       // Don't issue this warning for unavaialable inits.
12486       if (!MD->isUnavailable())
12487         Diag(MD->getLocation(),
12488              diag::warn_objc_secondary_init_missing_init_call);
12489       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12490     }
12491   } else {
12492     return nullptr;
12493   }
12494
12495   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12496     DiagnoseUnguardedAvailabilityViolations(dcl);
12497
12498   assert(!getCurFunction()->ObjCShouldCallSuper &&
12499          "This should only be set for ObjC methods, which should have been "
12500          "handled in the block above.");
12501
12502   // Verify and clean out per-function state.
12503   if (Body && (!FD || !FD->isDefaulted())) {
12504     // C++ constructors that have function-try-blocks can't have return
12505     // statements in the handlers of that block. (C++ [except.handle]p14)
12506     // Verify this.
12507     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12508       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12509
12510     // Verify that gotos and switch cases don't jump into scopes illegally.
12511     if (getCurFunction()->NeedsScopeChecking() &&
12512         !PP.isCodeCompletionEnabled())
12513       DiagnoseInvalidJumps(Body);
12514
12515     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12516       if (!Destructor->getParent()->isDependentType())
12517         CheckDestructor(Destructor);
12518
12519       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12520                                              Destructor->getParent());
12521     }
12522
12523     // If any errors have occurred, clear out any temporaries that may have
12524     // been leftover. This ensures that these temporaries won't be picked up for
12525     // deletion in some later function.
12526     if (getDiagnostics().hasErrorOccurred() ||
12527         getDiagnostics().getSuppressAllDiagnostics()) {
12528       DiscardCleanupsInEvaluationContext();
12529     }
12530     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12531         !isa<FunctionTemplateDecl>(dcl)) {
12532       // Since the body is valid, issue any analysis-based warnings that are
12533       // enabled.
12534       ActivePolicy = &WP;
12535     }
12536
12537     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12538         (!CheckConstexprFunctionDecl(FD) ||
12539          !CheckConstexprFunctionBody(FD, Body)))
12540       FD->setInvalidDecl();
12541
12542     if (FD && FD->hasAttr<NakedAttr>()) {
12543       for (const Stmt *S : Body->children()) {
12544         // Allow local register variables without initializer as they don't
12545         // require prologue.
12546         bool RegisterVariables = false;
12547         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12548           for (const auto *Decl : DS->decls()) {
12549             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12550               RegisterVariables =
12551                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12552               if (!RegisterVariables)
12553                 break;
12554             }
12555           }
12556         }
12557         if (RegisterVariables)
12558           continue;
12559         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12560           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12561           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12562           FD->setInvalidDecl();
12563           break;
12564         }
12565       }
12566     }
12567
12568     assert(ExprCleanupObjects.size() ==
12569                ExprEvalContexts.back().NumCleanupObjects &&
12570            "Leftover temporaries in function");
12571     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12572     assert(MaybeODRUseExprs.empty() &&
12573            "Leftover expressions for odr-use checking");
12574   }
12575
12576   if (!IsInstantiation)
12577     PopDeclContext();
12578
12579   PopFunctionScopeInfo(ActivePolicy, dcl);
12580   // If any errors have occurred, clear out any temporaries that may have
12581   // been leftover. This ensures that these temporaries won't be picked up for
12582   // deletion in some later function.
12583   if (getDiagnostics().hasErrorOccurred()) {
12584     DiscardCleanupsInEvaluationContext();
12585   }
12586
12587   return dcl;
12588 }
12589
12590 /// When we finish delayed parsing of an attribute, we must attach it to the
12591 /// relevant Decl.
12592 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12593                                        ParsedAttributes &Attrs) {
12594   // Always attach attributes to the underlying decl.
12595   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12596     D = TD->getTemplatedDecl();
12597   ProcessDeclAttributeList(S, D, Attrs.getList());
12598
12599   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12600     if (Method->isStatic())
12601       checkThisInStaticMemberFunctionAttributes(Method);
12602 }
12603
12604 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12605 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12606 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12607                                           IdentifierInfo &II, Scope *S) {
12608   // Before we produce a declaration for an implicitly defined
12609   // function, see whether there was a locally-scoped declaration of
12610   // this name as a function or variable. If so, use that
12611   // (non-visible) declaration, and complain about it.
12612   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12613     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12614     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12615     return ExternCPrev;
12616   }
12617
12618   // Extension in C99.  Legal in C90, but warn about it.
12619   unsigned diag_id;
12620   if (II.getName().startswith("__builtin_"))
12621     diag_id = diag::warn_builtin_unknown;
12622   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12623   else if (getLangOpts().OpenCL)
12624     diag_id = diag::err_opencl_implicit_function_decl;
12625   else if (getLangOpts().C99)
12626     diag_id = diag::ext_implicit_function_decl;
12627   else
12628     diag_id = diag::warn_implicit_function_decl;
12629   Diag(Loc, diag_id) << &II;
12630
12631   // Because typo correction is expensive, only do it if the implicit
12632   // function declaration is going to be treated as an error.
12633   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12634     TypoCorrection Corrected;
12635     if (S &&
12636         (Corrected = CorrectTypo(
12637              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12638              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12639       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12640                    /*ErrorRecovery*/false);
12641   }
12642
12643   // Set a Declarator for the implicit definition: int foo();
12644   const char *Dummy;
12645   AttributeFactory attrFactory;
12646   DeclSpec DS(attrFactory);
12647   unsigned DiagID;
12648   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12649                                   Context.getPrintingPolicy());
12650   (void)Error; // Silence warning.
12651   assert(!Error && "Error setting up implicit decl!");
12652   SourceLocation NoLoc;
12653   Declarator D(DS, Declarator::BlockContext);
12654   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12655                                              /*IsAmbiguous=*/false,
12656                                              /*LParenLoc=*/NoLoc,
12657                                              /*Params=*/nullptr,
12658                                              /*NumParams=*/0,
12659                                              /*EllipsisLoc=*/NoLoc,
12660                                              /*RParenLoc=*/NoLoc,
12661                                              /*TypeQuals=*/0,
12662                                              /*RefQualifierIsLvalueRef=*/true,
12663                                              /*RefQualifierLoc=*/NoLoc,
12664                                              /*ConstQualifierLoc=*/NoLoc,
12665                                              /*VolatileQualifierLoc=*/NoLoc,
12666                                              /*RestrictQualifierLoc=*/NoLoc,
12667                                              /*MutableLoc=*/NoLoc,
12668                                              EST_None,
12669                                              /*ESpecRange=*/SourceRange(),
12670                                              /*Exceptions=*/nullptr,
12671                                              /*ExceptionRanges=*/nullptr,
12672                                              /*NumExceptions=*/0,
12673                                              /*NoexceptExpr=*/nullptr,
12674                                              /*ExceptionSpecTokens=*/nullptr,
12675                                              /*DeclsInPrototype=*/None,
12676                                              Loc, Loc, D),
12677                 DS.getAttributes(),
12678                 SourceLocation());
12679   D.SetIdentifier(&II, Loc);
12680
12681   // Insert this function into translation-unit scope.
12682
12683   DeclContext *PrevDC = CurContext;
12684   CurContext = Context.getTranslationUnitDecl();
12685
12686   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12687   FD->setImplicit();
12688
12689   CurContext = PrevDC;
12690
12691   AddKnownFunctionAttributes(FD);
12692
12693   return FD;
12694 }
12695
12696 /// \brief Adds any function attributes that we know a priori based on
12697 /// the declaration of this function.
12698 ///
12699 /// These attributes can apply both to implicitly-declared builtins
12700 /// (like __builtin___printf_chk) or to library-declared functions
12701 /// like NSLog or printf.
12702 ///
12703 /// We need to check for duplicate attributes both here and where user-written
12704 /// attributes are applied to declarations.
12705 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12706   if (FD->isInvalidDecl())
12707     return;
12708
12709   // If this is a built-in function, map its builtin attributes to
12710   // actual attributes.
12711   if (unsigned BuiltinID = FD->getBuiltinID()) {
12712     // Handle printf-formatting attributes.
12713     unsigned FormatIdx;
12714     bool HasVAListArg;
12715     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12716       if (!FD->hasAttr<FormatAttr>()) {
12717         const char *fmt = "printf";
12718         unsigned int NumParams = FD->getNumParams();
12719         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12720             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12721           fmt = "NSString";
12722         FD->addAttr(FormatAttr::CreateImplicit(Context,
12723                                                &Context.Idents.get(fmt),
12724                                                FormatIdx+1,
12725                                                HasVAListArg ? 0 : FormatIdx+2,
12726                                                FD->getLocation()));
12727       }
12728     }
12729     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12730                                              HasVAListArg)) {
12731      if (!FD->hasAttr<FormatAttr>())
12732        FD->addAttr(FormatAttr::CreateImplicit(Context,
12733                                               &Context.Idents.get("scanf"),
12734                                               FormatIdx+1,
12735                                               HasVAListArg ? 0 : FormatIdx+2,
12736                                               FD->getLocation()));
12737     }
12738
12739     // Mark const if we don't care about errno and that is the only
12740     // thing preventing the function from being const. This allows
12741     // IRgen to use LLVM intrinsics for such functions.
12742     if (!getLangOpts().MathErrno &&
12743         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12744       if (!FD->hasAttr<ConstAttr>())
12745         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12746     }
12747
12748     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12749         !FD->hasAttr<ReturnsTwiceAttr>())
12750       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12751                                          FD->getLocation()));
12752     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12753       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12754     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12755       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12756     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12757       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12758     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12759         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12760       // Add the appropriate attribute, depending on the CUDA compilation mode
12761       // and which target the builtin belongs to. For example, during host
12762       // compilation, aux builtins are __device__, while the rest are __host__.
12763       if (getLangOpts().CUDAIsDevice !=
12764           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12765         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12766       else
12767         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12768     }
12769   }
12770
12771   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12772   // throw, add an implicit nothrow attribute to any extern "C" function we come
12773   // across.
12774   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12775       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12776     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12777     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12778       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12779   }
12780
12781   IdentifierInfo *Name = FD->getIdentifier();
12782   if (!Name)
12783     return;
12784   if ((!getLangOpts().CPlusPlus &&
12785        FD->getDeclContext()->isTranslationUnit()) ||
12786       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12787        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12788        LinkageSpecDecl::lang_c)) {
12789     // Okay: this could be a libc/libm/Objective-C function we know
12790     // about.
12791   } else
12792     return;
12793
12794   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12795     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12796     // target-specific builtins, perhaps?
12797     if (!FD->hasAttr<FormatAttr>())
12798       FD->addAttr(FormatAttr::CreateImplicit(Context,
12799                                              &Context.Idents.get("printf"), 2,
12800                                              Name->isStr("vasprintf") ? 0 : 3,
12801                                              FD->getLocation()));
12802   }
12803
12804   if (Name->isStr("__CFStringMakeConstantString")) {
12805     // We already have a __builtin___CFStringMakeConstantString,
12806     // but builds that use -fno-constant-cfstrings don't go through that.
12807     if (!FD->hasAttr<FormatArgAttr>())
12808       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12809                                                 FD->getLocation()));
12810   }
12811 }
12812
12813 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12814                                     TypeSourceInfo *TInfo) {
12815   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12816   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12817
12818   if (!TInfo) {
12819     assert(D.isInvalidType() && "no declarator info for valid type");
12820     TInfo = Context.getTrivialTypeSourceInfo(T);
12821   }
12822
12823   // Scope manipulation handled by caller.
12824   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12825                                            D.getLocStart(),
12826                                            D.getIdentifierLoc(),
12827                                            D.getIdentifier(),
12828                                            TInfo);
12829
12830   // Bail out immediately if we have an invalid declaration.
12831   if (D.isInvalidType()) {
12832     NewTD->setInvalidDecl();
12833     return NewTD;
12834   }
12835
12836   if (D.getDeclSpec().isModulePrivateSpecified()) {
12837     if (CurContext->isFunctionOrMethod())
12838       Diag(NewTD->getLocation(), diag::err_module_private_local)
12839         << 2 << NewTD->getDeclName()
12840         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12841         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12842     else
12843       NewTD->setModulePrivate();
12844   }
12845
12846   // C++ [dcl.typedef]p8:
12847   //   If the typedef declaration defines an unnamed class (or
12848   //   enum), the first typedef-name declared by the declaration
12849   //   to be that class type (or enum type) is used to denote the
12850   //   class type (or enum type) for linkage purposes only.
12851   // We need to check whether the type was declared in the declaration.
12852   switch (D.getDeclSpec().getTypeSpecType()) {
12853   case TST_enum:
12854   case TST_struct:
12855   case TST_interface:
12856   case TST_union:
12857   case TST_class: {
12858     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12859     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12860     break;
12861   }
12862
12863   default:
12864     break;
12865   }
12866
12867   return NewTD;
12868 }
12869
12870 /// \brief Check that this is a valid underlying type for an enum declaration.
12871 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12872   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12873   QualType T = TI->getType();
12874
12875   if (T->isDependentType())
12876     return false;
12877
12878   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12879     if (BT->isInteger())
12880       return false;
12881
12882   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12883   return true;
12884 }
12885
12886 /// Check whether this is a valid redeclaration of a previous enumeration.
12887 /// \return true if the redeclaration was invalid.
12888 bool Sema::CheckEnumRedeclaration(
12889     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12890     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12891   bool IsFixed = !EnumUnderlyingTy.isNull();
12892
12893   if (IsScoped != Prev->isScoped()) {
12894     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12895       << Prev->isScoped();
12896     Diag(Prev->getLocation(), diag::note_previous_declaration);
12897     return true;
12898   }
12899
12900   if (IsFixed && Prev->isFixed()) {
12901     if (!EnumUnderlyingTy->isDependentType() &&
12902         !Prev->getIntegerType()->isDependentType() &&
12903         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12904                                         Prev->getIntegerType())) {
12905       // TODO: Highlight the underlying type of the redeclaration.
12906       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12907         << EnumUnderlyingTy << Prev->getIntegerType();
12908       Diag(Prev->getLocation(), diag::note_previous_declaration)
12909           << Prev->getIntegerTypeRange();
12910       return true;
12911     }
12912   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12913     ;
12914   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12915     ;
12916   } else if (IsFixed != Prev->isFixed()) {
12917     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12918       << Prev->isFixed();
12919     Diag(Prev->getLocation(), diag::note_previous_declaration);
12920     return true;
12921   }
12922
12923   return false;
12924 }
12925
12926 /// \brief Get diagnostic %select index for tag kind for
12927 /// redeclaration diagnostic message.
12928 /// WARNING: Indexes apply to particular diagnostics only!
12929 ///
12930 /// \returns diagnostic %select index.
12931 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12932   switch (Tag) {
12933   case TTK_Struct: return 0;
12934   case TTK_Interface: return 1;
12935   case TTK_Class:  return 2;
12936   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12937   }
12938 }
12939
12940 /// \brief Determine if tag kind is a class-key compatible with
12941 /// class for redeclaration (class, struct, or __interface).
12942 ///
12943 /// \returns true iff the tag kind is compatible.
12944 static bool isClassCompatTagKind(TagTypeKind Tag)
12945 {
12946   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12947 }
12948
12949 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12950                                              TagTypeKind TTK) {
12951   if (isa<TypedefDecl>(PrevDecl))
12952     return NTK_Typedef;
12953   else if (isa<TypeAliasDecl>(PrevDecl))
12954     return NTK_TypeAlias;
12955   else if (isa<ClassTemplateDecl>(PrevDecl))
12956     return NTK_Template;
12957   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12958     return NTK_TypeAliasTemplate;
12959   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12960     return NTK_TemplateTemplateArgument;
12961   switch (TTK) {
12962   case TTK_Struct:
12963   case TTK_Interface:
12964   case TTK_Class:
12965     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12966   case TTK_Union:
12967     return NTK_NonUnion;
12968   case TTK_Enum:
12969     return NTK_NonEnum;
12970   }
12971   llvm_unreachable("invalid TTK");
12972 }
12973
12974 /// \brief Determine whether a tag with a given kind is acceptable
12975 /// as a redeclaration of the given tag declaration.
12976 ///
12977 /// \returns true if the new tag kind is acceptable, false otherwise.
12978 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12979                                         TagTypeKind NewTag, bool isDefinition,
12980                                         SourceLocation NewTagLoc,
12981                                         const IdentifierInfo *Name) {
12982   // C++ [dcl.type.elab]p3:
12983   //   The class-key or enum keyword present in the
12984   //   elaborated-type-specifier shall agree in kind with the
12985   //   declaration to which the name in the elaborated-type-specifier
12986   //   refers. This rule also applies to the form of
12987   //   elaborated-type-specifier that declares a class-name or
12988   //   friend class since it can be construed as referring to the
12989   //   definition of the class. Thus, in any
12990   //   elaborated-type-specifier, the enum keyword shall be used to
12991   //   refer to an enumeration (7.2), the union class-key shall be
12992   //   used to refer to a union (clause 9), and either the class or
12993   //   struct class-key shall be used to refer to a class (clause 9)
12994   //   declared using the class or struct class-key.
12995   TagTypeKind OldTag = Previous->getTagKind();
12996   if (!isDefinition || !isClassCompatTagKind(NewTag))
12997     if (OldTag == NewTag)
12998       return true;
12999
13000   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13001     // Warn about the struct/class tag mismatch.
13002     bool isTemplate = false;
13003     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13004       isTemplate = Record->getDescribedClassTemplate();
13005
13006     if (inTemplateInstantiation()) {
13007       // In a template instantiation, do not offer fix-its for tag mismatches
13008       // since they usually mess up the template instead of fixing the problem.
13009       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13010         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13011         << getRedeclDiagFromTagKind(OldTag);
13012       return true;
13013     }
13014
13015     if (isDefinition) {
13016       // On definitions, check previous tags and issue a fix-it for each
13017       // one that doesn't match the current tag.
13018       if (Previous->getDefinition()) {
13019         // Don't suggest fix-its for redefinitions.
13020         return true;
13021       }
13022
13023       bool previousMismatch = false;
13024       for (auto I : Previous->redecls()) {
13025         if (I->getTagKind() != NewTag) {
13026           if (!previousMismatch) {
13027             previousMismatch = true;
13028             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13029               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13030               << getRedeclDiagFromTagKind(I->getTagKind());
13031           }
13032           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13033             << getRedeclDiagFromTagKind(NewTag)
13034             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13035                  TypeWithKeyword::getTagTypeKindName(NewTag));
13036         }
13037       }
13038       return true;
13039     }
13040
13041     // Check for a previous definition.  If current tag and definition
13042     // are same type, do nothing.  If no definition, but disagree with
13043     // with previous tag type, give a warning, but no fix-it.
13044     const TagDecl *Redecl = Previous->getDefinition() ?
13045                             Previous->getDefinition() : Previous;
13046     if (Redecl->getTagKind() == NewTag) {
13047       return true;
13048     }
13049
13050     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13051       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13052       << getRedeclDiagFromTagKind(OldTag);
13053     Diag(Redecl->getLocation(), diag::note_previous_use);
13054
13055     // If there is a previous definition, suggest a fix-it.
13056     if (Previous->getDefinition()) {
13057         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13058           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13059           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13060                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13061     }
13062
13063     return true;
13064   }
13065   return false;
13066 }
13067
13068 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13069 /// from an outer enclosing namespace or file scope inside a friend declaration.
13070 /// This should provide the commented out code in the following snippet:
13071 ///   namespace N {
13072 ///     struct X;
13073 ///     namespace M {
13074 ///       struct Y { friend struct /*N::*/ X; };
13075 ///     }
13076 ///   }
13077 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13078                                          SourceLocation NameLoc) {
13079   // While the decl is in a namespace, do repeated lookup of that name and see
13080   // if we get the same namespace back.  If we do not, continue until
13081   // translation unit scope, at which point we have a fully qualified NNS.
13082   SmallVector<IdentifierInfo *, 4> Namespaces;
13083   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13084   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13085     // This tag should be declared in a namespace, which can only be enclosed by
13086     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13087     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13088     if (!Namespace || Namespace->isAnonymousNamespace())
13089       return FixItHint();
13090     IdentifierInfo *II = Namespace->getIdentifier();
13091     Namespaces.push_back(II);
13092     NamedDecl *Lookup = SemaRef.LookupSingleName(
13093         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13094     if (Lookup == Namespace)
13095       break;
13096   }
13097
13098   // Once we have all the namespaces, reverse them to go outermost first, and
13099   // build an NNS.
13100   SmallString<64> Insertion;
13101   llvm::raw_svector_ostream OS(Insertion);
13102   if (DC->isTranslationUnit())
13103     OS << "::";
13104   std::reverse(Namespaces.begin(), Namespaces.end());
13105   for (auto *II : Namespaces)
13106     OS << II->getName() << "::";
13107   return FixItHint::CreateInsertion(NameLoc, Insertion);
13108 }
13109
13110 /// \brief Determine whether a tag originally declared in context \p OldDC can
13111 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13112 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13113 /// using-declaration).
13114 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13115                                          DeclContext *NewDC) {
13116   OldDC = OldDC->getRedeclContext();
13117   NewDC = NewDC->getRedeclContext();
13118
13119   if (OldDC->Equals(NewDC))
13120     return true;
13121
13122   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13123   // encloses the other).
13124   if (S.getLangOpts().MSVCCompat &&
13125       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13126     return true;
13127
13128   return false;
13129 }
13130
13131 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13132 /// former case, Name will be non-null.  In the later case, Name will be null.
13133 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13134 /// reference/declaration/definition of a tag.
13135 ///
13136 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13137 /// trailing-type-specifier) other than one in an alias-declaration.
13138 ///
13139 /// \param SkipBody If non-null, will be set to indicate if the caller should
13140 /// skip the definition of this tag and treat it as if it were a declaration.
13141 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13142                      SourceLocation KWLoc, CXXScopeSpec &SS,
13143                      IdentifierInfo *Name, SourceLocation NameLoc,
13144                      AttributeList *Attr, AccessSpecifier AS,
13145                      SourceLocation ModulePrivateLoc,
13146                      MultiTemplateParamsArg TemplateParameterLists,
13147                      bool &OwnedDecl, bool &IsDependent,
13148                      SourceLocation ScopedEnumKWLoc,
13149                      bool ScopedEnumUsesClassTag,
13150                      TypeResult UnderlyingType,
13151                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13152                      SkipBodyInfo *SkipBody) {
13153   // If this is not a definition, it must have a name.
13154   IdentifierInfo *OrigName = Name;
13155   assert((Name != nullptr || TUK == TUK_Definition) &&
13156          "Nameless record must be a definition!");
13157   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13158
13159   OwnedDecl = false;
13160   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13161   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13162
13163   // FIXME: Check member specializations more carefully.
13164   bool isMemberSpecialization = false;
13165   bool Invalid = false;
13166
13167   // We only need to do this matching if we have template parameters
13168   // or a scope specifier, which also conveniently avoids this work
13169   // for non-C++ cases.
13170   if (TemplateParameterLists.size() > 0 ||
13171       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13172     if (TemplateParameterList *TemplateParams =
13173             MatchTemplateParametersToScopeSpecifier(
13174                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13175                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13176       if (Kind == TTK_Enum) {
13177         Diag(KWLoc, diag::err_enum_template);
13178         return nullptr;
13179       }
13180
13181       if (TemplateParams->size() > 0) {
13182         // This is a declaration or definition of a class template (which may
13183         // be a member of another template).
13184
13185         if (Invalid)
13186           return nullptr;
13187
13188         OwnedDecl = false;
13189         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13190                                                SS, Name, NameLoc, Attr,
13191                                                TemplateParams, AS,
13192                                                ModulePrivateLoc,
13193                                                /*FriendLoc*/SourceLocation(),
13194                                                TemplateParameterLists.size()-1,
13195                                                TemplateParameterLists.data(),
13196                                                SkipBody);
13197         return Result.get();
13198       } else {
13199         // The "template<>" header is extraneous.
13200         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13201           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13202         isMemberSpecialization = true;
13203       }
13204     }
13205   }
13206
13207   // Figure out the underlying type if this a enum declaration. We need to do
13208   // this early, because it's needed to detect if this is an incompatible
13209   // redeclaration.
13210   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13211   bool EnumUnderlyingIsImplicit = false;
13212
13213   if (Kind == TTK_Enum) {
13214     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13215       // No underlying type explicitly specified, or we failed to parse the
13216       // type, default to int.
13217       EnumUnderlying = Context.IntTy.getTypePtr();
13218     else if (UnderlyingType.get()) {
13219       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13220       // integral type; any cv-qualification is ignored.
13221       TypeSourceInfo *TI = nullptr;
13222       GetTypeFromParser(UnderlyingType.get(), &TI);
13223       EnumUnderlying = TI;
13224
13225       if (CheckEnumUnderlyingType(TI))
13226         // Recover by falling back to int.
13227         EnumUnderlying = Context.IntTy.getTypePtr();
13228
13229       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13230                                           UPPC_FixedUnderlyingType))
13231         EnumUnderlying = Context.IntTy.getTypePtr();
13232
13233     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13234       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13235         // Microsoft enums are always of int type.
13236         EnumUnderlying = Context.IntTy.getTypePtr();
13237         EnumUnderlyingIsImplicit = true;
13238       }
13239     }
13240   }
13241
13242   DeclContext *SearchDC = CurContext;
13243   DeclContext *DC = CurContext;
13244   bool isStdBadAlloc = false;
13245   bool isStdAlignValT = false;
13246
13247   RedeclarationKind Redecl = ForRedeclaration;
13248   if (TUK == TUK_Friend || TUK == TUK_Reference)
13249     Redecl = NotForRedeclaration;
13250
13251   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13252   /// implemented asks for structural equivalence checking, the returned decl
13253   /// here is passed back to the parser, allowing the tag body to be parsed.
13254   auto createTagFromNewDecl = [&]() -> TagDecl * {
13255     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13256     // If there is an identifier, use the location of the identifier as the
13257     // location of the decl, otherwise use the location of the struct/union
13258     // keyword.
13259     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13260     TagDecl *New = nullptr;
13261
13262     if (Kind == TTK_Enum) {
13263       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13264                              ScopedEnum, ScopedEnumUsesClassTag,
13265                              !EnumUnderlying.isNull());
13266       // If this is an undefined enum, bail.
13267       if (TUK != TUK_Definition && !Invalid)
13268         return nullptr;
13269       if (EnumUnderlying) {
13270         EnumDecl *ED = cast<EnumDecl>(New);
13271         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13272           ED->setIntegerTypeSourceInfo(TI);
13273         else
13274           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13275         ED->setPromotionType(ED->getIntegerType());
13276       }
13277     } else { // struct/union
13278       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13279                                nullptr);
13280     }
13281
13282     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13283       // Add alignment attributes if necessary; these attributes are checked
13284       // when the ASTContext lays out the structure.
13285       //
13286       // It is important for implementing the correct semantics that this
13287       // happen here (in ActOnTag). The #pragma pack stack is
13288       // maintained as a result of parser callbacks which can occur at
13289       // many points during the parsing of a struct declaration (because
13290       // the #pragma tokens are effectively skipped over during the
13291       // parsing of the struct).
13292       if (TUK == TUK_Definition) {
13293         AddAlignmentAttributesForRecord(RD);
13294         AddMsStructLayoutForRecord(RD);
13295       }
13296     }
13297     New->setLexicalDeclContext(CurContext);
13298     return New;
13299   };
13300
13301   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13302   if (Name && SS.isNotEmpty()) {
13303     // We have a nested-name tag ('struct foo::bar').
13304
13305     // Check for invalid 'foo::'.
13306     if (SS.isInvalid()) {
13307       Name = nullptr;
13308       goto CreateNewDecl;
13309     }
13310
13311     // If this is a friend or a reference to a class in a dependent
13312     // context, don't try to make a decl for it.
13313     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13314       DC = computeDeclContext(SS, false);
13315       if (!DC) {
13316         IsDependent = true;
13317         return nullptr;
13318       }
13319     } else {
13320       DC = computeDeclContext(SS, true);
13321       if (!DC) {
13322         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13323           << SS.getRange();
13324         return nullptr;
13325       }
13326     }
13327
13328     if (RequireCompleteDeclContext(SS, DC))
13329       return nullptr;
13330
13331     SearchDC = DC;
13332     // Look-up name inside 'foo::'.
13333     LookupQualifiedName(Previous, DC);
13334
13335     if (Previous.isAmbiguous())
13336       return nullptr;
13337
13338     if (Previous.empty()) {
13339       // Name lookup did not find anything. However, if the
13340       // nested-name-specifier refers to the current instantiation,
13341       // and that current instantiation has any dependent base
13342       // classes, we might find something at instantiation time: treat
13343       // this as a dependent elaborated-type-specifier.
13344       // But this only makes any sense for reference-like lookups.
13345       if (Previous.wasNotFoundInCurrentInstantiation() &&
13346           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13347         IsDependent = true;
13348         return nullptr;
13349       }
13350
13351       // A tag 'foo::bar' must already exist.
13352       Diag(NameLoc, diag::err_not_tag_in_scope)
13353         << Kind << Name << DC << SS.getRange();
13354       Name = nullptr;
13355       Invalid = true;
13356       goto CreateNewDecl;
13357     }
13358   } else if (Name) {
13359     // C++14 [class.mem]p14:
13360     //   If T is the name of a class, then each of the following shall have a
13361     //   name different from T:
13362     //    -- every member of class T that is itself a type
13363     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13364         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13365       return nullptr;
13366
13367     // If this is a named struct, check to see if there was a previous forward
13368     // declaration or definition.
13369     // FIXME: We're looking into outer scopes here, even when we
13370     // shouldn't be. Doing so can result in ambiguities that we
13371     // shouldn't be diagnosing.
13372     LookupName(Previous, S);
13373
13374     // When declaring or defining a tag, ignore ambiguities introduced
13375     // by types using'ed into this scope.
13376     if (Previous.isAmbiguous() &&
13377         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13378       LookupResult::Filter F = Previous.makeFilter();
13379       while (F.hasNext()) {
13380         NamedDecl *ND = F.next();
13381         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13382                 SearchDC->getRedeclContext()))
13383           F.erase();
13384       }
13385       F.done();
13386     }
13387
13388     // C++11 [namespace.memdef]p3:
13389     //   If the name in a friend declaration is neither qualified nor
13390     //   a template-id and the declaration is a function or an
13391     //   elaborated-type-specifier, the lookup to determine whether
13392     //   the entity has been previously declared shall not consider
13393     //   any scopes outside the innermost enclosing namespace.
13394     //
13395     // MSVC doesn't implement the above rule for types, so a friend tag
13396     // declaration may be a redeclaration of a type declared in an enclosing
13397     // scope.  They do implement this rule for friend functions.
13398     //
13399     // Does it matter that this should be by scope instead of by
13400     // semantic context?
13401     if (!Previous.empty() && TUK == TUK_Friend) {
13402       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13403       LookupResult::Filter F = Previous.makeFilter();
13404       bool FriendSawTagOutsideEnclosingNamespace = false;
13405       while (F.hasNext()) {
13406         NamedDecl *ND = F.next();
13407         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13408         if (DC->isFileContext() &&
13409             !EnclosingNS->Encloses(ND->getDeclContext())) {
13410           if (getLangOpts().MSVCCompat)
13411             FriendSawTagOutsideEnclosingNamespace = true;
13412           else
13413             F.erase();
13414         }
13415       }
13416       F.done();
13417
13418       // Diagnose this MSVC extension in the easy case where lookup would have
13419       // unambiguously found something outside the enclosing namespace.
13420       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13421         NamedDecl *ND = Previous.getFoundDecl();
13422         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13423             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13424       }
13425     }
13426
13427     // Note:  there used to be some attempt at recovery here.
13428     if (Previous.isAmbiguous())
13429       return nullptr;
13430
13431     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13432       // FIXME: This makes sure that we ignore the contexts associated
13433       // with C structs, unions, and enums when looking for a matching
13434       // tag declaration or definition. See the similar lookup tweak
13435       // in Sema::LookupName; is there a better way to deal with this?
13436       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13437         SearchDC = SearchDC->getParent();
13438     }
13439   }
13440
13441   if (Previous.isSingleResult() &&
13442       Previous.getFoundDecl()->isTemplateParameter()) {
13443     // Maybe we will complain about the shadowed template parameter.
13444     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13445     // Just pretend that we didn't see the previous declaration.
13446     Previous.clear();
13447   }
13448
13449   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13450       DC->Equals(getStdNamespace())) {
13451     if (Name->isStr("bad_alloc")) {
13452       // This is a declaration of or a reference to "std::bad_alloc".
13453       isStdBadAlloc = true;
13454
13455       // If std::bad_alloc has been implicitly declared (but made invisible to
13456       // name lookup), fill in this implicit declaration as the previous
13457       // declaration, so that the declarations get chained appropriately.
13458       if (Previous.empty() && StdBadAlloc)
13459         Previous.addDecl(getStdBadAlloc());
13460     } else if (Name->isStr("align_val_t")) {
13461       isStdAlignValT = true;
13462       if (Previous.empty() && StdAlignValT)
13463         Previous.addDecl(getStdAlignValT());
13464     }
13465   }
13466
13467   // If we didn't find a previous declaration, and this is a reference
13468   // (or friend reference), move to the correct scope.  In C++, we
13469   // also need to do a redeclaration lookup there, just in case
13470   // there's a shadow friend decl.
13471   if (Name && Previous.empty() &&
13472       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13473     if (Invalid) goto CreateNewDecl;
13474     assert(SS.isEmpty());
13475
13476     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13477       // C++ [basic.scope.pdecl]p5:
13478       //   -- for an elaborated-type-specifier of the form
13479       //
13480       //          class-key identifier
13481       //
13482       //      if the elaborated-type-specifier is used in the
13483       //      decl-specifier-seq or parameter-declaration-clause of a
13484       //      function defined in namespace scope, the identifier is
13485       //      declared as a class-name in the namespace that contains
13486       //      the declaration; otherwise, except as a friend
13487       //      declaration, the identifier is declared in the smallest
13488       //      non-class, non-function-prototype scope that contains the
13489       //      declaration.
13490       //
13491       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13492       // C structs and unions.
13493       //
13494       // It is an error in C++ to declare (rather than define) an enum
13495       // type, including via an elaborated type specifier.  We'll
13496       // diagnose that later; for now, declare the enum in the same
13497       // scope as we would have picked for any other tag type.
13498       //
13499       // GNU C also supports this behavior as part of its incomplete
13500       // enum types extension, while GNU C++ does not.
13501       //
13502       // Find the context where we'll be declaring the tag.
13503       // FIXME: We would like to maintain the current DeclContext as the
13504       // lexical context,
13505       SearchDC = getTagInjectionContext(SearchDC);
13506
13507       // Find the scope where we'll be declaring the tag.
13508       S = getTagInjectionScope(S, getLangOpts());
13509     } else {
13510       assert(TUK == TUK_Friend);
13511       // C++ [namespace.memdef]p3:
13512       //   If a friend declaration in a non-local class first declares a
13513       //   class or function, the friend class or function is a member of
13514       //   the innermost enclosing namespace.
13515       SearchDC = SearchDC->getEnclosingNamespaceContext();
13516     }
13517
13518     // In C++, we need to do a redeclaration lookup to properly
13519     // diagnose some problems.
13520     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13521     // hidden declaration so that we don't get ambiguity errors when using a
13522     // type declared by an elaborated-type-specifier.  In C that is not correct
13523     // and we should instead merge compatible types found by lookup.
13524     if (getLangOpts().CPlusPlus) {
13525       Previous.setRedeclarationKind(ForRedeclaration);
13526       LookupQualifiedName(Previous, SearchDC);
13527     } else {
13528       Previous.setRedeclarationKind(ForRedeclaration);
13529       LookupName(Previous, S);
13530     }
13531   }
13532
13533   // If we have a known previous declaration to use, then use it.
13534   if (Previous.empty() && SkipBody && SkipBody->Previous)
13535     Previous.addDecl(SkipBody->Previous);
13536
13537   if (!Previous.empty()) {
13538     NamedDecl *PrevDecl = Previous.getFoundDecl();
13539     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13540
13541     // It's okay to have a tag decl in the same scope as a typedef
13542     // which hides a tag decl in the same scope.  Finding this
13543     // insanity with a redeclaration lookup can only actually happen
13544     // in C++.
13545     //
13546     // This is also okay for elaborated-type-specifiers, which is
13547     // technically forbidden by the current standard but which is
13548     // okay according to the likely resolution of an open issue;
13549     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13550     if (getLangOpts().CPlusPlus) {
13551       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13552         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13553           TagDecl *Tag = TT->getDecl();
13554           if (Tag->getDeclName() == Name &&
13555               Tag->getDeclContext()->getRedeclContext()
13556                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13557             PrevDecl = Tag;
13558             Previous.clear();
13559             Previous.addDecl(Tag);
13560             Previous.resolveKind();
13561           }
13562         }
13563       }
13564     }
13565
13566     // If this is a redeclaration of a using shadow declaration, it must
13567     // declare a tag in the same context. In MSVC mode, we allow a
13568     // redefinition if either context is within the other.
13569     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13570       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13571       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13572           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13573           !(OldTag && isAcceptableTagRedeclContext(
13574                           *this, OldTag->getDeclContext(), SearchDC))) {
13575         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13576         Diag(Shadow->getTargetDecl()->getLocation(),
13577              diag::note_using_decl_target);
13578         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13579             << 0;
13580         // Recover by ignoring the old declaration.
13581         Previous.clear();
13582         goto CreateNewDecl;
13583       }
13584     }
13585
13586     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13587       // If this is a use of a previous tag, or if the tag is already declared
13588       // in the same scope (so that the definition/declaration completes or
13589       // rementions the tag), reuse the decl.
13590       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13591           isDeclInScope(DirectPrevDecl, SearchDC, S,
13592                         SS.isNotEmpty() || isMemberSpecialization)) {
13593         // Make sure that this wasn't declared as an enum and now used as a
13594         // struct or something similar.
13595         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13596                                           TUK == TUK_Definition, KWLoc,
13597                                           Name)) {
13598           bool SafeToContinue
13599             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13600                Kind != TTK_Enum);
13601           if (SafeToContinue)
13602             Diag(KWLoc, diag::err_use_with_wrong_tag)
13603               << Name
13604               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13605                                               PrevTagDecl->getKindName());
13606           else
13607             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13608           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13609
13610           if (SafeToContinue)
13611             Kind = PrevTagDecl->getTagKind();
13612           else {
13613             // Recover by making this an anonymous redefinition.
13614             Name = nullptr;
13615             Previous.clear();
13616             Invalid = true;
13617           }
13618         }
13619
13620         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13621           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13622
13623           // If this is an elaborated-type-specifier for a scoped enumeration,
13624           // the 'class' keyword is not necessary and not permitted.
13625           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13626             if (ScopedEnum)
13627               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13628                 << PrevEnum->isScoped()
13629                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13630             return PrevTagDecl;
13631           }
13632
13633           QualType EnumUnderlyingTy;
13634           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13635             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13636           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13637             EnumUnderlyingTy = QualType(T, 0);
13638
13639           // All conflicts with previous declarations are recovered by
13640           // returning the previous declaration, unless this is a definition,
13641           // in which case we want the caller to bail out.
13642           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13643                                      ScopedEnum, EnumUnderlyingTy,
13644                                      EnumUnderlyingIsImplicit, PrevEnum))
13645             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13646         }
13647
13648         // C++11 [class.mem]p1:
13649         //   A member shall not be declared twice in the member-specification,
13650         //   except that a nested class or member class template can be declared
13651         //   and then later defined.
13652         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13653             S->isDeclScope(PrevDecl)) {
13654           Diag(NameLoc, diag::ext_member_redeclared);
13655           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13656         }
13657
13658         if (!Invalid) {
13659           // If this is a use, just return the declaration we found, unless
13660           // we have attributes.
13661           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13662             if (Attr) {
13663               // FIXME: Diagnose these attributes. For now, we create a new
13664               // declaration to hold them.
13665             } else if (TUK == TUK_Reference &&
13666                        (PrevTagDecl->getFriendObjectKind() ==
13667                             Decl::FOK_Undeclared ||
13668                         PrevDecl->getOwningModule() != getCurrentModule()) &&
13669                        SS.isEmpty()) {
13670               // This declaration is a reference to an existing entity, but
13671               // has different visibility from that entity: it either makes
13672               // a friend visible or it makes a type visible in a new module.
13673               // In either case, create a new declaration. We only do this if
13674               // the declaration would have meant the same thing if no prior
13675               // declaration were found, that is, if it was found in the same
13676               // scope where we would have injected a declaration.
13677               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13678                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13679                 return PrevTagDecl;
13680               // This is in the injected scope, create a new declaration in
13681               // that scope.
13682               S = getTagInjectionScope(S, getLangOpts());
13683             } else {
13684               return PrevTagDecl;
13685             }
13686           }
13687
13688           // Diagnose attempts to redefine a tag.
13689           if (TUK == TUK_Definition) {
13690             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13691               // If we're defining a specialization and the previous definition
13692               // is from an implicit instantiation, don't emit an error
13693               // here; we'll catch this in the general case below.
13694               bool IsExplicitSpecializationAfterInstantiation = false;
13695               if (isMemberSpecialization) {
13696                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13697                   IsExplicitSpecializationAfterInstantiation =
13698                     RD->getTemplateSpecializationKind() !=
13699                     TSK_ExplicitSpecialization;
13700                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13701                   IsExplicitSpecializationAfterInstantiation =
13702                     ED->getTemplateSpecializationKind() !=
13703                     TSK_ExplicitSpecialization;
13704               }
13705
13706               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
13707               // not keep more that one definition around (merge them). However,
13708               // ensure the decl passes the structural compatibility check in
13709               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
13710               NamedDecl *Hidden = nullptr;
13711               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
13712                 // There is a definition of this tag, but it is not visible. We
13713                 // explicitly make use of C++'s one definition rule here, and
13714                 // assume that this definition is identical to the hidden one
13715                 // we already have. Make the existing definition visible and
13716                 // use it in place of this one.
13717                 if (!getLangOpts().CPlusPlus) {
13718                   // Postpone making the old definition visible until after we
13719                   // complete parsing the new one and do the structural
13720                   // comparison.
13721                   SkipBody->CheckSameAsPrevious = true;
13722                   SkipBody->New = createTagFromNewDecl();
13723                   SkipBody->Previous = Hidden;
13724                 } else {
13725                   SkipBody->ShouldSkip = true;
13726                   makeMergedDefinitionVisible(Hidden);
13727                 }
13728                 return Def;
13729               } else if (!IsExplicitSpecializationAfterInstantiation) {
13730                 // A redeclaration in function prototype scope in C isn't
13731                 // visible elsewhere, so merely issue a warning.
13732                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13733                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13734                 else
13735                   Diag(NameLoc, diag::err_redefinition) << Name;
13736                 notePreviousDefinition(Def,
13737                                        NameLoc.isValid() ? NameLoc : KWLoc);
13738                 // If this is a redefinition, recover by making this
13739                 // struct be anonymous, which will make any later
13740                 // references get the previous definition.
13741                 Name = nullptr;
13742                 Previous.clear();
13743                 Invalid = true;
13744               }
13745             } else {
13746               // If the type is currently being defined, complain
13747               // about a nested redefinition.
13748               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13749               if (TD->isBeingDefined()) {
13750                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13751                 Diag(PrevTagDecl->getLocation(),
13752                      diag::note_previous_definition);
13753                 Name = nullptr;
13754                 Previous.clear();
13755                 Invalid = true;
13756               }
13757             }
13758
13759             // Okay, this is definition of a previously declared or referenced
13760             // tag. We're going to create a new Decl for it.
13761           }
13762
13763           // Okay, we're going to make a redeclaration.  If this is some kind
13764           // of reference, make sure we build the redeclaration in the same DC
13765           // as the original, and ignore the current access specifier.
13766           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13767             SearchDC = PrevTagDecl->getDeclContext();
13768             AS = AS_none;
13769           }
13770         }
13771         // If we get here we have (another) forward declaration or we
13772         // have a definition.  Just create a new decl.
13773
13774       } else {
13775         // If we get here, this is a definition of a new tag type in a nested
13776         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13777         // new decl/type.  We set PrevDecl to NULL so that the entities
13778         // have distinct types.
13779         Previous.clear();
13780       }
13781       // If we get here, we're going to create a new Decl. If PrevDecl
13782       // is non-NULL, it's a definition of the tag declared by
13783       // PrevDecl. If it's NULL, we have a new definition.
13784
13785     // Otherwise, PrevDecl is not a tag, but was found with tag
13786     // lookup.  This is only actually possible in C++, where a few
13787     // things like templates still live in the tag namespace.
13788     } else {
13789       // Use a better diagnostic if an elaborated-type-specifier
13790       // found the wrong kind of type on the first
13791       // (non-redeclaration) lookup.
13792       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13793           !Previous.isForRedeclaration()) {
13794         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13795         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13796                                                        << Kind;
13797         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13798         Invalid = true;
13799
13800       // Otherwise, only diagnose if the declaration is in scope.
13801       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13802                                 SS.isNotEmpty() || isMemberSpecialization)) {
13803         // do nothing
13804
13805       // Diagnose implicit declarations introduced by elaborated types.
13806       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13807         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13808         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13809         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13810         Invalid = true;
13811
13812       // Otherwise it's a declaration.  Call out a particularly common
13813       // case here.
13814       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13815         unsigned Kind = 0;
13816         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13817         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13818           << Name << Kind << TND->getUnderlyingType();
13819         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13820         Invalid = true;
13821
13822       // Otherwise, diagnose.
13823       } else {
13824         // The tag name clashes with something else in the target scope,
13825         // issue an error and recover by making this tag be anonymous.
13826         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13827         notePreviousDefinition(PrevDecl, NameLoc);
13828         Name = nullptr;
13829         Invalid = true;
13830       }
13831
13832       // The existing declaration isn't relevant to us; we're in a
13833       // new scope, so clear out the previous declaration.
13834       Previous.clear();
13835     }
13836   }
13837
13838 CreateNewDecl:
13839
13840   TagDecl *PrevDecl = nullptr;
13841   if (Previous.isSingleResult())
13842     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13843
13844   // If there is an identifier, use the location of the identifier as the
13845   // location of the decl, otherwise use the location of the struct/union
13846   // keyword.
13847   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13848
13849   // Otherwise, create a new declaration. If there is a previous
13850   // declaration of the same entity, the two will be linked via
13851   // PrevDecl.
13852   TagDecl *New;
13853
13854   bool IsForwardReference = false;
13855   if (Kind == TTK_Enum) {
13856     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13857     // enum X { A, B, C } D;    D should chain to X.
13858     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13859                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13860                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13861
13862     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13863       StdAlignValT = cast<EnumDecl>(New);
13864
13865     // If this is an undefined enum, warn.
13866     if (TUK != TUK_Definition && !Invalid) {
13867       TagDecl *Def;
13868       if (!EnumUnderlyingIsImplicit &&
13869           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13870           cast<EnumDecl>(New)->isFixed()) {
13871         // C++0x: 7.2p2: opaque-enum-declaration.
13872         // Conflicts are diagnosed above. Do nothing.
13873       }
13874       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13875         Diag(Loc, diag::ext_forward_ref_enum_def)
13876           << New;
13877         Diag(Def->getLocation(), diag::note_previous_definition);
13878       } else {
13879         unsigned DiagID = diag::ext_forward_ref_enum;
13880         if (getLangOpts().MSVCCompat)
13881           DiagID = diag::ext_ms_forward_ref_enum;
13882         else if (getLangOpts().CPlusPlus)
13883           DiagID = diag::err_forward_ref_enum;
13884         Diag(Loc, DiagID);
13885
13886         // If this is a forward-declared reference to an enumeration, make a
13887         // note of it; we won't actually be introducing the declaration into
13888         // the declaration context.
13889         if (TUK == TUK_Reference)
13890           IsForwardReference = true;
13891       }
13892     }
13893
13894     if (EnumUnderlying) {
13895       EnumDecl *ED = cast<EnumDecl>(New);
13896       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13897         ED->setIntegerTypeSourceInfo(TI);
13898       else
13899         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13900       ED->setPromotionType(ED->getIntegerType());
13901     }
13902   } else {
13903     // struct/union/class
13904
13905     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13906     // struct X { int A; } D;    D should chain to X.
13907     if (getLangOpts().CPlusPlus) {
13908       // FIXME: Look for a way to use RecordDecl for simple structs.
13909       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13910                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13911
13912       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13913         StdBadAlloc = cast<CXXRecordDecl>(New);
13914     } else
13915       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13916                                cast_or_null<RecordDecl>(PrevDecl));
13917   }
13918
13919   // C++11 [dcl.type]p3:
13920   //   A type-specifier-seq shall not define a class or enumeration [...].
13921   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
13922       TUK == TUK_Definition) {
13923     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13924       << Context.getTagDeclType(New);
13925     Invalid = true;
13926   }
13927
13928   // Maybe add qualifier info.
13929   if (SS.isNotEmpty()) {
13930     if (SS.isSet()) {
13931       // If this is either a declaration or a definition, check the
13932       // nested-name-specifier against the current context. We don't do this
13933       // for explicit specializations, because they have similar checking
13934       // (with more specific diagnostics) in the call to
13935       // CheckMemberSpecialization, below.
13936       if (!isMemberSpecialization &&
13937           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13938           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13939         Invalid = true;
13940
13941       New->setQualifierInfo(SS.getWithLocInContext(Context));
13942       if (TemplateParameterLists.size() > 0) {
13943         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13944       }
13945     }
13946     else
13947       Invalid = true;
13948   }
13949
13950   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13951     // Add alignment attributes if necessary; these attributes are checked when
13952     // the ASTContext lays out the structure.
13953     //
13954     // It is important for implementing the correct semantics that this
13955     // happen here (in ActOnTag). The #pragma pack stack is
13956     // maintained as a result of parser callbacks which can occur at
13957     // many points during the parsing of a struct declaration (because
13958     // the #pragma tokens are effectively skipped over during the
13959     // parsing of the struct).
13960     if (TUK == TUK_Definition) {
13961       AddAlignmentAttributesForRecord(RD);
13962       AddMsStructLayoutForRecord(RD);
13963     }
13964   }
13965
13966   if (ModulePrivateLoc.isValid()) {
13967     if (isMemberSpecialization)
13968       Diag(New->getLocation(), diag::err_module_private_specialization)
13969         << 2
13970         << FixItHint::CreateRemoval(ModulePrivateLoc);
13971     // __module_private__ does not apply to local classes. However, we only
13972     // diagnose this as an error when the declaration specifiers are
13973     // freestanding. Here, we just ignore the __module_private__.
13974     else if (!SearchDC->isFunctionOrMethod())
13975       New->setModulePrivate();
13976   }
13977
13978   // If this is a specialization of a member class (of a class template),
13979   // check the specialization.
13980   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13981     Invalid = true;
13982
13983   // If we're declaring or defining a tag in function prototype scope in C,
13984   // note that this type can only be used within the function and add it to
13985   // the list of decls to inject into the function definition scope.
13986   if ((Name || Kind == TTK_Enum) &&
13987       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13988     if (getLangOpts().CPlusPlus) {
13989       // C++ [dcl.fct]p6:
13990       //   Types shall not be defined in return or parameter types.
13991       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13992         Diag(Loc, diag::err_type_defined_in_param_type)
13993             << Name;
13994         Invalid = true;
13995       }
13996     } else if (!PrevDecl) {
13997       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13998     }
13999   }
14000
14001   if (Invalid)
14002     New->setInvalidDecl();
14003
14004   // Set the lexical context. If the tag has a C++ scope specifier, the
14005   // lexical context will be different from the semantic context.
14006   New->setLexicalDeclContext(CurContext);
14007
14008   // Mark this as a friend decl if applicable.
14009   // In Microsoft mode, a friend declaration also acts as a forward
14010   // declaration so we always pass true to setObjectOfFriendDecl to make
14011   // the tag name visible.
14012   if (TUK == TUK_Friend)
14013     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14014
14015   // Set the access specifier.
14016   if (!Invalid && SearchDC->isRecord())
14017     SetMemberAccessSpecifier(New, PrevDecl, AS);
14018
14019   if (TUK == TUK_Definition)
14020     New->startDefinition();
14021
14022   if (Attr)
14023     ProcessDeclAttributeList(S, New, Attr);
14024   AddPragmaAttributes(S, New);
14025
14026   // If this has an identifier, add it to the scope stack.
14027   if (TUK == TUK_Friend) {
14028     // We might be replacing an existing declaration in the lookup tables;
14029     // if so, borrow its access specifier.
14030     if (PrevDecl)
14031       New->setAccess(PrevDecl->getAccess());
14032
14033     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14034     DC->makeDeclVisibleInContext(New);
14035     if (Name) // can be null along some error paths
14036       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14037         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14038   } else if (Name) {
14039     S = getNonFieldDeclScope(S);
14040     PushOnScopeChains(New, S, !IsForwardReference);
14041     if (IsForwardReference)
14042       SearchDC->makeDeclVisibleInContext(New);
14043   } else {
14044     CurContext->addDecl(New);
14045   }
14046
14047   // If this is the C FILE type, notify the AST context.
14048   if (IdentifierInfo *II = New->getIdentifier())
14049     if (!New->isInvalidDecl() &&
14050         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14051         II->isStr("FILE"))
14052       Context.setFILEDecl(New);
14053
14054   if (PrevDecl)
14055     mergeDeclAttributes(New, PrevDecl);
14056
14057   // If there's a #pragma GCC visibility in scope, set the visibility of this
14058   // record.
14059   AddPushedVisibilityAttribute(New);
14060
14061   if (isMemberSpecialization && !New->isInvalidDecl())
14062     CompleteMemberSpecialization(New, Previous);
14063
14064   OwnedDecl = true;
14065   // In C++, don't return an invalid declaration. We can't recover well from
14066   // the cases where we make the type anonymous.
14067   if (Invalid && getLangOpts().CPlusPlus) {
14068     if (New->isBeingDefined())
14069       if (auto RD = dyn_cast<RecordDecl>(New))
14070         RD->completeDefinition();
14071     return nullptr;
14072   } else {
14073     return New;
14074   }
14075 }
14076
14077 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14078   AdjustDeclIfTemplate(TagD);
14079   TagDecl *Tag = cast<TagDecl>(TagD);
14080
14081   // Enter the tag context.
14082   PushDeclContext(S, Tag);
14083
14084   ActOnDocumentableDecl(TagD);
14085
14086   // If there's a #pragma GCC visibility in scope, set the visibility of this
14087   // record.
14088   AddPushedVisibilityAttribute(Tag);
14089 }
14090
14091 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14092                                     SkipBodyInfo &SkipBody) {
14093   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14094     return false;
14095
14096   // Make the previous decl visible.
14097   makeMergedDefinitionVisible(SkipBody.Previous);
14098   return true;
14099 }
14100
14101 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14102   assert(isa<ObjCContainerDecl>(IDecl) &&
14103          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14104   DeclContext *OCD = cast<DeclContext>(IDecl);
14105   assert(getContainingDC(OCD) == CurContext &&
14106       "The next DeclContext should be lexically contained in the current one.");
14107   CurContext = OCD;
14108   return IDecl;
14109 }
14110
14111 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14112                                            SourceLocation FinalLoc,
14113                                            bool IsFinalSpelledSealed,
14114                                            SourceLocation LBraceLoc) {
14115   AdjustDeclIfTemplate(TagD);
14116   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14117
14118   FieldCollector->StartClass();
14119
14120   if (!Record->getIdentifier())
14121     return;
14122
14123   if (FinalLoc.isValid())
14124     Record->addAttr(new (Context)
14125                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14126
14127   // C++ [class]p2:
14128   //   [...] The class-name is also inserted into the scope of the
14129   //   class itself; this is known as the injected-class-name. For
14130   //   purposes of access checking, the injected-class-name is treated
14131   //   as if it were a public member name.
14132   CXXRecordDecl *InjectedClassName
14133     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14134                             Record->getLocStart(), Record->getLocation(),
14135                             Record->getIdentifier(),
14136                             /*PrevDecl=*/nullptr,
14137                             /*DelayTypeCreation=*/true);
14138   Context.getTypeDeclType(InjectedClassName, Record);
14139   InjectedClassName->setImplicit();
14140   InjectedClassName->setAccess(AS_public);
14141   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14142       InjectedClassName->setDescribedClassTemplate(Template);
14143   PushOnScopeChains(InjectedClassName, S);
14144   assert(InjectedClassName->isInjectedClassName() &&
14145          "Broken injected-class-name");
14146 }
14147
14148 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14149                                     SourceRange BraceRange) {
14150   AdjustDeclIfTemplate(TagD);
14151   TagDecl *Tag = cast<TagDecl>(TagD);
14152   Tag->setBraceRange(BraceRange);
14153
14154   // Make sure we "complete" the definition even it is invalid.
14155   if (Tag->isBeingDefined()) {
14156     assert(Tag->isInvalidDecl() && "We should already have completed it");
14157     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14158       RD->completeDefinition();
14159   }
14160
14161   if (isa<CXXRecordDecl>(Tag)) {
14162     FieldCollector->FinishClass();
14163   }
14164
14165   // Exit this scope of this tag's definition.
14166   PopDeclContext();
14167
14168   if (getCurLexicalContext()->isObjCContainer() &&
14169       Tag->getDeclContext()->isFileContext())
14170     Tag->setTopLevelDeclInObjCContainer();
14171
14172   // Notify the consumer that we've defined a tag.
14173   if (!Tag->isInvalidDecl())
14174     Consumer.HandleTagDeclDefinition(Tag);
14175 }
14176
14177 void Sema::ActOnObjCContainerFinishDefinition() {
14178   // Exit this scope of this interface definition.
14179   PopDeclContext();
14180 }
14181
14182 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14183   assert(DC == CurContext && "Mismatch of container contexts");
14184   OriginalLexicalContext = DC;
14185   ActOnObjCContainerFinishDefinition();
14186 }
14187
14188 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14189   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14190   OriginalLexicalContext = nullptr;
14191 }
14192
14193 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14194   AdjustDeclIfTemplate(TagD);
14195   TagDecl *Tag = cast<TagDecl>(TagD);
14196   Tag->setInvalidDecl();
14197
14198   // Make sure we "complete" the definition even it is invalid.
14199   if (Tag->isBeingDefined()) {
14200     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14201       RD->completeDefinition();
14202   }
14203
14204   // We're undoing ActOnTagStartDefinition here, not
14205   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14206   // the FieldCollector.
14207
14208   PopDeclContext();
14209 }
14210
14211 // Note that FieldName may be null for anonymous bitfields.
14212 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14213                                 IdentifierInfo *FieldName,
14214                                 QualType FieldTy, bool IsMsStruct,
14215                                 Expr *BitWidth, bool *ZeroWidth) {
14216   // Default to true; that shouldn't confuse checks for emptiness
14217   if (ZeroWidth)
14218     *ZeroWidth = true;
14219
14220   // C99 6.7.2.1p4 - verify the field type.
14221   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14222   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14223     // Handle incomplete types with specific error.
14224     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14225       return ExprError();
14226     if (FieldName)
14227       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14228         << FieldName << FieldTy << BitWidth->getSourceRange();
14229     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14230       << FieldTy << BitWidth->getSourceRange();
14231   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14232                                              UPPC_BitFieldWidth))
14233     return ExprError();
14234
14235   // If the bit-width is type- or value-dependent, don't try to check
14236   // it now.
14237   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14238     return BitWidth;
14239
14240   llvm::APSInt Value;
14241   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14242   if (ICE.isInvalid())
14243     return ICE;
14244   BitWidth = ICE.get();
14245
14246   if (Value != 0 && ZeroWidth)
14247     *ZeroWidth = false;
14248
14249   // Zero-width bitfield is ok for anonymous field.
14250   if (Value == 0 && FieldName)
14251     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14252
14253   if (Value.isSigned() && Value.isNegative()) {
14254     if (FieldName)
14255       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14256                << FieldName << Value.toString(10);
14257     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14258       << Value.toString(10);
14259   }
14260
14261   if (!FieldTy->isDependentType()) {
14262     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14263     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14264     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14265
14266     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14267     // ABI.
14268     bool CStdConstraintViolation =
14269         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14270     bool MSBitfieldViolation =
14271         Value.ugt(TypeStorageSize) &&
14272         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14273     if (CStdConstraintViolation || MSBitfieldViolation) {
14274       unsigned DiagWidth =
14275           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14276       if (FieldName)
14277         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14278                << FieldName << (unsigned)Value.getZExtValue()
14279                << !CStdConstraintViolation << DiagWidth;
14280
14281       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14282              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14283              << DiagWidth;
14284     }
14285
14286     // Warn on types where the user might conceivably expect to get all
14287     // specified bits as value bits: that's all integral types other than
14288     // 'bool'.
14289     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14290       if (FieldName)
14291         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14292             << FieldName << (unsigned)Value.getZExtValue()
14293             << (unsigned)TypeWidth;
14294       else
14295         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14296             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14297     }
14298   }
14299
14300   return BitWidth;
14301 }
14302
14303 /// ActOnField - Each field of a C struct/union is passed into this in order
14304 /// to create a FieldDecl object for it.
14305 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14306                        Declarator &D, Expr *BitfieldWidth) {
14307   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14308                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14309                                /*InitStyle=*/ICIS_NoInit, AS_public);
14310   return Res;
14311 }
14312
14313 /// HandleField - Analyze a field of a C struct or a C++ data member.
14314 ///
14315 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14316                              SourceLocation DeclStart,
14317                              Declarator &D, Expr *BitWidth,
14318                              InClassInitStyle InitStyle,
14319                              AccessSpecifier AS) {
14320   if (D.isDecompositionDeclarator()) {
14321     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14322     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14323       << Decomp.getSourceRange();
14324     return nullptr;
14325   }
14326
14327   IdentifierInfo *II = D.getIdentifier();
14328   SourceLocation Loc = DeclStart;
14329   if (II) Loc = D.getIdentifierLoc();
14330
14331   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14332   QualType T = TInfo->getType();
14333   if (getLangOpts().CPlusPlus) {
14334     CheckExtraCXXDefaultArguments(D);
14335
14336     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14337                                         UPPC_DataMemberType)) {
14338       D.setInvalidType();
14339       T = Context.IntTy;
14340       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14341     }
14342   }
14343
14344   // TR 18037 does not allow fields to be declared with address spaces.
14345   if (T.getQualifiers().hasAddressSpace()) {
14346     Diag(Loc, diag::err_field_with_address_space);
14347     D.setInvalidType();
14348   }
14349
14350   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14351   // used as structure or union field: image, sampler, event or block types.
14352   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14353                           T->isSamplerT() || T->isBlockPointerType())) {
14354     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14355     D.setInvalidType();
14356   }
14357
14358   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14359
14360   if (D.getDeclSpec().isInlineSpecified())
14361     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14362         << getLangOpts().CPlusPlus1z;
14363   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14364     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14365          diag::err_invalid_thread)
14366       << DeclSpec::getSpecifierName(TSCS);
14367
14368   // Check to see if this name was declared as a member previously
14369   NamedDecl *PrevDecl = nullptr;
14370   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14371   LookupName(Previous, S);
14372   switch (Previous.getResultKind()) {
14373     case LookupResult::Found:
14374     case LookupResult::FoundUnresolvedValue:
14375       PrevDecl = Previous.getAsSingle<NamedDecl>();
14376       break;
14377
14378     case LookupResult::FoundOverloaded:
14379       PrevDecl = Previous.getRepresentativeDecl();
14380       break;
14381
14382     case LookupResult::NotFound:
14383     case LookupResult::NotFoundInCurrentInstantiation:
14384     case LookupResult::Ambiguous:
14385       break;
14386   }
14387   Previous.suppressDiagnostics();
14388
14389   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14390     // Maybe we will complain about the shadowed template parameter.
14391     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14392     // Just pretend that we didn't see the previous declaration.
14393     PrevDecl = nullptr;
14394   }
14395
14396   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14397     PrevDecl = nullptr;
14398
14399   bool Mutable
14400     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14401   SourceLocation TSSL = D.getLocStart();
14402   FieldDecl *NewFD
14403     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14404                      TSSL, AS, PrevDecl, &D);
14405
14406   if (NewFD->isInvalidDecl())
14407     Record->setInvalidDecl();
14408
14409   if (D.getDeclSpec().isModulePrivateSpecified())
14410     NewFD->setModulePrivate();
14411
14412   if (NewFD->isInvalidDecl() && PrevDecl) {
14413     // Don't introduce NewFD into scope; there's already something
14414     // with the same name in the same scope.
14415   } else if (II) {
14416     PushOnScopeChains(NewFD, S);
14417   } else
14418     Record->addDecl(NewFD);
14419
14420   return NewFD;
14421 }
14422
14423 /// \brief Build a new FieldDecl and check its well-formedness.
14424 ///
14425 /// This routine builds a new FieldDecl given the fields name, type,
14426 /// record, etc. \p PrevDecl should refer to any previous declaration
14427 /// with the same name and in the same scope as the field to be
14428 /// created.
14429 ///
14430 /// \returns a new FieldDecl.
14431 ///
14432 /// \todo The Declarator argument is a hack. It will be removed once
14433 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14434                                 TypeSourceInfo *TInfo,
14435                                 RecordDecl *Record, SourceLocation Loc,
14436                                 bool Mutable, Expr *BitWidth,
14437                                 InClassInitStyle InitStyle,
14438                                 SourceLocation TSSL,
14439                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14440                                 Declarator *D) {
14441   IdentifierInfo *II = Name.getAsIdentifierInfo();
14442   bool InvalidDecl = false;
14443   if (D) InvalidDecl = D->isInvalidType();
14444
14445   // If we receive a broken type, recover by assuming 'int' and
14446   // marking this declaration as invalid.
14447   if (T.isNull()) {
14448     InvalidDecl = true;
14449     T = Context.IntTy;
14450   }
14451
14452   QualType EltTy = Context.getBaseElementType(T);
14453   if (!EltTy->isDependentType()) {
14454     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14455       // Fields of incomplete type force their record to be invalid.
14456       Record->setInvalidDecl();
14457       InvalidDecl = true;
14458     } else {
14459       NamedDecl *Def;
14460       EltTy->isIncompleteType(&Def);
14461       if (Def && Def->isInvalidDecl()) {
14462         Record->setInvalidDecl();
14463         InvalidDecl = true;
14464       }
14465     }
14466   }
14467
14468   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14469   if (BitWidth && getLangOpts().OpenCL) {
14470     Diag(Loc, diag::err_opencl_bitfields);
14471     InvalidDecl = true;
14472   }
14473
14474   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14475   // than a variably modified type.
14476   if (!InvalidDecl && T->isVariablyModifiedType()) {
14477     bool SizeIsNegative;
14478     llvm::APSInt Oversized;
14479
14480     TypeSourceInfo *FixedTInfo =
14481       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14482                                                     SizeIsNegative,
14483                                                     Oversized);
14484     if (FixedTInfo) {
14485       Diag(Loc, diag::warn_illegal_constant_array_size);
14486       TInfo = FixedTInfo;
14487       T = FixedTInfo->getType();
14488     } else {
14489       if (SizeIsNegative)
14490         Diag(Loc, diag::err_typecheck_negative_array_size);
14491       else if (Oversized.getBoolValue())
14492         Diag(Loc, diag::err_array_too_large)
14493           << Oversized.toString(10);
14494       else
14495         Diag(Loc, diag::err_typecheck_field_variable_size);
14496       InvalidDecl = true;
14497     }
14498   }
14499
14500   // Fields can not have abstract class types
14501   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14502                                              diag::err_abstract_type_in_decl,
14503                                              AbstractFieldType))
14504     InvalidDecl = true;
14505
14506   bool ZeroWidth = false;
14507   if (InvalidDecl)
14508     BitWidth = nullptr;
14509   // If this is declared as a bit-field, check the bit-field.
14510   if (BitWidth) {
14511     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14512                               &ZeroWidth).get();
14513     if (!BitWidth) {
14514       InvalidDecl = true;
14515       BitWidth = nullptr;
14516       ZeroWidth = false;
14517     }
14518   }
14519
14520   // Check that 'mutable' is consistent with the type of the declaration.
14521   if (!InvalidDecl && Mutable) {
14522     unsigned DiagID = 0;
14523     if (T->isReferenceType())
14524       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14525                                         : diag::err_mutable_reference;
14526     else if (T.isConstQualified())
14527       DiagID = diag::err_mutable_const;
14528
14529     if (DiagID) {
14530       SourceLocation ErrLoc = Loc;
14531       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14532         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14533       Diag(ErrLoc, DiagID);
14534       if (DiagID != diag::ext_mutable_reference) {
14535         Mutable = false;
14536         InvalidDecl = true;
14537       }
14538     }
14539   }
14540
14541   // C++11 [class.union]p8 (DR1460):
14542   //   At most one variant member of a union may have a
14543   //   brace-or-equal-initializer.
14544   if (InitStyle != ICIS_NoInit)
14545     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14546
14547   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14548                                        BitWidth, Mutable, InitStyle);
14549   if (InvalidDecl)
14550     NewFD->setInvalidDecl();
14551
14552   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14553     Diag(Loc, diag::err_duplicate_member) << II;
14554     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14555     NewFD->setInvalidDecl();
14556   }
14557
14558   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14559     if (Record->isUnion()) {
14560       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14561         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14562         if (RDecl->getDefinition()) {
14563           // C++ [class.union]p1: An object of a class with a non-trivial
14564           // constructor, a non-trivial copy constructor, a non-trivial
14565           // destructor, or a non-trivial copy assignment operator
14566           // cannot be a member of a union, nor can an array of such
14567           // objects.
14568           if (CheckNontrivialField(NewFD))
14569             NewFD->setInvalidDecl();
14570         }
14571       }
14572
14573       // C++ [class.union]p1: If a union contains a member of reference type,
14574       // the program is ill-formed, except when compiling with MSVC extensions
14575       // enabled.
14576       if (EltTy->isReferenceType()) {
14577         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14578                                     diag::ext_union_member_of_reference_type :
14579                                     diag::err_union_member_of_reference_type)
14580           << NewFD->getDeclName() << EltTy;
14581         if (!getLangOpts().MicrosoftExt)
14582           NewFD->setInvalidDecl();
14583       }
14584     }
14585   }
14586
14587   // FIXME: We need to pass in the attributes given an AST
14588   // representation, not a parser representation.
14589   if (D) {
14590     // FIXME: The current scope is almost... but not entirely... correct here.
14591     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14592
14593     if (NewFD->hasAttrs())
14594       CheckAlignasUnderalignment(NewFD);
14595   }
14596
14597   // In auto-retain/release, infer strong retension for fields of
14598   // retainable type.
14599   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14600     NewFD->setInvalidDecl();
14601
14602   if (T.isObjCGCWeak())
14603     Diag(Loc, diag::warn_attribute_weak_on_field);
14604
14605   NewFD->setAccess(AS);
14606   return NewFD;
14607 }
14608
14609 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14610   assert(FD);
14611   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14612
14613   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14614     return false;
14615
14616   QualType EltTy = Context.getBaseElementType(FD->getType());
14617   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14618     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14619     if (RDecl->getDefinition()) {
14620       // We check for copy constructors before constructors
14621       // because otherwise we'll never get complaints about
14622       // copy constructors.
14623
14624       CXXSpecialMember member = CXXInvalid;
14625       // We're required to check for any non-trivial constructors. Since the
14626       // implicit default constructor is suppressed if there are any
14627       // user-declared constructors, we just need to check that there is a
14628       // trivial default constructor and a trivial copy constructor. (We don't
14629       // worry about move constructors here, since this is a C++98 check.)
14630       if (RDecl->hasNonTrivialCopyConstructor())
14631         member = CXXCopyConstructor;
14632       else if (!RDecl->hasTrivialDefaultConstructor())
14633         member = CXXDefaultConstructor;
14634       else if (RDecl->hasNonTrivialCopyAssignment())
14635         member = CXXCopyAssignment;
14636       else if (RDecl->hasNonTrivialDestructor())
14637         member = CXXDestructor;
14638
14639       if (member != CXXInvalid) {
14640         if (!getLangOpts().CPlusPlus11 &&
14641             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14642           // Objective-C++ ARC: it is an error to have a non-trivial field of
14643           // a union. However, system headers in Objective-C programs
14644           // occasionally have Objective-C lifetime objects within unions,
14645           // and rather than cause the program to fail, we make those
14646           // members unavailable.
14647           SourceLocation Loc = FD->getLocation();
14648           if (getSourceManager().isInSystemHeader(Loc)) {
14649             if (!FD->hasAttr<UnavailableAttr>())
14650               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14651                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14652             return false;
14653           }
14654         }
14655
14656         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14657                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14658                diag::err_illegal_union_or_anon_struct_member)
14659           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14660         DiagnoseNontrivial(RDecl, member);
14661         return !getLangOpts().CPlusPlus11;
14662       }
14663     }
14664   }
14665
14666   return false;
14667 }
14668
14669 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14670 ///  AST enum value.
14671 static ObjCIvarDecl::AccessControl
14672 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14673   switch (ivarVisibility) {
14674   default: llvm_unreachable("Unknown visitibility kind");
14675   case tok::objc_private: return ObjCIvarDecl::Private;
14676   case tok::objc_public: return ObjCIvarDecl::Public;
14677   case tok::objc_protected: return ObjCIvarDecl::Protected;
14678   case tok::objc_package: return ObjCIvarDecl::Package;
14679   }
14680 }
14681
14682 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14683 /// in order to create an IvarDecl object for it.
14684 Decl *Sema::ActOnIvar(Scope *S,
14685                                 SourceLocation DeclStart,
14686                                 Declarator &D, Expr *BitfieldWidth,
14687                                 tok::ObjCKeywordKind Visibility) {
14688
14689   IdentifierInfo *II = D.getIdentifier();
14690   Expr *BitWidth = (Expr*)BitfieldWidth;
14691   SourceLocation Loc = DeclStart;
14692   if (II) Loc = D.getIdentifierLoc();
14693
14694   // FIXME: Unnamed fields can be handled in various different ways, for
14695   // example, unnamed unions inject all members into the struct namespace!
14696
14697   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14698   QualType T = TInfo->getType();
14699
14700   if (BitWidth) {
14701     // 6.7.2.1p3, 6.7.2.1p4
14702     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14703     if (!BitWidth)
14704       D.setInvalidType();
14705   } else {
14706     // Not a bitfield.
14707
14708     // validate II.
14709
14710   }
14711   if (T->isReferenceType()) {
14712     Diag(Loc, diag::err_ivar_reference_type);
14713     D.setInvalidType();
14714   }
14715   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14716   // than a variably modified type.
14717   else if (T->isVariablyModifiedType()) {
14718     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14719     D.setInvalidType();
14720   }
14721
14722   // Get the visibility (access control) for this ivar.
14723   ObjCIvarDecl::AccessControl ac =
14724     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14725                                         : ObjCIvarDecl::None;
14726   // Must set ivar's DeclContext to its enclosing interface.
14727   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14728   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14729     return nullptr;
14730   ObjCContainerDecl *EnclosingContext;
14731   if (ObjCImplementationDecl *IMPDecl =
14732       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14733     if (LangOpts.ObjCRuntime.isFragile()) {
14734     // Case of ivar declared in an implementation. Context is that of its class.
14735       EnclosingContext = IMPDecl->getClassInterface();
14736       assert(EnclosingContext && "Implementation has no class interface!");
14737     }
14738     else
14739       EnclosingContext = EnclosingDecl;
14740   } else {
14741     if (ObjCCategoryDecl *CDecl =
14742         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14743       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14744         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14745         return nullptr;
14746       }
14747     }
14748     EnclosingContext = EnclosingDecl;
14749   }
14750
14751   // Construct the decl.
14752   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14753                                              DeclStart, Loc, II, T,
14754                                              TInfo, ac, (Expr *)BitfieldWidth);
14755
14756   if (II) {
14757     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14758                                            ForRedeclaration);
14759     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14760         && !isa<TagDecl>(PrevDecl)) {
14761       Diag(Loc, diag::err_duplicate_member) << II;
14762       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14763       NewID->setInvalidDecl();
14764     }
14765   }
14766
14767   // Process attributes attached to the ivar.
14768   ProcessDeclAttributes(S, NewID, D);
14769
14770   if (D.isInvalidType())
14771     NewID->setInvalidDecl();
14772
14773   // In ARC, infer 'retaining' for ivars of retainable type.
14774   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14775     NewID->setInvalidDecl();
14776
14777   if (D.getDeclSpec().isModulePrivateSpecified())
14778     NewID->setModulePrivate();
14779
14780   if (II) {
14781     // FIXME: When interfaces are DeclContexts, we'll need to add
14782     // these to the interface.
14783     S->AddDecl(NewID);
14784     IdResolver.AddDecl(NewID);
14785   }
14786
14787   if (LangOpts.ObjCRuntime.isNonFragile() &&
14788       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14789     Diag(Loc, diag::warn_ivars_in_interface);
14790
14791   return NewID;
14792 }
14793
14794 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14795 /// class and class extensions. For every class \@interface and class
14796 /// extension \@interface, if the last ivar is a bitfield of any type,
14797 /// then add an implicit `char :0` ivar to the end of that interface.
14798 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14799                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14800   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14801     return;
14802
14803   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14804   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14805
14806   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14807     return;
14808   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14809   if (!ID) {
14810     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14811       if (!CD->IsClassExtension())
14812         return;
14813     }
14814     // No need to add this to end of @implementation.
14815     else
14816       return;
14817   }
14818   // All conditions are met. Add a new bitfield to the tail end of ivars.
14819   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14820   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14821
14822   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14823                               DeclLoc, DeclLoc, nullptr,
14824                               Context.CharTy,
14825                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14826                                                                DeclLoc),
14827                               ObjCIvarDecl::Private, BW,
14828                               true);
14829   AllIvarDecls.push_back(Ivar);
14830 }
14831
14832 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14833                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14834                        SourceLocation RBrac, AttributeList *Attr) {
14835   assert(EnclosingDecl && "missing record or interface decl");
14836
14837   // If this is an Objective-C @implementation or category and we have
14838   // new fields here we should reset the layout of the interface since
14839   // it will now change.
14840   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14841     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14842     switch (DC->getKind()) {
14843     default: break;
14844     case Decl::ObjCCategory:
14845       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14846       break;
14847     case Decl::ObjCImplementation:
14848       Context.
14849         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14850       break;
14851     }
14852   }
14853
14854   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14855
14856   // Start counting up the number of named members; make sure to include
14857   // members of anonymous structs and unions in the total.
14858   unsigned NumNamedMembers = 0;
14859   if (Record) {
14860     for (const auto *I : Record->decls()) {
14861       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14862         if (IFD->getDeclName())
14863           ++NumNamedMembers;
14864     }
14865   }
14866
14867   // Verify that all the fields are okay.
14868   SmallVector<FieldDecl*, 32> RecFields;
14869
14870   bool ObjCFieldLifetimeErrReported = false;
14871   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14872        i != end; ++i) {
14873     FieldDecl *FD = cast<FieldDecl>(*i);
14874
14875     // Get the type for the field.
14876     const Type *FDTy = FD->getType().getTypePtr();
14877
14878     if (!FD->isAnonymousStructOrUnion()) {
14879       // Remember all fields written by the user.
14880       RecFields.push_back(FD);
14881     }
14882
14883     // If the field is already invalid for some reason, don't emit more
14884     // diagnostics about it.
14885     if (FD->isInvalidDecl()) {
14886       EnclosingDecl->setInvalidDecl();
14887       continue;
14888     }
14889
14890     // C99 6.7.2.1p2:
14891     //   A structure or union shall not contain a member with
14892     //   incomplete or function type (hence, a structure shall not
14893     //   contain an instance of itself, but may contain a pointer to
14894     //   an instance of itself), except that the last member of a
14895     //   structure with more than one named member may have incomplete
14896     //   array type; such a structure (and any union containing,
14897     //   possibly recursively, a member that is such a structure)
14898     //   shall not be a member of a structure or an element of an
14899     //   array.
14900     if (FDTy->isFunctionType()) {
14901       // Field declared as a function.
14902       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14903         << FD->getDeclName();
14904       FD->setInvalidDecl();
14905       EnclosingDecl->setInvalidDecl();
14906       continue;
14907     } else if (FDTy->isIncompleteArrayType() && Record &&
14908                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14909                 ((getLangOpts().MicrosoftExt ||
14910                   getLangOpts().CPlusPlus) &&
14911                  (i + 1 == Fields.end() || Record->isUnion())))) {
14912       // Flexible array member.
14913       // Microsoft and g++ is more permissive regarding flexible array.
14914       // It will accept flexible array in union and also
14915       // as the sole element of a struct/class.
14916       unsigned DiagID = 0;
14917       if (Record->isUnion())
14918         DiagID = getLangOpts().MicrosoftExt
14919                      ? diag::ext_flexible_array_union_ms
14920                      : getLangOpts().CPlusPlus
14921                            ? diag::ext_flexible_array_union_gnu
14922                            : diag::err_flexible_array_union;
14923       else if (NumNamedMembers < 1)
14924         DiagID = getLangOpts().MicrosoftExt
14925                      ? diag::ext_flexible_array_empty_aggregate_ms
14926                      : getLangOpts().CPlusPlus
14927                            ? diag::ext_flexible_array_empty_aggregate_gnu
14928                            : diag::err_flexible_array_empty_aggregate;
14929
14930       if (DiagID)
14931         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14932                                         << Record->getTagKind();
14933       // While the layout of types that contain virtual bases is not specified
14934       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14935       // virtual bases after the derived members.  This would make a flexible
14936       // array member declared at the end of an object not adjacent to the end
14937       // of the type.
14938       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14939         if (RD->getNumVBases() != 0)
14940           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14941             << FD->getDeclName() << Record->getTagKind();
14942       if (!getLangOpts().C99)
14943         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14944           << FD->getDeclName() << Record->getTagKind();
14945
14946       // If the element type has a non-trivial destructor, we would not
14947       // implicitly destroy the elements, so disallow it for now.
14948       //
14949       // FIXME: GCC allows this. We should probably either implicitly delete
14950       // the destructor of the containing class, or just allow this.
14951       QualType BaseElem = Context.getBaseElementType(FD->getType());
14952       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14953         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14954           << FD->getDeclName() << FD->getType();
14955         FD->setInvalidDecl();
14956         EnclosingDecl->setInvalidDecl();
14957         continue;
14958       }
14959       // Okay, we have a legal flexible array member at the end of the struct.
14960       Record->setHasFlexibleArrayMember(true);
14961     } else if (!FDTy->isDependentType() &&
14962                RequireCompleteType(FD->getLocation(), FD->getType(),
14963                                    diag::err_field_incomplete)) {
14964       // Incomplete type
14965       FD->setInvalidDecl();
14966       EnclosingDecl->setInvalidDecl();
14967       continue;
14968     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14969       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14970         // A type which contains a flexible array member is considered to be a
14971         // flexible array member.
14972         Record->setHasFlexibleArrayMember(true);
14973         if (!Record->isUnion()) {
14974           // If this is a struct/class and this is not the last element, reject
14975           // it.  Note that GCC supports variable sized arrays in the middle of
14976           // structures.
14977           if (i + 1 != Fields.end())
14978             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14979               << FD->getDeclName() << FD->getType();
14980           else {
14981             // We support flexible arrays at the end of structs in
14982             // other structs as an extension.
14983             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14984               << FD->getDeclName();
14985           }
14986         }
14987       }
14988       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14989           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14990                                  diag::err_abstract_type_in_decl,
14991                                  AbstractIvarType)) {
14992         // Ivars can not have abstract class types
14993         FD->setInvalidDecl();
14994       }
14995       if (Record && FDTTy->getDecl()->hasObjectMember())
14996         Record->setHasObjectMember(true);
14997       if (Record && FDTTy->getDecl()->hasVolatileMember())
14998         Record->setHasVolatileMember(true);
14999     } else if (FDTy->isObjCObjectType()) {
15000       /// A field cannot be an Objective-c object
15001       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15002         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15003       QualType T = Context.getObjCObjectPointerType(FD->getType());
15004       FD->setType(T);
15005     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15006                Record && !ObjCFieldLifetimeErrReported &&
15007                (!getLangOpts().CPlusPlus || Record->isUnion())) {
15008       // It's an error in ARC or Weak if a field has lifetime.
15009       // We don't want to report this in a system header, though,
15010       // so we just make the field unavailable.
15011       // FIXME: that's really not sufficient; we need to make the type
15012       // itself invalid to, say, initialize or copy.
15013       QualType T = FD->getType();
15014       if (T.hasNonTrivialObjCLifetime()) {
15015         SourceLocation loc = FD->getLocation();
15016         if (getSourceManager().isInSystemHeader(loc)) {
15017           if (!FD->hasAttr<UnavailableAttr>()) {
15018             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15019                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15020           }
15021         } else {
15022           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15023             << T->isBlockPointerType() << Record->getTagKind();
15024         }
15025         ObjCFieldLifetimeErrReported = true;
15026       }
15027     } else if (getLangOpts().ObjC1 &&
15028                getLangOpts().getGC() != LangOptions::NonGC &&
15029                Record && !Record->hasObjectMember()) {
15030       if (FD->getType()->isObjCObjectPointerType() ||
15031           FD->getType().isObjCGCStrong())
15032         Record->setHasObjectMember(true);
15033       else if (Context.getAsArrayType(FD->getType())) {
15034         QualType BaseType = Context.getBaseElementType(FD->getType());
15035         if (BaseType->isRecordType() &&
15036             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15037           Record->setHasObjectMember(true);
15038         else if (BaseType->isObjCObjectPointerType() ||
15039                  BaseType.isObjCGCStrong())
15040                Record->setHasObjectMember(true);
15041       }
15042     }
15043     if (Record && FD->getType().isVolatileQualified())
15044       Record->setHasVolatileMember(true);
15045     // Keep track of the number of named members.
15046     if (FD->getIdentifier())
15047       ++NumNamedMembers;
15048   }
15049
15050   // Okay, we successfully defined 'Record'.
15051   if (Record) {
15052     bool Completed = false;
15053     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15054       if (!CXXRecord->isInvalidDecl()) {
15055         // Set access bits correctly on the directly-declared conversions.
15056         for (CXXRecordDecl::conversion_iterator
15057                I = CXXRecord->conversion_begin(),
15058                E = CXXRecord->conversion_end(); I != E; ++I)
15059           I.setAccess((*I)->getAccess());
15060       }
15061
15062       if (!CXXRecord->isDependentType()) {
15063         if (CXXRecord->hasUserDeclaredDestructor()) {
15064           // Adjust user-defined destructor exception spec.
15065           if (getLangOpts().CPlusPlus11)
15066             AdjustDestructorExceptionSpec(CXXRecord,
15067                                           CXXRecord->getDestructor());
15068         }
15069
15070         if (!CXXRecord->isInvalidDecl()) {
15071           // Add any implicitly-declared members to this class.
15072           AddImplicitlyDeclaredMembersToClass(CXXRecord);
15073
15074           // If we have virtual base classes, we may end up finding multiple
15075           // final overriders for a given virtual function. Check for this
15076           // problem now.
15077           if (CXXRecord->getNumVBases()) {
15078             CXXFinalOverriderMap FinalOverriders;
15079             CXXRecord->getFinalOverriders(FinalOverriders);
15080
15081             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15082                                              MEnd = FinalOverriders.end();
15083                  M != MEnd; ++M) {
15084               for (OverridingMethods::iterator SO = M->second.begin(),
15085                                             SOEnd = M->second.end();
15086                    SO != SOEnd; ++SO) {
15087                 assert(SO->second.size() > 0 &&
15088                        "Virtual function without overridding functions?");
15089                 if (SO->second.size() == 1)
15090                   continue;
15091
15092                 // C++ [class.virtual]p2:
15093                 //   In a derived class, if a virtual member function of a base
15094                 //   class subobject has more than one final overrider the
15095                 //   program is ill-formed.
15096                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15097                   << (const NamedDecl *)M->first << Record;
15098                 Diag(M->first->getLocation(),
15099                      diag::note_overridden_virtual_function);
15100                 for (OverridingMethods::overriding_iterator
15101                           OM = SO->second.begin(),
15102                        OMEnd = SO->second.end();
15103                      OM != OMEnd; ++OM)
15104                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15105                     << (const NamedDecl *)M->first << OM->Method->getParent();
15106
15107                 Record->setInvalidDecl();
15108               }
15109             }
15110             CXXRecord->completeDefinition(&FinalOverriders);
15111             Completed = true;
15112           }
15113         }
15114       }
15115     }
15116
15117     if (!Completed)
15118       Record->completeDefinition();
15119
15120     // We may have deferred checking for a deleted destructor. Check now.
15121     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15122       auto *Dtor = CXXRecord->getDestructor();
15123       if (Dtor && Dtor->isImplicit() &&
15124           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
15125         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15126     }
15127
15128     if (Record->hasAttrs()) {
15129       CheckAlignasUnderalignment(Record);
15130
15131       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15132         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15133                                            IA->getRange(), IA->getBestCase(),
15134                                            IA->getSemanticSpelling());
15135     }
15136
15137     // Check if the structure/union declaration is a type that can have zero
15138     // size in C. For C this is a language extension, for C++ it may cause
15139     // compatibility problems.
15140     bool CheckForZeroSize;
15141     if (!getLangOpts().CPlusPlus) {
15142       CheckForZeroSize = true;
15143     } else {
15144       // For C++ filter out types that cannot be referenced in C code.
15145       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15146       CheckForZeroSize =
15147           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15148           !CXXRecord->isDependentType() &&
15149           CXXRecord->isCLike();
15150     }
15151     if (CheckForZeroSize) {
15152       bool ZeroSize = true;
15153       bool IsEmpty = true;
15154       unsigned NonBitFields = 0;
15155       for (RecordDecl::field_iterator I = Record->field_begin(),
15156                                       E = Record->field_end();
15157            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15158         IsEmpty = false;
15159         if (I->isUnnamedBitfield()) {
15160           if (I->getBitWidthValue(Context) > 0)
15161             ZeroSize = false;
15162         } else {
15163           ++NonBitFields;
15164           QualType FieldType = I->getType();
15165           if (FieldType->isIncompleteType() ||
15166               !Context.getTypeSizeInChars(FieldType).isZero())
15167             ZeroSize = false;
15168         }
15169       }
15170
15171       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15172       // allowed in C++, but warn if its declaration is inside
15173       // extern "C" block.
15174       if (ZeroSize) {
15175         Diag(RecLoc, getLangOpts().CPlusPlus ?
15176                          diag::warn_zero_size_struct_union_in_extern_c :
15177                          diag::warn_zero_size_struct_union_compat)
15178           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15179       }
15180
15181       // Structs without named members are extension in C (C99 6.7.2.1p7),
15182       // but are accepted by GCC.
15183       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15184         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15185                                diag::ext_no_named_members_in_struct_union)
15186           << Record->isUnion();
15187       }
15188     }
15189   } else {
15190     ObjCIvarDecl **ClsFields =
15191       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15192     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15193       ID->setEndOfDefinitionLoc(RBrac);
15194       // Add ivar's to class's DeclContext.
15195       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15196         ClsFields[i]->setLexicalDeclContext(ID);
15197         ID->addDecl(ClsFields[i]);
15198       }
15199       // Must enforce the rule that ivars in the base classes may not be
15200       // duplicates.
15201       if (ID->getSuperClass())
15202         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15203     } else if (ObjCImplementationDecl *IMPDecl =
15204                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15205       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15206       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15207         // Ivar declared in @implementation never belongs to the implementation.
15208         // Only it is in implementation's lexical context.
15209         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15210       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15211       IMPDecl->setIvarLBraceLoc(LBrac);
15212       IMPDecl->setIvarRBraceLoc(RBrac);
15213     } else if (ObjCCategoryDecl *CDecl =
15214                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15215       // case of ivars in class extension; all other cases have been
15216       // reported as errors elsewhere.
15217       // FIXME. Class extension does not have a LocEnd field.
15218       // CDecl->setLocEnd(RBrac);
15219       // Add ivar's to class extension's DeclContext.
15220       // Diagnose redeclaration of private ivars.
15221       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15222       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15223         if (IDecl) {
15224           if (const ObjCIvarDecl *ClsIvar =
15225               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15226             Diag(ClsFields[i]->getLocation(),
15227                  diag::err_duplicate_ivar_declaration);
15228             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15229             continue;
15230           }
15231           for (const auto *Ext : IDecl->known_extensions()) {
15232             if (const ObjCIvarDecl *ClsExtIvar
15233                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15234               Diag(ClsFields[i]->getLocation(),
15235                    diag::err_duplicate_ivar_declaration);
15236               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15237               continue;
15238             }
15239           }
15240         }
15241         ClsFields[i]->setLexicalDeclContext(CDecl);
15242         CDecl->addDecl(ClsFields[i]);
15243       }
15244       CDecl->setIvarLBraceLoc(LBrac);
15245       CDecl->setIvarRBraceLoc(RBrac);
15246     }
15247   }
15248
15249   if (Attr)
15250     ProcessDeclAttributeList(S, Record, Attr);
15251 }
15252
15253 /// \brief Determine whether the given integral value is representable within
15254 /// the given type T.
15255 static bool isRepresentableIntegerValue(ASTContext &Context,
15256                                         llvm::APSInt &Value,
15257                                         QualType T) {
15258   assert(T->isIntegralType(Context) && "Integral type required!");
15259   unsigned BitWidth = Context.getIntWidth(T);
15260
15261   if (Value.isUnsigned() || Value.isNonNegative()) {
15262     if (T->isSignedIntegerOrEnumerationType())
15263       --BitWidth;
15264     return Value.getActiveBits() <= BitWidth;
15265   }
15266   return Value.getMinSignedBits() <= BitWidth;
15267 }
15268
15269 // \brief Given an integral type, return the next larger integral type
15270 // (or a NULL type of no such type exists).
15271 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15272   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15273   // enum checking below.
15274   assert(T->isIntegralType(Context) && "Integral type required!");
15275   const unsigned NumTypes = 4;
15276   QualType SignedIntegralTypes[NumTypes] = {
15277     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15278   };
15279   QualType UnsignedIntegralTypes[NumTypes] = {
15280     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15281     Context.UnsignedLongLongTy
15282   };
15283
15284   unsigned BitWidth = Context.getTypeSize(T);
15285   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15286                                                         : UnsignedIntegralTypes;
15287   for (unsigned I = 0; I != NumTypes; ++I)
15288     if (Context.getTypeSize(Types[I]) > BitWidth)
15289       return Types[I];
15290
15291   return QualType();
15292 }
15293
15294 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15295                                           EnumConstantDecl *LastEnumConst,
15296                                           SourceLocation IdLoc,
15297                                           IdentifierInfo *Id,
15298                                           Expr *Val) {
15299   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15300   llvm::APSInt EnumVal(IntWidth);
15301   QualType EltTy;
15302
15303   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15304     Val = nullptr;
15305
15306   if (Val)
15307     Val = DefaultLvalueConversion(Val).get();
15308
15309   if (Val) {
15310     if (Enum->isDependentType() || Val->isTypeDependent())
15311       EltTy = Context.DependentTy;
15312     else {
15313       SourceLocation ExpLoc;
15314       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15315           !getLangOpts().MSVCCompat) {
15316         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15317         // constant-expression in the enumerator-definition shall be a converted
15318         // constant expression of the underlying type.
15319         EltTy = Enum->getIntegerType();
15320         ExprResult Converted =
15321           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15322                                            CCEK_Enumerator);
15323         if (Converted.isInvalid())
15324           Val = nullptr;
15325         else
15326           Val = Converted.get();
15327       } else if (!Val->isValueDependent() &&
15328                  !(Val = VerifyIntegerConstantExpression(Val,
15329                                                          &EnumVal).get())) {
15330         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15331       } else {
15332         if (Enum->isFixed()) {
15333           EltTy = Enum->getIntegerType();
15334
15335           // In Obj-C and Microsoft mode, require the enumeration value to be
15336           // representable in the underlying type of the enumeration. In C++11,
15337           // we perform a non-narrowing conversion as part of converted constant
15338           // expression checking.
15339           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15340             if (getLangOpts().MSVCCompat) {
15341               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15342               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15343             } else
15344               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15345           } else
15346             Val = ImpCastExprToType(Val, EltTy,
15347                                     EltTy->isBooleanType() ?
15348                                     CK_IntegralToBoolean : CK_IntegralCast)
15349                     .get();
15350         } else if (getLangOpts().CPlusPlus) {
15351           // C++11 [dcl.enum]p5:
15352           //   If the underlying type is not fixed, the type of each enumerator
15353           //   is the type of its initializing value:
15354           //     - If an initializer is specified for an enumerator, the
15355           //       initializing value has the same type as the expression.
15356           EltTy = Val->getType();
15357         } else {
15358           // C99 6.7.2.2p2:
15359           //   The expression that defines the value of an enumeration constant
15360           //   shall be an integer constant expression that has a value
15361           //   representable as an int.
15362
15363           // Complain if the value is not representable in an int.
15364           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15365             Diag(IdLoc, diag::ext_enum_value_not_int)
15366               << EnumVal.toString(10) << Val->getSourceRange()
15367               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15368           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15369             // Force the type of the expression to 'int'.
15370             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15371           }
15372           EltTy = Val->getType();
15373         }
15374       }
15375     }
15376   }
15377
15378   if (!Val) {
15379     if (Enum->isDependentType())
15380       EltTy = Context.DependentTy;
15381     else if (!LastEnumConst) {
15382       // C++0x [dcl.enum]p5:
15383       //   If the underlying type is not fixed, the type of each enumerator
15384       //   is the type of its initializing value:
15385       //     - If no initializer is specified for the first enumerator, the
15386       //       initializing value has an unspecified integral type.
15387       //
15388       // GCC uses 'int' for its unspecified integral type, as does
15389       // C99 6.7.2.2p3.
15390       if (Enum->isFixed()) {
15391         EltTy = Enum->getIntegerType();
15392       }
15393       else {
15394         EltTy = Context.IntTy;
15395       }
15396     } else {
15397       // Assign the last value + 1.
15398       EnumVal = LastEnumConst->getInitVal();
15399       ++EnumVal;
15400       EltTy = LastEnumConst->getType();
15401
15402       // Check for overflow on increment.
15403       if (EnumVal < LastEnumConst->getInitVal()) {
15404         // C++0x [dcl.enum]p5:
15405         //   If the underlying type is not fixed, the type of each enumerator
15406         //   is the type of its initializing value:
15407         //
15408         //     - Otherwise the type of the initializing value is the same as
15409         //       the type of the initializing value of the preceding enumerator
15410         //       unless the incremented value is not representable in that type,
15411         //       in which case the type is an unspecified integral type
15412         //       sufficient to contain the incremented value. If no such type
15413         //       exists, the program is ill-formed.
15414         QualType T = getNextLargerIntegralType(Context, EltTy);
15415         if (T.isNull() || Enum->isFixed()) {
15416           // There is no integral type larger enough to represent this
15417           // value. Complain, then allow the value to wrap around.
15418           EnumVal = LastEnumConst->getInitVal();
15419           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15420           ++EnumVal;
15421           if (Enum->isFixed())
15422             // When the underlying type is fixed, this is ill-formed.
15423             Diag(IdLoc, diag::err_enumerator_wrapped)
15424               << EnumVal.toString(10)
15425               << EltTy;
15426           else
15427             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15428               << EnumVal.toString(10);
15429         } else {
15430           EltTy = T;
15431         }
15432
15433         // Retrieve the last enumerator's value, extent that type to the
15434         // type that is supposed to be large enough to represent the incremented
15435         // value, then increment.
15436         EnumVal = LastEnumConst->getInitVal();
15437         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15438         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15439         ++EnumVal;
15440
15441         // If we're not in C++, diagnose the overflow of enumerator values,
15442         // which in C99 means that the enumerator value is not representable in
15443         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15444         // permits enumerator values that are representable in some larger
15445         // integral type.
15446         if (!getLangOpts().CPlusPlus && !T.isNull())
15447           Diag(IdLoc, diag::warn_enum_value_overflow);
15448       } else if (!getLangOpts().CPlusPlus &&
15449                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15450         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15451         Diag(IdLoc, diag::ext_enum_value_not_int)
15452           << EnumVal.toString(10) << 1;
15453       }
15454     }
15455   }
15456
15457   if (!EltTy->isDependentType()) {
15458     // Make the enumerator value match the signedness and size of the
15459     // enumerator's type.
15460     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15461     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15462   }
15463
15464   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15465                                   Val, EnumVal);
15466 }
15467
15468 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15469                                                 SourceLocation IILoc) {
15470   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15471       !getLangOpts().CPlusPlus)
15472     return SkipBodyInfo();
15473
15474   // We have an anonymous enum definition. Look up the first enumerator to
15475   // determine if we should merge the definition with an existing one and
15476   // skip the body.
15477   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15478                                          ForRedeclaration);
15479   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15480   if (!PrevECD)
15481     return SkipBodyInfo();
15482
15483   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15484   NamedDecl *Hidden;
15485   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15486     SkipBodyInfo Skip;
15487     Skip.Previous = Hidden;
15488     return Skip;
15489   }
15490
15491   return SkipBodyInfo();
15492 }
15493
15494 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15495                               SourceLocation IdLoc, IdentifierInfo *Id,
15496                               AttributeList *Attr,
15497                               SourceLocation EqualLoc, Expr *Val) {
15498   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15499   EnumConstantDecl *LastEnumConst =
15500     cast_or_null<EnumConstantDecl>(lastEnumConst);
15501
15502   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15503   // we find one that is.
15504   S = getNonFieldDeclScope(S);
15505
15506   // Verify that there isn't already something declared with this name in this
15507   // scope.
15508   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15509                                          ForRedeclaration);
15510   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15511     // Maybe we will complain about the shadowed template parameter.
15512     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15513     // Just pretend that we didn't see the previous declaration.
15514     PrevDecl = nullptr;
15515   }
15516
15517   // C++ [class.mem]p15:
15518   // If T is the name of a class, then each of the following shall have a name
15519   // different from T:
15520   // - every enumerator of every member of class T that is an unscoped
15521   // enumerated type
15522   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15523     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15524                             DeclarationNameInfo(Id, IdLoc));
15525
15526   EnumConstantDecl *New =
15527     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15528   if (!New)
15529     return nullptr;
15530
15531   if (PrevDecl) {
15532     // When in C++, we may get a TagDecl with the same name; in this case the
15533     // enum constant will 'hide' the tag.
15534     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15535            "Received TagDecl when not in C++!");
15536     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15537         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15538       if (isa<EnumConstantDecl>(PrevDecl))
15539         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15540       else
15541         Diag(IdLoc, diag::err_redefinition) << Id;
15542       notePreviousDefinition(PrevDecl, IdLoc);
15543       return nullptr;
15544     }
15545   }
15546
15547   // Process attributes.
15548   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15549   AddPragmaAttributes(S, New);
15550
15551   // Register this decl in the current scope stack.
15552   New->setAccess(TheEnumDecl->getAccess());
15553   PushOnScopeChains(New, S);
15554
15555   ActOnDocumentableDecl(New);
15556
15557   return New;
15558 }
15559
15560 // Returns true when the enum initial expression does not trigger the
15561 // duplicate enum warning.  A few common cases are exempted as follows:
15562 // Element2 = Element1
15563 // Element2 = Element1 + 1
15564 // Element2 = Element1 - 1
15565 // Where Element2 and Element1 are from the same enum.
15566 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15567   Expr *InitExpr = ECD->getInitExpr();
15568   if (!InitExpr)
15569     return true;
15570   InitExpr = InitExpr->IgnoreImpCasts();
15571
15572   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15573     if (!BO->isAdditiveOp())
15574       return true;
15575     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15576     if (!IL)
15577       return true;
15578     if (IL->getValue() != 1)
15579       return true;
15580
15581     InitExpr = BO->getLHS();
15582   }
15583
15584   // This checks if the elements are from the same enum.
15585   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15586   if (!DRE)
15587     return true;
15588
15589   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15590   if (!EnumConstant)
15591     return true;
15592
15593   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15594       Enum)
15595     return true;
15596
15597   return false;
15598 }
15599
15600 namespace {
15601 struct DupKey {
15602   int64_t val;
15603   bool isTombstoneOrEmptyKey;
15604   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15605     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15606 };
15607
15608 static DupKey GetDupKey(const llvm::APSInt& Val) {
15609   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15610                 false);
15611 }
15612
15613 struct DenseMapInfoDupKey {
15614   static DupKey getEmptyKey() { return DupKey(0, true); }
15615   static DupKey getTombstoneKey() { return DupKey(1, true); }
15616   static unsigned getHashValue(const DupKey Key) {
15617     return (unsigned)(Key.val * 37);
15618   }
15619   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15620     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15621            LHS.val == RHS.val;
15622   }
15623 };
15624 } // end anonymous namespace
15625
15626 // Emits a warning when an element is implicitly set a value that
15627 // a previous element has already been set to.
15628 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15629                                         EnumDecl *Enum,
15630                                         QualType EnumType) {
15631   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15632     return;
15633   // Avoid anonymous enums
15634   if (!Enum->getIdentifier())
15635     return;
15636
15637   // Only check for small enums.
15638   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15639     return;
15640
15641   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15642   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15643
15644   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15645   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15646           ValueToVectorMap;
15647
15648   DuplicatesVector DupVector;
15649   ValueToVectorMap EnumMap;
15650
15651   // Populate the EnumMap with all values represented by enum constants without
15652   // an initialier.
15653   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15654     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15655
15656     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15657     // this constant.  Skip this enum since it may be ill-formed.
15658     if (!ECD) {
15659       return;
15660     }
15661
15662     if (ECD->getInitExpr())
15663       continue;
15664
15665     DupKey Key = GetDupKey(ECD->getInitVal());
15666     DeclOrVector &Entry = EnumMap[Key];
15667
15668     // First time encountering this value.
15669     if (Entry.isNull())
15670       Entry = ECD;
15671   }
15672
15673   // Create vectors for any values that has duplicates.
15674   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15675     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15676     if (!ValidDuplicateEnum(ECD, Enum))
15677       continue;
15678
15679     DupKey Key = GetDupKey(ECD->getInitVal());
15680
15681     DeclOrVector& Entry = EnumMap[Key];
15682     if (Entry.isNull())
15683       continue;
15684
15685     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15686       // Ensure constants are different.
15687       if (D == ECD)
15688         continue;
15689
15690       // Create new vector and push values onto it.
15691       ECDVector *Vec = new ECDVector();
15692       Vec->push_back(D);
15693       Vec->push_back(ECD);
15694
15695       // Update entry to point to the duplicates vector.
15696       Entry = Vec;
15697
15698       // Store the vector somewhere we can consult later for quick emission of
15699       // diagnostics.
15700       DupVector.push_back(Vec);
15701       continue;
15702     }
15703
15704     ECDVector *Vec = Entry.get<ECDVector*>();
15705     // Make sure constants are not added more than once.
15706     if (*Vec->begin() == ECD)
15707       continue;
15708
15709     Vec->push_back(ECD);
15710   }
15711
15712   // Emit diagnostics.
15713   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15714                                   DupVectorEnd = DupVector.end();
15715        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15716     ECDVector *Vec = *DupVectorIter;
15717     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15718
15719     // Emit warning for one enum constant.
15720     ECDVector::iterator I = Vec->begin();
15721     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15722       << (*I)->getName() << (*I)->getInitVal().toString(10)
15723       << (*I)->getSourceRange();
15724     ++I;
15725
15726     // Emit one note for each of the remaining enum constants with
15727     // the same value.
15728     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15729       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15730         << (*I)->getName() << (*I)->getInitVal().toString(10)
15731         << (*I)->getSourceRange();
15732     delete Vec;
15733   }
15734 }
15735
15736 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15737                              bool AllowMask) const {
15738   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15739   assert(ED->isCompleteDefinition() && "expected enum definition");
15740
15741   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15742   llvm::APInt &FlagBits = R.first->second;
15743
15744   if (R.second) {
15745     for (auto *E : ED->enumerators()) {
15746       const auto &EVal = E->getInitVal();
15747       // Only single-bit enumerators introduce new flag values.
15748       if (EVal.isPowerOf2())
15749         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15750     }
15751   }
15752
15753   // A value is in a flag enum if either its bits are a subset of the enum's
15754   // flag bits (the first condition) or we are allowing masks and the same is
15755   // true of its complement (the second condition). When masks are allowed, we
15756   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15757   //
15758   // While it's true that any value could be used as a mask, the assumption is
15759   // that a mask will have all of the insignificant bits set. Anything else is
15760   // likely a logic error.
15761   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15762   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15763 }
15764
15765 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15766                          Decl *EnumDeclX,
15767                          ArrayRef<Decl *> Elements,
15768                          Scope *S, AttributeList *Attr) {
15769   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15770   QualType EnumType = Context.getTypeDeclType(Enum);
15771
15772   if (Attr)
15773     ProcessDeclAttributeList(S, Enum, Attr);
15774
15775   if (Enum->isDependentType()) {
15776     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15777       EnumConstantDecl *ECD =
15778         cast_or_null<EnumConstantDecl>(Elements[i]);
15779       if (!ECD) continue;
15780
15781       ECD->setType(EnumType);
15782     }
15783
15784     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15785     return;
15786   }
15787
15788   // TODO: If the result value doesn't fit in an int, it must be a long or long
15789   // long value.  ISO C does not support this, but GCC does as an extension,
15790   // emit a warning.
15791   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15792   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15793   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15794
15795   // Verify that all the values are okay, compute the size of the values, and
15796   // reverse the list.
15797   unsigned NumNegativeBits = 0;
15798   unsigned NumPositiveBits = 0;
15799
15800   // Keep track of whether all elements have type int.
15801   bool AllElementsInt = true;
15802
15803   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15804     EnumConstantDecl *ECD =
15805       cast_or_null<EnumConstantDecl>(Elements[i]);
15806     if (!ECD) continue;  // Already issued a diagnostic.
15807
15808     const llvm::APSInt &InitVal = ECD->getInitVal();
15809
15810     // Keep track of the size of positive and negative values.
15811     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15812       NumPositiveBits = std::max(NumPositiveBits,
15813                                  (unsigned)InitVal.getActiveBits());
15814     else
15815       NumNegativeBits = std::max(NumNegativeBits,
15816                                  (unsigned)InitVal.getMinSignedBits());
15817
15818     // Keep track of whether every enum element has type int (very commmon).
15819     if (AllElementsInt)
15820       AllElementsInt = ECD->getType() == Context.IntTy;
15821   }
15822
15823   // Figure out the type that should be used for this enum.
15824   QualType BestType;
15825   unsigned BestWidth;
15826
15827   // C++0x N3000 [conv.prom]p3:
15828   //   An rvalue of an unscoped enumeration type whose underlying
15829   //   type is not fixed can be converted to an rvalue of the first
15830   //   of the following types that can represent all the values of
15831   //   the enumeration: int, unsigned int, long int, unsigned long
15832   //   int, long long int, or unsigned long long int.
15833   // C99 6.4.4.3p2:
15834   //   An identifier declared as an enumeration constant has type int.
15835   // The C99 rule is modified by a gcc extension
15836   QualType BestPromotionType;
15837
15838   bool Packed = Enum->hasAttr<PackedAttr>();
15839   // -fshort-enums is the equivalent to specifying the packed attribute on all
15840   // enum definitions.
15841   if (LangOpts.ShortEnums)
15842     Packed = true;
15843
15844   if (Enum->isFixed()) {
15845     BestType = Enum->getIntegerType();
15846     if (BestType->isPromotableIntegerType())
15847       BestPromotionType = Context.getPromotedIntegerType(BestType);
15848     else
15849       BestPromotionType = BestType;
15850
15851     BestWidth = Context.getIntWidth(BestType);
15852   }
15853   else if (NumNegativeBits) {
15854     // If there is a negative value, figure out the smallest integer type (of
15855     // int/long/longlong) that fits.
15856     // If it's packed, check also if it fits a char or a short.
15857     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15858       BestType = Context.SignedCharTy;
15859       BestWidth = CharWidth;
15860     } else if (Packed && NumNegativeBits <= ShortWidth &&
15861                NumPositiveBits < ShortWidth) {
15862       BestType = Context.ShortTy;
15863       BestWidth = ShortWidth;
15864     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15865       BestType = Context.IntTy;
15866       BestWidth = IntWidth;
15867     } else {
15868       BestWidth = Context.getTargetInfo().getLongWidth();
15869
15870       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15871         BestType = Context.LongTy;
15872       } else {
15873         BestWidth = Context.getTargetInfo().getLongLongWidth();
15874
15875         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15876           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15877         BestType = Context.LongLongTy;
15878       }
15879     }
15880     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15881   } else {
15882     // If there is no negative value, figure out the smallest type that fits
15883     // all of the enumerator values.
15884     // If it's packed, check also if it fits a char or a short.
15885     if (Packed && NumPositiveBits <= CharWidth) {
15886       BestType = Context.UnsignedCharTy;
15887       BestPromotionType = Context.IntTy;
15888       BestWidth = CharWidth;
15889     } else if (Packed && NumPositiveBits <= ShortWidth) {
15890       BestType = Context.UnsignedShortTy;
15891       BestPromotionType = Context.IntTy;
15892       BestWidth = ShortWidth;
15893     } else if (NumPositiveBits <= IntWidth) {
15894       BestType = Context.UnsignedIntTy;
15895       BestWidth = IntWidth;
15896       BestPromotionType
15897         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15898                            ? Context.UnsignedIntTy : Context.IntTy;
15899     } else if (NumPositiveBits <=
15900                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15901       BestType = Context.UnsignedLongTy;
15902       BestPromotionType
15903         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15904                            ? Context.UnsignedLongTy : Context.LongTy;
15905     } else {
15906       BestWidth = Context.getTargetInfo().getLongLongWidth();
15907       assert(NumPositiveBits <= BestWidth &&
15908              "How could an initializer get larger than ULL?");
15909       BestType = Context.UnsignedLongLongTy;
15910       BestPromotionType
15911         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15912                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15913     }
15914   }
15915
15916   // Loop over all of the enumerator constants, changing their types to match
15917   // the type of the enum if needed.
15918   for (auto *D : Elements) {
15919     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15920     if (!ECD) continue;  // Already issued a diagnostic.
15921
15922     // Standard C says the enumerators have int type, but we allow, as an
15923     // extension, the enumerators to be larger than int size.  If each
15924     // enumerator value fits in an int, type it as an int, otherwise type it the
15925     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15926     // that X has type 'int', not 'unsigned'.
15927
15928     // Determine whether the value fits into an int.
15929     llvm::APSInt InitVal = ECD->getInitVal();
15930
15931     // If it fits into an integer type, force it.  Otherwise force it to match
15932     // the enum decl type.
15933     QualType NewTy;
15934     unsigned NewWidth;
15935     bool NewSign;
15936     if (!getLangOpts().CPlusPlus &&
15937         !Enum->isFixed() &&
15938         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15939       NewTy = Context.IntTy;
15940       NewWidth = IntWidth;
15941       NewSign = true;
15942     } else if (ECD->getType() == BestType) {
15943       // Already the right type!
15944       if (getLangOpts().CPlusPlus)
15945         // C++ [dcl.enum]p4: Following the closing brace of an
15946         // enum-specifier, each enumerator has the type of its
15947         // enumeration.
15948         ECD->setType(EnumType);
15949       continue;
15950     } else {
15951       NewTy = BestType;
15952       NewWidth = BestWidth;
15953       NewSign = BestType->isSignedIntegerOrEnumerationType();
15954     }
15955
15956     // Adjust the APSInt value.
15957     InitVal = InitVal.extOrTrunc(NewWidth);
15958     InitVal.setIsSigned(NewSign);
15959     ECD->setInitVal(InitVal);
15960
15961     // Adjust the Expr initializer and type.
15962     if (ECD->getInitExpr() &&
15963         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15964       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15965                                                 CK_IntegralCast,
15966                                                 ECD->getInitExpr(),
15967                                                 /*base paths*/ nullptr,
15968                                                 VK_RValue));
15969     if (getLangOpts().CPlusPlus)
15970       // C++ [dcl.enum]p4: Following the closing brace of an
15971       // enum-specifier, each enumerator has the type of its
15972       // enumeration.
15973       ECD->setType(EnumType);
15974     else
15975       ECD->setType(NewTy);
15976   }
15977
15978   Enum->completeDefinition(BestType, BestPromotionType,
15979                            NumPositiveBits, NumNegativeBits);
15980
15981   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15982
15983   if (Enum->isClosedFlag()) {
15984     for (Decl *D : Elements) {
15985       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15986       if (!ECD) continue;  // Already issued a diagnostic.
15987
15988       llvm::APSInt InitVal = ECD->getInitVal();
15989       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15990           !IsValueInFlagEnum(Enum, InitVal, true))
15991         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15992           << ECD << Enum;
15993     }
15994   }
15995
15996   // Now that the enum type is defined, ensure it's not been underaligned.
15997   if (Enum->hasAttrs())
15998     CheckAlignasUnderalignment(Enum);
15999 }
16000
16001 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16002                                   SourceLocation StartLoc,
16003                                   SourceLocation EndLoc) {
16004   StringLiteral *AsmString = cast<StringLiteral>(expr);
16005
16006   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16007                                                    AsmString, StartLoc,
16008                                                    EndLoc);
16009   CurContext->addDecl(New);
16010   return New;
16011 }
16012
16013 static void checkModuleImportContext(Sema &S, Module *M,
16014                                      SourceLocation ImportLoc, DeclContext *DC,
16015                                      bool FromInclude = false) {
16016   SourceLocation ExternCLoc;
16017
16018   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16019     switch (LSD->getLanguage()) {
16020     case LinkageSpecDecl::lang_c:
16021       if (ExternCLoc.isInvalid())
16022         ExternCLoc = LSD->getLocStart();
16023       break;
16024     case LinkageSpecDecl::lang_cxx:
16025       break;
16026     }
16027     DC = LSD->getParent();
16028   }
16029
16030   while (isa<LinkageSpecDecl>(DC))
16031     DC = DC->getParent();
16032
16033   if (!isa<TranslationUnitDecl>(DC)) {
16034     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16035                           ? diag::ext_module_import_not_at_top_level_noop
16036                           : diag::err_module_import_not_at_top_level_fatal)
16037         << M->getFullModuleName() << DC;
16038     S.Diag(cast<Decl>(DC)->getLocStart(),
16039            diag::note_module_import_not_at_top_level) << DC;
16040   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16041     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16042       << M->getFullModuleName();
16043     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16044   }
16045 }
16046
16047 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16048                                            SourceLocation ModuleLoc,
16049                                            ModuleDeclKind MDK,
16050                                            ModuleIdPath Path) {
16051   // A module implementation unit requires that we are not compiling a module
16052   // of any kind. A module interface unit requires that we are not compiling a
16053   // module map.
16054   switch (getLangOpts().getCompilingModule()) {
16055   case LangOptions::CMK_None:
16056     // It's OK to compile a module interface as a normal translation unit.
16057     break;
16058
16059   case LangOptions::CMK_ModuleInterface:
16060     if (MDK != ModuleDeclKind::Implementation)
16061       break;
16062
16063     // We were asked to compile a module interface unit but this is a module
16064     // implementation unit. That indicates the 'export' is missing.
16065     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16066       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16067     break;
16068
16069   case LangOptions::CMK_ModuleMap:
16070     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16071     return nullptr;
16072   }
16073
16074   // FIXME: Most of this work should be done by the preprocessor rather than
16075   // here, in order to support macro import.
16076
16077   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16078   // modules, the dots here are just another character that can appear in a
16079   // module name.
16080   std::string ModuleName;
16081   for (auto &Piece : Path) {
16082     if (!ModuleName.empty())
16083       ModuleName += ".";
16084     ModuleName += Piece.first->getName();
16085   }
16086
16087   // FIXME: If we've already seen a module-declaration, report an error.
16088
16089   // If a module name was explicitly specified on the command line, it must be
16090   // correct.
16091   if (!getLangOpts().CurrentModule.empty() &&
16092       getLangOpts().CurrentModule != ModuleName) {
16093     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16094         << SourceRange(Path.front().second, Path.back().second)
16095         << getLangOpts().CurrentModule;
16096     return nullptr;
16097   }
16098   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16099
16100   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16101   Module *Mod;
16102
16103   switch (MDK) {
16104   case ModuleDeclKind::Module: {
16105     // FIXME: Check we're not in a submodule.
16106
16107     // We can't have parsed or imported a definition of this module or parsed a
16108     // module map defining it already.
16109     if (auto *M = Map.findModule(ModuleName)) {
16110       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16111       if (M->DefinitionLoc.isValid())
16112         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16113       else if (const auto *FE = M->getASTFile())
16114         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16115             << FE->getName();
16116       return nullptr;
16117     }
16118
16119     // Create a Module for the module that we're defining.
16120     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
16121     assert(Mod && "module creation should not fail");
16122     break;
16123   }
16124
16125   case ModuleDeclKind::Partition:
16126     // FIXME: Check we are in a submodule of the named module.
16127     return nullptr;
16128
16129   case ModuleDeclKind::Implementation:
16130     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16131         PP.getIdentifierInfo(ModuleName), Path[0].second);
16132     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16133                                        /*IsIncludeDirective=*/false);
16134     if (!Mod)
16135       return nullptr;
16136     break;
16137   }
16138
16139   // Enter the semantic scope of the module.
16140   ModuleScopes.push_back({});
16141   ModuleScopes.back().Module = Mod;
16142   ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16143   VisibleModules.setVisible(Mod, ModuleLoc);
16144
16145   // From now on, we have an owning module for all declarations we see.
16146   // However, those declarations are module-private unless explicitly
16147   // exported.
16148   Context.getTranslationUnitDecl()->setLocalOwningModule(Mod);
16149
16150   // FIXME: Create a ModuleDecl.
16151   return nullptr;
16152 }
16153
16154 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16155                                    SourceLocation ImportLoc,
16156                                    ModuleIdPath Path) {
16157   Module *Mod =
16158       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16159                                    /*IsIncludeDirective=*/false);
16160   if (!Mod)
16161     return true;
16162
16163   VisibleModules.setVisible(Mod, ImportLoc);
16164
16165   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16166
16167   // FIXME: we should support importing a submodule within a different submodule
16168   // of the same top-level module. Until we do, make it an error rather than
16169   // silently ignoring the import.
16170   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16171   // warn on a redundant import of the current module?
16172   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16173       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16174     Diag(ImportLoc, getLangOpts().isCompilingModule()
16175                         ? diag::err_module_self_import
16176                         : diag::err_module_import_in_implementation)
16177         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16178
16179   SmallVector<SourceLocation, 2> IdentifierLocs;
16180   Module *ModCheck = Mod;
16181   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16182     // If we've run out of module parents, just drop the remaining identifiers.
16183     // We need the length to be consistent.
16184     if (!ModCheck)
16185       break;
16186     ModCheck = ModCheck->Parent;
16187
16188     IdentifierLocs.push_back(Path[I].second);
16189   }
16190
16191   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16192   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
16193                                           Mod, IdentifierLocs);
16194   if (!ModuleScopes.empty())
16195     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16196   TU->addDecl(Import);
16197   return Import;
16198 }
16199
16200 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16201   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16202   BuildModuleInclude(DirectiveLoc, Mod);
16203 }
16204
16205 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16206   // Determine whether we're in the #include buffer for a module. The #includes
16207   // in that buffer do not qualify as module imports; they're just an
16208   // implementation detail of us building the module.
16209   //
16210   // FIXME: Should we even get ActOnModuleInclude calls for those?
16211   bool IsInModuleIncludes =
16212       TUKind == TU_Module &&
16213       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16214
16215   bool ShouldAddImport = !IsInModuleIncludes;
16216
16217   // If this module import was due to an inclusion directive, create an
16218   // implicit import declaration to capture it in the AST.
16219   if (ShouldAddImport) {
16220     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16221     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16222                                                      DirectiveLoc, Mod,
16223                                                      DirectiveLoc);
16224     if (!ModuleScopes.empty())
16225       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16226     TU->addDecl(ImportD);
16227     Consumer.HandleImplicitImportDecl(ImportD);
16228   }
16229
16230   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16231   VisibleModules.setVisible(Mod, DirectiveLoc);
16232 }
16233
16234 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16235   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16236
16237   ModuleScopes.push_back({});
16238   ModuleScopes.back().Module = Mod;
16239   if (getLangOpts().ModulesLocalVisibility)
16240     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16241
16242   VisibleModules.setVisible(Mod, DirectiveLoc);
16243
16244   // The enclosing context is now part of this module.
16245   // FIXME: Consider creating a child DeclContext to hold the entities
16246   // lexically within the module.
16247   if (getLangOpts().trackLocalOwningModule()) {
16248     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16249       cast<Decl>(DC)->setModuleOwnershipKind(
16250           getLangOpts().ModulesLocalVisibility
16251               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16252               : Decl::ModuleOwnershipKind::Visible);
16253       cast<Decl>(DC)->setLocalOwningModule(Mod);
16254     }
16255   }
16256 }
16257
16258 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16259   if (getLangOpts().ModulesLocalVisibility) {
16260     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16261     // Leaving a module hides namespace names, so our visible namespace cache
16262     // is now out of date.
16263     VisibleNamespaceCache.clear();
16264   }
16265
16266   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16267          "left the wrong module scope");
16268   ModuleScopes.pop_back();
16269
16270   // We got to the end of processing a local module. Create an
16271   // ImportDecl as we would for an imported module.
16272   FileID File = getSourceManager().getFileID(EomLoc);
16273   SourceLocation DirectiveLoc;
16274   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16275     // We reached the end of a #included module header. Use the #include loc.
16276     assert(File != getSourceManager().getMainFileID() &&
16277            "end of submodule in main source file");
16278     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16279   } else {
16280     // We reached an EOM pragma. Use the pragma location.
16281     DirectiveLoc = EomLoc;
16282   }
16283   BuildModuleInclude(DirectiveLoc, Mod);
16284
16285   // Any further declarations are in whatever module we returned to.
16286   if (getLangOpts().trackLocalOwningModule()) {
16287     // The parser guarantees that this is the same context that we entered
16288     // the module within.
16289     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16290       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16291       if (!getCurrentModule())
16292         cast<Decl>(DC)->setModuleOwnershipKind(
16293             Decl::ModuleOwnershipKind::Unowned);
16294     }
16295   }
16296 }
16297
16298 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16299                                                       Module *Mod) {
16300   // Bail if we're not allowed to implicitly import a module here.
16301   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16302       VisibleModules.isVisible(Mod))
16303     return;
16304
16305   // Create the implicit import declaration.
16306   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16307   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16308                                                    Loc, Mod, Loc);
16309   TU->addDecl(ImportD);
16310   Consumer.HandleImplicitImportDecl(ImportD);
16311
16312   // Make the module visible.
16313   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16314   VisibleModules.setVisible(Mod, Loc);
16315 }
16316
16317 /// We have parsed the start of an export declaration, including the '{'
16318 /// (if present).
16319 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16320                                  SourceLocation LBraceLoc) {
16321   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16322
16323   // C++ Modules TS draft:
16324   //   An export-declaration shall appear in the purview of a module other than
16325   //   the global module.
16326   if (ModuleScopes.empty() || !ModuleScopes.back().Module ||
16327       ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
16328     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16329
16330   //   An export-declaration [...] shall not contain more than one
16331   //   export keyword.
16332   //
16333   // The intent here is that an export-declaration cannot appear within another
16334   // export-declaration.
16335   if (D->isExported())
16336     Diag(ExportLoc, diag::err_export_within_export);
16337
16338   CurContext->addDecl(D);
16339   PushDeclContext(S, D);
16340   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16341   return D;
16342 }
16343
16344 /// Complete the definition of an export declaration.
16345 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16346   auto *ED = cast<ExportDecl>(D);
16347   if (RBraceLoc.isValid())
16348     ED->setRBraceLoc(RBraceLoc);
16349
16350   // FIXME: Diagnose export of internal-linkage declaration (including
16351   // anonymous namespace).
16352
16353   PopDeclContext();
16354   return D;
16355 }
16356
16357 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16358                                       IdentifierInfo* AliasName,
16359                                       SourceLocation PragmaLoc,
16360                                       SourceLocation NameLoc,
16361                                       SourceLocation AliasNameLoc) {
16362   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16363                                          LookupOrdinaryName);
16364   AsmLabelAttr *Attr =
16365       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16366
16367   // If a declaration that:
16368   // 1) declares a function or a variable
16369   // 2) has external linkage
16370   // already exists, add a label attribute to it.
16371   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16372     if (isDeclExternC(PrevDecl))
16373       PrevDecl->addAttr(Attr);
16374     else
16375       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16376           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16377   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16378   } else
16379     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16380 }
16381
16382 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16383                              SourceLocation PragmaLoc,
16384                              SourceLocation NameLoc) {
16385   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16386
16387   if (PrevDecl) {
16388     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16389   } else {
16390     (void)WeakUndeclaredIdentifiers.insert(
16391       std::pair<IdentifierInfo*,WeakInfo>
16392         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16393   }
16394 }
16395
16396 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16397                                 IdentifierInfo* AliasName,
16398                                 SourceLocation PragmaLoc,
16399                                 SourceLocation NameLoc,
16400                                 SourceLocation AliasNameLoc) {
16401   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16402                                     LookupOrdinaryName);
16403   WeakInfo W = WeakInfo(Name, NameLoc);
16404
16405   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16406     if (!PrevDecl->hasAttr<AliasAttr>())
16407       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16408         DeclApplyPragmaWeak(TUScope, ND, W);
16409   } else {
16410     (void)WeakUndeclaredIdentifiers.insert(
16411       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16412   }
16413 }
16414
16415 Decl *Sema::getObjCDeclContext() const {
16416   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16417 }