• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
ConvertDeclToDeclGroup(Decl * Ptr,Decl * OwnedType)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:
TypeNameValidatorCCC(bool AllowInvalid,bool WantClass=false,bool AllowTemplates=false)67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75 
ValidateCandidate(const TypoCorrection & candidate)76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91 
92 } // end anonymous namespace
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
isSimpleTypeSpecifier(tok::TokenKind Kind) const95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117 
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125 
126   default:
127     break;
128   }
129 
130   return false;
131 }
132 
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140 
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
lookupUnqualifiedTypeNameInBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc,const CXXRecordDecl * RD)146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       if (auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169           BaseRD = BasePrimaryTemplate;
170         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171           if (const ClassTemplatePartialSpecializationDecl *PS =
172                   CTD->findPartialSpecialization(Base.getType()))
173             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174               BaseRD = PS;
175         }
176       }
177     }
178     if (BaseRD) {
179       for (NamedDecl *ND : BaseRD->lookup(&II)) {
180         if (!isa<TypeDecl>(ND))
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183       }
184       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186         case UnqualifiedTypeNameLookupResult::FoundNonType:
187           return UnqualifiedTypeNameLookupResult::FoundNonType;
188         case UnqualifiedTypeNameLookupResult::FoundType:
189           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190           break;
191         case UnqualifiedTypeNameLookupResult::NotFound:
192           break;
193         }
194       }
195     }
196   }
197 
198   return FoundTypeDecl;
199 }
200 
recoverFromTypeInKnownDependentBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc)201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202                                                       const IdentifierInfo &II,
203                                                       SourceLocation NameLoc) {
204   // Lookup in the parent class template context, if any.
205   const CXXRecordDecl *RD = nullptr;
206   UnqualifiedTypeNameLookupResult FoundTypeDecl =
207       UnqualifiedTypeNameLookupResult::NotFound;
208   for (DeclContext *DC = S.CurContext;
209        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210        DC = DC->getParent()) {
211     // Look for type decls in dependent base classes that have known primary
212     // templates.
213     RD = dyn_cast<CXXRecordDecl>(DC);
214     if (RD && RD->getDescribedClassTemplate())
215       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216   }
217   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218     return nullptr;
219 
220   // We found some types in dependent base classes.  Recover as if the user
221   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
222   // lookup during template instantiation.
223   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
224 
225   ASTContext &Context = S.Context;
226   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227                                           cast<Type>(Context.getRecordType(RD)));
228   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
229 
230   CXXScopeSpec SS;
231   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232 
233   TypeLocBuilder Builder;
234   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235   DepTL.setNameLoc(NameLoc);
236   DepTL.setElaboratedKeywordLoc(SourceLocation());
237   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
239 }
240 
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
243 ///
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
getTypeName(const IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec * SS,bool isClassName,bool HasTrailingDot,ParsedType ObjectTypePtr,bool IsCtorOrDtorName,bool WantNontrivialTypeSourceInfo,IdentifierInfo ** CorrectedII)249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250                              Scope *S, CXXScopeSpec *SS,
251                              bool isClassName, bool HasTrailingDot,
252                              ParsedType ObjectTypePtr,
253                              bool IsCtorOrDtorName,
254                              bool WantNontrivialTypeSourceInfo,
255                              IdentifierInfo **CorrectedII) {
256   // Determine where we will perform name lookup.
257   DeclContext *LookupCtx = nullptr;
258   if (ObjectTypePtr) {
259     QualType ObjectType = ObjectTypePtr.get();
260     if (ObjectType->isRecordType())
261       LookupCtx = computeDeclContext(ObjectType);
262   } else if (SS && SS->isNotEmpty()) {
263     LookupCtx = computeDeclContext(*SS, false);
264 
265     if (!LookupCtx) {
266       if (isDependentScopeSpecifier(*SS)) {
267         // C++ [temp.res]p3:
268         //   A qualified-id that refers to a type and in which the
269         //   nested-name-specifier depends on a template-parameter (14.6.2)
270         //   shall be prefixed by the keyword typename to indicate that the
271         //   qualified-id denotes a type, forming an
272         //   elaborated-type-specifier (7.1.5.3).
273         //
274         // We therefore do not perform any name lookup if the result would
275         // refer to a member of an unknown specialization.
276         if (!isClassName && !IsCtorOrDtorName)
277           return nullptr;
278 
279         // We know from the grammar that this name refers to a type,
280         // so build a dependent node to describe the type.
281         if (WantNontrivialTypeSourceInfo)
282           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
283 
284         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
285         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
286                                        II, NameLoc);
287         return ParsedType::make(T);
288       }
289 
290       return nullptr;
291     }
292 
293     if (!LookupCtx->isDependentContext() &&
294         RequireCompleteDeclContext(*SS, LookupCtx))
295       return nullptr;
296   }
297 
298   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
299   // lookup for class-names.
300   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
301                                       LookupOrdinaryName;
302   LookupResult Result(*this, &II, NameLoc, Kind);
303   if (LookupCtx) {
304     // Perform "qualified" name lookup into the declaration context we
305     // computed, which is either the type of the base of a member access
306     // expression or the declaration context associated with a prior
307     // nested-name-specifier.
308     LookupQualifiedName(Result, LookupCtx);
309 
310     if (ObjectTypePtr && Result.empty()) {
311       // C++ [basic.lookup.classref]p3:
312       //   If the unqualified-id is ~type-name, the type-name is looked up
313       //   in the context of the entire postfix-expression. If the type T of
314       //   the object expression is of a class type C, the type-name is also
315       //   looked up in the scope of class C. At least one of the lookups shall
316       //   find a name that refers to (possibly cv-qualified) T.
317       LookupName(Result, S);
318     }
319   } else {
320     // Perform unqualified name lookup.
321     LookupName(Result, S);
322 
323     // For unqualified lookup in a class template in MSVC mode, look into
324     // dependent base classes where the primary class template is known.
325     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
326       if (ParsedType TypeInBase =
327               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
328         return TypeInBase;
329     }
330   }
331 
332   NamedDecl *IIDecl = nullptr;
333   switch (Result.getResultKind()) {
334   case LookupResult::NotFound:
335   case LookupResult::NotFoundInCurrentInstantiation:
336     if (CorrectedII) {
337       TypoCorrection Correction = CorrectTypo(
338           Result.getLookupNameInfo(), Kind, S, SS,
339           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
340           CTK_ErrorRecovery);
341       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
342       TemplateTy Template;
343       bool MemberOfUnknownSpecialization;
344       UnqualifiedId TemplateName;
345       TemplateName.setIdentifier(NewII, NameLoc);
346       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
347       CXXScopeSpec NewSS, *NewSSPtr = SS;
348       if (SS && NNS) {
349         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
350         NewSSPtr = &NewSS;
351       }
352       if (Correction && (NNS || NewII != &II) &&
353           // Ignore a correction to a template type as the to-be-corrected
354           // identifier is not a template (typo correction for template names
355           // is handled elsewhere).
356           !(getLangOpts().CPlusPlus && NewSSPtr &&
357             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
358                            Template, MemberOfUnknownSpecialization))) {
359         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
360                                     isClassName, HasTrailingDot, ObjectTypePtr,
361                                     IsCtorOrDtorName,
362                                     WantNontrivialTypeSourceInfo);
363         if (Ty) {
364           diagnoseTypo(Correction,
365                        PDiag(diag::err_unknown_type_or_class_name_suggest)
366                          << Result.getLookupName() << isClassName);
367           if (SS && NNS)
368             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
369           *CorrectedII = NewII;
370           return Ty;
371         }
372       }
373     }
374     // If typo correction failed or was not performed, fall through
375   case LookupResult::FoundOverloaded:
376   case LookupResult::FoundUnresolvedValue:
377     Result.suppressDiagnostics();
378     return nullptr;
379 
380   case LookupResult::Ambiguous:
381     // Recover from type-hiding ambiguities by hiding the type.  We'll
382     // do the lookup again when looking for an object, and we can
383     // diagnose the error then.  If we don't do this, then the error
384     // about hiding the type will be immediately followed by an error
385     // that only makes sense if the identifier was treated like a type.
386     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
387       Result.suppressDiagnostics();
388       return nullptr;
389     }
390 
391     // Look to see if we have a type anywhere in the list of results.
392     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
393          Res != ResEnd; ++Res) {
394       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
395         if (!IIDecl ||
396             (*Res)->getLocation().getRawEncoding() <
397               IIDecl->getLocation().getRawEncoding())
398           IIDecl = *Res;
399       }
400     }
401 
402     if (!IIDecl) {
403       // None of the entities we found is a type, so there is no way
404       // to even assume that the result is a type. In this case, don't
405       // complain about the ambiguity. The parser will either try to
406       // perform this lookup again (e.g., as an object name), which
407       // will produce the ambiguity, or will complain that it expected
408       // a type name.
409       Result.suppressDiagnostics();
410       return nullptr;
411     }
412 
413     // We found a type within the ambiguous lookup; diagnose the
414     // ambiguity and then return that type. This might be the right
415     // answer, or it might not be, but it suppresses any attempt to
416     // perform the name lookup again.
417     break;
418 
419   case LookupResult::Found:
420     IIDecl = Result.getFoundDecl();
421     break;
422   }
423 
424   assert(IIDecl && "Didn't find decl");
425 
426   QualType T;
427   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
428     DiagnoseUseOfDecl(IIDecl, NameLoc);
429 
430     T = Context.getTypeDeclType(TD);
431     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
432 
433     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
434     // constructor or destructor name (in such a case, the scope specifier
435     // will be attached to the enclosing Expr or Decl node).
436     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
437       if (WantNontrivialTypeSourceInfo) {
438         // Construct a type with type-source information.
439         TypeLocBuilder Builder;
440         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
441 
442         T = getElaboratedType(ETK_None, *SS, T);
443         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
444         ElabTL.setElaboratedKeywordLoc(SourceLocation());
445         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
446         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
447       } else {
448         T = getElaboratedType(ETK_None, *SS, T);
449       }
450     }
451   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
452     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
453     if (!HasTrailingDot)
454       T = Context.getObjCInterfaceType(IDecl);
455   }
456 
457   if (T.isNull()) {
458     // If it's not plausibly a type, suppress diagnostics.
459     Result.suppressDiagnostics();
460     return nullptr;
461   }
462   return ParsedType::make(T);
463 }
464 
465 // Builds a fake NNS for the given decl context.
466 static NestedNameSpecifier *
synthesizeCurrentNestedNameSpecifier(ASTContext & Context,DeclContext * DC)467 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
468   for (;; DC = DC->getLookupParent()) {
469     DC = DC->getPrimaryContext();
470     auto *ND = dyn_cast<NamespaceDecl>(DC);
471     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
472       return NestedNameSpecifier::Create(Context, nullptr, ND);
473     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
474       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
475                                          RD->getTypeForDecl());
476     else if (isa<TranslationUnitDecl>(DC))
477       return NestedNameSpecifier::GlobalSpecifier(Context);
478   }
479   llvm_unreachable("something isn't in TU scope?");
480 }
481 
482 /// Find the parent class with dependent bases of the innermost enclosing method
483 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
484 /// up allowing unqualified dependent type names at class-level, which MSVC
485 /// correctly rejects.
486 static const CXXRecordDecl *
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext * DC)487 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
488   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
489     DC = DC->getPrimaryContext();
490     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
491       if (MD->getParent()->hasAnyDependentBases())
492         return MD->getParent();
493   }
494   return nullptr;
495 }
496 
ActOnMSVCUnknownTypeName(const IdentifierInfo & II,SourceLocation NameLoc,bool IsTemplateTypeArg)497 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
498                                           SourceLocation NameLoc,
499                                           bool IsTemplateTypeArg) {
500   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
501 
502   NestedNameSpecifier *NNS = nullptr;
503   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
504     // If we weren't able to parse a default template argument, delay lookup
505     // until instantiation time by making a non-dependent DependentTypeName. We
506     // pretend we saw a NestedNameSpecifier referring to the current scope, and
507     // lookup is retried.
508     // FIXME: This hurts our diagnostic quality, since we get errors like "no
509     // type named 'Foo' in 'current_namespace'" when the user didn't write any
510     // name specifiers.
511     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
512     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
513   } else if (const CXXRecordDecl *RD =
514                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
515     // Build a DependentNameType that will perform lookup into RD at
516     // instantiation time.
517     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
518                                       RD->getTypeForDecl());
519 
520     // Diagnose that this identifier was undeclared, and retry the lookup during
521     // template instantiation.
522     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
523                                                                       << RD;
524   } else {
525     // This is not a situation that we should recover from.
526     return ParsedType();
527   }
528 
529   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
530 
531   // Build type location information.  We synthesized the qualifier, so we have
532   // to build a fake NestedNameSpecifierLoc.
533   NestedNameSpecifierLocBuilder NNSLocBuilder;
534   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
535   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
536 
537   TypeLocBuilder Builder;
538   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
539   DepTL.setNameLoc(NameLoc);
540   DepTL.setElaboratedKeywordLoc(SourceLocation());
541   DepTL.setQualifierLoc(QualifierLoc);
542   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
543 }
544 
545 /// isTagName() - This method is called *for error recovery purposes only*
546 /// to determine if the specified name is a valid tag name ("struct foo").  If
547 /// so, this returns the TST for the tag corresponding to it (TST_enum,
548 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
549 /// cases in C where the user forgot to specify the tag.
isTagName(IdentifierInfo & II,Scope * S)550 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
551   // Do a tag name lookup in this scope.
552   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
553   LookupName(R, S, false);
554   R.suppressDiagnostics();
555   if (R.getResultKind() == LookupResult::Found)
556     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
557       switch (TD->getTagKind()) {
558       case TTK_Struct: return DeclSpec::TST_struct;
559       case TTK_Interface: return DeclSpec::TST_interface;
560       case TTK_Union:  return DeclSpec::TST_union;
561       case TTK_Class:  return DeclSpec::TST_class;
562       case TTK_Enum:   return DeclSpec::TST_enum;
563       }
564     }
565 
566   return DeclSpec::TST_unspecified;
567 }
568 
569 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
570 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
571 /// then downgrade the missing typename error to a warning.
572 /// This is needed for MSVC compatibility; Example:
573 /// @code
574 /// template<class T> class A {
575 /// public:
576 ///   typedef int TYPE;
577 /// };
578 /// template<class T> class B : public A<T> {
579 /// public:
580 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
581 /// };
582 /// @endcode
isMicrosoftMissingTypename(const CXXScopeSpec * SS,Scope * S)583 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
584   if (CurContext->isRecord()) {
585     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
586       return true;
587 
588     const Type *Ty = SS->getScopeRep()->getAsType();
589 
590     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
591     for (const auto &Base : RD->bases())
592       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
593         return true;
594     return S->isFunctionPrototypeScope();
595   }
596   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
597 }
598 
DiagnoseUnknownTypeName(IdentifierInfo * & II,SourceLocation IILoc,Scope * S,CXXScopeSpec * SS,ParsedType & SuggestedType,bool AllowClassTemplates)599 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
600                                    SourceLocation IILoc,
601                                    Scope *S,
602                                    CXXScopeSpec *SS,
603                                    ParsedType &SuggestedType,
604                                    bool AllowClassTemplates) {
605   // We don't have anything to suggest (yet).
606   SuggestedType = nullptr;
607 
608   // There may have been a typo in the name of the type. Look up typo
609   // results, in case we have something that we can suggest.
610   if (TypoCorrection Corrected =
611           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
612                       llvm::make_unique<TypeNameValidatorCCC>(
613                           false, false, AllowClassTemplates),
614                       CTK_ErrorRecovery)) {
615     if (Corrected.isKeyword()) {
616       // We corrected to a keyword.
617       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
618       II = Corrected.getCorrectionAsIdentifierInfo();
619     } else {
620       // We found a similarly-named type or interface; suggest that.
621       if (!SS || !SS->isSet()) {
622         diagnoseTypo(Corrected,
623                      PDiag(diag::err_unknown_typename_suggest) << II);
624       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
625         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
626         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
627                                 II->getName().equals(CorrectedStr);
628         diagnoseTypo(Corrected,
629                      PDiag(diag::err_unknown_nested_typename_suggest)
630                        << II << DC << DroppedSpecifier << SS->getRange());
631       } else {
632         llvm_unreachable("could not have corrected a typo here");
633       }
634 
635       CXXScopeSpec tmpSS;
636       if (Corrected.getCorrectionSpecifier())
637         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
638                           SourceRange(IILoc));
639       SuggestedType =
640           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
641                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
642                       /*IsCtorOrDtorName=*/false,
643                       /*NonTrivialTypeSourceInfo=*/true);
644     }
645     return;
646   }
647 
648   if (getLangOpts().CPlusPlus) {
649     // See if II is a class template that the user forgot to pass arguments to.
650     UnqualifiedId Name;
651     Name.setIdentifier(II, IILoc);
652     CXXScopeSpec EmptySS;
653     TemplateTy TemplateResult;
654     bool MemberOfUnknownSpecialization;
655     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
656                        Name, nullptr, true, TemplateResult,
657                        MemberOfUnknownSpecialization) == TNK_Type_template) {
658       TemplateName TplName = TemplateResult.get();
659       Diag(IILoc, diag::err_template_missing_args) << TplName;
660       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
661         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
662           << TplDecl->getTemplateParameters()->getSourceRange();
663       }
664       return;
665     }
666   }
667 
668   // FIXME: Should we move the logic that tries to recover from a missing tag
669   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
670 
671   if (!SS || (!SS->isSet() && !SS->isInvalid()))
672     Diag(IILoc, diag::err_unknown_typename) << II;
673   else if (DeclContext *DC = computeDeclContext(*SS, false))
674     Diag(IILoc, diag::err_typename_nested_not_found)
675       << II << DC << SS->getRange();
676   else if (isDependentScopeSpecifier(*SS)) {
677     unsigned DiagID = diag::err_typename_missing;
678     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
679       DiagID = diag::ext_typename_missing;
680 
681     Diag(SS->getRange().getBegin(), DiagID)
682       << SS->getScopeRep() << II->getName()
683       << SourceRange(SS->getRange().getBegin(), IILoc)
684       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
685     SuggestedType = ActOnTypenameType(S, SourceLocation(),
686                                       *SS, *II, IILoc).get();
687   } else {
688     assert(SS && SS->isInvalid() &&
689            "Invalid scope specifier has already been diagnosed");
690   }
691 }
692 
693 /// \brief Determine whether the given result set contains either a type name
694 /// or
isResultTypeOrTemplate(LookupResult & R,const Token & NextToken)695 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
696   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
697                        NextToken.is(tok::less);
698 
699   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
700     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
701       return true;
702 
703     if (CheckTemplate && isa<TemplateDecl>(*I))
704       return true;
705   }
706 
707   return false;
708 }
709 
isTagTypeWithMissingTag(Sema & SemaRef,LookupResult & Result,Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc)710 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
711                                     Scope *S, CXXScopeSpec &SS,
712                                     IdentifierInfo *&Name,
713                                     SourceLocation NameLoc) {
714   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
715   SemaRef.LookupParsedName(R, S, &SS);
716   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
717     StringRef FixItTagName;
718     switch (Tag->getTagKind()) {
719       case TTK_Class:
720         FixItTagName = "class ";
721         break;
722 
723       case TTK_Enum:
724         FixItTagName = "enum ";
725         break;
726 
727       case TTK_Struct:
728         FixItTagName = "struct ";
729         break;
730 
731       case TTK_Interface:
732         FixItTagName = "__interface ";
733         break;
734 
735       case TTK_Union:
736         FixItTagName = "union ";
737         break;
738     }
739 
740     StringRef TagName = FixItTagName.drop_back();
741     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
742       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
743       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
744 
745     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
746          I != IEnd; ++I)
747       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
748         << Name << TagName;
749 
750     // Replace lookup results with just the tag decl.
751     Result.clear(Sema::LookupTagName);
752     SemaRef.LookupParsedName(Result, S, &SS);
753     return true;
754   }
755 
756   return false;
757 }
758 
759 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
buildNestedType(Sema & S,CXXScopeSpec & SS,QualType T,SourceLocation NameLoc)760 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
761                                   QualType T, SourceLocation NameLoc) {
762   ASTContext &Context = S.Context;
763 
764   TypeLocBuilder Builder;
765   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
766 
767   T = S.getElaboratedType(ETK_None, SS, T);
768   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
769   ElabTL.setElaboratedKeywordLoc(SourceLocation());
770   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
771   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
772 }
773 
774 Sema::NameClassification
ClassifyName(Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc,const Token & NextToken,bool IsAddressOfOperand,std::unique_ptr<CorrectionCandidateCallback> CCC)775 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
776                    SourceLocation NameLoc, const Token &NextToken,
777                    bool IsAddressOfOperand,
778                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
779   DeclarationNameInfo NameInfo(Name, NameLoc);
780   ObjCMethodDecl *CurMethod = getCurMethodDecl();
781 
782   if (NextToken.is(tok::coloncolon)) {
783     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
784                                 QualType(), false, SS, nullptr, false);
785   }
786 
787   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
788   LookupParsedName(Result, S, &SS, !CurMethod);
789 
790   // For unqualified lookup in a class template in MSVC mode, look into
791   // dependent base classes where the primary class template is known.
792   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
793     if (ParsedType TypeInBase =
794             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
795       return TypeInBase;
796   }
797 
798   // Perform lookup for Objective-C instance variables (including automatically
799   // synthesized instance variables), if we're in an Objective-C method.
800   // FIXME: This lookup really, really needs to be folded in to the normal
801   // unqualified lookup mechanism.
802   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
803     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
804     if (E.get() || E.isInvalid())
805       return E;
806   }
807 
808   bool SecondTry = false;
809   bool IsFilteredTemplateName = false;
810 
811 Corrected:
812   switch (Result.getResultKind()) {
813   case LookupResult::NotFound:
814     // If an unqualified-id is followed by a '(', then we have a function
815     // call.
816     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
817       // In C++, this is an ADL-only call.
818       // FIXME: Reference?
819       if (getLangOpts().CPlusPlus)
820         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
821 
822       // C90 6.3.2.2:
823       //   If the expression that precedes the parenthesized argument list in a
824       //   function call consists solely of an identifier, and if no
825       //   declaration is visible for this identifier, the identifier is
826       //   implicitly declared exactly as if, in the innermost block containing
827       //   the function call, the declaration
828       //
829       //     extern int identifier ();
830       //
831       //   appeared.
832       //
833       // We also allow this in C99 as an extension.
834       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
835         Result.addDecl(D);
836         Result.resolveKind();
837         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
838       }
839     }
840 
841     // In C, we first see whether there is a tag type by the same name, in
842     // which case it's likely that the user just forgot to write "enum",
843     // "struct", or "union".
844     if (!getLangOpts().CPlusPlus && !SecondTry &&
845         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
846       break;
847     }
848 
849     // Perform typo correction to determine if there is another name that is
850     // close to this name.
851     if (!SecondTry && CCC) {
852       SecondTry = true;
853       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
854                                                  Result.getLookupKind(), S,
855                                                  &SS, std::move(CCC),
856                                                  CTK_ErrorRecovery)) {
857         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
858         unsigned QualifiedDiag = diag::err_no_member_suggest;
859 
860         NamedDecl *FirstDecl = Corrected.getFoundDecl();
861         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
862         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
863             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
864           UnqualifiedDiag = diag::err_no_template_suggest;
865           QualifiedDiag = diag::err_no_member_template_suggest;
866         } else if (UnderlyingFirstDecl &&
867                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
868                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
869                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
870           UnqualifiedDiag = diag::err_unknown_typename_suggest;
871           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
872         }
873 
874         if (SS.isEmpty()) {
875           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
876         } else {// FIXME: is this even reachable? Test it.
877           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
878           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
879                                   Name->getName().equals(CorrectedStr);
880           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
881                                     << Name << computeDeclContext(SS, false)
882                                     << DroppedSpecifier << SS.getRange());
883         }
884 
885         // Update the name, so that the caller has the new name.
886         Name = Corrected.getCorrectionAsIdentifierInfo();
887 
888         // Typo correction corrected to a keyword.
889         if (Corrected.isKeyword())
890           return Name;
891 
892         // Also update the LookupResult...
893         // FIXME: This should probably go away at some point
894         Result.clear();
895         Result.setLookupName(Corrected.getCorrection());
896         if (FirstDecl)
897           Result.addDecl(FirstDecl);
898 
899         // If we found an Objective-C instance variable, let
900         // LookupInObjCMethod build the appropriate expression to
901         // reference the ivar.
902         // FIXME: This is a gross hack.
903         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
904           Result.clear();
905           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
906           return E;
907         }
908 
909         goto Corrected;
910       }
911     }
912 
913     // We failed to correct; just fall through and let the parser deal with it.
914     Result.suppressDiagnostics();
915     return NameClassification::Unknown();
916 
917   case LookupResult::NotFoundInCurrentInstantiation: {
918     // We performed name lookup into the current instantiation, and there were
919     // dependent bases, so we treat this result the same way as any other
920     // dependent nested-name-specifier.
921 
922     // C++ [temp.res]p2:
923     //   A name used in a template declaration or definition and that is
924     //   dependent on a template-parameter is assumed not to name a type
925     //   unless the applicable name lookup finds a type name or the name is
926     //   qualified by the keyword typename.
927     //
928     // FIXME: If the next token is '<', we might want to ask the parser to
929     // perform some heroics to see if we actually have a
930     // template-argument-list, which would indicate a missing 'template'
931     // keyword here.
932     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
933                                       NameInfo, IsAddressOfOperand,
934                                       /*TemplateArgs=*/nullptr);
935   }
936 
937   case LookupResult::Found:
938   case LookupResult::FoundOverloaded:
939   case LookupResult::FoundUnresolvedValue:
940     break;
941 
942   case LookupResult::Ambiguous:
943     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
944         hasAnyAcceptableTemplateNames(Result)) {
945       // C++ [temp.local]p3:
946       //   A lookup that finds an injected-class-name (10.2) can result in an
947       //   ambiguity in certain cases (for example, if it is found in more than
948       //   one base class). If all of the injected-class-names that are found
949       //   refer to specializations of the same class template, and if the name
950       //   is followed by a template-argument-list, the reference refers to the
951       //   class template itself and not a specialization thereof, and is not
952       //   ambiguous.
953       //
954       // This filtering can make an ambiguous result into an unambiguous one,
955       // so try again after filtering out template names.
956       FilterAcceptableTemplateNames(Result);
957       if (!Result.isAmbiguous()) {
958         IsFilteredTemplateName = true;
959         break;
960       }
961     }
962 
963     // Diagnose the ambiguity and return an error.
964     return NameClassification::Error();
965   }
966 
967   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
968       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
969     // C++ [temp.names]p3:
970     //   After name lookup (3.4) finds that a name is a template-name or that
971     //   an operator-function-id or a literal- operator-id refers to a set of
972     //   overloaded functions any member of which is a function template if
973     //   this is followed by a <, the < is always taken as the delimiter of a
974     //   template-argument-list and never as the less-than operator.
975     if (!IsFilteredTemplateName)
976       FilterAcceptableTemplateNames(Result);
977 
978     if (!Result.empty()) {
979       bool IsFunctionTemplate;
980       bool IsVarTemplate;
981       TemplateName Template;
982       if (Result.end() - Result.begin() > 1) {
983         IsFunctionTemplate = true;
984         Template = Context.getOverloadedTemplateName(Result.begin(),
985                                                      Result.end());
986       } else {
987         TemplateDecl *TD
988           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
989         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
990         IsVarTemplate = isa<VarTemplateDecl>(TD);
991 
992         if (SS.isSet() && !SS.isInvalid())
993           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
994                                                     /*TemplateKeyword=*/false,
995                                                       TD);
996         else
997           Template = TemplateName(TD);
998       }
999 
1000       if (IsFunctionTemplate) {
1001         // Function templates always go through overload resolution, at which
1002         // point we'll perform the various checks (e.g., accessibility) we need
1003         // to based on which function we selected.
1004         Result.suppressDiagnostics();
1005 
1006         return NameClassification::FunctionTemplate(Template);
1007       }
1008 
1009       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1010                            : NameClassification::TypeTemplate(Template);
1011     }
1012   }
1013 
1014   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1015   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1018     QualType T = Context.getTypeDeclType(Type);
1019     if (SS.isNotEmpty())
1020       return buildNestedType(*this, SS, T, NameLoc);
1021     return ParsedType::make(T);
1022   }
1023 
1024   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1025   if (!Class) {
1026     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1027     if (ObjCCompatibleAliasDecl *Alias =
1028             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1029       Class = Alias->getClassInterface();
1030   }
1031 
1032   if (Class) {
1033     DiagnoseUseOfDecl(Class, NameLoc);
1034 
1035     if (NextToken.is(tok::period)) {
1036       // Interface. <something> is parsed as a property reference expression.
1037       // Just return "unknown" as a fall-through for now.
1038       Result.suppressDiagnostics();
1039       return NameClassification::Unknown();
1040     }
1041 
1042     QualType T = Context.getObjCInterfaceType(Class);
1043     return ParsedType::make(T);
1044   }
1045 
1046   // We can have a type template here if we're classifying a template argument.
1047   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1048     return NameClassification::TypeTemplate(
1049         TemplateName(cast<TemplateDecl>(FirstDecl)));
1050 
1051   // Check for a tag type hidden by a non-type decl in a few cases where it
1052   // seems likely a type is wanted instead of the non-type that was found.
1053   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1054   if ((NextToken.is(tok::identifier) ||
1055        (NextIsOp &&
1056         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1057       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1058     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1059     DiagnoseUseOfDecl(Type, NameLoc);
1060     QualType T = Context.getTypeDeclType(Type);
1061     if (SS.isNotEmpty())
1062       return buildNestedType(*this, SS, T, NameLoc);
1063     return ParsedType::make(T);
1064   }
1065 
1066   if (FirstDecl->isCXXClassMember())
1067     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1068                                            nullptr, S);
1069 
1070   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1071   return BuildDeclarationNameExpr(SS, Result, ADL);
1072 }
1073 
1074 // Determines the context to return to after temporarily entering a
1075 // context.  This depends in an unnecessarily complicated way on the
1076 // exact ordering of callbacks from the parser.
getContainingDC(DeclContext * DC)1077 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1078 
1079   // Functions defined inline within classes aren't parsed until we've
1080   // finished parsing the top-level class, so the top-level class is
1081   // the context we'll need to return to.
1082   // A Lambda call operator whose parent is a class must not be treated
1083   // as an inline member function.  A Lambda can be used legally
1084   // either as an in-class member initializer or a default argument.  These
1085   // are parsed once the class has been marked complete and so the containing
1086   // context would be the nested class (when the lambda is defined in one);
1087   // If the class is not complete, then the lambda is being used in an
1088   // ill-formed fashion (such as to specify the width of a bit-field, or
1089   // in an array-bound) - in which case we still want to return the
1090   // lexically containing DC (which could be a nested class).
1091   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1092     DC = DC->getLexicalParent();
1093 
1094     // A function not defined within a class will always return to its
1095     // lexical context.
1096     if (!isa<CXXRecordDecl>(DC))
1097       return DC;
1098 
1099     // A C++ inline method/friend is parsed *after* the topmost class
1100     // it was declared in is fully parsed ("complete");  the topmost
1101     // class is the context we need to return to.
1102     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1103       DC = RD;
1104 
1105     // Return the declaration context of the topmost class the inline method is
1106     // declared in.
1107     return DC;
1108   }
1109 
1110   return DC->getLexicalParent();
1111 }
1112 
PushDeclContext(Scope * S,DeclContext * DC)1113 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1114   assert(getContainingDC(DC) == CurContext &&
1115       "The next DeclContext should be lexically contained in the current one.");
1116   CurContext = DC;
1117   S->setEntity(DC);
1118 }
1119 
PopDeclContext()1120 void Sema::PopDeclContext() {
1121   assert(CurContext && "DeclContext imbalance!");
1122 
1123   CurContext = getContainingDC(CurContext);
1124   assert(CurContext && "Popped translation unit!");
1125 }
1126 
ActOnTagStartSkippedDefinition(Scope * S,Decl * D)1127 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1128                                                                     Decl *D) {
1129   // Unlike PushDeclContext, the context to which we return is not necessarily
1130   // the containing DC of TD, because the new context will be some pre-existing
1131   // TagDecl definition instead of a fresh one.
1132   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1133   CurContext = cast<TagDecl>(D)->getDefinition();
1134   assert(CurContext && "skipping definition of undefined tag");
1135   // Start lookups from the parent of the current context; we don't want to look
1136   // into the pre-existing complete definition.
1137   S->setEntity(CurContext->getLookupParent());
1138   return Result;
1139 }
1140 
ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)1141 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1142   CurContext = static_cast<decltype(CurContext)>(Context);
1143 }
1144 
1145 /// EnterDeclaratorContext - Used when we must lookup names in the context
1146 /// of a declarator's nested name specifier.
1147 ///
EnterDeclaratorContext(Scope * S,DeclContext * DC)1148 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1149   // C++0x [basic.lookup.unqual]p13:
1150   //   A name used in the definition of a static data member of class
1151   //   X (after the qualified-id of the static member) is looked up as
1152   //   if the name was used in a member function of X.
1153   // C++0x [basic.lookup.unqual]p14:
1154   //   If a variable member of a namespace is defined outside of the
1155   //   scope of its namespace then any name used in the definition of
1156   //   the variable member (after the declarator-id) is looked up as
1157   //   if the definition of the variable member occurred in its
1158   //   namespace.
1159   // Both of these imply that we should push a scope whose context
1160   // is the semantic context of the declaration.  We can't use
1161   // PushDeclContext here because that context is not necessarily
1162   // lexically contained in the current context.  Fortunately,
1163   // the containing scope should have the appropriate information.
1164 
1165   assert(!S->getEntity() && "scope already has entity");
1166 
1167 #ifndef NDEBUG
1168   Scope *Ancestor = S->getParent();
1169   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1170   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1171 #endif
1172 
1173   CurContext = DC;
1174   S->setEntity(DC);
1175 }
1176 
ExitDeclaratorContext(Scope * S)1177 void Sema::ExitDeclaratorContext(Scope *S) {
1178   assert(S->getEntity() == CurContext && "Context imbalance!");
1179 
1180   // Switch back to the lexical context.  The safety of this is
1181   // enforced by an assert in EnterDeclaratorContext.
1182   Scope *Ancestor = S->getParent();
1183   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1184   CurContext = Ancestor->getEntity();
1185 
1186   // We don't need to do anything with the scope, which is going to
1187   // disappear.
1188 }
1189 
ActOnReenterFunctionContext(Scope * S,Decl * D)1190 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1191   // We assume that the caller has already called
1192   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1193   FunctionDecl *FD = D->getAsFunction();
1194   if (!FD)
1195     return;
1196 
1197   // Same implementation as PushDeclContext, but enters the context
1198   // from the lexical parent, rather than the top-level class.
1199   assert(CurContext == FD->getLexicalParent() &&
1200     "The next DeclContext should be lexically contained in the current one.");
1201   CurContext = FD;
1202   S->setEntity(CurContext);
1203 
1204   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1205     ParmVarDecl *Param = FD->getParamDecl(P);
1206     // If the parameter has an identifier, then add it to the scope
1207     if (Param->getIdentifier()) {
1208       S->AddDecl(Param);
1209       IdResolver.AddDecl(Param);
1210     }
1211   }
1212 }
1213 
ActOnExitFunctionContext()1214 void Sema::ActOnExitFunctionContext() {
1215   // Same implementation as PopDeclContext, but returns to the lexical parent,
1216   // rather than the top-level class.
1217   assert(CurContext && "DeclContext imbalance!");
1218   CurContext = CurContext->getLexicalParent();
1219   assert(CurContext && "Popped translation unit!");
1220 }
1221 
1222 /// \brief Determine whether we allow overloading of the function
1223 /// PrevDecl with another declaration.
1224 ///
1225 /// This routine determines whether overloading is possible, not
1226 /// whether some new function is actually an overload. It will return
1227 /// true in C++ (where we can always provide overloads) or, as an
1228 /// extension, in C when the previous function is already an
1229 /// overloaded function declaration or has the "overloadable"
1230 /// attribute.
AllowOverloadingOfFunction(LookupResult & Previous,ASTContext & Context)1231 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1232                                        ASTContext &Context) {
1233   if (Context.getLangOpts().CPlusPlus)
1234     return true;
1235 
1236   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1237     return true;
1238 
1239   return (Previous.getResultKind() == LookupResult::Found
1240           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1241 }
1242 
1243 /// Add this decl to the scope shadowed decl chains.
PushOnScopeChains(NamedDecl * D,Scope * S,bool AddToContext)1244 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1245   // Move up the scope chain until we find the nearest enclosing
1246   // non-transparent context. The declaration will be introduced into this
1247   // scope.
1248   while (S->getEntity() && S->getEntity()->isTransparentContext())
1249     S = S->getParent();
1250 
1251   // Add scoped declarations into their context, so that they can be
1252   // found later. Declarations without a context won't be inserted
1253   // into any context.
1254   if (AddToContext)
1255     CurContext->addDecl(D);
1256 
1257   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1258   // are function-local declarations.
1259   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1260       !D->getDeclContext()->getRedeclContext()->Equals(
1261         D->getLexicalDeclContext()->getRedeclContext()) &&
1262       !D->getLexicalDeclContext()->isFunctionOrMethod())
1263     return;
1264 
1265   // Template instantiations should also not be pushed into scope.
1266   if (isa<FunctionDecl>(D) &&
1267       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1268     return;
1269 
1270   // If this replaces anything in the current scope,
1271   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1272                                IEnd = IdResolver.end();
1273   for (; I != IEnd; ++I) {
1274     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1275       S->RemoveDecl(*I);
1276       IdResolver.RemoveDecl(*I);
1277 
1278       // Should only need to replace one decl.
1279       break;
1280     }
1281   }
1282 
1283   S->AddDecl(D);
1284 
1285   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1286     // Implicitly-generated labels may end up getting generated in an order that
1287     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1288     // the label at the appropriate place in the identifier chain.
1289     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1290       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1291       if (IDC == CurContext) {
1292         if (!S->isDeclScope(*I))
1293           continue;
1294       } else if (IDC->Encloses(CurContext))
1295         break;
1296     }
1297 
1298     IdResolver.InsertDeclAfter(I, D);
1299   } else {
1300     IdResolver.AddDecl(D);
1301   }
1302 }
1303 
pushExternalDeclIntoScope(NamedDecl * D,DeclarationName Name)1304 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1305   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1306     TUScope->AddDecl(D);
1307 }
1308 
isDeclInScope(NamedDecl * D,DeclContext * Ctx,Scope * S,bool AllowInlineNamespace)1309 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1310                          bool AllowInlineNamespace) {
1311   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1312 }
1313 
getScopeForDeclContext(Scope * S,DeclContext * DC)1314 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1315   DeclContext *TargetDC = DC->getPrimaryContext();
1316   do {
1317     if (DeclContext *ScopeDC = S->getEntity())
1318       if (ScopeDC->getPrimaryContext() == TargetDC)
1319         return S;
1320   } while ((S = S->getParent()));
1321 
1322   return nullptr;
1323 }
1324 
1325 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1326                                             DeclContext*,
1327                                             ASTContext&);
1328 
1329 /// Filters out lookup results that don't fall within the given scope
1330 /// as determined by isDeclInScope.
FilterLookupForScope(LookupResult & R,DeclContext * Ctx,Scope * S,bool ConsiderLinkage,bool AllowInlineNamespace)1331 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1332                                 bool ConsiderLinkage,
1333                                 bool AllowInlineNamespace) {
1334   LookupResult::Filter F = R.makeFilter();
1335   while (F.hasNext()) {
1336     NamedDecl *D = F.next();
1337 
1338     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1339       continue;
1340 
1341     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1342       continue;
1343 
1344     F.erase();
1345   }
1346 
1347   F.done();
1348 }
1349 
isUsingDecl(NamedDecl * D)1350 static bool isUsingDecl(NamedDecl *D) {
1351   return isa<UsingShadowDecl>(D) ||
1352          isa<UnresolvedUsingTypenameDecl>(D) ||
1353          isa<UnresolvedUsingValueDecl>(D);
1354 }
1355 
1356 /// Removes using shadow declarations from the lookup results.
RemoveUsingDecls(LookupResult & R)1357 static void RemoveUsingDecls(LookupResult &R) {
1358   LookupResult::Filter F = R.makeFilter();
1359   while (F.hasNext())
1360     if (isUsingDecl(F.next()))
1361       F.erase();
1362 
1363   F.done();
1364 }
1365 
1366 /// \brief Check for this common pattern:
1367 /// @code
1368 /// class S {
1369 ///   S(const S&); // DO NOT IMPLEMENT
1370 ///   void operator=(const S&); // DO NOT IMPLEMENT
1371 /// };
1372 /// @endcode
IsDisallowedCopyOrAssign(const CXXMethodDecl * D)1373 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1374   // FIXME: Should check for private access too but access is set after we get
1375   // the decl here.
1376   if (D->doesThisDeclarationHaveABody())
1377     return false;
1378 
1379   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1380     return CD->isCopyConstructor();
1381   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1382     return Method->isCopyAssignmentOperator();
1383   return false;
1384 }
1385 
1386 // We need this to handle
1387 //
1388 // typedef struct {
1389 //   void *foo() { return 0; }
1390 // } A;
1391 //
1392 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1393 // for example. If 'A', foo will have external linkage. If we have '*A',
1394 // foo will have no linkage. Since we can't know until we get to the end
1395 // of the typedef, this function finds out if D might have non-external linkage.
1396 // Callers should verify at the end of the TU if it D has external linkage or
1397 // not.
mightHaveNonExternalLinkage(const DeclaratorDecl * D)1398 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1399   const DeclContext *DC = D->getDeclContext();
1400   while (!DC->isTranslationUnit()) {
1401     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1402       if (!RD->hasNameForLinkage())
1403         return true;
1404     }
1405     DC = DC->getParent();
1406   }
1407 
1408   return !D->isExternallyVisible();
1409 }
1410 
1411 // FIXME: This needs to be refactored; some other isInMainFile users want
1412 // these semantics.
isMainFileLoc(const Sema & S,SourceLocation Loc)1413 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1414   if (S.TUKind != TU_Complete)
1415     return false;
1416   return S.SourceMgr.isInMainFile(Loc);
1417 }
1418 
ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl * D) const1419 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1420   assert(D);
1421 
1422   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1423     return false;
1424 
1425   // Ignore all entities declared within templates, and out-of-line definitions
1426   // of members of class templates.
1427   if (D->getDeclContext()->isDependentContext() ||
1428       D->getLexicalDeclContext()->isDependentContext())
1429     return false;
1430 
1431   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1432     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1433       return false;
1434 
1435     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1436       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1437         return false;
1438     } else {
1439       // 'static inline' functions are defined in headers; don't warn.
1440       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1441         return false;
1442     }
1443 
1444     if (FD->doesThisDeclarationHaveABody() &&
1445         Context.DeclMustBeEmitted(FD))
1446       return false;
1447   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1448     // Constants and utility variables are defined in headers with internal
1449     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1450     // like "inline".)
1451     if (!isMainFileLoc(*this, VD->getLocation()))
1452       return false;
1453 
1454     if (Context.DeclMustBeEmitted(VD))
1455       return false;
1456 
1457     if (VD->isStaticDataMember() &&
1458         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1459       return false;
1460 
1461     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1462       return false;
1463   } else {
1464     return false;
1465   }
1466 
1467   // Only warn for unused decls internal to the translation unit.
1468   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1469   // for inline functions defined in the main source file, for instance.
1470   return mightHaveNonExternalLinkage(D);
1471 }
1472 
MarkUnusedFileScopedDecl(const DeclaratorDecl * D)1473 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1474   if (!D)
1475     return;
1476 
1477   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1478     const FunctionDecl *First = FD->getFirstDecl();
1479     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1480       return; // First should already be in the vector.
1481   }
1482 
1483   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1484     const VarDecl *First = VD->getFirstDecl();
1485     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1486       return; // First should already be in the vector.
1487   }
1488 
1489   if (ShouldWarnIfUnusedFileScopedDecl(D))
1490     UnusedFileScopedDecls.push_back(D);
1491 }
1492 
ShouldDiagnoseUnusedDecl(const NamedDecl * D)1493 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1494   if (D->isInvalidDecl())
1495     return false;
1496 
1497   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1498       D->hasAttr<ObjCPreciseLifetimeAttr>())
1499     return false;
1500 
1501   if (isa<LabelDecl>(D))
1502     return true;
1503 
1504   // Except for labels, we only care about unused decls that are local to
1505   // functions.
1506   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1507   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1508     // For dependent types, the diagnostic is deferred.
1509     WithinFunction =
1510         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1511   if (!WithinFunction)
1512     return false;
1513 
1514   if (isa<TypedefNameDecl>(D))
1515     return true;
1516 
1517   // White-list anything that isn't a local variable.
1518   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1519     return false;
1520 
1521   // Types of valid local variables should be complete, so this should succeed.
1522   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1523 
1524     // White-list anything with an __attribute__((unused)) type.
1525     QualType Ty = VD->getType();
1526 
1527     // Only look at the outermost level of typedef.
1528     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1529       if (TT->getDecl()->hasAttr<UnusedAttr>())
1530         return false;
1531     }
1532 
1533     // If we failed to complete the type for some reason, or if the type is
1534     // dependent, don't diagnose the variable.
1535     if (Ty->isIncompleteType() || Ty->isDependentType())
1536       return false;
1537 
1538     if (const TagType *TT = Ty->getAs<TagType>()) {
1539       const TagDecl *Tag = TT->getDecl();
1540       if (Tag->hasAttr<UnusedAttr>())
1541         return false;
1542 
1543       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1544         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1545           return false;
1546 
1547         if (const Expr *Init = VD->getInit()) {
1548           if (const ExprWithCleanups *Cleanups =
1549                   dyn_cast<ExprWithCleanups>(Init))
1550             Init = Cleanups->getSubExpr();
1551           const CXXConstructExpr *Construct =
1552             dyn_cast<CXXConstructExpr>(Init);
1553           if (Construct && !Construct->isElidable()) {
1554             CXXConstructorDecl *CD = Construct->getConstructor();
1555             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1556               return false;
1557           }
1558         }
1559       }
1560     }
1561 
1562     // TODO: __attribute__((unused)) templates?
1563   }
1564 
1565   return true;
1566 }
1567 
GenerateFixForUnusedDecl(const NamedDecl * D,ASTContext & Ctx,FixItHint & Hint)1568 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1569                                      FixItHint &Hint) {
1570   if (isa<LabelDecl>(D)) {
1571     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1572                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1573     if (AfterColon.isInvalid())
1574       return;
1575     Hint = FixItHint::CreateRemoval(CharSourceRange::
1576                                     getCharRange(D->getLocStart(), AfterColon));
1577   }
1578 }
1579 
DiagnoseUnusedNestedTypedefs(const RecordDecl * D)1580 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1581   if (D->getTypeForDecl()->isDependentType())
1582     return;
1583 
1584   for (auto *TmpD : D->decls()) {
1585     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1586       DiagnoseUnusedDecl(T);
1587     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1588       DiagnoseUnusedNestedTypedefs(R);
1589   }
1590 }
1591 
1592 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1593 /// unless they are marked attr(unused).
DiagnoseUnusedDecl(const NamedDecl * D)1594 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1595   if (!ShouldDiagnoseUnusedDecl(D))
1596     return;
1597 
1598   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1599     // typedefs can be referenced later on, so the diagnostics are emitted
1600     // at end-of-translation-unit.
1601     UnusedLocalTypedefNameCandidates.insert(TD);
1602     return;
1603   }
1604 
1605   FixItHint Hint;
1606   GenerateFixForUnusedDecl(D, Context, Hint);
1607 
1608   unsigned DiagID;
1609   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1610     DiagID = diag::warn_unused_exception_param;
1611   else if (isa<LabelDecl>(D))
1612     DiagID = diag::warn_unused_label;
1613   else
1614     DiagID = diag::warn_unused_variable;
1615 
1616   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1617 }
1618 
CheckPoppedLabel(LabelDecl * L,Sema & S)1619 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1620   // Verify that we have no forward references left.  If so, there was a goto
1621   // or address of a label taken, but no definition of it.  Label fwd
1622   // definitions are indicated with a null substmt which is also not a resolved
1623   // MS inline assembly label name.
1624   bool Diagnose = false;
1625   if (L->isMSAsmLabel())
1626     Diagnose = !L->isResolvedMSAsmLabel();
1627   else
1628     Diagnose = L->getStmt() == nullptr;
1629   if (Diagnose)
1630     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1631 }
1632 
ActOnPopScope(SourceLocation Loc,Scope * S)1633 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1634   S->mergeNRVOIntoParent();
1635 
1636   if (S->decl_empty()) return;
1637   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1638          "Scope shouldn't contain decls!");
1639 
1640   for (auto *TmpD : S->decls()) {
1641     assert(TmpD && "This decl didn't get pushed??");
1642 
1643     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1644     NamedDecl *D = cast<NamedDecl>(TmpD);
1645 
1646     if (!D->getDeclName()) continue;
1647 
1648     // Diagnose unused variables in this scope.
1649     if (!S->hasUnrecoverableErrorOccurred()) {
1650       DiagnoseUnusedDecl(D);
1651       if (const auto *RD = dyn_cast<RecordDecl>(D))
1652         DiagnoseUnusedNestedTypedefs(RD);
1653     }
1654 
1655     // If this was a forward reference to a label, verify it was defined.
1656     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1657       CheckPoppedLabel(LD, *this);
1658 
1659     // Remove this name from our lexical scope, and warn on it if we haven't
1660     // already.
1661     IdResolver.RemoveDecl(D);
1662     auto ShadowI = ShadowingDecls.find(D);
1663     if (ShadowI != ShadowingDecls.end()) {
1664       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1665         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1666             << D << FD << FD->getParent();
1667         Diag(FD->getLocation(), diag::note_previous_declaration);
1668       }
1669       ShadowingDecls.erase(ShadowI);
1670     }
1671   }
1672 }
1673 
1674 /// \brief Look for an Objective-C class in the translation unit.
1675 ///
1676 /// \param Id The name of the Objective-C class we're looking for. If
1677 /// typo-correction fixes this name, the Id will be updated
1678 /// to the fixed name.
1679 ///
1680 /// \param IdLoc The location of the name in the translation unit.
1681 ///
1682 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1683 /// if there is no class with the given name.
1684 ///
1685 /// \returns The declaration of the named Objective-C class, or NULL if the
1686 /// class could not be found.
getObjCInterfaceDecl(IdentifierInfo * & Id,SourceLocation IdLoc,bool DoTypoCorrection)1687 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1688                                               SourceLocation IdLoc,
1689                                               bool DoTypoCorrection) {
1690   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1691   // creation from this context.
1692   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1693 
1694   if (!IDecl && DoTypoCorrection) {
1695     // Perform typo correction at the given location, but only if we
1696     // find an Objective-C class name.
1697     if (TypoCorrection C = CorrectTypo(
1698             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1699             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1700             CTK_ErrorRecovery)) {
1701       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1702       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1703       Id = IDecl->getIdentifier();
1704     }
1705   }
1706   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1707   // This routine must always return a class definition, if any.
1708   if (Def && Def->getDefinition())
1709       Def = Def->getDefinition();
1710   return Def;
1711 }
1712 
1713 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1714 /// from S, where a non-field would be declared. This routine copes
1715 /// with the difference between C and C++ scoping rules in structs and
1716 /// unions. For example, the following code is well-formed in C but
1717 /// ill-formed in C++:
1718 /// @code
1719 /// struct S6 {
1720 ///   enum { BAR } e;
1721 /// };
1722 ///
1723 /// void test_S6() {
1724 ///   struct S6 a;
1725 ///   a.e = BAR;
1726 /// }
1727 /// @endcode
1728 /// For the declaration of BAR, this routine will return a different
1729 /// scope. The scope S will be the scope of the unnamed enumeration
1730 /// within S6. In C++, this routine will return the scope associated
1731 /// with S6, because the enumeration's scope is a transparent
1732 /// context but structures can contain non-field names. In C, this
1733 /// routine will return the translation unit scope, since the
1734 /// enumeration's scope is a transparent context and structures cannot
1735 /// contain non-field names.
getNonFieldDeclScope(Scope * S)1736 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1737   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1738          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1739          (S->isClassScope() && !getLangOpts().CPlusPlus))
1740     S = S->getParent();
1741   return S;
1742 }
1743 
1744 /// \brief Looks up the declaration of "struct objc_super" and
1745 /// saves it for later use in building builtin declaration of
1746 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1747 /// pre-existing declaration exists no action takes place.
LookupPredefedObjCSuperType(Sema & ThisSema,Scope * S,IdentifierInfo * II)1748 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1749                                         IdentifierInfo *II) {
1750   if (!II->isStr("objc_msgSendSuper"))
1751     return;
1752   ASTContext &Context = ThisSema.Context;
1753 
1754   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1755                       SourceLocation(), Sema::LookupTagName);
1756   ThisSema.LookupName(Result, S);
1757   if (Result.getResultKind() == LookupResult::Found)
1758     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1759       Context.setObjCSuperType(Context.getTagDeclType(TD));
1760 }
1761 
getHeaderName(ASTContext::GetBuiltinTypeError Error)1762 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1763   switch (Error) {
1764   case ASTContext::GE_None:
1765     return "";
1766   case ASTContext::GE_Missing_stdio:
1767     return "stdio.h";
1768   case ASTContext::GE_Missing_setjmp:
1769     return "setjmp.h";
1770   case ASTContext::GE_Missing_ucontext:
1771     return "ucontext.h";
1772   }
1773   llvm_unreachable("unhandled error kind");
1774 }
1775 
1776 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1777 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1778 /// if we're creating this built-in in anticipation of redeclaring the
1779 /// built-in.
LazilyCreateBuiltin(IdentifierInfo * II,unsigned ID,Scope * S,bool ForRedeclaration,SourceLocation Loc)1780 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1781                                      Scope *S, bool ForRedeclaration,
1782                                      SourceLocation Loc) {
1783   LookupPredefedObjCSuperType(*this, S, II);
1784 
1785   ASTContext::GetBuiltinTypeError Error;
1786   QualType R = Context.GetBuiltinType(ID, Error);
1787   if (Error) {
1788     if (ForRedeclaration)
1789       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1790           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1791     return nullptr;
1792   }
1793 
1794   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1795     Diag(Loc, diag::ext_implicit_lib_function_decl)
1796         << Context.BuiltinInfo.getName(ID) << R;
1797     if (Context.BuiltinInfo.getHeaderName(ID) &&
1798         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1799       Diag(Loc, diag::note_include_header_or_declare)
1800           << Context.BuiltinInfo.getHeaderName(ID)
1801           << Context.BuiltinInfo.getName(ID);
1802   }
1803 
1804   if (R.isNull())
1805     return nullptr;
1806 
1807   DeclContext *Parent = Context.getTranslationUnitDecl();
1808   if (getLangOpts().CPlusPlus) {
1809     LinkageSpecDecl *CLinkageDecl =
1810         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1811                                 LinkageSpecDecl::lang_c, false);
1812     CLinkageDecl->setImplicit();
1813     Parent->addDecl(CLinkageDecl);
1814     Parent = CLinkageDecl;
1815   }
1816 
1817   FunctionDecl *New = FunctionDecl::Create(Context,
1818                                            Parent,
1819                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1820                                            SC_Extern,
1821                                            false,
1822                                            R->isFunctionProtoType());
1823   New->setImplicit();
1824 
1825   // Create Decl objects for each parameter, adding them to the
1826   // FunctionDecl.
1827   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1828     SmallVector<ParmVarDecl*, 16> Params;
1829     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1830       ParmVarDecl *parm =
1831           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1832                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1833                               SC_None, nullptr);
1834       parm->setScopeInfo(0, i);
1835       Params.push_back(parm);
1836     }
1837     New->setParams(Params);
1838   }
1839 
1840   AddKnownFunctionAttributes(New);
1841   RegisterLocallyScopedExternCDecl(New, S);
1842 
1843   // TUScope is the translation-unit scope to insert this function into.
1844   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1845   // relate Scopes to DeclContexts, and probably eliminate CurContext
1846   // entirely, but we're not there yet.
1847   DeclContext *SavedContext = CurContext;
1848   CurContext = Parent;
1849   PushOnScopeChains(New, TUScope);
1850   CurContext = SavedContext;
1851   return New;
1852 }
1853 
1854 /// Typedef declarations don't have linkage, but they still denote the same
1855 /// entity if their types are the same.
1856 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1857 /// isSameEntity.
filterNonConflictingPreviousTypedefDecls(Sema & S,TypedefNameDecl * Decl,LookupResult & Previous)1858 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1859                                                      TypedefNameDecl *Decl,
1860                                                      LookupResult &Previous) {
1861   // This is only interesting when modules are enabled.
1862   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1863     return;
1864 
1865   // Empty sets are uninteresting.
1866   if (Previous.empty())
1867     return;
1868 
1869   LookupResult::Filter Filter = Previous.makeFilter();
1870   while (Filter.hasNext()) {
1871     NamedDecl *Old = Filter.next();
1872 
1873     // Non-hidden declarations are never ignored.
1874     if (S.isVisible(Old))
1875       continue;
1876 
1877     // Declarations of the same entity are not ignored, even if they have
1878     // different linkages.
1879     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1880       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1881                                 Decl->getUnderlyingType()))
1882         continue;
1883 
1884       // If both declarations give a tag declaration a typedef name for linkage
1885       // purposes, then they declare the same entity.
1886       if (S.getLangOpts().CPlusPlus &&
1887           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1888           Decl->getAnonDeclWithTypedefName())
1889         continue;
1890     }
1891 
1892     Filter.erase();
1893   }
1894 
1895   Filter.done();
1896 }
1897 
isIncompatibleTypedef(TypeDecl * Old,TypedefNameDecl * New)1898 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1899   QualType OldType;
1900   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1901     OldType = OldTypedef->getUnderlyingType();
1902   else
1903     OldType = Context.getTypeDeclType(Old);
1904   QualType NewType = New->getUnderlyingType();
1905 
1906   if (NewType->isVariablyModifiedType()) {
1907     // Must not redefine a typedef with a variably-modified type.
1908     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1909     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1910       << Kind << NewType;
1911     if (Old->getLocation().isValid())
1912       Diag(Old->getLocation(), diag::note_previous_definition);
1913     New->setInvalidDecl();
1914     return true;
1915   }
1916 
1917   if (OldType != NewType &&
1918       !OldType->isDependentType() &&
1919       !NewType->isDependentType() &&
1920       !Context.hasSameType(OldType, NewType)) {
1921     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1922     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1923       << Kind << NewType << OldType;
1924     if (Old->getLocation().isValid())
1925       Diag(Old->getLocation(), diag::note_previous_definition);
1926     New->setInvalidDecl();
1927     return true;
1928   }
1929   return false;
1930 }
1931 
1932 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1933 /// same name and scope as a previous declaration 'Old'.  Figure out
1934 /// how to resolve this situation, merging decls or emitting
1935 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1936 ///
MergeTypedefNameDecl(Scope * S,TypedefNameDecl * New,LookupResult & OldDecls)1937 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1938                                 LookupResult &OldDecls) {
1939   // If the new decl is known invalid already, don't bother doing any
1940   // merging checks.
1941   if (New->isInvalidDecl()) return;
1942 
1943   // Allow multiple definitions for ObjC built-in typedefs.
1944   // FIXME: Verify the underlying types are equivalent!
1945   if (getLangOpts().ObjC1) {
1946     const IdentifierInfo *TypeID = New->getIdentifier();
1947     switch (TypeID->getLength()) {
1948     default: break;
1949     case 2:
1950       {
1951         if (!TypeID->isStr("id"))
1952           break;
1953         QualType T = New->getUnderlyingType();
1954         if (!T->isPointerType())
1955           break;
1956         if (!T->isVoidPointerType()) {
1957           QualType PT = T->getAs<PointerType>()->getPointeeType();
1958           if (!PT->isStructureType())
1959             break;
1960         }
1961         Context.setObjCIdRedefinitionType(T);
1962         // Install the built-in type for 'id', ignoring the current definition.
1963         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1964         return;
1965       }
1966     case 5:
1967       if (!TypeID->isStr("Class"))
1968         break;
1969       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1970       // Install the built-in type for 'Class', ignoring the current definition.
1971       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1972       return;
1973     case 3:
1974       if (!TypeID->isStr("SEL"))
1975         break;
1976       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1977       // Install the built-in type for 'SEL', ignoring the current definition.
1978       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1979       return;
1980     }
1981     // Fall through - the typedef name was not a builtin type.
1982   }
1983 
1984   // Verify the old decl was also a type.
1985   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1986   if (!Old) {
1987     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1988       << New->getDeclName();
1989 
1990     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1991     if (OldD->getLocation().isValid())
1992       Diag(OldD->getLocation(), diag::note_previous_definition);
1993 
1994     return New->setInvalidDecl();
1995   }
1996 
1997   // If the old declaration is invalid, just give up here.
1998   if (Old->isInvalidDecl())
1999     return New->setInvalidDecl();
2000 
2001   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2002     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2003     auto *NewTag = New->getAnonDeclWithTypedefName();
2004     NamedDecl *Hidden = nullptr;
2005     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2006         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2007         !hasVisibleDefinition(OldTag, &Hidden)) {
2008       // There is a definition of this tag, but it is not visible. Use it
2009       // instead of our tag.
2010       New->setTypeForDecl(OldTD->getTypeForDecl());
2011       if (OldTD->isModed())
2012         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2013                                     OldTD->getUnderlyingType());
2014       else
2015         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2016 
2017       // Make the old tag definition visible.
2018       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2019 
2020       // If this was an unscoped enumeration, yank all of its enumerators
2021       // out of the scope.
2022       if (isa<EnumDecl>(NewTag)) {
2023         Scope *EnumScope = getNonFieldDeclScope(S);
2024         for (auto *D : NewTag->decls()) {
2025           auto *ED = cast<EnumConstantDecl>(D);
2026           assert(EnumScope->isDeclScope(ED));
2027           EnumScope->RemoveDecl(ED);
2028           IdResolver.RemoveDecl(ED);
2029           ED->getLexicalDeclContext()->removeDecl(ED);
2030         }
2031       }
2032     }
2033   }
2034 
2035   // If the typedef types are not identical, reject them in all languages and
2036   // with any extensions enabled.
2037   if (isIncompatibleTypedef(Old, New))
2038     return;
2039 
2040   // The types match.  Link up the redeclaration chain and merge attributes if
2041   // the old declaration was a typedef.
2042   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2043     New->setPreviousDecl(Typedef);
2044     mergeDeclAttributes(New, Old);
2045   }
2046 
2047   if (getLangOpts().MicrosoftExt)
2048     return;
2049 
2050   if (getLangOpts().CPlusPlus) {
2051     // C++ [dcl.typedef]p2:
2052     //   In a given non-class scope, a typedef specifier can be used to
2053     //   redefine the name of any type declared in that scope to refer
2054     //   to the type to which it already refers.
2055     if (!isa<CXXRecordDecl>(CurContext))
2056       return;
2057 
2058     // C++0x [dcl.typedef]p4:
2059     //   In a given class scope, a typedef specifier can be used to redefine
2060     //   any class-name declared in that scope that is not also a typedef-name
2061     //   to refer to the type to which it already refers.
2062     //
2063     // This wording came in via DR424, which was a correction to the
2064     // wording in DR56, which accidentally banned code like:
2065     //
2066     //   struct S {
2067     //     typedef struct A { } A;
2068     //   };
2069     //
2070     // in the C++03 standard. We implement the C++0x semantics, which
2071     // allow the above but disallow
2072     //
2073     //   struct S {
2074     //     typedef int I;
2075     //     typedef int I;
2076     //   };
2077     //
2078     // since that was the intent of DR56.
2079     if (!isa<TypedefNameDecl>(Old))
2080       return;
2081 
2082     Diag(New->getLocation(), diag::err_redefinition)
2083       << New->getDeclName();
2084     Diag(Old->getLocation(), diag::note_previous_definition);
2085     return New->setInvalidDecl();
2086   }
2087 
2088   // Modules always permit redefinition of typedefs, as does C11.
2089   if (getLangOpts().Modules || getLangOpts().C11)
2090     return;
2091 
2092   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2093   // is normally mapped to an error, but can be controlled with
2094   // -Wtypedef-redefinition.  If either the original or the redefinition is
2095   // in a system header, don't emit this for compatibility with GCC.
2096   if (getDiagnostics().getSuppressSystemWarnings() &&
2097       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2098        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2099     return;
2100 
2101   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2102     << New->getDeclName();
2103   Diag(Old->getLocation(), diag::note_previous_definition);
2104 }
2105 
2106 /// DeclhasAttr - returns true if decl Declaration already has the target
2107 /// attribute.
DeclHasAttr(const Decl * D,const Attr * A)2108 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2109   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2110   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2111   for (const auto *i : D->attrs())
2112     if (i->getKind() == A->getKind()) {
2113       if (Ann) {
2114         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2115           return true;
2116         continue;
2117       }
2118       // FIXME: Don't hardcode this check
2119       if (OA && isa<OwnershipAttr>(i))
2120         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2121       return true;
2122     }
2123 
2124   return false;
2125 }
2126 
isAttributeTargetADefinition(Decl * D)2127 static bool isAttributeTargetADefinition(Decl *D) {
2128   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2129     return VD->isThisDeclarationADefinition();
2130   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2131     return TD->isCompleteDefinition() || TD->isBeingDefined();
2132   return true;
2133 }
2134 
2135 /// Merge alignment attributes from \p Old to \p New, taking into account the
2136 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2137 ///
2138 /// \return \c true if any attributes were added to \p New.
mergeAlignedAttrs(Sema & S,NamedDecl * New,Decl * Old)2139 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2140   // Look for alignas attributes on Old, and pick out whichever attribute
2141   // specifies the strictest alignment requirement.
2142   AlignedAttr *OldAlignasAttr = nullptr;
2143   AlignedAttr *OldStrictestAlignAttr = nullptr;
2144   unsigned OldAlign = 0;
2145   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2146     // FIXME: We have no way of representing inherited dependent alignments
2147     // in a case like:
2148     //   template<int A, int B> struct alignas(A) X;
2149     //   template<int A, int B> struct alignas(B) X {};
2150     // For now, we just ignore any alignas attributes which are not on the
2151     // definition in such a case.
2152     if (I->isAlignmentDependent())
2153       return false;
2154 
2155     if (I->isAlignas())
2156       OldAlignasAttr = I;
2157 
2158     unsigned Align = I->getAlignment(S.Context);
2159     if (Align > OldAlign) {
2160       OldAlign = Align;
2161       OldStrictestAlignAttr = I;
2162     }
2163   }
2164 
2165   // Look for alignas attributes on New.
2166   AlignedAttr *NewAlignasAttr = nullptr;
2167   unsigned NewAlign = 0;
2168   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2169     if (I->isAlignmentDependent())
2170       return false;
2171 
2172     if (I->isAlignas())
2173       NewAlignasAttr = I;
2174 
2175     unsigned Align = I->getAlignment(S.Context);
2176     if (Align > NewAlign)
2177       NewAlign = Align;
2178   }
2179 
2180   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2181     // Both declarations have 'alignas' attributes. We require them to match.
2182     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2183     // fall short. (If two declarations both have alignas, they must both match
2184     // every definition, and so must match each other if there is a definition.)
2185 
2186     // If either declaration only contains 'alignas(0)' specifiers, then it
2187     // specifies the natural alignment for the type.
2188     if (OldAlign == 0 || NewAlign == 0) {
2189       QualType Ty;
2190       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2191         Ty = VD->getType();
2192       else
2193         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2194 
2195       if (OldAlign == 0)
2196         OldAlign = S.Context.getTypeAlign(Ty);
2197       if (NewAlign == 0)
2198         NewAlign = S.Context.getTypeAlign(Ty);
2199     }
2200 
2201     if (OldAlign != NewAlign) {
2202       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2203         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2204         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2205       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2206     }
2207   }
2208 
2209   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2210     // C++11 [dcl.align]p6:
2211     //   if any declaration of an entity has an alignment-specifier,
2212     //   every defining declaration of that entity shall specify an
2213     //   equivalent alignment.
2214     // C11 6.7.5/7:
2215     //   If the definition of an object does not have an alignment
2216     //   specifier, any other declaration of that object shall also
2217     //   have no alignment specifier.
2218     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2219       << OldAlignasAttr;
2220     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2221       << OldAlignasAttr;
2222   }
2223 
2224   bool AnyAdded = false;
2225 
2226   // Ensure we have an attribute representing the strictest alignment.
2227   if (OldAlign > NewAlign) {
2228     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2229     Clone->setInherited(true);
2230     New->addAttr(Clone);
2231     AnyAdded = true;
2232   }
2233 
2234   // Ensure we have an alignas attribute if the old declaration had one.
2235   if (OldAlignasAttr && !NewAlignasAttr &&
2236       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2237     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2238     Clone->setInherited(true);
2239     New->addAttr(Clone);
2240     AnyAdded = true;
2241   }
2242 
2243   return AnyAdded;
2244 }
2245 
mergeDeclAttribute(Sema & S,NamedDecl * D,const InheritableAttr * Attr,Sema::AvailabilityMergeKind AMK)2246 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2247                                const InheritableAttr *Attr,
2248                                Sema::AvailabilityMergeKind AMK) {
2249   InheritableAttr *NewAttr = nullptr;
2250   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2251   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2252     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2253                                       AA->isImplicit(), AA->getIntroduced(),
2254                                       AA->getDeprecated(),
2255                                       AA->getObsoleted(), AA->getUnavailable(),
2256                                       AA->getMessage(), AA->getStrict(),
2257                                       AA->getReplacement(), AMK,
2258                                       AttrSpellingListIndex);
2259   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2260     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2261                                     AttrSpellingListIndex);
2262   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2263     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2264                                         AttrSpellingListIndex);
2265   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2266     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2267                                    AttrSpellingListIndex);
2268   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2269     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2270                                    AttrSpellingListIndex);
2271   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2272     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2273                                 FA->getFormatIdx(), FA->getFirstArg(),
2274                                 AttrSpellingListIndex);
2275   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2276     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2277                                  AttrSpellingListIndex);
2278   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2279     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2280                                        AttrSpellingListIndex,
2281                                        IA->getSemanticSpelling());
2282   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2283     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2284                                       &S.Context.Idents.get(AA->getSpelling()),
2285                                       AttrSpellingListIndex);
2286   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2287     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2288   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2289     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2290   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2291     NewAttr = S.mergeInternalLinkageAttr(
2292         D, InternalLinkageA->getRange(),
2293         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2294         AttrSpellingListIndex);
2295   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2296     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2297                                 &S.Context.Idents.get(CommonA->getSpelling()),
2298                                 AttrSpellingListIndex);
2299   else if (isa<AlignedAttr>(Attr))
2300     // AlignedAttrs are handled separately, because we need to handle all
2301     // such attributes on a declaration at the same time.
2302     NewAttr = nullptr;
2303   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2304            (AMK == Sema::AMK_Override ||
2305             AMK == Sema::AMK_ProtocolImplementation))
2306     NewAttr = nullptr;
2307   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2308     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2309 
2310   if (NewAttr) {
2311     NewAttr->setInherited(true);
2312     D->addAttr(NewAttr);
2313     if (isa<MSInheritanceAttr>(NewAttr))
2314       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2315     return true;
2316   }
2317 
2318   return false;
2319 }
2320 
getDefinition(const Decl * D)2321 static const Decl *getDefinition(const Decl *D) {
2322   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2323     return TD->getDefinition();
2324   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2325     const VarDecl *Def = VD->getDefinition();
2326     if (Def)
2327       return Def;
2328     return VD->getActingDefinition();
2329   }
2330   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2331     return FD->getDefinition();
2332   return nullptr;
2333 }
2334 
hasAttribute(const Decl * D,attr::Kind Kind)2335 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2336   for (const auto *Attribute : D->attrs())
2337     if (Attribute->getKind() == Kind)
2338       return true;
2339   return false;
2340 }
2341 
2342 /// checkNewAttributesAfterDef - If we already have a definition, check that
2343 /// there are no new attributes in this declaration.
checkNewAttributesAfterDef(Sema & S,Decl * New,const Decl * Old)2344 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2345   if (!New->hasAttrs())
2346     return;
2347 
2348   const Decl *Def = getDefinition(Old);
2349   if (!Def || Def == New)
2350     return;
2351 
2352   AttrVec &NewAttributes = New->getAttrs();
2353   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2354     const Attr *NewAttribute = NewAttributes[I];
2355 
2356     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2357       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2358         Sema::SkipBodyInfo SkipBody;
2359         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2360 
2361         // If we're skipping this definition, drop the "alias" attribute.
2362         if (SkipBody.ShouldSkip) {
2363           NewAttributes.erase(NewAttributes.begin() + I);
2364           --E;
2365           continue;
2366         }
2367       } else {
2368         VarDecl *VD = cast<VarDecl>(New);
2369         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2370                                 VarDecl::TentativeDefinition
2371                             ? diag::err_alias_after_tentative
2372                             : diag::err_redefinition;
2373         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2374         S.Diag(Def->getLocation(), diag::note_previous_definition);
2375         VD->setInvalidDecl();
2376       }
2377       ++I;
2378       continue;
2379     }
2380 
2381     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2382       // Tentative definitions are only interesting for the alias check above.
2383       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2384         ++I;
2385         continue;
2386       }
2387     }
2388 
2389     if (hasAttribute(Def, NewAttribute->getKind())) {
2390       ++I;
2391       continue; // regular attr merging will take care of validating this.
2392     }
2393 
2394     if (isa<C11NoReturnAttr>(NewAttribute)) {
2395       // C's _Noreturn is allowed to be added to a function after it is defined.
2396       ++I;
2397       continue;
2398     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2399       if (AA->isAlignas()) {
2400         // C++11 [dcl.align]p6:
2401         //   if any declaration of an entity has an alignment-specifier,
2402         //   every defining declaration of that entity shall specify an
2403         //   equivalent alignment.
2404         // C11 6.7.5/7:
2405         //   If the definition of an object does not have an alignment
2406         //   specifier, any other declaration of that object shall also
2407         //   have no alignment specifier.
2408         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2409           << AA;
2410         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2411           << AA;
2412         NewAttributes.erase(NewAttributes.begin() + I);
2413         --E;
2414         continue;
2415       }
2416     }
2417 
2418     S.Diag(NewAttribute->getLocation(),
2419            diag::warn_attribute_precede_definition);
2420     S.Diag(Def->getLocation(), diag::note_previous_definition);
2421     NewAttributes.erase(NewAttributes.begin() + I);
2422     --E;
2423   }
2424 }
2425 
2426 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
mergeDeclAttributes(NamedDecl * New,Decl * Old,AvailabilityMergeKind AMK)2427 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2428                                AvailabilityMergeKind AMK) {
2429   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2430     UsedAttr *NewAttr = OldAttr->clone(Context);
2431     NewAttr->setInherited(true);
2432     New->addAttr(NewAttr);
2433   }
2434 
2435   if (!Old->hasAttrs() && !New->hasAttrs())
2436     return;
2437 
2438   // Attributes declared post-definition are currently ignored.
2439   checkNewAttributesAfterDef(*this, New, Old);
2440 
2441   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2442     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2443       if (OldA->getLabel() != NewA->getLabel()) {
2444         // This redeclaration changes __asm__ label.
2445         Diag(New->getLocation(), diag::err_different_asm_label);
2446         Diag(OldA->getLocation(), diag::note_previous_declaration);
2447       }
2448     } else if (Old->isUsed()) {
2449       // This redeclaration adds an __asm__ label to a declaration that has
2450       // already been ODR-used.
2451       Diag(New->getLocation(), diag::err_late_asm_label_name)
2452         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2453     }
2454   }
2455 
2456   // Re-declaration cannot add abi_tag's.
2457   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2458     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2459       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2460         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2461                       NewTag) == OldAbiTagAttr->tags_end()) {
2462           Diag(NewAbiTagAttr->getLocation(),
2463                diag::err_new_abi_tag_on_redeclaration)
2464               << NewTag;
2465           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2466         }
2467       }
2468     } else {
2469       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2470       Diag(Old->getLocation(), diag::note_previous_declaration);
2471     }
2472   }
2473 
2474   if (!Old->hasAttrs())
2475     return;
2476 
2477   bool foundAny = New->hasAttrs();
2478 
2479   // Ensure that any moving of objects within the allocated map is done before
2480   // we process them.
2481   if (!foundAny) New->setAttrs(AttrVec());
2482 
2483   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2484     // Ignore deprecated/unavailable/availability attributes if requested.
2485     AvailabilityMergeKind LocalAMK = AMK_None;
2486     if (isa<DeprecatedAttr>(I) ||
2487         isa<UnavailableAttr>(I) ||
2488         isa<AvailabilityAttr>(I)) {
2489       switch (AMK) {
2490       case AMK_None:
2491         continue;
2492 
2493       case AMK_Redeclaration:
2494       case AMK_Override:
2495       case AMK_ProtocolImplementation:
2496         LocalAMK = AMK;
2497         break;
2498       }
2499     }
2500 
2501     // Already handled.
2502     if (isa<UsedAttr>(I))
2503       continue;
2504 
2505     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2506       foundAny = true;
2507   }
2508 
2509   if (mergeAlignedAttrs(*this, New, Old))
2510     foundAny = true;
2511 
2512   if (!foundAny) New->dropAttrs();
2513 }
2514 
2515 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2516 /// to the new one.
mergeParamDeclAttributes(ParmVarDecl * newDecl,const ParmVarDecl * oldDecl,Sema & S)2517 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2518                                      const ParmVarDecl *oldDecl,
2519                                      Sema &S) {
2520   // C++11 [dcl.attr.depend]p2:
2521   //   The first declaration of a function shall specify the
2522   //   carries_dependency attribute for its declarator-id if any declaration
2523   //   of the function specifies the carries_dependency attribute.
2524   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2525   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2526     S.Diag(CDA->getLocation(),
2527            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2528     // Find the first declaration of the parameter.
2529     // FIXME: Should we build redeclaration chains for function parameters?
2530     const FunctionDecl *FirstFD =
2531       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2532     const ParmVarDecl *FirstVD =
2533       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2534     S.Diag(FirstVD->getLocation(),
2535            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2536   }
2537 
2538   if (!oldDecl->hasAttrs())
2539     return;
2540 
2541   bool foundAny = newDecl->hasAttrs();
2542 
2543   // Ensure that any moving of objects within the allocated map is
2544   // done before we process them.
2545   if (!foundAny) newDecl->setAttrs(AttrVec());
2546 
2547   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2548     if (!DeclHasAttr(newDecl, I)) {
2549       InheritableAttr *newAttr =
2550         cast<InheritableParamAttr>(I->clone(S.Context));
2551       newAttr->setInherited(true);
2552       newDecl->addAttr(newAttr);
2553       foundAny = true;
2554     }
2555   }
2556 
2557   if (!foundAny) newDecl->dropAttrs();
2558 }
2559 
mergeParamDeclTypes(ParmVarDecl * NewParam,const ParmVarDecl * OldParam,Sema & S)2560 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2561                                 const ParmVarDecl *OldParam,
2562                                 Sema &S) {
2563   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2564     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2565       if (*Oldnullability != *Newnullability) {
2566         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2567           << DiagNullabilityKind(
2568                *Newnullability,
2569                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2570                 != 0))
2571           << DiagNullabilityKind(
2572                *Oldnullability,
2573                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2574                 != 0));
2575         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2576       }
2577     } else {
2578       QualType NewT = NewParam->getType();
2579       NewT = S.Context.getAttributedType(
2580                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2581                          NewT, NewT);
2582       NewParam->setType(NewT);
2583     }
2584   }
2585 }
2586 
2587 namespace {
2588 
2589 /// Used in MergeFunctionDecl to keep track of function parameters in
2590 /// C.
2591 struct GNUCompatibleParamWarning {
2592   ParmVarDecl *OldParm;
2593   ParmVarDecl *NewParm;
2594   QualType PromotedType;
2595 };
2596 
2597 } // end anonymous namespace
2598 
2599 /// getSpecialMember - get the special member enum for a method.
getSpecialMember(const CXXMethodDecl * MD)2600 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2601   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2602     if (Ctor->isDefaultConstructor())
2603       return Sema::CXXDefaultConstructor;
2604 
2605     if (Ctor->isCopyConstructor())
2606       return Sema::CXXCopyConstructor;
2607 
2608     if (Ctor->isMoveConstructor())
2609       return Sema::CXXMoveConstructor;
2610   } else if (isa<CXXDestructorDecl>(MD)) {
2611     return Sema::CXXDestructor;
2612   } else if (MD->isCopyAssignmentOperator()) {
2613     return Sema::CXXCopyAssignment;
2614   } else if (MD->isMoveAssignmentOperator()) {
2615     return Sema::CXXMoveAssignment;
2616   }
2617 
2618   return Sema::CXXInvalid;
2619 }
2620 
2621 // Determine whether the previous declaration was a definition, implicit
2622 // declaration, or a declaration.
2623 template <typename T>
2624 static std::pair<diag::kind, SourceLocation>
getNoteDiagForInvalidRedeclaration(const T * Old,const T * New)2625 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2626   diag::kind PrevDiag;
2627   SourceLocation OldLocation = Old->getLocation();
2628   if (Old->isThisDeclarationADefinition())
2629     PrevDiag = diag::note_previous_definition;
2630   else if (Old->isImplicit()) {
2631     PrevDiag = diag::note_previous_implicit_declaration;
2632     if (OldLocation.isInvalid())
2633       OldLocation = New->getLocation();
2634   } else
2635     PrevDiag = diag::note_previous_declaration;
2636   return std::make_pair(PrevDiag, OldLocation);
2637 }
2638 
2639 /// canRedefineFunction - checks if a function can be redefined. Currently,
2640 /// only extern inline functions can be redefined, and even then only in
2641 /// GNU89 mode.
canRedefineFunction(const FunctionDecl * FD,const LangOptions & LangOpts)2642 static bool canRedefineFunction(const FunctionDecl *FD,
2643                                 const LangOptions& LangOpts) {
2644   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2645           !LangOpts.CPlusPlus &&
2646           FD->isInlineSpecified() &&
2647           FD->getStorageClass() == SC_Extern);
2648 }
2649 
getCallingConvAttributedType(QualType T) const2650 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2651   const AttributedType *AT = T->getAs<AttributedType>();
2652   while (AT && !AT->isCallingConv())
2653     AT = AT->getModifiedType()->getAs<AttributedType>();
2654   return AT;
2655 }
2656 
2657 template <typename T>
haveIncompatibleLanguageLinkages(const T * Old,const T * New)2658 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2659   const DeclContext *DC = Old->getDeclContext();
2660   if (DC->isRecord())
2661     return false;
2662 
2663   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2664   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2665     return true;
2666   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2667     return true;
2668   return false;
2669 }
2670 
isExternC(T * D)2671 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
isExternC(VarTemplateDecl *)2672 static bool isExternC(VarTemplateDecl *) { return false; }
2673 
2674 /// \brief Check whether a redeclaration of an entity introduced by a
2675 /// using-declaration is valid, given that we know it's not an overload
2676 /// (nor a hidden tag declaration).
2677 template<typename ExpectedDecl>
checkUsingShadowRedecl(Sema & S,UsingShadowDecl * OldS,ExpectedDecl * New)2678 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2679                                    ExpectedDecl *New) {
2680   // C++11 [basic.scope.declarative]p4:
2681   //   Given a set of declarations in a single declarative region, each of
2682   //   which specifies the same unqualified name,
2683   //   -- they shall all refer to the same entity, or all refer to functions
2684   //      and function templates; or
2685   //   -- exactly one declaration shall declare a class name or enumeration
2686   //      name that is not a typedef name and the other declarations shall all
2687   //      refer to the same variable or enumerator, or all refer to functions
2688   //      and function templates; in this case the class name or enumeration
2689   //      name is hidden (3.3.10).
2690 
2691   // C++11 [namespace.udecl]p14:
2692   //   If a function declaration in namespace scope or block scope has the
2693   //   same name and the same parameter-type-list as a function introduced
2694   //   by a using-declaration, and the declarations do not declare the same
2695   //   function, the program is ill-formed.
2696 
2697   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2698   if (Old &&
2699       !Old->getDeclContext()->getRedeclContext()->Equals(
2700           New->getDeclContext()->getRedeclContext()) &&
2701       !(isExternC(Old) && isExternC(New)))
2702     Old = nullptr;
2703 
2704   if (!Old) {
2705     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2706     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2707     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2708     return true;
2709   }
2710   return false;
2711 }
2712 
hasIdenticalPassObjectSizeAttrs(const FunctionDecl * A,const FunctionDecl * B)2713 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2714                                             const FunctionDecl *B) {
2715   assert(A->getNumParams() == B->getNumParams());
2716 
2717   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2718     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2719     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2720     if (AttrA == AttrB)
2721       return true;
2722     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2723   };
2724 
2725   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2726 }
2727 
2728 /// MergeFunctionDecl - We just parsed a function 'New' from
2729 /// declarator D which has the same name and scope as a previous
2730 /// declaration 'Old'.  Figure out how to resolve this situation,
2731 /// merging decls or emitting diagnostics as appropriate.
2732 ///
2733 /// In C++, New and Old must be declarations that are not
2734 /// overloaded. Use IsOverload to determine whether New and Old are
2735 /// overloaded, and to select the Old declaration that New should be
2736 /// merged with.
2737 ///
2738 /// Returns true if there was an error, false otherwise.
MergeFunctionDecl(FunctionDecl * New,NamedDecl * & OldD,Scope * S,bool MergeTypeWithOld)2739 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2740                              Scope *S, bool MergeTypeWithOld) {
2741   // Verify the old decl was also a function.
2742   FunctionDecl *Old = OldD->getAsFunction();
2743   if (!Old) {
2744     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2745       if (New->getFriendObjectKind()) {
2746         Diag(New->getLocation(), diag::err_using_decl_friend);
2747         Diag(Shadow->getTargetDecl()->getLocation(),
2748              diag::note_using_decl_target);
2749         Diag(Shadow->getUsingDecl()->getLocation(),
2750              diag::note_using_decl) << 0;
2751         return true;
2752       }
2753 
2754       // Check whether the two declarations might declare the same function.
2755       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2756         return true;
2757       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2758     } else {
2759       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2760         << New->getDeclName();
2761       Diag(OldD->getLocation(), diag::note_previous_definition);
2762       return true;
2763     }
2764   }
2765 
2766   // If the old declaration is invalid, just give up here.
2767   if (Old->isInvalidDecl())
2768     return true;
2769 
2770   diag::kind PrevDiag;
2771   SourceLocation OldLocation;
2772   std::tie(PrevDiag, OldLocation) =
2773       getNoteDiagForInvalidRedeclaration(Old, New);
2774 
2775   // Don't complain about this if we're in GNU89 mode and the old function
2776   // is an extern inline function.
2777   // Don't complain about specializations. They are not supposed to have
2778   // storage classes.
2779   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2780       New->getStorageClass() == SC_Static &&
2781       Old->hasExternalFormalLinkage() &&
2782       !New->getTemplateSpecializationInfo() &&
2783       !canRedefineFunction(Old, getLangOpts())) {
2784     if (getLangOpts().MicrosoftExt) {
2785       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2786       Diag(OldLocation, PrevDiag);
2787     } else {
2788       Diag(New->getLocation(), diag::err_static_non_static) << New;
2789       Diag(OldLocation, PrevDiag);
2790       return true;
2791     }
2792   }
2793 
2794   if (New->hasAttr<InternalLinkageAttr>() &&
2795       !Old->hasAttr<InternalLinkageAttr>()) {
2796     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2797         << New->getDeclName();
2798     Diag(Old->getLocation(), diag::note_previous_definition);
2799     New->dropAttr<InternalLinkageAttr>();
2800   }
2801 
2802   // If a function is first declared with a calling convention, but is later
2803   // declared or defined without one, all following decls assume the calling
2804   // convention of the first.
2805   //
2806   // It's OK if a function is first declared without a calling convention,
2807   // but is later declared or defined with the default calling convention.
2808   //
2809   // To test if either decl has an explicit calling convention, we look for
2810   // AttributedType sugar nodes on the type as written.  If they are missing or
2811   // were canonicalized away, we assume the calling convention was implicit.
2812   //
2813   // Note also that we DO NOT return at this point, because we still have
2814   // other tests to run.
2815   QualType OldQType = Context.getCanonicalType(Old->getType());
2816   QualType NewQType = Context.getCanonicalType(New->getType());
2817   const FunctionType *OldType = cast<FunctionType>(OldQType);
2818   const FunctionType *NewType = cast<FunctionType>(NewQType);
2819   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2820   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2821   bool RequiresAdjustment = false;
2822 
2823   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2824     FunctionDecl *First = Old->getFirstDecl();
2825     const FunctionType *FT =
2826         First->getType().getCanonicalType()->castAs<FunctionType>();
2827     FunctionType::ExtInfo FI = FT->getExtInfo();
2828     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2829     if (!NewCCExplicit) {
2830       // Inherit the CC from the previous declaration if it was specified
2831       // there but not here.
2832       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2833       RequiresAdjustment = true;
2834     } else {
2835       // Calling conventions aren't compatible, so complain.
2836       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2837       Diag(New->getLocation(), diag::err_cconv_change)
2838         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2839         << !FirstCCExplicit
2840         << (!FirstCCExplicit ? "" :
2841             FunctionType::getNameForCallConv(FI.getCC()));
2842 
2843       // Put the note on the first decl, since it is the one that matters.
2844       Diag(First->getLocation(), diag::note_previous_declaration);
2845       return true;
2846     }
2847   }
2848 
2849   // FIXME: diagnose the other way around?
2850   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2851     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2852     RequiresAdjustment = true;
2853   }
2854 
2855   // Merge regparm attribute.
2856   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2857       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2858     if (NewTypeInfo.getHasRegParm()) {
2859       Diag(New->getLocation(), diag::err_regparm_mismatch)
2860         << NewType->getRegParmType()
2861         << OldType->getRegParmType();
2862       Diag(OldLocation, diag::note_previous_declaration);
2863       return true;
2864     }
2865 
2866     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2867     RequiresAdjustment = true;
2868   }
2869 
2870   // Merge ns_returns_retained attribute.
2871   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2872     if (NewTypeInfo.getProducesResult()) {
2873       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2874       Diag(OldLocation, diag::note_previous_declaration);
2875       return true;
2876     }
2877 
2878     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2879     RequiresAdjustment = true;
2880   }
2881 
2882   if (RequiresAdjustment) {
2883     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2884     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2885     New->setType(QualType(AdjustedType, 0));
2886     NewQType = Context.getCanonicalType(New->getType());
2887     NewType = cast<FunctionType>(NewQType);
2888   }
2889 
2890   // If this redeclaration makes the function inline, we may need to add it to
2891   // UndefinedButUsed.
2892   if (!Old->isInlined() && New->isInlined() &&
2893       !New->hasAttr<GNUInlineAttr>() &&
2894       !getLangOpts().GNUInline &&
2895       Old->isUsed(false) &&
2896       !Old->isDefined() && !New->isThisDeclarationADefinition())
2897     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2898                                            SourceLocation()));
2899 
2900   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2901   // about it.
2902   if (New->hasAttr<GNUInlineAttr>() &&
2903       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2904     UndefinedButUsed.erase(Old->getCanonicalDecl());
2905   }
2906 
2907   // If pass_object_size params don't match up perfectly, this isn't a valid
2908   // redeclaration.
2909   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2910       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2911     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2912         << New->getDeclName();
2913     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2914     return true;
2915   }
2916 
2917   if (getLangOpts().CPlusPlus) {
2918     // (C++98 13.1p2):
2919     //   Certain function declarations cannot be overloaded:
2920     //     -- Function declarations that differ only in the return type
2921     //        cannot be overloaded.
2922 
2923     // Go back to the type source info to compare the declared return types,
2924     // per C++1y [dcl.type.auto]p13:
2925     //   Redeclarations or specializations of a function or function template
2926     //   with a declared return type that uses a placeholder type shall also
2927     //   use that placeholder, not a deduced type.
2928     QualType OldDeclaredReturnType =
2929         (Old->getTypeSourceInfo()
2930              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2931              : OldType)->getReturnType();
2932     QualType NewDeclaredReturnType =
2933         (New->getTypeSourceInfo()
2934              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2935              : NewType)->getReturnType();
2936     QualType ResQT;
2937     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2938         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2939           New->isLocalExternDecl())) {
2940       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2941           OldDeclaredReturnType->isObjCObjectPointerType())
2942         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2943       if (ResQT.isNull()) {
2944         if (New->isCXXClassMember() && New->isOutOfLine())
2945           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2946               << New << New->getReturnTypeSourceRange();
2947         else
2948           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2949               << New->getReturnTypeSourceRange();
2950         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2951                                     << Old->getReturnTypeSourceRange();
2952         return true;
2953       }
2954       else
2955         NewQType = ResQT;
2956     }
2957 
2958     QualType OldReturnType = OldType->getReturnType();
2959     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2960     if (OldReturnType != NewReturnType) {
2961       // If this function has a deduced return type and has already been
2962       // defined, copy the deduced value from the old declaration.
2963       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2964       if (OldAT && OldAT->isDeduced()) {
2965         New->setType(
2966             SubstAutoType(New->getType(),
2967                           OldAT->isDependentType() ? Context.DependentTy
2968                                                    : OldAT->getDeducedType()));
2969         NewQType = Context.getCanonicalType(
2970             SubstAutoType(NewQType,
2971                           OldAT->isDependentType() ? Context.DependentTy
2972                                                    : OldAT->getDeducedType()));
2973       }
2974     }
2975 
2976     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2977     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2978     if (OldMethod && NewMethod) {
2979       // Preserve triviality.
2980       NewMethod->setTrivial(OldMethod->isTrivial());
2981 
2982       // MSVC allows explicit template specialization at class scope:
2983       // 2 CXXMethodDecls referring to the same function will be injected.
2984       // We don't want a redeclaration error.
2985       bool IsClassScopeExplicitSpecialization =
2986                               OldMethod->isFunctionTemplateSpecialization() &&
2987                               NewMethod->isFunctionTemplateSpecialization();
2988       bool isFriend = NewMethod->getFriendObjectKind();
2989 
2990       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2991           !IsClassScopeExplicitSpecialization) {
2992         //    -- Member function declarations with the same name and the
2993         //       same parameter types cannot be overloaded if any of them
2994         //       is a static member function declaration.
2995         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2996           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2997           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2998           return true;
2999         }
3000 
3001         // C++ [class.mem]p1:
3002         //   [...] A member shall not be declared twice in the
3003         //   member-specification, except that a nested class or member
3004         //   class template can be declared and then later defined.
3005         if (ActiveTemplateInstantiations.empty()) {
3006           unsigned NewDiag;
3007           if (isa<CXXConstructorDecl>(OldMethod))
3008             NewDiag = diag::err_constructor_redeclared;
3009           else if (isa<CXXDestructorDecl>(NewMethod))
3010             NewDiag = diag::err_destructor_redeclared;
3011           else if (isa<CXXConversionDecl>(NewMethod))
3012             NewDiag = diag::err_conv_function_redeclared;
3013           else
3014             NewDiag = diag::err_member_redeclared;
3015 
3016           Diag(New->getLocation(), NewDiag);
3017         } else {
3018           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3019             << New << New->getType();
3020         }
3021         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3022         return true;
3023 
3024       // Complain if this is an explicit declaration of a special
3025       // member that was initially declared implicitly.
3026       //
3027       // As an exception, it's okay to befriend such methods in order
3028       // to permit the implicit constructor/destructor/operator calls.
3029       } else if (OldMethod->isImplicit()) {
3030         if (isFriend) {
3031           NewMethod->setImplicit();
3032         } else {
3033           Diag(NewMethod->getLocation(),
3034                diag::err_definition_of_implicitly_declared_member)
3035             << New << getSpecialMember(OldMethod);
3036           return true;
3037         }
3038       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3039         Diag(NewMethod->getLocation(),
3040              diag::err_definition_of_explicitly_defaulted_member)
3041           << getSpecialMember(OldMethod);
3042         return true;
3043       }
3044     }
3045 
3046     // C++11 [dcl.attr.noreturn]p1:
3047     //   The first declaration of a function shall specify the noreturn
3048     //   attribute if any declaration of that function specifies the noreturn
3049     //   attribute.
3050     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3051     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3052       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3053       Diag(Old->getFirstDecl()->getLocation(),
3054            diag::note_noreturn_missing_first_decl);
3055     }
3056 
3057     // C++11 [dcl.attr.depend]p2:
3058     //   The first declaration of a function shall specify the
3059     //   carries_dependency attribute for its declarator-id if any declaration
3060     //   of the function specifies the carries_dependency attribute.
3061     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3062     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3063       Diag(CDA->getLocation(),
3064            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3065       Diag(Old->getFirstDecl()->getLocation(),
3066            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3067     }
3068 
3069     // (C++98 8.3.5p3):
3070     //   All declarations for a function shall agree exactly in both the
3071     //   return type and the parameter-type-list.
3072     // We also want to respect all the extended bits except noreturn.
3073 
3074     // noreturn should now match unless the old type info didn't have it.
3075     QualType OldQTypeForComparison = OldQType;
3076     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3077       assert(OldQType == QualType(OldType, 0));
3078       const FunctionType *OldTypeForComparison
3079         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3080       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3081       assert(OldQTypeForComparison.isCanonical());
3082     }
3083 
3084     if (haveIncompatibleLanguageLinkages(Old, New)) {
3085       // As a special case, retain the language linkage from previous
3086       // declarations of a friend function as an extension.
3087       //
3088       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3089       // and is useful because there's otherwise no way to specify language
3090       // linkage within class scope.
3091       //
3092       // Check cautiously as the friend object kind isn't yet complete.
3093       if (New->getFriendObjectKind() != Decl::FOK_None) {
3094         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3095         Diag(OldLocation, PrevDiag);
3096       } else {
3097         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3098         Diag(OldLocation, PrevDiag);
3099         return true;
3100       }
3101     }
3102 
3103     if (OldQTypeForComparison == NewQType)
3104       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3105 
3106     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3107         New->isLocalExternDecl()) {
3108       // It's OK if we couldn't merge types for a local function declaraton
3109       // if either the old or new type is dependent. We'll merge the types
3110       // when we instantiate the function.
3111       return false;
3112     }
3113 
3114     // Fall through for conflicting redeclarations and redefinitions.
3115   }
3116 
3117   // C: Function types need to be compatible, not identical. This handles
3118   // duplicate function decls like "void f(int); void f(enum X);" properly.
3119   if (!getLangOpts().CPlusPlus &&
3120       Context.typesAreCompatible(OldQType, NewQType)) {
3121     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3122     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3123     const FunctionProtoType *OldProto = nullptr;
3124     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3125         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3126       // The old declaration provided a function prototype, but the
3127       // new declaration does not. Merge in the prototype.
3128       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3129       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3130       NewQType =
3131           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3132                                   OldProto->getExtProtoInfo());
3133       New->setType(NewQType);
3134       New->setHasInheritedPrototype();
3135 
3136       // Synthesize parameters with the same types.
3137       SmallVector<ParmVarDecl*, 16> Params;
3138       for (const auto &ParamType : OldProto->param_types()) {
3139         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3140                                                  SourceLocation(), nullptr,
3141                                                  ParamType, /*TInfo=*/nullptr,
3142                                                  SC_None, nullptr);
3143         Param->setScopeInfo(0, Params.size());
3144         Param->setImplicit();
3145         Params.push_back(Param);
3146       }
3147 
3148       New->setParams(Params);
3149     }
3150 
3151     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3152   }
3153 
3154   // GNU C permits a K&R definition to follow a prototype declaration
3155   // if the declared types of the parameters in the K&R definition
3156   // match the types in the prototype declaration, even when the
3157   // promoted types of the parameters from the K&R definition differ
3158   // from the types in the prototype. GCC then keeps the types from
3159   // the prototype.
3160   //
3161   // If a variadic prototype is followed by a non-variadic K&R definition,
3162   // the K&R definition becomes variadic.  This is sort of an edge case, but
3163   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3164   // C99 6.9.1p8.
3165   if (!getLangOpts().CPlusPlus &&
3166       Old->hasPrototype() && !New->hasPrototype() &&
3167       New->getType()->getAs<FunctionProtoType>() &&
3168       Old->getNumParams() == New->getNumParams()) {
3169     SmallVector<QualType, 16> ArgTypes;
3170     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3171     const FunctionProtoType *OldProto
3172       = Old->getType()->getAs<FunctionProtoType>();
3173     const FunctionProtoType *NewProto
3174       = New->getType()->getAs<FunctionProtoType>();
3175 
3176     // Determine whether this is the GNU C extension.
3177     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3178                                                NewProto->getReturnType());
3179     bool LooseCompatible = !MergedReturn.isNull();
3180     for (unsigned Idx = 0, End = Old->getNumParams();
3181          LooseCompatible && Idx != End; ++Idx) {
3182       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3183       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3184       if (Context.typesAreCompatible(OldParm->getType(),
3185                                      NewProto->getParamType(Idx))) {
3186         ArgTypes.push_back(NewParm->getType());
3187       } else if (Context.typesAreCompatible(OldParm->getType(),
3188                                             NewParm->getType(),
3189                                             /*CompareUnqualified=*/true)) {
3190         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3191                                            NewProto->getParamType(Idx) };
3192         Warnings.push_back(Warn);
3193         ArgTypes.push_back(NewParm->getType());
3194       } else
3195         LooseCompatible = false;
3196     }
3197 
3198     if (LooseCompatible) {
3199       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3200         Diag(Warnings[Warn].NewParm->getLocation(),
3201              diag::ext_param_promoted_not_compatible_with_prototype)
3202           << Warnings[Warn].PromotedType
3203           << Warnings[Warn].OldParm->getType();
3204         if (Warnings[Warn].OldParm->getLocation().isValid())
3205           Diag(Warnings[Warn].OldParm->getLocation(),
3206                diag::note_previous_declaration);
3207       }
3208 
3209       if (MergeTypeWithOld)
3210         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3211                                              OldProto->getExtProtoInfo()));
3212       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3213     }
3214 
3215     // Fall through to diagnose conflicting types.
3216   }
3217 
3218   // A function that has already been declared has been redeclared or
3219   // defined with a different type; show an appropriate diagnostic.
3220 
3221   // If the previous declaration was an implicitly-generated builtin
3222   // declaration, then at the very least we should use a specialized note.
3223   unsigned BuiltinID;
3224   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3225     // If it's actually a library-defined builtin function like 'malloc'
3226     // or 'printf', just warn about the incompatible redeclaration.
3227     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3228       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3229       Diag(OldLocation, diag::note_previous_builtin_declaration)
3230         << Old << Old->getType();
3231 
3232       // If this is a global redeclaration, just forget hereafter
3233       // about the "builtin-ness" of the function.
3234       //
3235       // Doing this for local extern declarations is problematic.  If
3236       // the builtin declaration remains visible, a second invalid
3237       // local declaration will produce a hard error; if it doesn't
3238       // remain visible, a single bogus local redeclaration (which is
3239       // actually only a warning) could break all the downstream code.
3240       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3241         New->getIdentifier()->revertBuiltin();
3242 
3243       return false;
3244     }
3245 
3246     PrevDiag = diag::note_previous_builtin_declaration;
3247   }
3248 
3249   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3250   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3251   return true;
3252 }
3253 
3254 /// \brief Completes the merge of two function declarations that are
3255 /// known to be compatible.
3256 ///
3257 /// This routine handles the merging of attributes and other
3258 /// properties of function declarations from the old declaration to
3259 /// the new declaration, once we know that New is in fact a
3260 /// redeclaration of Old.
3261 ///
3262 /// \returns false
MergeCompatibleFunctionDecls(FunctionDecl * New,FunctionDecl * Old,Scope * S,bool MergeTypeWithOld)3263 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3264                                         Scope *S, bool MergeTypeWithOld) {
3265   // Merge the attributes
3266   mergeDeclAttributes(New, Old);
3267 
3268   // Merge "pure" flag.
3269   if (Old->isPure())
3270     New->setPure();
3271 
3272   // Merge "used" flag.
3273   if (Old->getMostRecentDecl()->isUsed(false))
3274     New->setIsUsed();
3275 
3276   // Merge attributes from the parameters.  These can mismatch with K&R
3277   // declarations.
3278   if (New->getNumParams() == Old->getNumParams())
3279       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3280         ParmVarDecl *NewParam = New->getParamDecl(i);
3281         ParmVarDecl *OldParam = Old->getParamDecl(i);
3282         mergeParamDeclAttributes(NewParam, OldParam, *this);
3283         mergeParamDeclTypes(NewParam, OldParam, *this);
3284       }
3285 
3286   if (getLangOpts().CPlusPlus)
3287     return MergeCXXFunctionDecl(New, Old, S);
3288 
3289   // Merge the function types so the we get the composite types for the return
3290   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3291   // was visible.
3292   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3293   if (!Merged.isNull() && MergeTypeWithOld)
3294     New->setType(Merged);
3295 
3296   return false;
3297 }
3298 
mergeObjCMethodDecls(ObjCMethodDecl * newMethod,ObjCMethodDecl * oldMethod)3299 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3300                                 ObjCMethodDecl *oldMethod) {
3301   // Merge the attributes, including deprecated/unavailable
3302   AvailabilityMergeKind MergeKind =
3303     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3304       ? AMK_ProtocolImplementation
3305       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3306                                                        : AMK_Override;
3307 
3308   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3309 
3310   // Merge attributes from the parameters.
3311   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3312                                        oe = oldMethod->param_end();
3313   for (ObjCMethodDecl::param_iterator
3314          ni = newMethod->param_begin(), ne = newMethod->param_end();
3315        ni != ne && oi != oe; ++ni, ++oi)
3316     mergeParamDeclAttributes(*ni, *oi, *this);
3317 
3318   CheckObjCMethodOverride(newMethod, oldMethod);
3319 }
3320 
diagnoseVarDeclTypeMismatch(Sema & S,VarDecl * New,VarDecl * Old)3321 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3322   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3323 
3324   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3325          ? diag::err_redefinition_different_type
3326          : diag::err_redeclaration_different_type)
3327     << New->getDeclName() << New->getType() << Old->getType();
3328 
3329   diag::kind PrevDiag;
3330   SourceLocation OldLocation;
3331   std::tie(PrevDiag, OldLocation)
3332     = getNoteDiagForInvalidRedeclaration(Old, New);
3333   S.Diag(OldLocation, PrevDiag);
3334   New->setInvalidDecl();
3335 }
3336 
3337 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3338 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3339 /// emitting diagnostics as appropriate.
3340 ///
3341 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3342 /// to here in AddInitializerToDecl. We can't check them before the initializer
3343 /// is attached.
MergeVarDeclTypes(VarDecl * New,VarDecl * Old,bool MergeTypeWithOld)3344 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3345                              bool MergeTypeWithOld) {
3346   if (New->isInvalidDecl() || Old->isInvalidDecl())
3347     return;
3348 
3349   QualType MergedT;
3350   if (getLangOpts().CPlusPlus) {
3351     if (New->getType()->isUndeducedType()) {
3352       // We don't know what the new type is until the initializer is attached.
3353       return;
3354     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3355       // These could still be something that needs exception specs checked.
3356       return MergeVarDeclExceptionSpecs(New, Old);
3357     }
3358     // C++ [basic.link]p10:
3359     //   [...] the types specified by all declarations referring to a given
3360     //   object or function shall be identical, except that declarations for an
3361     //   array object can specify array types that differ by the presence or
3362     //   absence of a major array bound (8.3.4).
3363     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3364       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3365       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3366 
3367       // We are merging a variable declaration New into Old. If it has an array
3368       // bound, and that bound differs from Old's bound, we should diagnose the
3369       // mismatch.
3370       if (!NewArray->isIncompleteArrayType()) {
3371         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3372              PrevVD = PrevVD->getPreviousDecl()) {
3373           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3374           if (PrevVDTy->isIncompleteArrayType())
3375             continue;
3376 
3377           if (!Context.hasSameType(NewArray, PrevVDTy))
3378             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3379         }
3380       }
3381 
3382       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3383         if (Context.hasSameType(OldArray->getElementType(),
3384                                 NewArray->getElementType()))
3385           MergedT = New->getType();
3386       }
3387       // FIXME: Check visibility. New is hidden but has a complete type. If New
3388       // has no array bound, it should not inherit one from Old, if Old is not
3389       // visible.
3390       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3391         if (Context.hasSameType(OldArray->getElementType(),
3392                                 NewArray->getElementType()))
3393           MergedT = Old->getType();
3394       }
3395     }
3396     else if (New->getType()->isObjCObjectPointerType() &&
3397                Old->getType()->isObjCObjectPointerType()) {
3398       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3399                                               Old->getType());
3400     }
3401   } else {
3402     // C 6.2.7p2:
3403     //   All declarations that refer to the same object or function shall have
3404     //   compatible type.
3405     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3406   }
3407   if (MergedT.isNull()) {
3408     // It's OK if we couldn't merge types if either type is dependent, for a
3409     // block-scope variable. In other cases (static data members of class
3410     // templates, variable templates, ...), we require the types to be
3411     // equivalent.
3412     // FIXME: The C++ standard doesn't say anything about this.
3413     if ((New->getType()->isDependentType() ||
3414          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3415       // If the old type was dependent, we can't merge with it, so the new type
3416       // becomes dependent for now. We'll reproduce the original type when we
3417       // instantiate the TypeSourceInfo for the variable.
3418       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3419         New->setType(Context.DependentTy);
3420       return;
3421     }
3422     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3423   }
3424 
3425   // Don't actually update the type on the new declaration if the old
3426   // declaration was an extern declaration in a different scope.
3427   if (MergeTypeWithOld)
3428     New->setType(MergedT);
3429 }
3430 
mergeTypeWithPrevious(Sema & S,VarDecl * NewVD,VarDecl * OldVD,LookupResult & Previous)3431 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3432                                   LookupResult &Previous) {
3433   // C11 6.2.7p4:
3434   //   For an identifier with internal or external linkage declared
3435   //   in a scope in which a prior declaration of that identifier is
3436   //   visible, if the prior declaration specifies internal or
3437   //   external linkage, the type of the identifier at the later
3438   //   declaration becomes the composite type.
3439   //
3440   // If the variable isn't visible, we do not merge with its type.
3441   if (Previous.isShadowed())
3442     return false;
3443 
3444   if (S.getLangOpts().CPlusPlus) {
3445     // C++11 [dcl.array]p3:
3446     //   If there is a preceding declaration of the entity in the same
3447     //   scope in which the bound was specified, an omitted array bound
3448     //   is taken to be the same as in that earlier declaration.
3449     return NewVD->isPreviousDeclInSameBlockScope() ||
3450            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3451             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3452   } else {
3453     // If the old declaration was function-local, don't merge with its
3454     // type unless we're in the same function.
3455     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3456            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3457   }
3458 }
3459 
3460 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3461 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3462 /// situation, merging decls or emitting diagnostics as appropriate.
3463 ///
3464 /// Tentative definition rules (C99 6.9.2p2) are checked by
3465 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3466 /// definitions here, since the initializer hasn't been attached.
3467 ///
MergeVarDecl(VarDecl * New,LookupResult & Previous)3468 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3469   // If the new decl is already invalid, don't do any other checking.
3470   if (New->isInvalidDecl())
3471     return;
3472 
3473   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3474     return;
3475 
3476   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3477 
3478   // Verify the old decl was also a variable or variable template.
3479   VarDecl *Old = nullptr;
3480   VarTemplateDecl *OldTemplate = nullptr;
3481   if (Previous.isSingleResult()) {
3482     if (NewTemplate) {
3483       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3484       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3485 
3486       if (auto *Shadow =
3487               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3488         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3489           return New->setInvalidDecl();
3490     } else {
3491       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3492 
3493       if (auto *Shadow =
3494               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3495         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3496           return New->setInvalidDecl();
3497     }
3498   }
3499   if (!Old) {
3500     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3501       << New->getDeclName();
3502     Diag(Previous.getRepresentativeDecl()->getLocation(),
3503          diag::note_previous_definition);
3504     return New->setInvalidDecl();
3505   }
3506 
3507   // Ensure the template parameters are compatible.
3508   if (NewTemplate &&
3509       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3510                                       OldTemplate->getTemplateParameters(),
3511                                       /*Complain=*/true, TPL_TemplateMatch))
3512     return New->setInvalidDecl();
3513 
3514   // C++ [class.mem]p1:
3515   //   A member shall not be declared twice in the member-specification [...]
3516   //
3517   // Here, we need only consider static data members.
3518   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3519     Diag(New->getLocation(), diag::err_duplicate_member)
3520       << New->getIdentifier();
3521     Diag(Old->getLocation(), diag::note_previous_declaration);
3522     New->setInvalidDecl();
3523   }
3524 
3525   mergeDeclAttributes(New, Old);
3526   // Warn if an already-declared variable is made a weak_import in a subsequent
3527   // declaration
3528   if (New->hasAttr<WeakImportAttr>() &&
3529       Old->getStorageClass() == SC_None &&
3530       !Old->hasAttr<WeakImportAttr>()) {
3531     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3532     Diag(Old->getLocation(), diag::note_previous_definition);
3533     // Remove weak_import attribute on new declaration.
3534     New->dropAttr<WeakImportAttr>();
3535   }
3536 
3537   if (New->hasAttr<InternalLinkageAttr>() &&
3538       !Old->hasAttr<InternalLinkageAttr>()) {
3539     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3540         << New->getDeclName();
3541     Diag(Old->getLocation(), diag::note_previous_definition);
3542     New->dropAttr<InternalLinkageAttr>();
3543   }
3544 
3545   // Merge the types.
3546   VarDecl *MostRecent = Old->getMostRecentDecl();
3547   if (MostRecent != Old) {
3548     MergeVarDeclTypes(New, MostRecent,
3549                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3550     if (New->isInvalidDecl())
3551       return;
3552   }
3553 
3554   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3555   if (New->isInvalidDecl())
3556     return;
3557 
3558   diag::kind PrevDiag;
3559   SourceLocation OldLocation;
3560   std::tie(PrevDiag, OldLocation) =
3561       getNoteDiagForInvalidRedeclaration(Old, New);
3562 
3563   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3564   if (New->getStorageClass() == SC_Static &&
3565       !New->isStaticDataMember() &&
3566       Old->hasExternalFormalLinkage()) {
3567     if (getLangOpts().MicrosoftExt) {
3568       Diag(New->getLocation(), diag::ext_static_non_static)
3569           << New->getDeclName();
3570       Diag(OldLocation, PrevDiag);
3571     } else {
3572       Diag(New->getLocation(), diag::err_static_non_static)
3573           << New->getDeclName();
3574       Diag(OldLocation, PrevDiag);
3575       return New->setInvalidDecl();
3576     }
3577   }
3578   // C99 6.2.2p4:
3579   //   For an identifier declared with the storage-class specifier
3580   //   extern in a scope in which a prior declaration of that
3581   //   identifier is visible,23) if the prior declaration specifies
3582   //   internal or external linkage, the linkage of the identifier at
3583   //   the later declaration is the same as the linkage specified at
3584   //   the prior declaration. If no prior declaration is visible, or
3585   //   if the prior declaration specifies no linkage, then the
3586   //   identifier has external linkage.
3587   if (New->hasExternalStorage() && Old->hasLinkage())
3588     /* Okay */;
3589   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3590            !New->isStaticDataMember() &&
3591            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3592     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3593     Diag(OldLocation, PrevDiag);
3594     return New->setInvalidDecl();
3595   }
3596 
3597   // Check if extern is followed by non-extern and vice-versa.
3598   if (New->hasExternalStorage() &&
3599       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3600     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3601     Diag(OldLocation, PrevDiag);
3602     return New->setInvalidDecl();
3603   }
3604   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3605       !New->hasExternalStorage()) {
3606     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3607     Diag(OldLocation, PrevDiag);
3608     return New->setInvalidDecl();
3609   }
3610 
3611   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3612 
3613   // FIXME: The test for external storage here seems wrong? We still
3614   // need to check for mismatches.
3615   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3616       // Don't complain about out-of-line definitions of static members.
3617       !(Old->getLexicalDeclContext()->isRecord() &&
3618         !New->getLexicalDeclContext()->isRecord())) {
3619     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3620     Diag(OldLocation, PrevDiag);
3621     return New->setInvalidDecl();
3622   }
3623 
3624   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3625     if (VarDecl *Def = Old->getDefinition()) {
3626       // C++1z [dcl.fcn.spec]p4:
3627       //   If the definition of a variable appears in a translation unit before
3628       //   its first declaration as inline, the program is ill-formed.
3629       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3630       Diag(Def->getLocation(), diag::note_previous_definition);
3631     }
3632   }
3633 
3634   // If this redeclaration makes the function inline, we may need to add it to
3635   // UndefinedButUsed.
3636   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3637       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3638     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3639                                            SourceLocation()));
3640 
3641   if (New->getTLSKind() != Old->getTLSKind()) {
3642     if (!Old->getTLSKind()) {
3643       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3644       Diag(OldLocation, PrevDiag);
3645     } else if (!New->getTLSKind()) {
3646       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3647       Diag(OldLocation, PrevDiag);
3648     } else {
3649       // Do not allow redeclaration to change the variable between requiring
3650       // static and dynamic initialization.
3651       // FIXME: GCC allows this, but uses the TLS keyword on the first
3652       // declaration to determine the kind. Do we need to be compatible here?
3653       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3654         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3655       Diag(OldLocation, PrevDiag);
3656     }
3657   }
3658 
3659   // C++ doesn't have tentative definitions, so go right ahead and check here.
3660   VarDecl *Def;
3661   if (getLangOpts().CPlusPlus &&
3662       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3663       (Def = Old->getDefinition())) {
3664     NamedDecl *Hidden = nullptr;
3665     if (!hasVisibleDefinition(Def, &Hidden) &&
3666         (New->getFormalLinkage() == InternalLinkage ||
3667          New->getDescribedVarTemplate() ||
3668          New->getNumTemplateParameterLists() ||
3669          New->getDeclContext()->isDependentContext())) {
3670       // The previous definition is hidden, and multiple definitions are
3671       // permitted (in separate TUs). Form another definition of it.
3672     } else if (Old->isStaticDataMember() &&
3673                Old->getCanonicalDecl()->isInline() &&
3674                Old->getCanonicalDecl()->isConstexpr()) {
3675       // This definition won't be a definition any more once it's been merged.
3676       Diag(New->getLocation(),
3677            diag::warn_deprecated_redundant_constexpr_static_def);
3678     } else {
3679       Diag(New->getLocation(), diag::err_redefinition) << New;
3680       Diag(Def->getLocation(), diag::note_previous_definition);
3681       New->setInvalidDecl();
3682       return;
3683     }
3684   }
3685 
3686   if (haveIncompatibleLanguageLinkages(Old, New)) {
3687     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3688     Diag(OldLocation, PrevDiag);
3689     New->setInvalidDecl();
3690     return;
3691   }
3692 
3693   // Merge "used" flag.
3694   if (Old->getMostRecentDecl()->isUsed(false))
3695     New->setIsUsed();
3696 
3697   // Keep a chain of previous declarations.
3698   New->setPreviousDecl(Old);
3699   if (NewTemplate)
3700     NewTemplate->setPreviousDecl(OldTemplate);
3701 
3702   // Inherit access appropriately.
3703   New->setAccess(Old->getAccess());
3704   if (NewTemplate)
3705     NewTemplate->setAccess(New->getAccess());
3706 
3707   if (Old->isInline())
3708     New->setImplicitlyInline();
3709 }
3710 
3711 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3712 /// no declarator (e.g. "struct foo;") is parsed.
3713 Decl *
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,RecordDecl * & AnonRecord)3714 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3715                                  RecordDecl *&AnonRecord) {
3716   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3717                                     AnonRecord);
3718 }
3719 
3720 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3721 // disambiguate entities defined in different scopes.
3722 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3723 // compatibility.
3724 // We will pick our mangling number depending on which version of MSVC is being
3725 // targeted.
getMSManglingNumber(const LangOptions & LO,Scope * S)3726 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3727   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3728              ? S->getMSCurManglingNumber()
3729              : S->getMSLastManglingNumber();
3730 }
3731 
handleTagNumbering(const TagDecl * Tag,Scope * TagScope)3732 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3733   if (!Context.getLangOpts().CPlusPlus)
3734     return;
3735 
3736   if (isa<CXXRecordDecl>(Tag->getParent())) {
3737     // If this tag is the direct child of a class, number it if
3738     // it is anonymous.
3739     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3740       return;
3741     MangleNumberingContext &MCtx =
3742         Context.getManglingNumberContext(Tag->getParent());
3743     Context.setManglingNumber(
3744         Tag, MCtx.getManglingNumber(
3745                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3746     return;
3747   }
3748 
3749   // If this tag isn't a direct child of a class, number it if it is local.
3750   Decl *ManglingContextDecl;
3751   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3752           Tag->getDeclContext(), ManglingContextDecl)) {
3753     Context.setManglingNumber(
3754         Tag, MCtx->getManglingNumber(
3755                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3756   }
3757 }
3758 
setTagNameForLinkagePurposes(TagDecl * TagFromDeclSpec,TypedefNameDecl * NewTD)3759 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3760                                         TypedefNameDecl *NewTD) {
3761   if (TagFromDeclSpec->isInvalidDecl())
3762     return;
3763 
3764   // Do nothing if the tag already has a name for linkage purposes.
3765   if (TagFromDeclSpec->hasNameForLinkage())
3766     return;
3767 
3768   // A well-formed anonymous tag must always be a TUK_Definition.
3769   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3770 
3771   // The type must match the tag exactly;  no qualifiers allowed.
3772   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3773                            Context.getTagDeclType(TagFromDeclSpec))) {
3774     if (getLangOpts().CPlusPlus)
3775       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3776     return;
3777   }
3778 
3779   // If we've already computed linkage for the anonymous tag, then
3780   // adding a typedef name for the anonymous decl can change that
3781   // linkage, which might be a serious problem.  Diagnose this as
3782   // unsupported and ignore the typedef name.  TODO: we should
3783   // pursue this as a language defect and establish a formal rule
3784   // for how to handle it.
3785   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3786     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3787 
3788     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3789     tagLoc = getLocForEndOfToken(tagLoc);
3790 
3791     llvm::SmallString<40> textToInsert;
3792     textToInsert += ' ';
3793     textToInsert += NewTD->getIdentifier()->getName();
3794     Diag(tagLoc, diag::note_typedef_changes_linkage)
3795         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3796     return;
3797   }
3798 
3799   // Otherwise, set this is the anon-decl typedef for the tag.
3800   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3801 }
3802 
GetDiagnosticTypeSpecifierID(DeclSpec::TST T)3803 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3804   switch (T) {
3805   case DeclSpec::TST_class:
3806     return 0;
3807   case DeclSpec::TST_struct:
3808     return 1;
3809   case DeclSpec::TST_interface:
3810     return 2;
3811   case DeclSpec::TST_union:
3812     return 3;
3813   case DeclSpec::TST_enum:
3814     return 4;
3815   default:
3816     llvm_unreachable("unexpected type specifier");
3817   }
3818 }
3819 
3820 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3821 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3822 /// parameters to cope with template friend declarations.
3823 Decl *
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,MultiTemplateParamsArg TemplateParams,bool IsExplicitInstantiation,RecordDecl * & AnonRecord)3824 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3825                                  MultiTemplateParamsArg TemplateParams,
3826                                  bool IsExplicitInstantiation,
3827                                  RecordDecl *&AnonRecord) {
3828   Decl *TagD = nullptr;
3829   TagDecl *Tag = nullptr;
3830   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3831       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3832       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3833       DS.getTypeSpecType() == DeclSpec::TST_union ||
3834       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3835     TagD = DS.getRepAsDecl();
3836 
3837     if (!TagD) // We probably had an error
3838       return nullptr;
3839 
3840     // Note that the above type specs guarantee that the
3841     // type rep is a Decl, whereas in many of the others
3842     // it's a Type.
3843     if (isa<TagDecl>(TagD))
3844       Tag = cast<TagDecl>(TagD);
3845     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3846       Tag = CTD->getTemplatedDecl();
3847   }
3848 
3849   if (Tag) {
3850     handleTagNumbering(Tag, S);
3851     Tag->setFreeStanding();
3852     if (Tag->isInvalidDecl())
3853       return Tag;
3854   }
3855 
3856   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3857     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3858     // or incomplete types shall not be restrict-qualified."
3859     if (TypeQuals & DeclSpec::TQ_restrict)
3860       Diag(DS.getRestrictSpecLoc(),
3861            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3862            << DS.getSourceRange();
3863   }
3864 
3865   if (DS.isInlineSpecified())
3866     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3867         << getLangOpts().CPlusPlus1z;
3868 
3869   if (DS.isConstexprSpecified()) {
3870     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3871     // and definitions of functions and variables.
3872     if (Tag)
3873       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3874           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3875     else
3876       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3877     // Don't emit warnings after this error.
3878     return TagD;
3879   }
3880 
3881   if (DS.isConceptSpecified()) {
3882     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3883     // either a function concept and its definition or a variable concept and
3884     // its initializer.
3885     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3886     return TagD;
3887   }
3888 
3889   DiagnoseFunctionSpecifiers(DS);
3890 
3891   if (DS.isFriendSpecified()) {
3892     // If we're dealing with a decl but not a TagDecl, assume that
3893     // whatever routines created it handled the friendship aspect.
3894     if (TagD && !Tag)
3895       return nullptr;
3896     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3897   }
3898 
3899   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3900   bool IsExplicitSpecialization =
3901     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3902   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3903       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3904       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3905     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3906     // nested-name-specifier unless it is an explicit instantiation
3907     // or an explicit specialization.
3908     //
3909     // FIXME: We allow class template partial specializations here too, per the
3910     // obvious intent of DR1819.
3911     //
3912     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3913     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3914         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3915     return nullptr;
3916   }
3917 
3918   // Track whether this decl-specifier declares anything.
3919   bool DeclaresAnything = true;
3920 
3921   // Handle anonymous struct definitions.
3922   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3923     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3924         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3925       if (getLangOpts().CPlusPlus ||
3926           Record->getDeclContext()->isRecord()) {
3927         // If CurContext is a DeclContext that can contain statements,
3928         // RecursiveASTVisitor won't visit the decls that
3929         // BuildAnonymousStructOrUnion() will put into CurContext.
3930         // Also store them here so that they can be part of the
3931         // DeclStmt that gets created in this case.
3932         // FIXME: Also return the IndirectFieldDecls created by
3933         // BuildAnonymousStructOr union, for the same reason?
3934         if (CurContext->isFunctionOrMethod())
3935           AnonRecord = Record;
3936         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3937                                            Context.getPrintingPolicy());
3938       }
3939 
3940       DeclaresAnything = false;
3941     }
3942   }
3943 
3944   // C11 6.7.2.1p2:
3945   //   A struct-declaration that does not declare an anonymous structure or
3946   //   anonymous union shall contain a struct-declarator-list.
3947   //
3948   // This rule also existed in C89 and C99; the grammar for struct-declaration
3949   // did not permit a struct-declaration without a struct-declarator-list.
3950   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3951       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3952     // Check for Microsoft C extension: anonymous struct/union member.
3953     // Handle 2 kinds of anonymous struct/union:
3954     //   struct STRUCT;
3955     //   union UNION;
3956     // and
3957     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3958     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3959     if ((Tag && Tag->getDeclName()) ||
3960         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3961       RecordDecl *Record = nullptr;
3962       if (Tag)
3963         Record = dyn_cast<RecordDecl>(Tag);
3964       else if (const RecordType *RT =
3965                    DS.getRepAsType().get()->getAsStructureType())
3966         Record = RT->getDecl();
3967       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3968         Record = UT->getDecl();
3969 
3970       if (Record && getLangOpts().MicrosoftExt) {
3971         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3972           << Record->isUnion() << DS.getSourceRange();
3973         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3974       }
3975 
3976       DeclaresAnything = false;
3977     }
3978   }
3979 
3980   // Skip all the checks below if we have a type error.
3981   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3982       (TagD && TagD->isInvalidDecl()))
3983     return TagD;
3984 
3985   if (getLangOpts().CPlusPlus &&
3986       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3987     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3988       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3989           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3990         DeclaresAnything = false;
3991 
3992   if (!DS.isMissingDeclaratorOk()) {
3993     // Customize diagnostic for a typedef missing a name.
3994     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3995       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3996         << DS.getSourceRange();
3997     else
3998       DeclaresAnything = false;
3999   }
4000 
4001   if (DS.isModulePrivateSpecified() &&
4002       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4003     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4004       << Tag->getTagKind()
4005       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4006 
4007   ActOnDocumentableDecl(TagD);
4008 
4009   // C 6.7/2:
4010   //   A declaration [...] shall declare at least a declarator [...], a tag,
4011   //   or the members of an enumeration.
4012   // C++ [dcl.dcl]p3:
4013   //   [If there are no declarators], and except for the declaration of an
4014   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4015   //   names into the program, or shall redeclare a name introduced by a
4016   //   previous declaration.
4017   if (!DeclaresAnything) {
4018     // In C, we allow this as a (popular) extension / bug. Don't bother
4019     // producing further diagnostics for redundant qualifiers after this.
4020     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4021     return TagD;
4022   }
4023 
4024   // C++ [dcl.stc]p1:
4025   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4026   //   init-declarator-list of the declaration shall not be empty.
4027   // C++ [dcl.fct.spec]p1:
4028   //   If a cv-qualifier appears in a decl-specifier-seq, the
4029   //   init-declarator-list of the declaration shall not be empty.
4030   //
4031   // Spurious qualifiers here appear to be valid in C.
4032   unsigned DiagID = diag::warn_standalone_specifier;
4033   if (getLangOpts().CPlusPlus)
4034     DiagID = diag::ext_standalone_specifier;
4035 
4036   // Note that a linkage-specification sets a storage class, but
4037   // 'extern "C" struct foo;' is actually valid and not theoretically
4038   // useless.
4039   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4040     if (SCS == DeclSpec::SCS_mutable)
4041       // Since mutable is not a viable storage class specifier in C, there is
4042       // no reason to treat it as an extension. Instead, diagnose as an error.
4043       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4044     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4045       Diag(DS.getStorageClassSpecLoc(), DiagID)
4046         << DeclSpec::getSpecifierName(SCS);
4047   }
4048 
4049   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4050     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4051       << DeclSpec::getSpecifierName(TSCS);
4052   if (DS.getTypeQualifiers()) {
4053     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4054       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4055     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4056       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4057     // Restrict is covered above.
4058     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4059       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4060     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4061       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4062   }
4063 
4064   // Warn about ignored type attributes, for example:
4065   // __attribute__((aligned)) struct A;
4066   // Attributes should be placed after tag to apply to type declaration.
4067   if (!DS.getAttributes().empty()) {
4068     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4069     if (TypeSpecType == DeclSpec::TST_class ||
4070         TypeSpecType == DeclSpec::TST_struct ||
4071         TypeSpecType == DeclSpec::TST_interface ||
4072         TypeSpecType == DeclSpec::TST_union ||
4073         TypeSpecType == DeclSpec::TST_enum) {
4074       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4075            attrs = attrs->getNext())
4076         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4077             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4078     }
4079   }
4080 
4081   return TagD;
4082 }
4083 
4084 /// We are trying to inject an anonymous member into the given scope;
4085 /// check if there's an existing declaration that can't be overloaded.
4086 ///
4087 /// \return true if this is a forbidden redeclaration
CheckAnonMemberRedeclaration(Sema & SemaRef,Scope * S,DeclContext * Owner,DeclarationName Name,SourceLocation NameLoc,bool IsUnion)4088 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4089                                          Scope *S,
4090                                          DeclContext *Owner,
4091                                          DeclarationName Name,
4092                                          SourceLocation NameLoc,
4093                                          bool IsUnion) {
4094   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4095                  Sema::ForRedeclaration);
4096   if (!SemaRef.LookupName(R, S)) return false;
4097 
4098   // Pick a representative declaration.
4099   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4100   assert(PrevDecl && "Expected a non-null Decl");
4101 
4102   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4103     return false;
4104 
4105   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4106     << IsUnion << Name;
4107   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4108 
4109   return true;
4110 }
4111 
4112 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4113 /// anonymous struct or union AnonRecord into the owning context Owner
4114 /// and scope S. This routine will be invoked just after we realize
4115 /// that an unnamed union or struct is actually an anonymous union or
4116 /// struct, e.g.,
4117 ///
4118 /// @code
4119 /// union {
4120 ///   int i;
4121 ///   float f;
4122 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4123 ///    // f into the surrounding scope.x
4124 /// @endcode
4125 ///
4126 /// This routine is recursive, injecting the names of nested anonymous
4127 /// structs/unions into the owning context and scope as well.
4128 static bool
InjectAnonymousStructOrUnionMembers(Sema & SemaRef,Scope * S,DeclContext * Owner,RecordDecl * AnonRecord,AccessSpecifier AS,SmallVectorImpl<NamedDecl * > & Chaining)4129 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4130                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4131                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4132   bool Invalid = false;
4133 
4134   // Look every FieldDecl and IndirectFieldDecl with a name.
4135   for (auto *D : AnonRecord->decls()) {
4136     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4137         cast<NamedDecl>(D)->getDeclName()) {
4138       ValueDecl *VD = cast<ValueDecl>(D);
4139       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4140                                        VD->getLocation(),
4141                                        AnonRecord->isUnion())) {
4142         // C++ [class.union]p2:
4143         //   The names of the members of an anonymous union shall be
4144         //   distinct from the names of any other entity in the
4145         //   scope in which the anonymous union is declared.
4146         Invalid = true;
4147       } else {
4148         // C++ [class.union]p2:
4149         //   For the purpose of name lookup, after the anonymous union
4150         //   definition, the members of the anonymous union are
4151         //   considered to have been defined in the scope in which the
4152         //   anonymous union is declared.
4153         unsigned OldChainingSize = Chaining.size();
4154         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4155           Chaining.append(IF->chain_begin(), IF->chain_end());
4156         else
4157           Chaining.push_back(VD);
4158 
4159         assert(Chaining.size() >= 2);
4160         NamedDecl **NamedChain =
4161           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4162         for (unsigned i = 0; i < Chaining.size(); i++)
4163           NamedChain[i] = Chaining[i];
4164 
4165         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4166             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4167             VD->getType(), {NamedChain, Chaining.size()});
4168 
4169         for (const auto *Attr : VD->attrs())
4170           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4171 
4172         IndirectField->setAccess(AS);
4173         IndirectField->setImplicit();
4174         SemaRef.PushOnScopeChains(IndirectField, S);
4175 
4176         // That includes picking up the appropriate access specifier.
4177         if (AS != AS_none) IndirectField->setAccess(AS);
4178 
4179         Chaining.resize(OldChainingSize);
4180       }
4181     }
4182   }
4183 
4184   return Invalid;
4185 }
4186 
4187 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4188 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4189 /// illegal input values are mapped to SC_None.
4190 static StorageClass
StorageClassSpecToVarDeclStorageClass(const DeclSpec & DS)4191 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4192   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4193   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4194          "Parser allowed 'typedef' as storage class VarDecl.");
4195   switch (StorageClassSpec) {
4196   case DeclSpec::SCS_unspecified:    return SC_None;
4197   case DeclSpec::SCS_extern:
4198     if (DS.isExternInLinkageSpec())
4199       return SC_None;
4200     return SC_Extern;
4201   case DeclSpec::SCS_static:         return SC_Static;
4202   case DeclSpec::SCS_auto:           return SC_Auto;
4203   case DeclSpec::SCS_register:       return SC_Register;
4204   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4205     // Illegal SCSs map to None: error reporting is up to the caller.
4206   case DeclSpec::SCS_mutable:        // Fall through.
4207   case DeclSpec::SCS_typedef:        return SC_None;
4208   }
4209   llvm_unreachable("unknown storage class specifier");
4210 }
4211 
findDefaultInitializer(const CXXRecordDecl * Record)4212 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4213   assert(Record->hasInClassInitializer());
4214 
4215   for (const auto *I : Record->decls()) {
4216     const auto *FD = dyn_cast<FieldDecl>(I);
4217     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4218       FD = IFD->getAnonField();
4219     if (FD && FD->hasInClassInitializer())
4220       return FD->getLocation();
4221   }
4222 
4223   llvm_unreachable("couldn't find in-class initializer");
4224 }
4225 
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,SourceLocation DefaultInitLoc)4226 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4227                                       SourceLocation DefaultInitLoc) {
4228   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4229     return;
4230 
4231   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4232   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4233 }
4234 
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,CXXRecordDecl * AnonUnion)4235 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4236                                       CXXRecordDecl *AnonUnion) {
4237   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4238     return;
4239 
4240   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4241 }
4242 
4243 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4244 /// anonymous structure or union. Anonymous unions are a C++ feature
4245 /// (C++ [class.union]) and a C11 feature; anonymous structures
4246 /// are a C11 feature and GNU C++ extension.
BuildAnonymousStructOrUnion(Scope * S,DeclSpec & DS,AccessSpecifier AS,RecordDecl * Record,const PrintingPolicy & Policy)4247 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4248                                         AccessSpecifier AS,
4249                                         RecordDecl *Record,
4250                                         const PrintingPolicy &Policy) {
4251   DeclContext *Owner = Record->getDeclContext();
4252 
4253   // Diagnose whether this anonymous struct/union is an extension.
4254   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4255     Diag(Record->getLocation(), diag::ext_anonymous_union);
4256   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4257     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4258   else if (!Record->isUnion() && !getLangOpts().C11)
4259     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4260 
4261   // C and C++ require different kinds of checks for anonymous
4262   // structs/unions.
4263   bool Invalid = false;
4264   if (getLangOpts().CPlusPlus) {
4265     const char *PrevSpec = nullptr;
4266     unsigned DiagID;
4267     if (Record->isUnion()) {
4268       // C++ [class.union]p6:
4269       //   Anonymous unions declared in a named namespace or in the
4270       //   global namespace shall be declared static.
4271       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4272           (isa<TranslationUnitDecl>(Owner) ||
4273            (isa<NamespaceDecl>(Owner) &&
4274             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4275         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4276           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4277 
4278         // Recover by adding 'static'.
4279         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4280                                PrevSpec, DiagID, Policy);
4281       }
4282       // C++ [class.union]p6:
4283       //   A storage class is not allowed in a declaration of an
4284       //   anonymous union in a class scope.
4285       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4286                isa<RecordDecl>(Owner)) {
4287         Diag(DS.getStorageClassSpecLoc(),
4288              diag::err_anonymous_union_with_storage_spec)
4289           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4290 
4291         // Recover by removing the storage specifier.
4292         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4293                                SourceLocation(),
4294                                PrevSpec, DiagID, Context.getPrintingPolicy());
4295       }
4296     }
4297 
4298     // Ignore const/volatile/restrict qualifiers.
4299     if (DS.getTypeQualifiers()) {
4300       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4301         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4302           << Record->isUnion() << "const"
4303           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4304       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4305         Diag(DS.getVolatileSpecLoc(),
4306              diag::ext_anonymous_struct_union_qualified)
4307           << Record->isUnion() << "volatile"
4308           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4309       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4310         Diag(DS.getRestrictSpecLoc(),
4311              diag::ext_anonymous_struct_union_qualified)
4312           << Record->isUnion() << "restrict"
4313           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4314       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4315         Diag(DS.getAtomicSpecLoc(),
4316              diag::ext_anonymous_struct_union_qualified)
4317           << Record->isUnion() << "_Atomic"
4318           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4319       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4320         Diag(DS.getUnalignedSpecLoc(),
4321              diag::ext_anonymous_struct_union_qualified)
4322           << Record->isUnion() << "__unaligned"
4323           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4324 
4325       DS.ClearTypeQualifiers();
4326     }
4327 
4328     // C++ [class.union]p2:
4329     //   The member-specification of an anonymous union shall only
4330     //   define non-static data members. [Note: nested types and
4331     //   functions cannot be declared within an anonymous union. ]
4332     for (auto *Mem : Record->decls()) {
4333       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4334         // C++ [class.union]p3:
4335         //   An anonymous union shall not have private or protected
4336         //   members (clause 11).
4337         assert(FD->getAccess() != AS_none);
4338         if (FD->getAccess() != AS_public) {
4339           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4340             << Record->isUnion() << (FD->getAccess() == AS_protected);
4341           Invalid = true;
4342         }
4343 
4344         // C++ [class.union]p1
4345         //   An object of a class with a non-trivial constructor, a non-trivial
4346         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4347         //   assignment operator cannot be a member of a union, nor can an
4348         //   array of such objects.
4349         if (CheckNontrivialField(FD))
4350           Invalid = true;
4351       } else if (Mem->isImplicit()) {
4352         // Any implicit members are fine.
4353       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4354         // This is a type that showed up in an
4355         // elaborated-type-specifier inside the anonymous struct or
4356         // union, but which actually declares a type outside of the
4357         // anonymous struct or union. It's okay.
4358       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4359         if (!MemRecord->isAnonymousStructOrUnion() &&
4360             MemRecord->getDeclName()) {
4361           // Visual C++ allows type definition in anonymous struct or union.
4362           if (getLangOpts().MicrosoftExt)
4363             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4364               << Record->isUnion();
4365           else {
4366             // This is a nested type declaration.
4367             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4368               << Record->isUnion();
4369             Invalid = true;
4370           }
4371         } else {
4372           // This is an anonymous type definition within another anonymous type.
4373           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4374           // not part of standard C++.
4375           Diag(MemRecord->getLocation(),
4376                diag::ext_anonymous_record_with_anonymous_type)
4377             << Record->isUnion();
4378         }
4379       } else if (isa<AccessSpecDecl>(Mem)) {
4380         // Any access specifier is fine.
4381       } else if (isa<StaticAssertDecl>(Mem)) {
4382         // In C++1z, static_assert declarations are also fine.
4383       } else {
4384         // We have something that isn't a non-static data
4385         // member. Complain about it.
4386         unsigned DK = diag::err_anonymous_record_bad_member;
4387         if (isa<TypeDecl>(Mem))
4388           DK = diag::err_anonymous_record_with_type;
4389         else if (isa<FunctionDecl>(Mem))
4390           DK = diag::err_anonymous_record_with_function;
4391         else if (isa<VarDecl>(Mem))
4392           DK = diag::err_anonymous_record_with_static;
4393 
4394         // Visual C++ allows type definition in anonymous struct or union.
4395         if (getLangOpts().MicrosoftExt &&
4396             DK == diag::err_anonymous_record_with_type)
4397           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4398             << Record->isUnion();
4399         else {
4400           Diag(Mem->getLocation(), DK) << Record->isUnion();
4401           Invalid = true;
4402         }
4403       }
4404     }
4405 
4406     // C++11 [class.union]p8 (DR1460):
4407     //   At most one variant member of a union may have a
4408     //   brace-or-equal-initializer.
4409     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4410         Owner->isRecord())
4411       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4412                                 cast<CXXRecordDecl>(Record));
4413   }
4414 
4415   if (!Record->isUnion() && !Owner->isRecord()) {
4416     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4417       << getLangOpts().CPlusPlus;
4418     Invalid = true;
4419   }
4420 
4421   // Mock up a declarator.
4422   Declarator Dc(DS, Declarator::MemberContext);
4423   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4424   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4425 
4426   // Create a declaration for this anonymous struct/union.
4427   NamedDecl *Anon = nullptr;
4428   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4429     Anon = FieldDecl::Create(Context, OwningClass,
4430                              DS.getLocStart(),
4431                              Record->getLocation(),
4432                              /*IdentifierInfo=*/nullptr,
4433                              Context.getTypeDeclType(Record),
4434                              TInfo,
4435                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4436                              /*InitStyle=*/ICIS_NoInit);
4437     Anon->setAccess(AS);
4438     if (getLangOpts().CPlusPlus)
4439       FieldCollector->Add(cast<FieldDecl>(Anon));
4440   } else {
4441     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4442     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4443     if (SCSpec == DeclSpec::SCS_mutable) {
4444       // mutable can only appear on non-static class members, so it's always
4445       // an error here
4446       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4447       Invalid = true;
4448       SC = SC_None;
4449     }
4450 
4451     Anon = VarDecl::Create(Context, Owner,
4452                            DS.getLocStart(),
4453                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4454                            Context.getTypeDeclType(Record),
4455                            TInfo, SC);
4456 
4457     // Default-initialize the implicit variable. This initialization will be
4458     // trivial in almost all cases, except if a union member has an in-class
4459     // initializer:
4460     //   union { int n = 0; };
4461     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4462   }
4463   Anon->setImplicit();
4464 
4465   // Mark this as an anonymous struct/union type.
4466   Record->setAnonymousStructOrUnion(true);
4467 
4468   // Add the anonymous struct/union object to the current
4469   // context. We'll be referencing this object when we refer to one of
4470   // its members.
4471   Owner->addDecl(Anon);
4472 
4473   // Inject the members of the anonymous struct/union into the owning
4474   // context and into the identifier resolver chain for name lookup
4475   // purposes.
4476   SmallVector<NamedDecl*, 2> Chain;
4477   Chain.push_back(Anon);
4478 
4479   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4480     Invalid = true;
4481 
4482   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4483     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4484       Decl *ManglingContextDecl;
4485       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4486               NewVD->getDeclContext(), ManglingContextDecl)) {
4487         Context.setManglingNumber(
4488             NewVD, MCtx->getManglingNumber(
4489                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4490         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4491       }
4492     }
4493   }
4494 
4495   if (Invalid)
4496     Anon->setInvalidDecl();
4497 
4498   return Anon;
4499 }
4500 
4501 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4502 /// Microsoft C anonymous structure.
4503 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4504 /// Example:
4505 ///
4506 /// struct A { int a; };
4507 /// struct B { struct A; int b; };
4508 ///
4509 /// void foo() {
4510 ///   B var;
4511 ///   var.a = 3;
4512 /// }
4513 ///
BuildMicrosoftCAnonymousStruct(Scope * S,DeclSpec & DS,RecordDecl * Record)4514 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4515                                            RecordDecl *Record) {
4516   assert(Record && "expected a record!");
4517 
4518   // Mock up a declarator.
4519   Declarator Dc(DS, Declarator::TypeNameContext);
4520   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4521   assert(TInfo && "couldn't build declarator info for anonymous struct");
4522 
4523   auto *ParentDecl = cast<RecordDecl>(CurContext);
4524   QualType RecTy = Context.getTypeDeclType(Record);
4525 
4526   // Create a declaration for this anonymous struct.
4527   NamedDecl *Anon = FieldDecl::Create(Context,
4528                              ParentDecl,
4529                              DS.getLocStart(),
4530                              DS.getLocStart(),
4531                              /*IdentifierInfo=*/nullptr,
4532                              RecTy,
4533                              TInfo,
4534                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4535                              /*InitStyle=*/ICIS_NoInit);
4536   Anon->setImplicit();
4537 
4538   // Add the anonymous struct object to the current context.
4539   CurContext->addDecl(Anon);
4540 
4541   // Inject the members of the anonymous struct into the current
4542   // context and into the identifier resolver chain for name lookup
4543   // purposes.
4544   SmallVector<NamedDecl*, 2> Chain;
4545   Chain.push_back(Anon);
4546 
4547   RecordDecl *RecordDef = Record->getDefinition();
4548   if (RequireCompleteType(Anon->getLocation(), RecTy,
4549                           diag::err_field_incomplete) ||
4550       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4551                                           AS_none, Chain)) {
4552     Anon->setInvalidDecl();
4553     ParentDecl->setInvalidDecl();
4554   }
4555 
4556   return Anon;
4557 }
4558 
4559 /// GetNameForDeclarator - Determine the full declaration name for the
4560 /// given Declarator.
GetNameForDeclarator(Declarator & D)4561 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4562   return GetNameFromUnqualifiedId(D.getName());
4563 }
4564 
4565 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4566 DeclarationNameInfo
GetNameFromUnqualifiedId(const UnqualifiedId & Name)4567 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4568   DeclarationNameInfo NameInfo;
4569   NameInfo.setLoc(Name.StartLocation);
4570 
4571   switch (Name.getKind()) {
4572 
4573   case UnqualifiedId::IK_ImplicitSelfParam:
4574   case UnqualifiedId::IK_Identifier:
4575     NameInfo.setName(Name.Identifier);
4576     NameInfo.setLoc(Name.StartLocation);
4577     return NameInfo;
4578 
4579   case UnqualifiedId::IK_OperatorFunctionId:
4580     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4581                                            Name.OperatorFunctionId.Operator));
4582     NameInfo.setLoc(Name.StartLocation);
4583     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4584       = Name.OperatorFunctionId.SymbolLocations[0];
4585     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4586       = Name.EndLocation.getRawEncoding();
4587     return NameInfo;
4588 
4589   case UnqualifiedId::IK_LiteralOperatorId:
4590     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4591                                                            Name.Identifier));
4592     NameInfo.setLoc(Name.StartLocation);
4593     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4594     return NameInfo;
4595 
4596   case UnqualifiedId::IK_ConversionFunctionId: {
4597     TypeSourceInfo *TInfo;
4598     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4599     if (Ty.isNull())
4600       return DeclarationNameInfo();
4601     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4602                                                Context.getCanonicalType(Ty)));
4603     NameInfo.setLoc(Name.StartLocation);
4604     NameInfo.setNamedTypeInfo(TInfo);
4605     return NameInfo;
4606   }
4607 
4608   case UnqualifiedId::IK_ConstructorName: {
4609     TypeSourceInfo *TInfo;
4610     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4611     if (Ty.isNull())
4612       return DeclarationNameInfo();
4613     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4614                                               Context.getCanonicalType(Ty)));
4615     NameInfo.setLoc(Name.StartLocation);
4616     NameInfo.setNamedTypeInfo(TInfo);
4617     return NameInfo;
4618   }
4619 
4620   case UnqualifiedId::IK_ConstructorTemplateId: {
4621     // In well-formed code, we can only have a constructor
4622     // template-id that refers to the current context, so go there
4623     // to find the actual type being constructed.
4624     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4625     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4626       return DeclarationNameInfo();
4627 
4628     // Determine the type of the class being constructed.
4629     QualType CurClassType = Context.getTypeDeclType(CurClass);
4630 
4631     // FIXME: Check two things: that the template-id names the same type as
4632     // CurClassType, and that the template-id does not occur when the name
4633     // was qualified.
4634 
4635     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4636                                     Context.getCanonicalType(CurClassType)));
4637     NameInfo.setLoc(Name.StartLocation);
4638     // FIXME: should we retrieve TypeSourceInfo?
4639     NameInfo.setNamedTypeInfo(nullptr);
4640     return NameInfo;
4641   }
4642 
4643   case UnqualifiedId::IK_DestructorName: {
4644     TypeSourceInfo *TInfo;
4645     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4646     if (Ty.isNull())
4647       return DeclarationNameInfo();
4648     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4649                                               Context.getCanonicalType(Ty)));
4650     NameInfo.setLoc(Name.StartLocation);
4651     NameInfo.setNamedTypeInfo(TInfo);
4652     return NameInfo;
4653   }
4654 
4655   case UnqualifiedId::IK_TemplateId: {
4656     TemplateName TName = Name.TemplateId->Template.get();
4657     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4658     return Context.getNameForTemplate(TName, TNameLoc);
4659   }
4660 
4661   } // switch (Name.getKind())
4662 
4663   llvm_unreachable("Unknown name kind");
4664 }
4665 
getCoreType(QualType Ty)4666 static QualType getCoreType(QualType Ty) {
4667   do {
4668     if (Ty->isPointerType() || Ty->isReferenceType())
4669       Ty = Ty->getPointeeType();
4670     else if (Ty->isArrayType())
4671       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4672     else
4673       return Ty.withoutLocalFastQualifiers();
4674   } while (true);
4675 }
4676 
4677 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4678 /// and Definition have "nearly" matching parameters. This heuristic is
4679 /// used to improve diagnostics in the case where an out-of-line function
4680 /// definition doesn't match any declaration within the class or namespace.
4681 /// Also sets Params to the list of indices to the parameters that differ
4682 /// between the declaration and the definition. If hasSimilarParameters
4683 /// returns true and Params is empty, then all of the parameters match.
hasSimilarParameters(ASTContext & Context,FunctionDecl * Declaration,FunctionDecl * Definition,SmallVectorImpl<unsigned> & Params)4684 static bool hasSimilarParameters(ASTContext &Context,
4685                                      FunctionDecl *Declaration,
4686                                      FunctionDecl *Definition,
4687                                      SmallVectorImpl<unsigned> &Params) {
4688   Params.clear();
4689   if (Declaration->param_size() != Definition->param_size())
4690     return false;
4691   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4692     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4693     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4694 
4695     // The parameter types are identical
4696     if (Context.hasSameType(DefParamTy, DeclParamTy))
4697       continue;
4698 
4699     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4700     QualType DefParamBaseTy = getCoreType(DefParamTy);
4701     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4702     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4703 
4704     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4705         (DeclTyName && DeclTyName == DefTyName))
4706       Params.push_back(Idx);
4707     else  // The two parameters aren't even close
4708       return false;
4709   }
4710 
4711   return true;
4712 }
4713 
4714 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4715 /// declarator needs to be rebuilt in the current instantiation.
4716 /// Any bits of declarator which appear before the name are valid for
4717 /// consideration here.  That's specifically the type in the decl spec
4718 /// and the base type in any member-pointer chunks.
RebuildDeclaratorInCurrentInstantiation(Sema & S,Declarator & D,DeclarationName Name)4719 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4720                                                     DeclarationName Name) {
4721   // The types we specifically need to rebuild are:
4722   //   - typenames, typeofs, and decltypes
4723   //   - types which will become injected class names
4724   // Of course, we also need to rebuild any type referencing such a
4725   // type.  It's safest to just say "dependent", but we call out a
4726   // few cases here.
4727 
4728   DeclSpec &DS = D.getMutableDeclSpec();
4729   switch (DS.getTypeSpecType()) {
4730   case DeclSpec::TST_typename:
4731   case DeclSpec::TST_typeofType:
4732   case DeclSpec::TST_underlyingType:
4733   case DeclSpec::TST_atomic: {
4734     // Grab the type from the parser.
4735     TypeSourceInfo *TSI = nullptr;
4736     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4737     if (T.isNull() || !T->isDependentType()) break;
4738 
4739     // Make sure there's a type source info.  This isn't really much
4740     // of a waste; most dependent types should have type source info
4741     // attached already.
4742     if (!TSI)
4743       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4744 
4745     // Rebuild the type in the current instantiation.
4746     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4747     if (!TSI) return true;
4748 
4749     // Store the new type back in the decl spec.
4750     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4751     DS.UpdateTypeRep(LocType);
4752     break;
4753   }
4754 
4755   case DeclSpec::TST_decltype:
4756   case DeclSpec::TST_typeofExpr: {
4757     Expr *E = DS.getRepAsExpr();
4758     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4759     if (Result.isInvalid()) return true;
4760     DS.UpdateExprRep(Result.get());
4761     break;
4762   }
4763 
4764   default:
4765     // Nothing to do for these decl specs.
4766     break;
4767   }
4768 
4769   // It doesn't matter what order we do this in.
4770   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4771     DeclaratorChunk &Chunk = D.getTypeObject(I);
4772 
4773     // The only type information in the declarator which can come
4774     // before the declaration name is the base type of a member
4775     // pointer.
4776     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4777       continue;
4778 
4779     // Rebuild the scope specifier in-place.
4780     CXXScopeSpec &SS = Chunk.Mem.Scope();
4781     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4782       return true;
4783   }
4784 
4785   return false;
4786 }
4787 
ActOnDeclarator(Scope * S,Declarator & D)4788 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4789   D.setFunctionDefinitionKind(FDK_Declaration);
4790   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4791 
4792   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4793       Dcl && Dcl->getDeclContext()->isFileContext())
4794     Dcl->setTopLevelDeclInObjCContainer();
4795 
4796   return Dcl;
4797 }
4798 
4799 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4800 ///   If T is the name of a class, then each of the following shall have a
4801 ///   name different from T:
4802 ///     - every static data member of class T;
4803 ///     - every member function of class T
4804 ///     - every member of class T that is itself a type;
4805 /// \returns true if the declaration name violates these rules.
DiagnoseClassNameShadow(DeclContext * DC,DeclarationNameInfo NameInfo)4806 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4807                                    DeclarationNameInfo NameInfo) {
4808   DeclarationName Name = NameInfo.getName();
4809 
4810   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4811   while (Record && Record->isAnonymousStructOrUnion())
4812     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4813   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4814     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4815     return true;
4816   }
4817 
4818   return false;
4819 }
4820 
4821 /// \brief Diagnose a declaration whose declarator-id has the given
4822 /// nested-name-specifier.
4823 ///
4824 /// \param SS The nested-name-specifier of the declarator-id.
4825 ///
4826 /// \param DC The declaration context to which the nested-name-specifier
4827 /// resolves.
4828 ///
4829 /// \param Name The name of the entity being declared.
4830 ///
4831 /// \param Loc The location of the name of the entity being declared.
4832 ///
4833 /// \returns true if we cannot safely recover from this error, false otherwise.
diagnoseQualifiedDeclaration(CXXScopeSpec & SS,DeclContext * DC,DeclarationName Name,SourceLocation Loc)4834 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4835                                         DeclarationName Name,
4836                                         SourceLocation Loc) {
4837   DeclContext *Cur = CurContext;
4838   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4839     Cur = Cur->getParent();
4840 
4841   // If the user provided a superfluous scope specifier that refers back to the
4842   // class in which the entity is already declared, diagnose and ignore it.
4843   //
4844   // class X {
4845   //   void X::f();
4846   // };
4847   //
4848   // Note, it was once ill-formed to give redundant qualification in all
4849   // contexts, but that rule was removed by DR482.
4850   if (Cur->Equals(DC)) {
4851     if (Cur->isRecord()) {
4852       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4853                                       : diag::err_member_extra_qualification)
4854         << Name << FixItHint::CreateRemoval(SS.getRange());
4855       SS.clear();
4856     } else {
4857       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4858     }
4859     return false;
4860   }
4861 
4862   // Check whether the qualifying scope encloses the scope of the original
4863   // declaration.
4864   if (!Cur->Encloses(DC)) {
4865     if (Cur->isRecord())
4866       Diag(Loc, diag::err_member_qualification)
4867         << Name << SS.getRange();
4868     else if (isa<TranslationUnitDecl>(DC))
4869       Diag(Loc, diag::err_invalid_declarator_global_scope)
4870         << Name << SS.getRange();
4871     else if (isa<FunctionDecl>(Cur))
4872       Diag(Loc, diag::err_invalid_declarator_in_function)
4873         << Name << SS.getRange();
4874     else if (isa<BlockDecl>(Cur))
4875       Diag(Loc, diag::err_invalid_declarator_in_block)
4876         << Name << SS.getRange();
4877     else
4878       Diag(Loc, diag::err_invalid_declarator_scope)
4879       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4880 
4881     return true;
4882   }
4883 
4884   if (Cur->isRecord()) {
4885     // Cannot qualify members within a class.
4886     Diag(Loc, diag::err_member_qualification)
4887       << Name << SS.getRange();
4888     SS.clear();
4889 
4890     // C++ constructors and destructors with incorrect scopes can break
4891     // our AST invariants by having the wrong underlying types. If
4892     // that's the case, then drop this declaration entirely.
4893     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4894          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4895         !Context.hasSameType(Name.getCXXNameType(),
4896                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4897       return true;
4898 
4899     return false;
4900   }
4901 
4902   // C++11 [dcl.meaning]p1:
4903   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4904   //   not begin with a decltype-specifer"
4905   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4906   while (SpecLoc.getPrefix())
4907     SpecLoc = SpecLoc.getPrefix();
4908   if (dyn_cast_or_null<DecltypeType>(
4909         SpecLoc.getNestedNameSpecifier()->getAsType()))
4910     Diag(Loc, diag::err_decltype_in_declarator)
4911       << SpecLoc.getTypeLoc().getSourceRange();
4912 
4913   return false;
4914 }
4915 
HandleDeclarator(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParamLists)4916 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4917                                   MultiTemplateParamsArg TemplateParamLists) {
4918   // TODO: consider using NameInfo for diagnostic.
4919   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4920   DeclarationName Name = NameInfo.getName();
4921 
4922   // All of these full declarators require an identifier.  If it doesn't have
4923   // one, the ParsedFreeStandingDeclSpec action should be used.
4924   if (!Name) {
4925     if (!D.isInvalidType())  // Reject this if we think it is valid.
4926       Diag(D.getDeclSpec().getLocStart(),
4927            diag::err_declarator_need_ident)
4928         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4929     return nullptr;
4930   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4931     return nullptr;
4932 
4933   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4934   // we find one that is.
4935   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4936          (S->getFlags() & Scope::TemplateParamScope) != 0)
4937     S = S->getParent();
4938 
4939   DeclContext *DC = CurContext;
4940   if (D.getCXXScopeSpec().isInvalid())
4941     D.setInvalidType();
4942   else if (D.getCXXScopeSpec().isSet()) {
4943     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4944                                         UPPC_DeclarationQualifier))
4945       return nullptr;
4946 
4947     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4948     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4949     if (!DC || isa<EnumDecl>(DC)) {
4950       // If we could not compute the declaration context, it's because the
4951       // declaration context is dependent but does not refer to a class,
4952       // class template, or class template partial specialization. Complain
4953       // and return early, to avoid the coming semantic disaster.
4954       Diag(D.getIdentifierLoc(),
4955            diag::err_template_qualified_declarator_no_match)
4956         << D.getCXXScopeSpec().getScopeRep()
4957         << D.getCXXScopeSpec().getRange();
4958       return nullptr;
4959     }
4960     bool IsDependentContext = DC->isDependentContext();
4961 
4962     if (!IsDependentContext &&
4963         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4964       return nullptr;
4965 
4966     // If a class is incomplete, do not parse entities inside it.
4967     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4968       Diag(D.getIdentifierLoc(),
4969            diag::err_member_def_undefined_record)
4970         << Name << DC << D.getCXXScopeSpec().getRange();
4971       return nullptr;
4972     }
4973     if (!D.getDeclSpec().isFriendSpecified()) {
4974       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4975                                       Name, D.getIdentifierLoc())) {
4976         if (DC->isRecord())
4977           return nullptr;
4978 
4979         D.setInvalidType();
4980       }
4981     }
4982 
4983     // Check whether we need to rebuild the type of the given
4984     // declaration in the current instantiation.
4985     if (EnteringContext && IsDependentContext &&
4986         TemplateParamLists.size() != 0) {
4987       ContextRAII SavedContext(*this, DC);
4988       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4989         D.setInvalidType();
4990     }
4991   }
4992 
4993   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4994   QualType R = TInfo->getType();
4995 
4996   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4997     // If this is a typedef, we'll end up spewing multiple diagnostics.
4998     // Just return early; it's safer. If this is a function, let the
4999     // "constructor cannot have a return type" diagnostic handle it.
5000     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5001       return nullptr;
5002 
5003   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5004                                       UPPC_DeclarationType))
5005     D.setInvalidType();
5006 
5007   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5008                         ForRedeclaration);
5009 
5010   // See if this is a redefinition of a variable in the same scope.
5011   if (!D.getCXXScopeSpec().isSet()) {
5012     bool IsLinkageLookup = false;
5013     bool CreateBuiltins = false;
5014 
5015     // If the declaration we're planning to build will be a function
5016     // or object with linkage, then look for another declaration with
5017     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5018     //
5019     // If the declaration we're planning to build will be declared with
5020     // external linkage in the translation unit, create any builtin with
5021     // the same name.
5022     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5023       /* Do nothing*/;
5024     else if (CurContext->isFunctionOrMethod() &&
5025              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5026               R->isFunctionType())) {
5027       IsLinkageLookup = true;
5028       CreateBuiltins =
5029           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5030     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5031                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5032       CreateBuiltins = true;
5033 
5034     if (IsLinkageLookup)
5035       Previous.clear(LookupRedeclarationWithLinkage);
5036 
5037     LookupName(Previous, S, CreateBuiltins);
5038   } else { // Something like "int foo::x;"
5039     LookupQualifiedName(Previous, DC);
5040 
5041     // C++ [dcl.meaning]p1:
5042     //   When the declarator-id is qualified, the declaration shall refer to a
5043     //  previously declared member of the class or namespace to which the
5044     //  qualifier refers (or, in the case of a namespace, of an element of the
5045     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5046     //  thereof; [...]
5047     //
5048     // Note that we already checked the context above, and that we do not have
5049     // enough information to make sure that Previous contains the declaration
5050     // we want to match. For example, given:
5051     //
5052     //   class X {
5053     //     void f();
5054     //     void f(float);
5055     //   };
5056     //
5057     //   void X::f(int) { } // ill-formed
5058     //
5059     // In this case, Previous will point to the overload set
5060     // containing the two f's declared in X, but neither of them
5061     // matches.
5062 
5063     // C++ [dcl.meaning]p1:
5064     //   [...] the member shall not merely have been introduced by a
5065     //   using-declaration in the scope of the class or namespace nominated by
5066     //   the nested-name-specifier of the declarator-id.
5067     RemoveUsingDecls(Previous);
5068   }
5069 
5070   if (Previous.isSingleResult() &&
5071       Previous.getFoundDecl()->isTemplateParameter()) {
5072     // Maybe we will complain about the shadowed template parameter.
5073     if (!D.isInvalidType())
5074       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5075                                       Previous.getFoundDecl());
5076 
5077     // Just pretend that we didn't see the previous declaration.
5078     Previous.clear();
5079   }
5080 
5081   // In C++, the previous declaration we find might be a tag type
5082   // (class or enum). In this case, the new declaration will hide the
5083   // tag type. Note that this does does not apply if we're declaring a
5084   // typedef (C++ [dcl.typedef]p4).
5085   if (Previous.isSingleTagDecl() &&
5086       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5087     Previous.clear();
5088 
5089   // Check that there are no default arguments other than in the parameters
5090   // of a function declaration (C++ only).
5091   if (getLangOpts().CPlusPlus)
5092     CheckExtraCXXDefaultArguments(D);
5093 
5094   if (D.getDeclSpec().isConceptSpecified()) {
5095     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5096     // applied only to the definition of a function template or variable
5097     // template, declared in namespace scope
5098     if (!TemplateParamLists.size()) {
5099       Diag(D.getDeclSpec().getConceptSpecLoc(),
5100            diag:: err_concept_wrong_decl_kind);
5101       return nullptr;
5102     }
5103 
5104     if (!DC->getRedeclContext()->isFileContext()) {
5105       Diag(D.getIdentifierLoc(),
5106            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5107       return nullptr;
5108     }
5109   }
5110 
5111   NamedDecl *New;
5112 
5113   bool AddToScope = true;
5114   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5115     if (TemplateParamLists.size()) {
5116       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5117       return nullptr;
5118     }
5119 
5120     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5121   } else if (R->isFunctionType()) {
5122     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5123                                   TemplateParamLists,
5124                                   AddToScope);
5125   } else {
5126     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5127                                   AddToScope);
5128   }
5129 
5130   if (!New)
5131     return nullptr;
5132 
5133   // If this has an identifier and is not a function template specialization,
5134   // add it to the scope stack.
5135   if (New->getDeclName() && AddToScope) {
5136     // Only make a locally-scoped extern declaration visible if it is the first
5137     // declaration of this entity. Qualified lookup for such an entity should
5138     // only find this declaration if there is no visible declaration of it.
5139     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5140     PushOnScopeChains(New, S, AddToContext);
5141     if (!AddToContext)
5142       CurContext->addHiddenDecl(New);
5143   }
5144 
5145   if (isInOpenMPDeclareTargetContext())
5146     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5147 
5148   return New;
5149 }
5150 
5151 /// Helper method to turn variable array types into constant array
5152 /// types in certain situations which would otherwise be errors (for
5153 /// GCC compatibility).
TryToFixInvalidVariablyModifiedType(QualType T,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)5154 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5155                                                     ASTContext &Context,
5156                                                     bool &SizeIsNegative,
5157                                                     llvm::APSInt &Oversized) {
5158   // This method tries to turn a variable array into a constant
5159   // array even when the size isn't an ICE.  This is necessary
5160   // for compatibility with code that depends on gcc's buggy
5161   // constant expression folding, like struct {char x[(int)(char*)2];}
5162   SizeIsNegative = false;
5163   Oversized = 0;
5164 
5165   if (T->isDependentType())
5166     return QualType();
5167 
5168   QualifierCollector Qs;
5169   const Type *Ty = Qs.strip(T);
5170 
5171   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5172     QualType Pointee = PTy->getPointeeType();
5173     QualType FixedType =
5174         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5175                                             Oversized);
5176     if (FixedType.isNull()) return FixedType;
5177     FixedType = Context.getPointerType(FixedType);
5178     return Qs.apply(Context, FixedType);
5179   }
5180   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5181     QualType Inner = PTy->getInnerType();
5182     QualType FixedType =
5183         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5184                                             Oversized);
5185     if (FixedType.isNull()) return FixedType;
5186     FixedType = Context.getParenType(FixedType);
5187     return Qs.apply(Context, FixedType);
5188   }
5189 
5190   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5191   if (!VLATy)
5192     return QualType();
5193   // FIXME: We should probably handle this case
5194   if (VLATy->getElementType()->isVariablyModifiedType())
5195     return QualType();
5196 
5197   llvm::APSInt Res;
5198   if (!VLATy->getSizeExpr() ||
5199       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5200     return QualType();
5201 
5202   // Check whether the array size is negative.
5203   if (Res.isSigned() && Res.isNegative()) {
5204     SizeIsNegative = true;
5205     return QualType();
5206   }
5207 
5208   // Check whether the array is too large to be addressed.
5209   unsigned ActiveSizeBits
5210     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5211                                               Res);
5212   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5213     Oversized = Res;
5214     return QualType();
5215   }
5216 
5217   return Context.getConstantArrayType(VLATy->getElementType(),
5218                                       Res, ArrayType::Normal, 0);
5219 }
5220 
5221 static void
FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL,TypeLoc DstTL)5222 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5223   SrcTL = SrcTL.getUnqualifiedLoc();
5224   DstTL = DstTL.getUnqualifiedLoc();
5225   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5226     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5227     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5228                                       DstPTL.getPointeeLoc());
5229     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5230     return;
5231   }
5232   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5233     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5234     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5235                                       DstPTL.getInnerLoc());
5236     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5237     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5238     return;
5239   }
5240   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5241   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5242   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5243   TypeLoc DstElemTL = DstATL.getElementLoc();
5244   DstElemTL.initializeFullCopy(SrcElemTL);
5245   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5246   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5247   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5248 }
5249 
5250 /// Helper method to turn variable array types into constant array
5251 /// types in certain situations which would otherwise be errors (for
5252 /// GCC compatibility).
5253 static TypeSourceInfo*
TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo * TInfo,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)5254 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5255                                               ASTContext &Context,
5256                                               bool &SizeIsNegative,
5257                                               llvm::APSInt &Oversized) {
5258   QualType FixedTy
5259     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5260                                           SizeIsNegative, Oversized);
5261   if (FixedTy.isNull())
5262     return nullptr;
5263   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5264   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5265                                     FixedTInfo->getTypeLoc());
5266   return FixedTInfo;
5267 }
5268 
5269 /// \brief Register the given locally-scoped extern "C" declaration so
5270 /// that it can be found later for redeclarations. We include any extern "C"
5271 /// declaration that is not visible in the translation unit here, not just
5272 /// function-scope declarations.
5273 void
RegisterLocallyScopedExternCDecl(NamedDecl * ND,Scope * S)5274 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5275   if (!getLangOpts().CPlusPlus &&
5276       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5277     // Don't need to track declarations in the TU in C.
5278     return;
5279 
5280   // Note that we have a locally-scoped external with this name.
5281   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5282 }
5283 
findLocallyScopedExternCDecl(DeclarationName Name)5284 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5285   // FIXME: We can have multiple results via __attribute__((overloadable)).
5286   auto Result = Context.getExternCContextDecl()->lookup(Name);
5287   return Result.empty() ? nullptr : *Result.begin();
5288 }
5289 
5290 /// \brief Diagnose function specifiers on a declaration of an identifier that
5291 /// does not identify a function.
DiagnoseFunctionSpecifiers(const DeclSpec & DS)5292 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5293   // FIXME: We should probably indicate the identifier in question to avoid
5294   // confusion for constructs like "virtual int a(), b;"
5295   if (DS.isVirtualSpecified())
5296     Diag(DS.getVirtualSpecLoc(),
5297          diag::err_virtual_non_function);
5298 
5299   if (DS.isExplicitSpecified())
5300     Diag(DS.getExplicitSpecLoc(),
5301          diag::err_explicit_non_function);
5302 
5303   if (DS.isNoreturnSpecified())
5304     Diag(DS.getNoreturnSpecLoc(),
5305          diag::err_noreturn_non_function);
5306 }
5307 
5308 NamedDecl*
ActOnTypedefDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous)5309 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5310                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5311   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5312   if (D.getCXXScopeSpec().isSet()) {
5313     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5314       << D.getCXXScopeSpec().getRange();
5315     D.setInvalidType();
5316     // Pretend we didn't see the scope specifier.
5317     DC = CurContext;
5318     Previous.clear();
5319   }
5320 
5321   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5322 
5323   if (D.getDeclSpec().isInlineSpecified())
5324     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5325         << getLangOpts().CPlusPlus1z;
5326   if (D.getDeclSpec().isConstexprSpecified())
5327     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5328       << 1;
5329   if (D.getDeclSpec().isConceptSpecified())
5330     Diag(D.getDeclSpec().getConceptSpecLoc(),
5331          diag::err_concept_wrong_decl_kind);
5332 
5333   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5334     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5335       << D.getName().getSourceRange();
5336     return nullptr;
5337   }
5338 
5339   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5340   if (!NewTD) return nullptr;
5341 
5342   // Handle attributes prior to checking for duplicates in MergeVarDecl
5343   ProcessDeclAttributes(S, NewTD, D);
5344 
5345   CheckTypedefForVariablyModifiedType(S, NewTD);
5346 
5347   bool Redeclaration = D.isRedeclaration();
5348   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5349   D.setRedeclaration(Redeclaration);
5350   return ND;
5351 }
5352 
5353 void
CheckTypedefForVariablyModifiedType(Scope * S,TypedefNameDecl * NewTD)5354 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5355   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5356   // then it shall have block scope.
5357   // Note that variably modified types must be fixed before merging the decl so
5358   // that redeclarations will match.
5359   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5360   QualType T = TInfo->getType();
5361   if (T->isVariablyModifiedType()) {
5362     getCurFunction()->setHasBranchProtectedScope();
5363 
5364     if (S->getFnParent() == nullptr) {
5365       bool SizeIsNegative;
5366       llvm::APSInt Oversized;
5367       TypeSourceInfo *FixedTInfo =
5368         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5369                                                       SizeIsNegative,
5370                                                       Oversized);
5371       if (FixedTInfo) {
5372         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5373         NewTD->setTypeSourceInfo(FixedTInfo);
5374       } else {
5375         if (SizeIsNegative)
5376           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5377         else if (T->isVariableArrayType())
5378           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5379         else if (Oversized.getBoolValue())
5380           Diag(NewTD->getLocation(), diag::err_array_too_large)
5381             << Oversized.toString(10);
5382         else
5383           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5384         NewTD->setInvalidDecl();
5385       }
5386     }
5387   }
5388 }
5389 
5390 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5391 /// declares a typedef-name, either using the 'typedef' type specifier or via
5392 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5393 NamedDecl*
ActOnTypedefNameDecl(Scope * S,DeclContext * DC,TypedefNameDecl * NewTD,LookupResult & Previous,bool & Redeclaration)5394 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5395                            LookupResult &Previous, bool &Redeclaration) {
5396   // Merge the decl with the existing one if appropriate. If the decl is
5397   // in an outer scope, it isn't the same thing.
5398   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5399                        /*AllowInlineNamespace*/false);
5400   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5401   if (!Previous.empty()) {
5402     Redeclaration = true;
5403     MergeTypedefNameDecl(S, NewTD, Previous);
5404   }
5405 
5406   // If this is the C FILE type, notify the AST context.
5407   if (IdentifierInfo *II = NewTD->getIdentifier())
5408     if (!NewTD->isInvalidDecl() &&
5409         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5410       if (II->isStr("FILE"))
5411         Context.setFILEDecl(NewTD);
5412       else if (II->isStr("jmp_buf"))
5413         Context.setjmp_bufDecl(NewTD);
5414       else if (II->isStr("sigjmp_buf"))
5415         Context.setsigjmp_bufDecl(NewTD);
5416       else if (II->isStr("ucontext_t"))
5417         Context.setucontext_tDecl(NewTD);
5418     }
5419 
5420   return NewTD;
5421 }
5422 
5423 /// \brief Determines whether the given declaration is an out-of-scope
5424 /// previous declaration.
5425 ///
5426 /// This routine should be invoked when name lookup has found a
5427 /// previous declaration (PrevDecl) that is not in the scope where a
5428 /// new declaration by the same name is being introduced. If the new
5429 /// declaration occurs in a local scope, previous declarations with
5430 /// linkage may still be considered previous declarations (C99
5431 /// 6.2.2p4-5, C++ [basic.link]p6).
5432 ///
5433 /// \param PrevDecl the previous declaration found by name
5434 /// lookup
5435 ///
5436 /// \param DC the context in which the new declaration is being
5437 /// declared.
5438 ///
5439 /// \returns true if PrevDecl is an out-of-scope previous declaration
5440 /// for a new delcaration with the same name.
5441 static bool
isOutOfScopePreviousDeclaration(NamedDecl * PrevDecl,DeclContext * DC,ASTContext & Context)5442 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5443                                 ASTContext &Context) {
5444   if (!PrevDecl)
5445     return false;
5446 
5447   if (!PrevDecl->hasLinkage())
5448     return false;
5449 
5450   if (Context.getLangOpts().CPlusPlus) {
5451     // C++ [basic.link]p6:
5452     //   If there is a visible declaration of an entity with linkage
5453     //   having the same name and type, ignoring entities declared
5454     //   outside the innermost enclosing namespace scope, the block
5455     //   scope declaration declares that same entity and receives the
5456     //   linkage of the previous declaration.
5457     DeclContext *OuterContext = DC->getRedeclContext();
5458     if (!OuterContext->isFunctionOrMethod())
5459       // This rule only applies to block-scope declarations.
5460       return false;
5461 
5462     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5463     if (PrevOuterContext->isRecord())
5464       // We found a member function: ignore it.
5465       return false;
5466 
5467     // Find the innermost enclosing namespace for the new and
5468     // previous declarations.
5469     OuterContext = OuterContext->getEnclosingNamespaceContext();
5470     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5471 
5472     // The previous declaration is in a different namespace, so it
5473     // isn't the same function.
5474     if (!OuterContext->Equals(PrevOuterContext))
5475       return false;
5476   }
5477 
5478   return true;
5479 }
5480 
SetNestedNameSpecifier(DeclaratorDecl * DD,Declarator & D)5481 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5482   CXXScopeSpec &SS = D.getCXXScopeSpec();
5483   if (!SS.isSet()) return;
5484   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5485 }
5486 
inferObjCARCLifetime(ValueDecl * decl)5487 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5488   QualType type = decl->getType();
5489   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5490   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5491     // Various kinds of declaration aren't allowed to be __autoreleasing.
5492     unsigned kind = -1U;
5493     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5494       if (var->hasAttr<BlocksAttr>())
5495         kind = 0; // __block
5496       else if (!var->hasLocalStorage())
5497         kind = 1; // global
5498     } else if (isa<ObjCIvarDecl>(decl)) {
5499       kind = 3; // ivar
5500     } else if (isa<FieldDecl>(decl)) {
5501       kind = 2; // field
5502     }
5503 
5504     if (kind != -1U) {
5505       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5506         << kind;
5507     }
5508   } else if (lifetime == Qualifiers::OCL_None) {
5509     // Try to infer lifetime.
5510     if (!type->isObjCLifetimeType())
5511       return false;
5512 
5513     lifetime = type->getObjCARCImplicitLifetime();
5514     type = Context.getLifetimeQualifiedType(type, lifetime);
5515     decl->setType(type);
5516   }
5517 
5518   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5519     // Thread-local variables cannot have lifetime.
5520     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5521         var->getTLSKind()) {
5522       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5523         << var->getType();
5524       return true;
5525     }
5526   }
5527 
5528   return false;
5529 }
5530 
checkAttributesAfterMerging(Sema & S,NamedDecl & ND)5531 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5532   // Ensure that an auto decl is deduced otherwise the checks below might cache
5533   // the wrong linkage.
5534   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5535 
5536   // 'weak' only applies to declarations with external linkage.
5537   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5538     if (!ND.isExternallyVisible()) {
5539       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5540       ND.dropAttr<WeakAttr>();
5541     }
5542   }
5543   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5544     if (ND.isExternallyVisible()) {
5545       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5546       ND.dropAttr<WeakRefAttr>();
5547       ND.dropAttr<AliasAttr>();
5548     }
5549   }
5550 
5551   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5552     if (VD->hasInit()) {
5553       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5554         assert(VD->isThisDeclarationADefinition() &&
5555                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5556         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5557         VD->dropAttr<AliasAttr>();
5558       }
5559     }
5560   }
5561 
5562   // 'selectany' only applies to externally visible variable declarations.
5563   // It does not apply to functions.
5564   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5565     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5566       S.Diag(Attr->getLocation(),
5567              diag::err_attribute_selectany_non_extern_data);
5568       ND.dropAttr<SelectAnyAttr>();
5569     }
5570   }
5571 
5572   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5573     // dll attributes require external linkage. Static locals may have external
5574     // linkage but still cannot be explicitly imported or exported.
5575     auto *VD = dyn_cast<VarDecl>(&ND);
5576     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5577       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5578         << &ND << Attr;
5579       ND.setInvalidDecl();
5580     }
5581   }
5582 
5583   // Virtual functions cannot be marked as 'notail'.
5584   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5585     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5586       if (MD->isVirtual()) {
5587         S.Diag(ND.getLocation(),
5588                diag::err_invalid_attribute_on_virtual_function)
5589             << Attr;
5590         ND.dropAttr<NotTailCalledAttr>();
5591       }
5592 }
5593 
checkDLLAttributeRedeclaration(Sema & S,NamedDecl * OldDecl,NamedDecl * NewDecl,bool IsSpecialization,bool IsDefinition)5594 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5595                                            NamedDecl *NewDecl,
5596                                            bool IsSpecialization,
5597                                            bool IsDefinition) {
5598   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5599     OldDecl = OldTD->getTemplatedDecl();
5600     if (!IsSpecialization)
5601       IsDefinition = false;
5602   }
5603   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5604     NewDecl = NewTD->getTemplatedDecl();
5605 
5606   if (!OldDecl || !NewDecl)
5607     return;
5608 
5609   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5610   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5611   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5612   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5613 
5614   // dllimport and dllexport are inheritable attributes so we have to exclude
5615   // inherited attribute instances.
5616   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5617                     (NewExportAttr && !NewExportAttr->isInherited());
5618 
5619   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5620   // the only exception being explicit specializations.
5621   // Implicitly generated declarations are also excluded for now because there
5622   // is no other way to switch these to use dllimport or dllexport.
5623   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5624 
5625   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5626     // Allow with a warning for free functions and global variables.
5627     bool JustWarn = false;
5628     if (!OldDecl->isCXXClassMember()) {
5629       auto *VD = dyn_cast<VarDecl>(OldDecl);
5630       if (VD && !VD->getDescribedVarTemplate())
5631         JustWarn = true;
5632       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5633       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5634         JustWarn = true;
5635     }
5636 
5637     // We cannot change a declaration that's been used because IR has already
5638     // been emitted. Dllimported functions will still work though (modulo
5639     // address equality) as they can use the thunk.
5640     if (OldDecl->isUsed())
5641       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5642         JustWarn = false;
5643 
5644     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5645                                : diag::err_attribute_dll_redeclaration;
5646     S.Diag(NewDecl->getLocation(), DiagID)
5647         << NewDecl
5648         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5649     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5650     if (!JustWarn) {
5651       NewDecl->setInvalidDecl();
5652       return;
5653     }
5654   }
5655 
5656   // A redeclaration is not allowed to drop a dllimport attribute, the only
5657   // exceptions being inline function definitions, local extern declarations,
5658   // qualified friend declarations or special MSVC extension: in the last case,
5659   // the declaration is treated as if it were marked dllexport.
5660   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5661   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5662   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5663     // Ignore static data because out-of-line definitions are diagnosed
5664     // separately.
5665     IsStaticDataMember = VD->isStaticDataMember();
5666     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5667                    VarDecl::DeclarationOnly;
5668   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5669     IsInline = FD->isInlined();
5670     IsQualifiedFriend = FD->getQualifier() &&
5671                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5672   }
5673 
5674   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5675       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5676     if (IsMicrosoft && IsDefinition) {
5677       S.Diag(NewDecl->getLocation(),
5678              diag::warn_redeclaration_without_import_attribute)
5679           << NewDecl;
5680       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5681       NewDecl->dropAttr<DLLImportAttr>();
5682       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5683           NewImportAttr->getRange(), S.Context,
5684           NewImportAttr->getSpellingListIndex()));
5685     } else {
5686       S.Diag(NewDecl->getLocation(),
5687              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5688           << NewDecl << OldImportAttr;
5689       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5690       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5691       OldDecl->dropAttr<DLLImportAttr>();
5692       NewDecl->dropAttr<DLLImportAttr>();
5693     }
5694   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5695     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5696     OldDecl->dropAttr<DLLImportAttr>();
5697     NewDecl->dropAttr<DLLImportAttr>();
5698     S.Diag(NewDecl->getLocation(),
5699            diag::warn_dllimport_dropped_from_inline_function)
5700         << NewDecl << OldImportAttr;
5701   }
5702 }
5703 
5704 /// Given that we are within the definition of the given function,
5705 /// will that definition behave like C99's 'inline', where the
5706 /// definition is discarded except for optimization purposes?
isFunctionDefinitionDiscarded(Sema & S,FunctionDecl * FD)5707 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5708   // Try to avoid calling GetGVALinkageForFunction.
5709 
5710   // All cases of this require the 'inline' keyword.
5711   if (!FD->isInlined()) return false;
5712 
5713   // This is only possible in C++ with the gnu_inline attribute.
5714   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5715     return false;
5716 
5717   // Okay, go ahead and call the relatively-more-expensive function.
5718 
5719 #ifndef NDEBUG
5720   // AST quite reasonably asserts that it's working on a function
5721   // definition.  We don't really have a way to tell it that we're
5722   // currently defining the function, so just lie to it in +Asserts
5723   // builds.  This is an awful hack.
5724   FD->setLazyBody(1);
5725 #endif
5726 
5727   bool isC99Inline =
5728       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5729 
5730 #ifndef NDEBUG
5731   FD->setLazyBody(0);
5732 #endif
5733 
5734   return isC99Inline;
5735 }
5736 
5737 /// Determine whether a variable is extern "C" prior to attaching
5738 /// an initializer. We can't just call isExternC() here, because that
5739 /// will also compute and cache whether the declaration is externally
5740 /// visible, which might change when we attach the initializer.
5741 ///
5742 /// This can only be used if the declaration is known to not be a
5743 /// redeclaration of an internal linkage declaration.
5744 ///
5745 /// For instance:
5746 ///
5747 ///   auto x = []{};
5748 ///
5749 /// Attaching the initializer here makes this declaration not externally
5750 /// visible, because its type has internal linkage.
5751 ///
5752 /// FIXME: This is a hack.
5753 template<typename T>
isIncompleteDeclExternC(Sema & S,const T * D)5754 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5755   if (S.getLangOpts().CPlusPlus) {
5756     // In C++, the overloadable attribute negates the effects of extern "C".
5757     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5758       return false;
5759 
5760     // So do CUDA's host/device attributes.
5761     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5762                                  D->template hasAttr<CUDAHostAttr>()))
5763       return false;
5764   }
5765   return D->isExternC();
5766 }
5767 
shouldConsiderLinkage(const VarDecl * VD)5768 static bool shouldConsiderLinkage(const VarDecl *VD) {
5769   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5770   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5771     return VD->hasExternalStorage();
5772   if (DC->isFileContext())
5773     return true;
5774   if (DC->isRecord())
5775     return false;
5776   llvm_unreachable("Unexpected context");
5777 }
5778 
shouldConsiderLinkage(const FunctionDecl * FD)5779 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5780   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5781   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5782       isa<OMPDeclareReductionDecl>(DC))
5783     return true;
5784   if (DC->isRecord())
5785     return false;
5786   llvm_unreachable("Unexpected context");
5787 }
5788 
hasParsedAttr(Scope * S,const AttributeList * AttrList,AttributeList::Kind Kind)5789 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5790                           AttributeList::Kind Kind) {
5791   for (const AttributeList *L = AttrList; L; L = L->getNext())
5792     if (L->getKind() == Kind)
5793       return true;
5794   return false;
5795 }
5796 
hasParsedAttr(Scope * S,const Declarator & PD,AttributeList::Kind Kind)5797 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5798                           AttributeList::Kind Kind) {
5799   // Check decl attributes on the DeclSpec.
5800   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5801     return true;
5802 
5803   // Walk the declarator structure, checking decl attributes that were in a type
5804   // position to the decl itself.
5805   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5806     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5807       return true;
5808   }
5809 
5810   // Finally, check attributes on the decl itself.
5811   return hasParsedAttr(S, PD.getAttributes(), Kind);
5812 }
5813 
5814 /// Adjust the \c DeclContext for a function or variable that might be a
5815 /// function-local external declaration.
adjustContextForLocalExternDecl(DeclContext * & DC)5816 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5817   if (!DC->isFunctionOrMethod())
5818     return false;
5819 
5820   // If this is a local extern function or variable declared within a function
5821   // template, don't add it into the enclosing namespace scope until it is
5822   // instantiated; it might have a dependent type right now.
5823   if (DC->isDependentContext())
5824     return true;
5825 
5826   // C++11 [basic.link]p7:
5827   //   When a block scope declaration of an entity with linkage is not found to
5828   //   refer to some other declaration, then that entity is a member of the
5829   //   innermost enclosing namespace.
5830   //
5831   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5832   // semantically-enclosing namespace, not a lexically-enclosing one.
5833   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5834     DC = DC->getParent();
5835   return true;
5836 }
5837 
5838 /// \brief Returns true if given declaration has external C language linkage.
isDeclExternC(const Decl * D)5839 static bool isDeclExternC(const Decl *D) {
5840   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5841     return FD->isExternC();
5842   if (const auto *VD = dyn_cast<VarDecl>(D))
5843     return VD->isExternC();
5844 
5845   llvm_unreachable("Unknown type of decl!");
5846 }
5847 
5848 NamedDecl *
ActOnVariableDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists,bool & AddToScope)5849 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5850                               TypeSourceInfo *TInfo, LookupResult &Previous,
5851                               MultiTemplateParamsArg TemplateParamLists,
5852                               bool &AddToScope) {
5853   QualType R = TInfo->getType();
5854   DeclarationName Name = GetNameForDeclarator(D).getName();
5855 
5856   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5857   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5858   // argument.
5859   if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5860     Diag(D.getIdentifierLoc(),
5861          diag::err_opencl_type_can_only_be_used_as_function_parameter)
5862         << R;
5863     D.setInvalidType();
5864     return nullptr;
5865   }
5866 
5867   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5868   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5869 
5870   // dllimport globals without explicit storage class are treated as extern. We
5871   // have to change the storage class this early to get the right DeclContext.
5872   if (SC == SC_None && !DC->isRecord() &&
5873       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5874       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5875     SC = SC_Extern;
5876 
5877   DeclContext *OriginalDC = DC;
5878   bool IsLocalExternDecl = SC == SC_Extern &&
5879                            adjustContextForLocalExternDecl(DC);
5880 
5881   if (getLangOpts().OpenCL) {
5882     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5883     QualType NR = R;
5884     while (NR->isPointerType()) {
5885       if (NR->isFunctionPointerType()) {
5886         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5887         D.setInvalidType();
5888         break;
5889       }
5890       NR = NR->getPointeeType();
5891     }
5892 
5893     if (!getOpenCLOptions().cl_khr_fp16) {
5894       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5895       // half array type (unless the cl_khr_fp16 extension is enabled).
5896       if (Context.getBaseElementType(R)->isHalfType()) {
5897         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5898         D.setInvalidType();
5899       }
5900     }
5901   }
5902 
5903   if (SCSpec == DeclSpec::SCS_mutable) {
5904     // mutable can only appear on non-static class members, so it's always
5905     // an error here
5906     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5907     D.setInvalidType();
5908     SC = SC_None;
5909   }
5910 
5911   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5912       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5913                               D.getDeclSpec().getStorageClassSpecLoc())) {
5914     // In C++11, the 'register' storage class specifier is deprecated.
5915     // Suppress the warning in system macros, it's used in macros in some
5916     // popular C system headers, such as in glibc's htonl() macro.
5917     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5918          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5919                                    : diag::warn_deprecated_register)
5920       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5921   }
5922 
5923   IdentifierInfo *II = Name.getAsIdentifierInfo();
5924   if (!II) {
5925     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5926       << Name;
5927     return nullptr;
5928   }
5929 
5930   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5931 
5932   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5933     // C99 6.9p2: The storage-class specifiers auto and register shall not
5934     // appear in the declaration specifiers in an external declaration.
5935     // Global Register+Asm is a GNU extension we support.
5936     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5937       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5938       D.setInvalidType();
5939     }
5940   }
5941 
5942   if (getLangOpts().OpenCL) {
5943     // OpenCL v1.2 s6.9.b p4:
5944     // The sampler type cannot be used with the __local and __global address
5945     // space qualifiers.
5946     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5947       R.getAddressSpace() == LangAS::opencl_global)) {
5948       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5949     }
5950 
5951     // OpenCL 1.2 spec, p6.9 r:
5952     // The event type cannot be used to declare a program scope variable.
5953     // The event type cannot be used with the __local, __constant and __global
5954     // address space qualifiers.
5955     if (R->isEventT()) {
5956       if (S->getParent() == nullptr) {
5957         Diag(D.getLocStart(), diag::err_event_t_global_var);
5958         D.setInvalidType();
5959       }
5960 
5961       if (R.getAddressSpace()) {
5962         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5963         D.setInvalidType();
5964       }
5965     }
5966   }
5967 
5968   bool IsExplicitSpecialization = false;
5969   bool IsVariableTemplateSpecialization = false;
5970   bool IsPartialSpecialization = false;
5971   bool IsVariableTemplate = false;
5972   VarDecl *NewVD = nullptr;
5973   VarTemplateDecl *NewTemplate = nullptr;
5974   TemplateParameterList *TemplateParams = nullptr;
5975   if (!getLangOpts().CPlusPlus) {
5976     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5977                             D.getIdentifierLoc(), II,
5978                             R, TInfo, SC);
5979 
5980     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5981       ParsingInitForAutoVars.insert(NewVD);
5982 
5983     if (D.isInvalidType())
5984       NewVD->setInvalidDecl();
5985   } else {
5986     bool Invalid = false;
5987 
5988     if (DC->isRecord() && !CurContext->isRecord()) {
5989       // This is an out-of-line definition of a static data member.
5990       switch (SC) {
5991       case SC_None:
5992         break;
5993       case SC_Static:
5994         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5995              diag::err_static_out_of_line)
5996           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5997         break;
5998       case SC_Auto:
5999       case SC_Register:
6000       case SC_Extern:
6001         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6002         // to names of variables declared in a block or to function parameters.
6003         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6004         // of class members
6005 
6006         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6007              diag::err_storage_class_for_static_member)
6008           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6009         break;
6010       case SC_PrivateExtern:
6011         llvm_unreachable("C storage class in c++!");
6012       }
6013     }
6014 
6015     if (SC == SC_Static && CurContext->isRecord()) {
6016       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6017         if (RD->isLocalClass())
6018           Diag(D.getIdentifierLoc(),
6019                diag::err_static_data_member_not_allowed_in_local_class)
6020             << Name << RD->getDeclName();
6021 
6022         // C++98 [class.union]p1: If a union contains a static data member,
6023         // the program is ill-formed. C++11 drops this restriction.
6024         if (RD->isUnion())
6025           Diag(D.getIdentifierLoc(),
6026                getLangOpts().CPlusPlus11
6027                  ? diag::warn_cxx98_compat_static_data_member_in_union
6028                  : diag::ext_static_data_member_in_union) << Name;
6029         // We conservatively disallow static data members in anonymous structs.
6030         else if (!RD->getDeclName())
6031           Diag(D.getIdentifierLoc(),
6032                diag::err_static_data_member_not_allowed_in_anon_struct)
6033             << Name << RD->isUnion();
6034       }
6035     }
6036 
6037     // Match up the template parameter lists with the scope specifier, then
6038     // determine whether we have a template or a template specialization.
6039     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6040         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6041         D.getCXXScopeSpec(),
6042         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6043             ? D.getName().TemplateId
6044             : nullptr,
6045         TemplateParamLists,
6046         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6047 
6048     if (TemplateParams) {
6049       if (!TemplateParams->size() &&
6050           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6051         // There is an extraneous 'template<>' for this variable. Complain
6052         // about it, but allow the declaration of the variable.
6053         Diag(TemplateParams->getTemplateLoc(),
6054              diag::err_template_variable_noparams)
6055           << II
6056           << SourceRange(TemplateParams->getTemplateLoc(),
6057                          TemplateParams->getRAngleLoc());
6058         TemplateParams = nullptr;
6059       } else {
6060         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6061           // This is an explicit specialization or a partial specialization.
6062           // FIXME: Check that we can declare a specialization here.
6063           IsVariableTemplateSpecialization = true;
6064           IsPartialSpecialization = TemplateParams->size() > 0;
6065         } else { // if (TemplateParams->size() > 0)
6066           // This is a template declaration.
6067           IsVariableTemplate = true;
6068 
6069           // Check that we can declare a template here.
6070           if (CheckTemplateDeclScope(S, TemplateParams))
6071             return nullptr;
6072 
6073           // Only C++1y supports variable templates (N3651).
6074           Diag(D.getIdentifierLoc(),
6075                getLangOpts().CPlusPlus14
6076                    ? diag::warn_cxx11_compat_variable_template
6077                    : diag::ext_variable_template);
6078         }
6079       }
6080     } else {
6081       assert(
6082           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6083           "should have a 'template<>' for this decl");
6084     }
6085 
6086     if (IsVariableTemplateSpecialization) {
6087       SourceLocation TemplateKWLoc =
6088           TemplateParamLists.size() > 0
6089               ? TemplateParamLists[0]->getTemplateLoc()
6090               : SourceLocation();
6091       DeclResult Res = ActOnVarTemplateSpecialization(
6092           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6093           IsPartialSpecialization);
6094       if (Res.isInvalid())
6095         return nullptr;
6096       NewVD = cast<VarDecl>(Res.get());
6097       AddToScope = false;
6098     } else
6099       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6100                               D.getIdentifierLoc(), II, R, TInfo, SC);
6101 
6102     // If this is supposed to be a variable template, create it as such.
6103     if (IsVariableTemplate) {
6104       NewTemplate =
6105           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6106                                   TemplateParams, NewVD);
6107       NewVD->setDescribedVarTemplate(NewTemplate);
6108     }
6109 
6110     // If this decl has an auto type in need of deduction, make a note of the
6111     // Decl so we can diagnose uses of it in its own initializer.
6112     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6113       ParsingInitForAutoVars.insert(NewVD);
6114 
6115     if (D.isInvalidType() || Invalid) {
6116       NewVD->setInvalidDecl();
6117       if (NewTemplate)
6118         NewTemplate->setInvalidDecl();
6119     }
6120 
6121     SetNestedNameSpecifier(NewVD, D);
6122 
6123     // If we have any template parameter lists that don't directly belong to
6124     // the variable (matching the scope specifier), store them.
6125     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6126     if (TemplateParamLists.size() > VDTemplateParamLists)
6127       NewVD->setTemplateParameterListsInfo(
6128           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6129 
6130     if (D.getDeclSpec().isConstexprSpecified()) {
6131       NewVD->setConstexpr(true);
6132       // C++1z [dcl.spec.constexpr]p1:
6133       //   A static data member declared with the constexpr specifier is
6134       //   implicitly an inline variable.
6135       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6136         NewVD->setImplicitlyInline();
6137     }
6138 
6139     if (D.getDeclSpec().isConceptSpecified()) {
6140       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6141         VTD->setConcept();
6142 
6143       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6144       // be declared with the thread_local, inline, friend, or constexpr
6145       // specifiers, [...]
6146       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6147         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6148              diag::err_concept_decl_invalid_specifiers)
6149             << 0 << 0;
6150         NewVD->setInvalidDecl(true);
6151       }
6152 
6153       if (D.getDeclSpec().isConstexprSpecified()) {
6154         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6155              diag::err_concept_decl_invalid_specifiers)
6156             << 0 << 3;
6157         NewVD->setInvalidDecl(true);
6158       }
6159 
6160       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6161       // applied only to the definition of a function template or variable
6162       // template, declared in namespace scope.
6163       if (IsVariableTemplateSpecialization) {
6164         Diag(D.getDeclSpec().getConceptSpecLoc(),
6165              diag::err_concept_specified_specialization)
6166             << (IsPartialSpecialization ? 2 : 1);
6167       }
6168 
6169       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6170       // following restrictions:
6171       // - The declared type shall have the type bool.
6172       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6173           !NewVD->isInvalidDecl()) {
6174         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6175         NewVD->setInvalidDecl(true);
6176       }
6177     }
6178   }
6179 
6180   if (D.getDeclSpec().isInlineSpecified()) {
6181     if (CurContext->isFunctionOrMethod()) {
6182       // 'inline' is not allowed on block scope variable declaration.
6183       Diag(D.getDeclSpec().getInlineSpecLoc(),
6184            diag::err_inline_declaration_block_scope) << Name
6185         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6186     } else {
6187       Diag(D.getDeclSpec().getInlineSpecLoc(),
6188            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6189                                      : diag::ext_inline_variable);
6190       NewVD->setInlineSpecified();
6191     }
6192   }
6193 
6194   // Set the lexical context. If the declarator has a C++ scope specifier, the
6195   // lexical context will be different from the semantic context.
6196   NewVD->setLexicalDeclContext(CurContext);
6197   if (NewTemplate)
6198     NewTemplate->setLexicalDeclContext(CurContext);
6199 
6200   if (IsLocalExternDecl)
6201     NewVD->setLocalExternDecl();
6202 
6203   bool EmitTLSUnsupportedError = false;
6204   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6205     // C++11 [dcl.stc]p4:
6206     //   When thread_local is applied to a variable of block scope the
6207     //   storage-class-specifier static is implied if it does not appear
6208     //   explicitly.
6209     // Core issue: 'static' is not implied if the variable is declared
6210     //   'extern'.
6211     if (NewVD->hasLocalStorage() &&
6212         (SCSpec != DeclSpec::SCS_unspecified ||
6213          TSCS != DeclSpec::TSCS_thread_local ||
6214          !DC->isFunctionOrMethod()))
6215       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6216            diag::err_thread_non_global)
6217         << DeclSpec::getSpecifierName(TSCS);
6218     else if (!Context.getTargetInfo().isTLSSupported()) {
6219       if (getLangOpts().CUDA) {
6220         // Postpone error emission until we've collected attributes required to
6221         // figure out whether it's a host or device variable and whether the
6222         // error should be ignored.
6223         EmitTLSUnsupportedError = true;
6224         // We still need to mark the variable as TLS so it shows up in AST with
6225         // proper storage class for other tools to use even if we're not going
6226         // to emit any code for it.
6227         NewVD->setTSCSpec(TSCS);
6228       } else
6229         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6230              diag::err_thread_unsupported);
6231     } else
6232       NewVD->setTSCSpec(TSCS);
6233   }
6234 
6235   // C99 6.7.4p3
6236   //   An inline definition of a function with external linkage shall
6237   //   not contain a definition of a modifiable object with static or
6238   //   thread storage duration...
6239   // We only apply this when the function is required to be defined
6240   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6241   // that a local variable with thread storage duration still has to
6242   // be marked 'static'.  Also note that it's possible to get these
6243   // semantics in C++ using __attribute__((gnu_inline)).
6244   if (SC == SC_Static && S->getFnParent() != nullptr &&
6245       !NewVD->getType().isConstQualified()) {
6246     FunctionDecl *CurFD = getCurFunctionDecl();
6247     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6248       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6249            diag::warn_static_local_in_extern_inline);
6250       MaybeSuggestAddingStaticToDecl(CurFD);
6251     }
6252   }
6253 
6254   if (D.getDeclSpec().isModulePrivateSpecified()) {
6255     if (IsVariableTemplateSpecialization)
6256       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6257           << (IsPartialSpecialization ? 1 : 0)
6258           << FixItHint::CreateRemoval(
6259                  D.getDeclSpec().getModulePrivateSpecLoc());
6260     else if (IsExplicitSpecialization)
6261       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6262         << 2
6263         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6264     else if (NewVD->hasLocalStorage())
6265       Diag(NewVD->getLocation(), diag::err_module_private_local)
6266         << 0 << NewVD->getDeclName()
6267         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6268         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6269     else {
6270       NewVD->setModulePrivate();
6271       if (NewTemplate)
6272         NewTemplate->setModulePrivate();
6273     }
6274   }
6275 
6276   // Handle attributes prior to checking for duplicates in MergeVarDecl
6277   ProcessDeclAttributes(S, NewVD, D);
6278 
6279   if (getLangOpts().CUDA) {
6280     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6281       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6282            diag::err_thread_unsupported);
6283     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6284     // storage [duration]."
6285     if (SC == SC_None && S->getFnParent() != nullptr &&
6286         (NewVD->hasAttr<CUDASharedAttr>() ||
6287          NewVD->hasAttr<CUDAConstantAttr>())) {
6288       NewVD->setStorageClass(SC_Static);
6289     }
6290   }
6291 
6292   // Ensure that dllimport globals without explicit storage class are treated as
6293   // extern. The storage class is set above using parsed attributes. Now we can
6294   // check the VarDecl itself.
6295   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6296          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6297          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6298 
6299   // In auto-retain/release, infer strong retension for variables of
6300   // retainable type.
6301   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6302     NewVD->setInvalidDecl();
6303 
6304   // Handle GNU asm-label extension (encoded as an attribute).
6305   if (Expr *E = (Expr*)D.getAsmLabel()) {
6306     // The parser guarantees this is a string.
6307     StringLiteral *SE = cast<StringLiteral>(E);
6308     StringRef Label = SE->getString();
6309     if (S->getFnParent() != nullptr) {
6310       switch (SC) {
6311       case SC_None:
6312       case SC_Auto:
6313         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6314         break;
6315       case SC_Register:
6316         // Local Named register
6317         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6318             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6319           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6320         break;
6321       case SC_Static:
6322       case SC_Extern:
6323       case SC_PrivateExtern:
6324         break;
6325       }
6326     } else if (SC == SC_Register) {
6327       // Global Named register
6328       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6329         const auto &TI = Context.getTargetInfo();
6330         bool HasSizeMismatch;
6331 
6332         if (!TI.isValidGCCRegisterName(Label))
6333           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6334         else if (!TI.validateGlobalRegisterVariable(Label,
6335                                                     Context.getTypeSize(R),
6336                                                     HasSizeMismatch))
6337           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6338         else if (HasSizeMismatch)
6339           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6340       }
6341 
6342       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6343         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6344         NewVD->setInvalidDecl(true);
6345       }
6346     }
6347 
6348     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6349                                                 Context, Label, 0));
6350   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6351     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6352       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6353     if (I != ExtnameUndeclaredIdentifiers.end()) {
6354       if (isDeclExternC(NewVD)) {
6355         NewVD->addAttr(I->second);
6356         ExtnameUndeclaredIdentifiers.erase(I);
6357       } else
6358         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6359             << /*Variable*/1 << NewVD;
6360     }
6361   }
6362 
6363   // Diagnose shadowed variables before filtering for scope.
6364   if (D.getCXXScopeSpec().isEmpty())
6365     CheckShadow(S, NewVD, Previous);
6366 
6367   // Don't consider existing declarations that are in a different
6368   // scope and are out-of-semantic-context declarations (if the new
6369   // declaration has linkage).
6370   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6371                        D.getCXXScopeSpec().isNotEmpty() ||
6372                        IsExplicitSpecialization ||
6373                        IsVariableTemplateSpecialization);
6374 
6375   // Check whether the previous declaration is in the same block scope. This
6376   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6377   if (getLangOpts().CPlusPlus &&
6378       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6379     NewVD->setPreviousDeclInSameBlockScope(
6380         Previous.isSingleResult() && !Previous.isShadowed() &&
6381         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6382 
6383   if (!getLangOpts().CPlusPlus) {
6384     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6385   } else {
6386     // If this is an explicit specialization of a static data member, check it.
6387     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6388         CheckMemberSpecialization(NewVD, Previous))
6389       NewVD->setInvalidDecl();
6390 
6391     // Merge the decl with the existing one if appropriate.
6392     if (!Previous.empty()) {
6393       if (Previous.isSingleResult() &&
6394           isa<FieldDecl>(Previous.getFoundDecl()) &&
6395           D.getCXXScopeSpec().isSet()) {
6396         // The user tried to define a non-static data member
6397         // out-of-line (C++ [dcl.meaning]p1).
6398         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6399           << D.getCXXScopeSpec().getRange();
6400         Previous.clear();
6401         NewVD->setInvalidDecl();
6402       }
6403     } else if (D.getCXXScopeSpec().isSet()) {
6404       // No previous declaration in the qualifying scope.
6405       Diag(D.getIdentifierLoc(), diag::err_no_member)
6406         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6407         << D.getCXXScopeSpec().getRange();
6408       NewVD->setInvalidDecl();
6409     }
6410 
6411     if (!IsVariableTemplateSpecialization)
6412       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6413 
6414     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6415     // an explicit specialization (14.8.3) or a partial specialization of a
6416     // concept definition.
6417     if (IsVariableTemplateSpecialization &&
6418         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6419         Previous.isSingleResult()) {
6420       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6421       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6422         if (VarTmpl->isConcept()) {
6423           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6424               << 1                            /*variable*/
6425               << (IsPartialSpecialization ? 2 /*partially specialized*/
6426                                           : 1 /*explicitly specialized*/);
6427           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6428           NewVD->setInvalidDecl();
6429         }
6430       }
6431     }
6432 
6433     if (NewTemplate) {
6434       VarTemplateDecl *PrevVarTemplate =
6435           NewVD->getPreviousDecl()
6436               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6437               : nullptr;
6438 
6439       // Check the template parameter list of this declaration, possibly
6440       // merging in the template parameter list from the previous variable
6441       // template declaration.
6442       if (CheckTemplateParameterList(
6443               TemplateParams,
6444               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6445                               : nullptr,
6446               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6447                DC->isDependentContext())
6448                   ? TPC_ClassTemplateMember
6449                   : TPC_VarTemplate))
6450         NewVD->setInvalidDecl();
6451 
6452       // If we are providing an explicit specialization of a static variable
6453       // template, make a note of that.
6454       if (PrevVarTemplate &&
6455           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6456         PrevVarTemplate->setMemberSpecialization();
6457     }
6458   }
6459 
6460   ProcessPragmaWeak(S, NewVD);
6461 
6462   // If this is the first declaration of an extern C variable, update
6463   // the map of such variables.
6464   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6465       isIncompleteDeclExternC(*this, NewVD))
6466     RegisterLocallyScopedExternCDecl(NewVD, S);
6467 
6468   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6469     Decl *ManglingContextDecl;
6470     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6471             NewVD->getDeclContext(), ManglingContextDecl)) {
6472       Context.setManglingNumber(
6473           NewVD, MCtx->getManglingNumber(
6474                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6475       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6476     }
6477   }
6478 
6479   // Special handling of variable named 'main'.
6480   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6481       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6482       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6483 
6484     // C++ [basic.start.main]p3
6485     // A program that declares a variable main at global scope is ill-formed.
6486     if (getLangOpts().CPlusPlus)
6487       Diag(D.getLocStart(), diag::err_main_global_variable);
6488 
6489     // In C, and external-linkage variable named main results in undefined
6490     // behavior.
6491     else if (NewVD->hasExternalFormalLinkage())
6492       Diag(D.getLocStart(), diag::warn_main_redefined);
6493   }
6494 
6495   if (D.isRedeclaration() && !Previous.empty()) {
6496     checkDLLAttributeRedeclaration(
6497         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6498         IsExplicitSpecialization, D.isFunctionDefinition());
6499   }
6500 
6501   if (NewTemplate) {
6502     if (NewVD->isInvalidDecl())
6503       NewTemplate->setInvalidDecl();
6504     ActOnDocumentableDecl(NewTemplate);
6505     return NewTemplate;
6506   }
6507 
6508   return NewVD;
6509 }
6510 
6511 /// Enum describing the %select options in diag::warn_decl_shadow.
6512 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6513 
6514 /// Determine what kind of declaration we're shadowing.
computeShadowedDeclKind(const NamedDecl * ShadowedDecl,const DeclContext * OldDC)6515 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6516                                                 const DeclContext *OldDC) {
6517   if (isa<RecordDecl>(OldDC))
6518     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6519   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6520 }
6521 
6522 /// \brief Diagnose variable or built-in function shadowing.  Implements
6523 /// -Wshadow.
6524 ///
6525 /// This method is called whenever a VarDecl is added to a "useful"
6526 /// scope.
6527 ///
6528 /// \param S the scope in which the shadowing name is being declared
6529 /// \param R the lookup of the name
6530 ///
CheckShadow(Scope * S,VarDecl * D,const LookupResult & R)6531 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6532   // Return if warning is ignored.
6533   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6534     return;
6535 
6536   // Don't diagnose declarations at file scope.
6537   if (D->hasGlobalStorage())
6538     return;
6539 
6540   DeclContext *NewDC = D->getDeclContext();
6541 
6542   // Only diagnose if we're shadowing an unambiguous field or variable.
6543   if (R.getResultKind() != LookupResult::Found)
6544     return;
6545 
6546   NamedDecl* ShadowedDecl = R.getFoundDecl();
6547   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6548     return;
6549 
6550   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6551     // Fields are not shadowed by variables in C++ static methods.
6552     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6553       if (MD->isStatic())
6554         return;
6555 
6556     // Fields shadowed by constructor parameters are a special case. Usually
6557     // the constructor initializes the field with the parameter.
6558     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6559       // Remember that this was shadowed so we can either warn about its
6560       // modification or its existence depending on warning settings.
6561       D = D->getCanonicalDecl();
6562       ShadowingDecls.insert({D, FD});
6563       return;
6564     }
6565   }
6566 
6567   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6568     if (shadowedVar->isExternC()) {
6569       // For shadowing external vars, make sure that we point to the global
6570       // declaration, not a locally scoped extern declaration.
6571       for (auto I : shadowedVar->redecls())
6572         if (I->isFileVarDecl()) {
6573           ShadowedDecl = I;
6574           break;
6575         }
6576     }
6577 
6578   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6579 
6580   // Only warn about certain kinds of shadowing for class members.
6581   if (NewDC && NewDC->isRecord()) {
6582     // In particular, don't warn about shadowing non-class members.
6583     if (!OldDC->isRecord())
6584       return;
6585 
6586     // TODO: should we warn about static data members shadowing
6587     // static data members from base classes?
6588 
6589     // TODO: don't diagnose for inaccessible shadowed members.
6590     // This is hard to do perfectly because we might friend the
6591     // shadowing context, but that's just a false negative.
6592   }
6593 
6594 
6595   DeclarationName Name = R.getLookupName();
6596 
6597   // Emit warning and note.
6598   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6599     return;
6600   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6601   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6602   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6603 }
6604 
6605 /// \brief Check -Wshadow without the advantage of a previous lookup.
CheckShadow(Scope * S,VarDecl * D)6606 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6607   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6608     return;
6609 
6610   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6611                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6612   LookupName(R, S);
6613   CheckShadow(S, D, R);
6614 }
6615 
6616 /// Check if 'E', which is an expression that is about to be modified, refers
6617 /// to a constructor parameter that shadows a field.
CheckShadowingDeclModification(Expr * E,SourceLocation Loc)6618 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6619   // Quickly ignore expressions that can't be shadowing ctor parameters.
6620   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6621     return;
6622   E = E->IgnoreParenImpCasts();
6623   auto *DRE = dyn_cast<DeclRefExpr>(E);
6624   if (!DRE)
6625     return;
6626   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6627   auto I = ShadowingDecls.find(D);
6628   if (I == ShadowingDecls.end())
6629     return;
6630   const NamedDecl *ShadowedDecl = I->second;
6631   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6632   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6633   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6634   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6635 
6636   // Avoid issuing multiple warnings about the same decl.
6637   ShadowingDecls.erase(I);
6638 }
6639 
6640 /// Check for conflict between this global or extern "C" declaration and
6641 /// previous global or extern "C" declarations. This is only used in C++.
6642 template<typename T>
checkGlobalOrExternCConflict(Sema & S,const T * ND,bool IsGlobal,LookupResult & Previous)6643 static bool checkGlobalOrExternCConflict(
6644     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6645   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6646   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6647 
6648   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6649     // The common case: this global doesn't conflict with any extern "C"
6650     // declaration.
6651     return false;
6652   }
6653 
6654   if (Prev) {
6655     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6656       // Both the old and new declarations have C language linkage. This is a
6657       // redeclaration.
6658       Previous.clear();
6659       Previous.addDecl(Prev);
6660       return true;
6661     }
6662 
6663     // This is a global, non-extern "C" declaration, and there is a previous
6664     // non-global extern "C" declaration. Diagnose if this is a variable
6665     // declaration.
6666     if (!isa<VarDecl>(ND))
6667       return false;
6668   } else {
6669     // The declaration is extern "C". Check for any declaration in the
6670     // translation unit which might conflict.
6671     if (IsGlobal) {
6672       // We have already performed the lookup into the translation unit.
6673       IsGlobal = false;
6674       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6675            I != E; ++I) {
6676         if (isa<VarDecl>(*I)) {
6677           Prev = *I;
6678           break;
6679         }
6680       }
6681     } else {
6682       DeclContext::lookup_result R =
6683           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6684       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6685            I != E; ++I) {
6686         if (isa<VarDecl>(*I)) {
6687           Prev = *I;
6688           break;
6689         }
6690         // FIXME: If we have any other entity with this name in global scope,
6691         // the declaration is ill-formed, but that is a defect: it breaks the
6692         // 'stat' hack, for instance. Only variables can have mangled name
6693         // clashes with extern "C" declarations, so only they deserve a
6694         // diagnostic.
6695       }
6696     }
6697 
6698     if (!Prev)
6699       return false;
6700   }
6701 
6702   // Use the first declaration's location to ensure we point at something which
6703   // is lexically inside an extern "C" linkage-spec.
6704   assert(Prev && "should have found a previous declaration to diagnose");
6705   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6706     Prev = FD->getFirstDecl();
6707   else
6708     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6709 
6710   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6711     << IsGlobal << ND;
6712   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6713     << IsGlobal;
6714   return false;
6715 }
6716 
6717 /// Apply special rules for handling extern "C" declarations. Returns \c true
6718 /// if we have found that this is a redeclaration of some prior entity.
6719 ///
6720 /// Per C++ [dcl.link]p6:
6721 ///   Two declarations [for a function or variable] with C language linkage
6722 ///   with the same name that appear in different scopes refer to the same
6723 ///   [entity]. An entity with C language linkage shall not be declared with
6724 ///   the same name as an entity in global scope.
6725 template<typename T>
checkForConflictWithNonVisibleExternC(Sema & S,const T * ND,LookupResult & Previous)6726 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6727                                                   LookupResult &Previous) {
6728   if (!S.getLangOpts().CPlusPlus) {
6729     // In C, when declaring a global variable, look for a corresponding 'extern'
6730     // variable declared in function scope. We don't need this in C++, because
6731     // we find local extern decls in the surrounding file-scope DeclContext.
6732     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6733       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6734         Previous.clear();
6735         Previous.addDecl(Prev);
6736         return true;
6737       }
6738     }
6739     return false;
6740   }
6741 
6742   // A declaration in the translation unit can conflict with an extern "C"
6743   // declaration.
6744   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6745     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6746 
6747   // An extern "C" declaration can conflict with a declaration in the
6748   // translation unit or can be a redeclaration of an extern "C" declaration
6749   // in another scope.
6750   if (isIncompleteDeclExternC(S,ND))
6751     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6752 
6753   // Neither global nor extern "C": nothing to do.
6754   return false;
6755 }
6756 
CheckVariableDeclarationType(VarDecl * NewVD)6757 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6758   // If the decl is already known invalid, don't check it.
6759   if (NewVD->isInvalidDecl())
6760     return;
6761 
6762   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6763   QualType T = TInfo->getType();
6764 
6765   // Defer checking an 'auto' type until its initializer is attached.
6766   if (T->isUndeducedType())
6767     return;
6768 
6769   if (NewVD->hasAttrs())
6770     CheckAlignasUnderalignment(NewVD);
6771 
6772   if (T->isObjCObjectType()) {
6773     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6774       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6775     T = Context.getObjCObjectPointerType(T);
6776     NewVD->setType(T);
6777   }
6778 
6779   // Emit an error if an address space was applied to decl with local storage.
6780   // This includes arrays of objects with address space qualifiers, but not
6781   // automatic variables that point to other address spaces.
6782   // ISO/IEC TR 18037 S5.1.2
6783   if (!getLangOpts().OpenCL
6784       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6785     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6786     NewVD->setInvalidDecl();
6787     return;
6788   }
6789 
6790   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6791   // scope.
6792   if (getLangOpts().OpenCLVersion == 120 &&
6793       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6794       NewVD->isStaticLocal()) {
6795     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6796     NewVD->setInvalidDecl();
6797     return;
6798   }
6799 
6800   if (getLangOpts().OpenCL) {
6801     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6802     if (NewVD->hasAttr<BlocksAttr>()) {
6803       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6804       return;
6805     }
6806 
6807     if (T->isBlockPointerType()) {
6808       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6809       // can't use 'extern' storage class.
6810       if (!T.isConstQualified()) {
6811         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6812             << 0 /*const*/;
6813         NewVD->setInvalidDecl();
6814         return;
6815       }
6816       if (NewVD->hasExternalStorage()) {
6817         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6818         NewVD->setInvalidDecl();
6819         return;
6820       }
6821       // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6822       // TODO: this check is not enough as it doesn't diagnose the typedef
6823       const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6824       const FunctionProtoType *FTy =
6825           BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6826       if (FTy && FTy->isVariadic()) {
6827         Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6828             << T << NewVD->getSourceRange();
6829         NewVD->setInvalidDecl();
6830         return;
6831       }
6832     }
6833     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6834     // __constant address space.
6835     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6836     // variables inside a function can also be declared in the global
6837     // address space.
6838     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6839         NewVD->hasExternalStorage()) {
6840       if (!T->isSamplerT() &&
6841           !(T.getAddressSpace() == LangAS::opencl_constant ||
6842             (T.getAddressSpace() == LangAS::opencl_global &&
6843              getLangOpts().OpenCLVersion == 200))) {
6844         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6845         if (getLangOpts().OpenCLVersion == 200)
6846           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6847               << Scope << "global or constant";
6848         else
6849           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6850               << Scope << "constant";
6851         NewVD->setInvalidDecl();
6852         return;
6853       }
6854     } else {
6855       if (T.getAddressSpace() == LangAS::opencl_global) {
6856         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6857             << 1 /*is any function*/ << "global";
6858         NewVD->setInvalidDecl();
6859         return;
6860       }
6861       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6862       // in functions.
6863       if (T.getAddressSpace() == LangAS::opencl_constant ||
6864           T.getAddressSpace() == LangAS::opencl_local) {
6865         FunctionDecl *FD = getCurFunctionDecl();
6866         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6867           if (T.getAddressSpace() == LangAS::opencl_constant)
6868             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6869                 << 0 /*non-kernel only*/ << "constant";
6870           else
6871             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6872                 << 0 /*non-kernel only*/ << "local";
6873           NewVD->setInvalidDecl();
6874           return;
6875         }
6876       }
6877     }
6878   }
6879 
6880   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6881       && !NewVD->hasAttr<BlocksAttr>()) {
6882     if (getLangOpts().getGC() != LangOptions::NonGC)
6883       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6884     else {
6885       assert(!getLangOpts().ObjCAutoRefCount);
6886       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6887     }
6888   }
6889 
6890   bool isVM = T->isVariablyModifiedType();
6891   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6892       NewVD->hasAttr<BlocksAttr>())
6893     getCurFunction()->setHasBranchProtectedScope();
6894 
6895   if ((isVM && NewVD->hasLinkage()) ||
6896       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6897     bool SizeIsNegative;
6898     llvm::APSInt Oversized;
6899     TypeSourceInfo *FixedTInfo =
6900       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6901                                                     SizeIsNegative, Oversized);
6902     if (!FixedTInfo && T->isVariableArrayType()) {
6903       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6904       // FIXME: This won't give the correct result for
6905       // int a[10][n];
6906       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6907 
6908       if (NewVD->isFileVarDecl())
6909         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6910         << SizeRange;
6911       else if (NewVD->isStaticLocal())
6912         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6913         << SizeRange;
6914       else
6915         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6916         << SizeRange;
6917       NewVD->setInvalidDecl();
6918       return;
6919     }
6920 
6921     if (!FixedTInfo) {
6922       if (NewVD->isFileVarDecl())
6923         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6924       else
6925         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6926       NewVD->setInvalidDecl();
6927       return;
6928     }
6929 
6930     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6931     NewVD->setType(FixedTInfo->getType());
6932     NewVD->setTypeSourceInfo(FixedTInfo);
6933   }
6934 
6935   if (T->isVoidType()) {
6936     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6937     //                    of objects and functions.
6938     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6939       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6940         << T;
6941       NewVD->setInvalidDecl();
6942       return;
6943     }
6944   }
6945 
6946   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6947     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6948     NewVD->setInvalidDecl();
6949     return;
6950   }
6951 
6952   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6953     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6954     NewVD->setInvalidDecl();
6955     return;
6956   }
6957 
6958   if (NewVD->isConstexpr() && !T->isDependentType() &&
6959       RequireLiteralType(NewVD->getLocation(), T,
6960                          diag::err_constexpr_var_non_literal)) {
6961     NewVD->setInvalidDecl();
6962     return;
6963   }
6964 }
6965 
6966 /// \brief Perform semantic checking on a newly-created variable
6967 /// declaration.
6968 ///
6969 /// This routine performs all of the type-checking required for a
6970 /// variable declaration once it has been built. It is used both to
6971 /// check variables after they have been parsed and their declarators
6972 /// have been translated into a declaration, and to check variables
6973 /// that have been instantiated from a template.
6974 ///
6975 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6976 ///
6977 /// Returns true if the variable declaration is a redeclaration.
CheckVariableDeclaration(VarDecl * NewVD,LookupResult & Previous)6978 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6979   CheckVariableDeclarationType(NewVD);
6980 
6981   // If the decl is already known invalid, don't check it.
6982   if (NewVD->isInvalidDecl())
6983     return false;
6984 
6985   // If we did not find anything by this name, look for a non-visible
6986   // extern "C" declaration with the same name.
6987   if (Previous.empty() &&
6988       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6989     Previous.setShadowed();
6990 
6991   if (!Previous.empty()) {
6992     MergeVarDecl(NewVD, Previous);
6993     return true;
6994   }
6995   return false;
6996 }
6997 
6998 namespace {
6999 struct FindOverriddenMethod {
7000   Sema *S;
7001   CXXMethodDecl *Method;
7002 
7003   /// Member lookup function that determines whether a given C++
7004   /// method overrides a method in a base class, to be used with
7005   /// CXXRecordDecl::lookupInBases().
operator ()__anon9ef05b340511::FindOverriddenMethod7006   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7007     RecordDecl *BaseRecord =
7008         Specifier->getType()->getAs<RecordType>()->getDecl();
7009 
7010     DeclarationName Name = Method->getDeclName();
7011 
7012     // FIXME: Do we care about other names here too?
7013     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7014       // We really want to find the base class destructor here.
7015       QualType T = S->Context.getTypeDeclType(BaseRecord);
7016       CanQualType CT = S->Context.getCanonicalType(T);
7017 
7018       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7019     }
7020 
7021     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7022          Path.Decls = Path.Decls.slice(1)) {
7023       NamedDecl *D = Path.Decls.front();
7024       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7025         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7026           return true;
7027       }
7028     }
7029 
7030     return false;
7031   }
7032 };
7033 
7034 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7035 } // end anonymous namespace
7036 
7037 /// \brief Report an error regarding overriding, along with any relevant
7038 /// overriden methods.
7039 ///
7040 /// \param DiagID the primary error to report.
7041 /// \param MD the overriding method.
7042 /// \param OEK which overrides to include as notes.
ReportOverrides(Sema & S,unsigned DiagID,const CXXMethodDecl * MD,OverrideErrorKind OEK=OEK_All)7043 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7044                             OverrideErrorKind OEK = OEK_All) {
7045   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7046   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7047                                       E = MD->end_overridden_methods();
7048        I != E; ++I) {
7049     // This check (& the OEK parameter) could be replaced by a predicate, but
7050     // without lambdas that would be overkill. This is still nicer than writing
7051     // out the diag loop 3 times.
7052     if ((OEK == OEK_All) ||
7053         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7054         (OEK == OEK_Deleted && (*I)->isDeleted()))
7055       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7056   }
7057 }
7058 
7059 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7060 /// and if so, check that it's a valid override and remember it.
AddOverriddenMethods(CXXRecordDecl * DC,CXXMethodDecl * MD)7061 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7062   // Look for methods in base classes that this method might override.
7063   CXXBasePaths Paths;
7064   FindOverriddenMethod FOM;
7065   FOM.Method = MD;
7066   FOM.S = this;
7067   bool hasDeletedOverridenMethods = false;
7068   bool hasNonDeletedOverridenMethods = false;
7069   bool AddedAny = false;
7070   if (DC->lookupInBases(FOM, Paths)) {
7071     for (auto *I : Paths.found_decls()) {
7072       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7073         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7074         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7075             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7076             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7077             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7078           hasDeletedOverridenMethods |= OldMD->isDeleted();
7079           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7080           AddedAny = true;
7081         }
7082       }
7083     }
7084   }
7085 
7086   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7087     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7088   }
7089   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7090     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7091   }
7092 
7093   return AddedAny;
7094 }
7095 
7096 namespace {
7097   // Struct for holding all of the extra arguments needed by
7098   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7099   struct ActOnFDArgs {
7100     Scope *S;
7101     Declarator &D;
7102     MultiTemplateParamsArg TemplateParamLists;
7103     bool AddToScope;
7104   };
7105 } // end anonymous namespace
7106 
7107 namespace {
7108 
7109 // Callback to only accept typo corrections that have a non-zero edit distance.
7110 // Also only accept corrections that have the same parent decl.
7111 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7112  public:
DifferentNameValidatorCCC(ASTContext & Context,FunctionDecl * TypoFD,CXXRecordDecl * Parent)7113   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7114                             CXXRecordDecl *Parent)
7115       : Context(Context), OriginalFD(TypoFD),
7116         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7117 
ValidateCandidate(const TypoCorrection & candidate)7118   bool ValidateCandidate(const TypoCorrection &candidate) override {
7119     if (candidate.getEditDistance() == 0)
7120       return false;
7121 
7122     SmallVector<unsigned, 1> MismatchedParams;
7123     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7124                                           CDeclEnd = candidate.end();
7125          CDecl != CDeclEnd; ++CDecl) {
7126       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7127 
7128       if (FD && !FD->hasBody() &&
7129           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7130         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7131           CXXRecordDecl *Parent = MD->getParent();
7132           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7133             return true;
7134         } else if (!ExpectedParent) {
7135           return true;
7136         }
7137       }
7138     }
7139 
7140     return false;
7141   }
7142 
7143  private:
7144   ASTContext &Context;
7145   FunctionDecl *OriginalFD;
7146   CXXRecordDecl *ExpectedParent;
7147 };
7148 
7149 } // end anonymous namespace
7150 
7151 /// \brief Generate diagnostics for an invalid function redeclaration.
7152 ///
7153 /// This routine handles generating the diagnostic messages for an invalid
7154 /// function redeclaration, including finding possible similar declarations
7155 /// or performing typo correction if there are no previous declarations with
7156 /// the same name.
7157 ///
7158 /// Returns a NamedDecl iff typo correction was performed and substituting in
7159 /// the new declaration name does not cause new errors.
DiagnoseInvalidRedeclaration(Sema & SemaRef,LookupResult & Previous,FunctionDecl * NewFD,ActOnFDArgs & ExtraArgs,bool IsLocalFriend,Scope * S)7160 static NamedDecl *DiagnoseInvalidRedeclaration(
7161     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7162     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7163   DeclarationName Name = NewFD->getDeclName();
7164   DeclContext *NewDC = NewFD->getDeclContext();
7165   SmallVector<unsigned, 1> MismatchedParams;
7166   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7167   TypoCorrection Correction;
7168   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7169   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7170                                    : diag::err_member_decl_does_not_match;
7171   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7172                     IsLocalFriend ? Sema::LookupLocalFriendName
7173                                   : Sema::LookupOrdinaryName,
7174                     Sema::ForRedeclaration);
7175 
7176   NewFD->setInvalidDecl();
7177   if (IsLocalFriend)
7178     SemaRef.LookupName(Prev, S);
7179   else
7180     SemaRef.LookupQualifiedName(Prev, NewDC);
7181   assert(!Prev.isAmbiguous() &&
7182          "Cannot have an ambiguity in previous-declaration lookup");
7183   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7184   if (!Prev.empty()) {
7185     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7186          Func != FuncEnd; ++Func) {
7187       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7188       if (FD &&
7189           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7190         // Add 1 to the index so that 0 can mean the mismatch didn't
7191         // involve a parameter
7192         unsigned ParamNum =
7193             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7194         NearMatches.push_back(std::make_pair(FD, ParamNum));
7195       }
7196     }
7197   // If the qualified name lookup yielded nothing, try typo correction
7198   } else if ((Correction = SemaRef.CorrectTypo(
7199                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7200                   &ExtraArgs.D.getCXXScopeSpec(),
7201                   llvm::make_unique<DifferentNameValidatorCCC>(
7202                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7203                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7204     // Set up everything for the call to ActOnFunctionDeclarator
7205     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7206                               ExtraArgs.D.getIdentifierLoc());
7207     Previous.clear();
7208     Previous.setLookupName(Correction.getCorrection());
7209     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7210                                     CDeclEnd = Correction.end();
7211          CDecl != CDeclEnd; ++CDecl) {
7212       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7213       if (FD && !FD->hasBody() &&
7214           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7215         Previous.addDecl(FD);
7216       }
7217     }
7218     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7219 
7220     NamedDecl *Result;
7221     // Retry building the function declaration with the new previous
7222     // declarations, and with errors suppressed.
7223     {
7224       // Trap errors.
7225       Sema::SFINAETrap Trap(SemaRef);
7226 
7227       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7228       // pieces need to verify the typo-corrected C++ declaration and hopefully
7229       // eliminate the need for the parameter pack ExtraArgs.
7230       Result = SemaRef.ActOnFunctionDeclarator(
7231           ExtraArgs.S, ExtraArgs.D,
7232           Correction.getCorrectionDecl()->getDeclContext(),
7233           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7234           ExtraArgs.AddToScope);
7235 
7236       if (Trap.hasErrorOccurred())
7237         Result = nullptr;
7238     }
7239 
7240     if (Result) {
7241       // Determine which correction we picked.
7242       Decl *Canonical = Result->getCanonicalDecl();
7243       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7244            I != E; ++I)
7245         if ((*I)->getCanonicalDecl() == Canonical)
7246           Correction.setCorrectionDecl(*I);
7247 
7248       SemaRef.diagnoseTypo(
7249           Correction,
7250           SemaRef.PDiag(IsLocalFriend
7251                           ? diag::err_no_matching_local_friend_suggest
7252                           : diag::err_member_decl_does_not_match_suggest)
7253             << Name << NewDC << IsDefinition);
7254       return Result;
7255     }
7256 
7257     // Pretend the typo correction never occurred
7258     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7259                               ExtraArgs.D.getIdentifierLoc());
7260     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7261     Previous.clear();
7262     Previous.setLookupName(Name);
7263   }
7264 
7265   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7266       << Name << NewDC << IsDefinition << NewFD->getLocation();
7267 
7268   bool NewFDisConst = false;
7269   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7270     NewFDisConst = NewMD->isConst();
7271 
7272   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7273        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7274        NearMatch != NearMatchEnd; ++NearMatch) {
7275     FunctionDecl *FD = NearMatch->first;
7276     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7277     bool FDisConst = MD && MD->isConst();
7278     bool IsMember = MD || !IsLocalFriend;
7279 
7280     // FIXME: These notes are poorly worded for the local friend case.
7281     if (unsigned Idx = NearMatch->second) {
7282       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7283       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7284       if (Loc.isInvalid()) Loc = FD->getLocation();
7285       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7286                                  : diag::note_local_decl_close_param_match)
7287         << Idx << FDParam->getType()
7288         << NewFD->getParamDecl(Idx - 1)->getType();
7289     } else if (FDisConst != NewFDisConst) {
7290       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7291           << NewFDisConst << FD->getSourceRange().getEnd();
7292     } else
7293       SemaRef.Diag(FD->getLocation(),
7294                    IsMember ? diag::note_member_def_close_match
7295                             : diag::note_local_decl_close_match);
7296   }
7297   return nullptr;
7298 }
7299 
getFunctionStorageClass(Sema & SemaRef,Declarator & D)7300 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7301   switch (D.getDeclSpec().getStorageClassSpec()) {
7302   default: llvm_unreachable("Unknown storage class!");
7303   case DeclSpec::SCS_auto:
7304   case DeclSpec::SCS_register:
7305   case DeclSpec::SCS_mutable:
7306     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7307                  diag::err_typecheck_sclass_func);
7308     D.setInvalidType();
7309     break;
7310   case DeclSpec::SCS_unspecified: break;
7311   case DeclSpec::SCS_extern:
7312     if (D.getDeclSpec().isExternInLinkageSpec())
7313       return SC_None;
7314     return SC_Extern;
7315   case DeclSpec::SCS_static: {
7316     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7317       // C99 6.7.1p5:
7318       //   The declaration of an identifier for a function that has
7319       //   block scope shall have no explicit storage-class specifier
7320       //   other than extern
7321       // See also (C++ [dcl.stc]p4).
7322       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7323                    diag::err_static_block_func);
7324       break;
7325     } else
7326       return SC_Static;
7327   }
7328   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7329   }
7330 
7331   // No explicit storage class has already been returned
7332   return SC_None;
7333 }
7334 
CreateNewFunctionDecl(Sema & SemaRef,Declarator & D,DeclContext * DC,QualType & R,TypeSourceInfo * TInfo,StorageClass SC,bool & IsVirtualOkay)7335 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7336                                            DeclContext *DC, QualType &R,
7337                                            TypeSourceInfo *TInfo,
7338                                            StorageClass SC,
7339                                            bool &IsVirtualOkay) {
7340   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7341   DeclarationName Name = NameInfo.getName();
7342 
7343   FunctionDecl *NewFD = nullptr;
7344   bool isInline = D.getDeclSpec().isInlineSpecified();
7345 
7346   if (!SemaRef.getLangOpts().CPlusPlus) {
7347     // Determine whether the function was written with a
7348     // prototype. This true when:
7349     //   - there is a prototype in the declarator, or
7350     //   - the type R of the function is some kind of typedef or other reference
7351     //     to a type name (which eventually refers to a function type).
7352     bool HasPrototype =
7353       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7354       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7355 
7356     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7357                                  D.getLocStart(), NameInfo, R,
7358                                  TInfo, SC, isInline,
7359                                  HasPrototype, false);
7360     if (D.isInvalidType())
7361       NewFD->setInvalidDecl();
7362 
7363     return NewFD;
7364   }
7365 
7366   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7367   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7368 
7369   // Check that the return type is not an abstract class type.
7370   // For record types, this is done by the AbstractClassUsageDiagnoser once
7371   // the class has been completely parsed.
7372   if (!DC->isRecord() &&
7373       SemaRef.RequireNonAbstractType(
7374           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7375           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7376     D.setInvalidType();
7377 
7378   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7379     // This is a C++ constructor declaration.
7380     assert(DC->isRecord() &&
7381            "Constructors can only be declared in a member context");
7382 
7383     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7384     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7385                                       D.getLocStart(), NameInfo,
7386                                       R, TInfo, isExplicit, isInline,
7387                                       /*isImplicitlyDeclared=*/false,
7388                                       isConstexpr);
7389 
7390   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7391     // This is a C++ destructor declaration.
7392     if (DC->isRecord()) {
7393       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7394       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7395       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7396                                         SemaRef.Context, Record,
7397                                         D.getLocStart(),
7398                                         NameInfo, R, TInfo, isInline,
7399                                         /*isImplicitlyDeclared=*/false);
7400 
7401       // If the class is complete, then we now create the implicit exception
7402       // specification. If the class is incomplete or dependent, we can't do
7403       // it yet.
7404       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7405           Record->getDefinition() && !Record->isBeingDefined() &&
7406           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7407         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7408       }
7409 
7410       IsVirtualOkay = true;
7411       return NewDD;
7412 
7413     } else {
7414       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7415       D.setInvalidType();
7416 
7417       // Create a FunctionDecl to satisfy the function definition parsing
7418       // code path.
7419       return FunctionDecl::Create(SemaRef.Context, DC,
7420                                   D.getLocStart(),
7421                                   D.getIdentifierLoc(), Name, R, TInfo,
7422                                   SC, isInline,
7423                                   /*hasPrototype=*/true, isConstexpr);
7424     }
7425 
7426   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7427     if (!DC->isRecord()) {
7428       SemaRef.Diag(D.getIdentifierLoc(),
7429            diag::err_conv_function_not_member);
7430       return nullptr;
7431     }
7432 
7433     SemaRef.CheckConversionDeclarator(D, R, SC);
7434     IsVirtualOkay = true;
7435     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7436                                      D.getLocStart(), NameInfo,
7437                                      R, TInfo, isInline, isExplicit,
7438                                      isConstexpr, SourceLocation());
7439 
7440   } else if (DC->isRecord()) {
7441     // If the name of the function is the same as the name of the record,
7442     // then this must be an invalid constructor that has a return type.
7443     // (The parser checks for a return type and makes the declarator a
7444     // constructor if it has no return type).
7445     if (Name.getAsIdentifierInfo() &&
7446         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7447       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7448         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7449         << SourceRange(D.getIdentifierLoc());
7450       return nullptr;
7451     }
7452 
7453     // This is a C++ method declaration.
7454     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7455                                                cast<CXXRecordDecl>(DC),
7456                                                D.getLocStart(), NameInfo, R,
7457                                                TInfo, SC, isInline,
7458                                                isConstexpr, SourceLocation());
7459     IsVirtualOkay = !Ret->isStatic();
7460     return Ret;
7461   } else {
7462     bool isFriend =
7463         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7464     if (!isFriend && SemaRef.CurContext->isRecord())
7465       return nullptr;
7466 
7467     // Determine whether the function was written with a
7468     // prototype. This true when:
7469     //   - we're in C++ (where every function has a prototype),
7470     return FunctionDecl::Create(SemaRef.Context, DC,
7471                                 D.getLocStart(),
7472                                 NameInfo, R, TInfo, SC, isInline,
7473                                 true/*HasPrototype*/, isConstexpr);
7474   }
7475 }
7476 
7477 enum OpenCLParamType {
7478   ValidKernelParam,
7479   PtrPtrKernelParam,
7480   PtrKernelParam,
7481   PrivatePtrKernelParam,
7482   InvalidKernelParam,
7483   RecordKernelParam
7484 };
7485 
getOpenCLKernelParameterType(QualType PT)7486 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7487   if (PT->isPointerType()) {
7488     QualType PointeeType = PT->getPointeeType();
7489     if (PointeeType->isPointerType())
7490       return PtrPtrKernelParam;
7491     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7492                                               : PtrKernelParam;
7493   }
7494 
7495   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7496   // be used as builtin types.
7497 
7498   if (PT->isImageType())
7499     return PtrKernelParam;
7500 
7501   if (PT->isBooleanType())
7502     return InvalidKernelParam;
7503 
7504   if (PT->isEventT())
7505     return InvalidKernelParam;
7506 
7507   if (PT->isHalfType())
7508     return InvalidKernelParam;
7509 
7510   if (PT->isRecordType())
7511     return RecordKernelParam;
7512 
7513   return ValidKernelParam;
7514 }
7515 
checkIsValidOpenCLKernelParameter(Sema & S,Declarator & D,ParmVarDecl * Param,llvm::SmallPtrSetImpl<const Type * > & ValidTypes)7516 static void checkIsValidOpenCLKernelParameter(
7517   Sema &S,
7518   Declarator &D,
7519   ParmVarDecl *Param,
7520   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7521   QualType PT = Param->getType();
7522 
7523   // Cache the valid types we encounter to avoid rechecking structs that are
7524   // used again
7525   if (ValidTypes.count(PT.getTypePtr()))
7526     return;
7527 
7528   switch (getOpenCLKernelParameterType(PT)) {
7529   case PtrPtrKernelParam:
7530     // OpenCL v1.2 s6.9.a:
7531     // A kernel function argument cannot be declared as a
7532     // pointer to a pointer type.
7533     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7534     D.setInvalidType();
7535     return;
7536 
7537   case PrivatePtrKernelParam:
7538     // OpenCL v1.2 s6.9.a:
7539     // A kernel function argument cannot be declared as a
7540     // pointer to the private address space.
7541     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7542     D.setInvalidType();
7543     return;
7544 
7545     // OpenCL v1.2 s6.9.k:
7546     // Arguments to kernel functions in a program cannot be declared with the
7547     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7548     // uintptr_t or a struct and/or union that contain fields declared to be
7549     // one of these built-in scalar types.
7550 
7551   case InvalidKernelParam:
7552     // OpenCL v1.2 s6.8 n:
7553     // A kernel function argument cannot be declared
7554     // of event_t type.
7555     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7556     D.setInvalidType();
7557     return;
7558 
7559   case PtrKernelParam:
7560   case ValidKernelParam:
7561     ValidTypes.insert(PT.getTypePtr());
7562     return;
7563 
7564   case RecordKernelParam:
7565     break;
7566   }
7567 
7568   // Track nested structs we will inspect
7569   SmallVector<const Decl *, 4> VisitStack;
7570 
7571   // Track where we are in the nested structs. Items will migrate from
7572   // VisitStack to HistoryStack as we do the DFS for bad field.
7573   SmallVector<const FieldDecl *, 4> HistoryStack;
7574   HistoryStack.push_back(nullptr);
7575 
7576   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7577   VisitStack.push_back(PD);
7578 
7579   assert(VisitStack.back() && "First decl null?");
7580 
7581   do {
7582     const Decl *Next = VisitStack.pop_back_val();
7583     if (!Next) {
7584       assert(!HistoryStack.empty());
7585       // Found a marker, we have gone up a level
7586       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7587         ValidTypes.insert(Hist->getType().getTypePtr());
7588 
7589       continue;
7590     }
7591 
7592     // Adds everything except the original parameter declaration (which is not a
7593     // field itself) to the history stack.
7594     const RecordDecl *RD;
7595     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7596       HistoryStack.push_back(Field);
7597       RD = Field->getType()->castAs<RecordType>()->getDecl();
7598     } else {
7599       RD = cast<RecordDecl>(Next);
7600     }
7601 
7602     // Add a null marker so we know when we've gone back up a level
7603     VisitStack.push_back(nullptr);
7604 
7605     for (const auto *FD : RD->fields()) {
7606       QualType QT = FD->getType();
7607 
7608       if (ValidTypes.count(QT.getTypePtr()))
7609         continue;
7610 
7611       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7612       if (ParamType == ValidKernelParam)
7613         continue;
7614 
7615       if (ParamType == RecordKernelParam) {
7616         VisitStack.push_back(FD);
7617         continue;
7618       }
7619 
7620       // OpenCL v1.2 s6.9.p:
7621       // Arguments to kernel functions that are declared to be a struct or union
7622       // do not allow OpenCL objects to be passed as elements of the struct or
7623       // union.
7624       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7625           ParamType == PrivatePtrKernelParam) {
7626         S.Diag(Param->getLocation(),
7627                diag::err_record_with_pointers_kernel_param)
7628           << PT->isUnionType()
7629           << PT;
7630       } else {
7631         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7632       }
7633 
7634       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7635         << PD->getDeclName();
7636 
7637       // We have an error, now let's go back up through history and show where
7638       // the offending field came from
7639       for (ArrayRef<const FieldDecl *>::const_iterator
7640                I = HistoryStack.begin() + 1,
7641                E = HistoryStack.end();
7642            I != E; ++I) {
7643         const FieldDecl *OuterField = *I;
7644         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7645           << OuterField->getType();
7646       }
7647 
7648       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7649         << QT->isPointerType()
7650         << QT;
7651       D.setInvalidType();
7652       return;
7653     }
7654   } while (!VisitStack.empty());
7655 }
7656 
7657 NamedDecl*
ActOnFunctionDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists,bool & AddToScope)7658 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7659                               TypeSourceInfo *TInfo, LookupResult &Previous,
7660                               MultiTemplateParamsArg TemplateParamLists,
7661                               bool &AddToScope) {
7662   QualType R = TInfo->getType();
7663 
7664   assert(R.getTypePtr()->isFunctionType());
7665 
7666   // TODO: consider using NameInfo for diagnostic.
7667   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7668   DeclarationName Name = NameInfo.getName();
7669   StorageClass SC = getFunctionStorageClass(*this, D);
7670 
7671   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7672     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7673          diag::err_invalid_thread)
7674       << DeclSpec::getSpecifierName(TSCS);
7675 
7676   if (D.isFirstDeclarationOfMember())
7677     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7678                            D.getIdentifierLoc());
7679 
7680   bool isFriend = false;
7681   FunctionTemplateDecl *FunctionTemplate = nullptr;
7682   bool isExplicitSpecialization = false;
7683   bool isFunctionTemplateSpecialization = false;
7684 
7685   bool isDependentClassScopeExplicitSpecialization = false;
7686   bool HasExplicitTemplateArgs = false;
7687   TemplateArgumentListInfo TemplateArgs;
7688 
7689   bool isVirtualOkay = false;
7690 
7691   DeclContext *OriginalDC = DC;
7692   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7693 
7694   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7695                                               isVirtualOkay);
7696   if (!NewFD) return nullptr;
7697 
7698   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7699     NewFD->setTopLevelDeclInObjCContainer();
7700 
7701   // Set the lexical context. If this is a function-scope declaration, or has a
7702   // C++ scope specifier, or is the object of a friend declaration, the lexical
7703   // context will be different from the semantic context.
7704   NewFD->setLexicalDeclContext(CurContext);
7705 
7706   if (IsLocalExternDecl)
7707     NewFD->setLocalExternDecl();
7708 
7709   if (getLangOpts().CPlusPlus) {
7710     bool isInline = D.getDeclSpec().isInlineSpecified();
7711     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7712     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7713     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7714     bool isConcept = D.getDeclSpec().isConceptSpecified();
7715     isFriend = D.getDeclSpec().isFriendSpecified();
7716     if (isFriend && !isInline && D.isFunctionDefinition()) {
7717       // C++ [class.friend]p5
7718       //   A function can be defined in a friend declaration of a
7719       //   class . . . . Such a function is implicitly inline.
7720       NewFD->setImplicitlyInline();
7721     }
7722 
7723     // If this is a method defined in an __interface, and is not a constructor
7724     // or an overloaded operator, then set the pure flag (isVirtual will already
7725     // return true).
7726     if (const CXXRecordDecl *Parent =
7727           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7728       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7729         NewFD->setPure(true);
7730 
7731       // C++ [class.union]p2
7732       //   A union can have member functions, but not virtual functions.
7733       if (isVirtual && Parent->isUnion())
7734         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7735     }
7736 
7737     SetNestedNameSpecifier(NewFD, D);
7738     isExplicitSpecialization = false;
7739     isFunctionTemplateSpecialization = false;
7740     if (D.isInvalidType())
7741       NewFD->setInvalidDecl();
7742 
7743     // Match up the template parameter lists with the scope specifier, then
7744     // determine whether we have a template or a template specialization.
7745     bool Invalid = false;
7746     if (TemplateParameterList *TemplateParams =
7747             MatchTemplateParametersToScopeSpecifier(
7748                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7749                 D.getCXXScopeSpec(),
7750                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7751                     ? D.getName().TemplateId
7752                     : nullptr,
7753                 TemplateParamLists, isFriend, isExplicitSpecialization,
7754                 Invalid)) {
7755       if (TemplateParams->size() > 0) {
7756         // This is a function template
7757 
7758         // Check that we can declare a template here.
7759         if (CheckTemplateDeclScope(S, TemplateParams))
7760           NewFD->setInvalidDecl();
7761 
7762         // A destructor cannot be a template.
7763         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7764           Diag(NewFD->getLocation(), diag::err_destructor_template);
7765           NewFD->setInvalidDecl();
7766         }
7767 
7768         // If we're adding a template to a dependent context, we may need to
7769         // rebuilding some of the types used within the template parameter list,
7770         // now that we know what the current instantiation is.
7771         if (DC->isDependentContext()) {
7772           ContextRAII SavedContext(*this, DC);
7773           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7774             Invalid = true;
7775         }
7776 
7777         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7778                                                         NewFD->getLocation(),
7779                                                         Name, TemplateParams,
7780                                                         NewFD);
7781         FunctionTemplate->setLexicalDeclContext(CurContext);
7782         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7783 
7784         // For source fidelity, store the other template param lists.
7785         if (TemplateParamLists.size() > 1) {
7786           NewFD->setTemplateParameterListsInfo(Context,
7787                                                TemplateParamLists.drop_back(1));
7788         }
7789       } else {
7790         // This is a function template specialization.
7791         isFunctionTemplateSpecialization = true;
7792         // For source fidelity, store all the template param lists.
7793         if (TemplateParamLists.size() > 0)
7794           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7795 
7796         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7797         if (isFriend) {
7798           // We want to remove the "template<>", found here.
7799           SourceRange RemoveRange = TemplateParams->getSourceRange();
7800 
7801           // If we remove the template<> and the name is not a
7802           // template-id, we're actually silently creating a problem:
7803           // the friend declaration will refer to an untemplated decl,
7804           // and clearly the user wants a template specialization.  So
7805           // we need to insert '<>' after the name.
7806           SourceLocation InsertLoc;
7807           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7808             InsertLoc = D.getName().getSourceRange().getEnd();
7809             InsertLoc = getLocForEndOfToken(InsertLoc);
7810           }
7811 
7812           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7813             << Name << RemoveRange
7814             << FixItHint::CreateRemoval(RemoveRange)
7815             << FixItHint::CreateInsertion(InsertLoc, "<>");
7816         }
7817       }
7818     }
7819     else {
7820       // All template param lists were matched against the scope specifier:
7821       // this is NOT (an explicit specialization of) a template.
7822       if (TemplateParamLists.size() > 0)
7823         // For source fidelity, store all the template param lists.
7824         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7825     }
7826 
7827     if (Invalid) {
7828       NewFD->setInvalidDecl();
7829       if (FunctionTemplate)
7830         FunctionTemplate->setInvalidDecl();
7831     }
7832 
7833     // C++ [dcl.fct.spec]p5:
7834     //   The virtual specifier shall only be used in declarations of
7835     //   nonstatic class member functions that appear within a
7836     //   member-specification of a class declaration; see 10.3.
7837     //
7838     if (isVirtual && !NewFD->isInvalidDecl()) {
7839       if (!isVirtualOkay) {
7840         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7841              diag::err_virtual_non_function);
7842       } else if (!CurContext->isRecord()) {
7843         // 'virtual' was specified outside of the class.
7844         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7845              diag::err_virtual_out_of_class)
7846           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7847       } else if (NewFD->getDescribedFunctionTemplate()) {
7848         // C++ [temp.mem]p3:
7849         //  A member function template shall not be virtual.
7850         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7851              diag::err_virtual_member_function_template)
7852           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7853       } else {
7854         // Okay: Add virtual to the method.
7855         NewFD->setVirtualAsWritten(true);
7856       }
7857 
7858       if (getLangOpts().CPlusPlus14 &&
7859           NewFD->getReturnType()->isUndeducedType())
7860         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7861     }
7862 
7863     if (getLangOpts().CPlusPlus14 &&
7864         (NewFD->isDependentContext() ||
7865          (isFriend && CurContext->isDependentContext())) &&
7866         NewFD->getReturnType()->isUndeducedType()) {
7867       // If the function template is referenced directly (for instance, as a
7868       // member of the current instantiation), pretend it has a dependent type.
7869       // This is not really justified by the standard, but is the only sane
7870       // thing to do.
7871       // FIXME: For a friend function, we have not marked the function as being
7872       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7873       const FunctionProtoType *FPT =
7874           NewFD->getType()->castAs<FunctionProtoType>();
7875       QualType Result =
7876           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7877       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7878                                              FPT->getExtProtoInfo()));
7879     }
7880 
7881     // C++ [dcl.fct.spec]p3:
7882     //  The inline specifier shall not appear on a block scope function
7883     //  declaration.
7884     if (isInline && !NewFD->isInvalidDecl()) {
7885       if (CurContext->isFunctionOrMethod()) {
7886         // 'inline' is not allowed on block scope function declaration.
7887         Diag(D.getDeclSpec().getInlineSpecLoc(),
7888              diag::err_inline_declaration_block_scope) << Name
7889           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7890       }
7891     }
7892 
7893     // C++ [dcl.fct.spec]p6:
7894     //  The explicit specifier shall be used only in the declaration of a
7895     //  constructor or conversion function within its class definition;
7896     //  see 12.3.1 and 12.3.2.
7897     if (isExplicit && !NewFD->isInvalidDecl()) {
7898       if (!CurContext->isRecord()) {
7899         // 'explicit' was specified outside of the class.
7900         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7901              diag::err_explicit_out_of_class)
7902           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7903       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7904                  !isa<CXXConversionDecl>(NewFD)) {
7905         // 'explicit' was specified on a function that wasn't a constructor
7906         // or conversion function.
7907         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7908              diag::err_explicit_non_ctor_or_conv_function)
7909           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7910       }
7911     }
7912 
7913     if (isConstexpr) {
7914       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7915       // are implicitly inline.
7916       NewFD->setImplicitlyInline();
7917 
7918       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7919       // be either constructors or to return a literal type. Therefore,
7920       // destructors cannot be declared constexpr.
7921       if (isa<CXXDestructorDecl>(NewFD))
7922         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7923     }
7924 
7925     if (isConcept) {
7926       // This is a function concept.
7927       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7928         FTD->setConcept();
7929 
7930       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7931       // applied only to the definition of a function template [...]
7932       if (!D.isFunctionDefinition()) {
7933         Diag(D.getDeclSpec().getConceptSpecLoc(),
7934              diag::err_function_concept_not_defined);
7935         NewFD->setInvalidDecl();
7936       }
7937 
7938       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7939       // have no exception-specification and is treated as if it were specified
7940       // with noexcept(true) (15.4). [...]
7941       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7942         if (FPT->hasExceptionSpec()) {
7943           SourceRange Range;
7944           if (D.isFunctionDeclarator())
7945             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7946           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7947               << FixItHint::CreateRemoval(Range);
7948           NewFD->setInvalidDecl();
7949         } else {
7950           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7951         }
7952 
7953         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7954         // following restrictions:
7955         // - The declared return type shall have the type bool.
7956         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7957           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7958           NewFD->setInvalidDecl();
7959         }
7960 
7961         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7962         // following restrictions:
7963         // - The declaration's parameter list shall be equivalent to an empty
7964         //   parameter list.
7965         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7966           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7967       }
7968 
7969       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7970       // implicity defined to be a constexpr declaration (implicitly inline)
7971       NewFD->setImplicitlyInline();
7972 
7973       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7974       // be declared with the thread_local, inline, friend, or constexpr
7975       // specifiers, [...]
7976       if (isInline) {
7977         Diag(D.getDeclSpec().getInlineSpecLoc(),
7978              diag::err_concept_decl_invalid_specifiers)
7979             << 1 << 1;
7980         NewFD->setInvalidDecl(true);
7981       }
7982 
7983       if (isFriend) {
7984         Diag(D.getDeclSpec().getFriendSpecLoc(),
7985              diag::err_concept_decl_invalid_specifiers)
7986             << 1 << 2;
7987         NewFD->setInvalidDecl(true);
7988       }
7989 
7990       if (isConstexpr) {
7991         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7992              diag::err_concept_decl_invalid_specifiers)
7993             << 1 << 3;
7994         NewFD->setInvalidDecl(true);
7995       }
7996 
7997       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7998       // applied only to the definition of a function template or variable
7999       // template, declared in namespace scope.
8000       if (isFunctionTemplateSpecialization) {
8001         Diag(D.getDeclSpec().getConceptSpecLoc(),
8002              diag::err_concept_specified_specialization) << 1;
8003         NewFD->setInvalidDecl(true);
8004         return NewFD;
8005       }
8006     }
8007 
8008     // If __module_private__ was specified, mark the function accordingly.
8009     if (D.getDeclSpec().isModulePrivateSpecified()) {
8010       if (isFunctionTemplateSpecialization) {
8011         SourceLocation ModulePrivateLoc
8012           = D.getDeclSpec().getModulePrivateSpecLoc();
8013         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8014           << 0
8015           << FixItHint::CreateRemoval(ModulePrivateLoc);
8016       } else {
8017         NewFD->setModulePrivate();
8018         if (FunctionTemplate)
8019           FunctionTemplate->setModulePrivate();
8020       }
8021     }
8022 
8023     if (isFriend) {
8024       if (FunctionTemplate) {
8025         FunctionTemplate->setObjectOfFriendDecl();
8026         FunctionTemplate->setAccess(AS_public);
8027       }
8028       NewFD->setObjectOfFriendDecl();
8029       NewFD->setAccess(AS_public);
8030     }
8031 
8032     // If a function is defined as defaulted or deleted, mark it as such now.
8033     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8034     // definition kind to FDK_Definition.
8035     switch (D.getFunctionDefinitionKind()) {
8036       case FDK_Declaration:
8037       case FDK_Definition:
8038         break;
8039 
8040       case FDK_Defaulted:
8041         NewFD->setDefaulted();
8042         break;
8043 
8044       case FDK_Deleted:
8045         NewFD->setDeletedAsWritten();
8046         break;
8047     }
8048 
8049     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8050         D.isFunctionDefinition()) {
8051       // C++ [class.mfct]p2:
8052       //   A member function may be defined (8.4) in its class definition, in
8053       //   which case it is an inline member function (7.1.2)
8054       NewFD->setImplicitlyInline();
8055     }
8056 
8057     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8058         !CurContext->isRecord()) {
8059       // C++ [class.static]p1:
8060       //   A data or function member of a class may be declared static
8061       //   in a class definition, in which case it is a static member of
8062       //   the class.
8063 
8064       // Complain about the 'static' specifier if it's on an out-of-line
8065       // member function definition.
8066       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8067            diag::err_static_out_of_line)
8068         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8069     }
8070 
8071     // C++11 [except.spec]p15:
8072     //   A deallocation function with no exception-specification is treated
8073     //   as if it were specified with noexcept(true).
8074     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8075     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8076          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8077         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8078       NewFD->setType(Context.getFunctionType(
8079           FPT->getReturnType(), FPT->getParamTypes(),
8080           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8081   }
8082 
8083   // Filter out previous declarations that don't match the scope.
8084   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8085                        D.getCXXScopeSpec().isNotEmpty() ||
8086                        isExplicitSpecialization ||
8087                        isFunctionTemplateSpecialization);
8088 
8089   // Handle GNU asm-label extension (encoded as an attribute).
8090   if (Expr *E = (Expr*) D.getAsmLabel()) {
8091     // The parser guarantees this is a string.
8092     StringLiteral *SE = cast<StringLiteral>(E);
8093     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8094                                                 SE->getString(), 0));
8095   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8096     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8097       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8098     if (I != ExtnameUndeclaredIdentifiers.end()) {
8099       if (isDeclExternC(NewFD)) {
8100         NewFD->addAttr(I->second);
8101         ExtnameUndeclaredIdentifiers.erase(I);
8102       } else
8103         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8104             << /*Variable*/0 << NewFD;
8105     }
8106   }
8107 
8108   // Copy the parameter declarations from the declarator D to the function
8109   // declaration NewFD, if they are available.  First scavenge them into Params.
8110   SmallVector<ParmVarDecl*, 16> Params;
8111   if (D.isFunctionDeclarator()) {
8112     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8113 
8114     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8115     // function that takes no arguments, not a function that takes a
8116     // single void argument.
8117     // We let through "const void" here because Sema::GetTypeForDeclarator
8118     // already checks for that case.
8119     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8120       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8121         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8122         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8123         Param->setDeclContext(NewFD);
8124         Params.push_back(Param);
8125 
8126         if (Param->isInvalidDecl())
8127           NewFD->setInvalidDecl();
8128       }
8129     }
8130   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8131     // When we're declaring a function with a typedef, typeof, etc as in the
8132     // following example, we'll need to synthesize (unnamed)
8133     // parameters for use in the declaration.
8134     //
8135     // @code
8136     // typedef void fn(int);
8137     // fn f;
8138     // @endcode
8139 
8140     // Synthesize a parameter for each argument type.
8141     for (const auto &AI : FT->param_types()) {
8142       ParmVarDecl *Param =
8143           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8144       Param->setScopeInfo(0, Params.size());
8145       Params.push_back(Param);
8146     }
8147   } else {
8148     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8149            "Should not need args for typedef of non-prototype fn");
8150   }
8151 
8152   // Finally, we know we have the right number of parameters, install them.
8153   NewFD->setParams(Params);
8154 
8155   // Find all anonymous symbols defined during the declaration of this function
8156   // and add to NewFD. This lets us track decls such 'enum Y' in:
8157   //
8158   //   void f(enum Y {AA} x) {}
8159   //
8160   // which would otherwise incorrectly end up in the translation unit scope.
8161   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8162   DeclsInPrototypeScope.clear();
8163 
8164   if (D.getDeclSpec().isNoreturnSpecified())
8165     NewFD->addAttr(
8166         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8167                                        Context, 0));
8168 
8169   // Functions returning a variably modified type violate C99 6.7.5.2p2
8170   // because all functions have linkage.
8171   if (!NewFD->isInvalidDecl() &&
8172       NewFD->getReturnType()->isVariablyModifiedType()) {
8173     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8174     NewFD->setInvalidDecl();
8175   }
8176 
8177   // Apply an implicit SectionAttr if #pragma code_seg is active.
8178   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8179       !NewFD->hasAttr<SectionAttr>()) {
8180     NewFD->addAttr(
8181         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8182                                     CodeSegStack.CurrentValue->getString(),
8183                                     CodeSegStack.CurrentPragmaLocation));
8184     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8185                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8186                          ASTContext::PSF_Read,
8187                      NewFD))
8188       NewFD->dropAttr<SectionAttr>();
8189   }
8190 
8191   // Handle attributes.
8192   ProcessDeclAttributes(S, NewFD, D);
8193 
8194   if (getLangOpts().CUDA)
8195     maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8196 
8197   if (getLangOpts().OpenCL) {
8198     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8199     // type declaration will generate a compilation error.
8200     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8201     if (AddressSpace == LangAS::opencl_local ||
8202         AddressSpace == LangAS::opencl_global ||
8203         AddressSpace == LangAS::opencl_constant) {
8204       Diag(NewFD->getLocation(),
8205            diag::err_opencl_return_value_with_address_space);
8206       NewFD->setInvalidDecl();
8207     }
8208   }
8209 
8210   if (!getLangOpts().CPlusPlus) {
8211     // Perform semantic checking on the function declaration.
8212     bool isExplicitSpecialization=false;
8213     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8214       CheckMain(NewFD, D.getDeclSpec());
8215 
8216     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8217       CheckMSVCRTEntryPoint(NewFD);
8218 
8219     if (!NewFD->isInvalidDecl())
8220       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8221                                                   isExplicitSpecialization));
8222     else if (!Previous.empty())
8223       // Recover gracefully from an invalid redeclaration.
8224       D.setRedeclaration(true);
8225     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8226             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8227            "previous declaration set still overloaded");
8228 
8229     // Diagnose no-prototype function declarations with calling conventions that
8230     // don't support variadic calls. Only do this in C and do it after merging
8231     // possibly prototyped redeclarations.
8232     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8233     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8234       CallingConv CC = FT->getExtInfo().getCC();
8235       if (!supportsVariadicCall(CC)) {
8236         // Windows system headers sometimes accidentally use stdcall without
8237         // (void) parameters, so we relax this to a warning.
8238         int DiagID =
8239             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8240         Diag(NewFD->getLocation(), DiagID)
8241             << FunctionType::getNameForCallConv(CC);
8242       }
8243     }
8244   } else {
8245     // C++11 [replacement.functions]p3:
8246     //  The program's definitions shall not be specified as inline.
8247     //
8248     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8249     //
8250     // Suppress the diagnostic if the function is __attribute__((used)), since
8251     // that forces an external definition to be emitted.
8252     if (D.getDeclSpec().isInlineSpecified() &&
8253         NewFD->isReplaceableGlobalAllocationFunction() &&
8254         !NewFD->hasAttr<UsedAttr>())
8255       Diag(D.getDeclSpec().getInlineSpecLoc(),
8256            diag::ext_operator_new_delete_declared_inline)
8257         << NewFD->getDeclName();
8258 
8259     // If the declarator is a template-id, translate the parser's template
8260     // argument list into our AST format.
8261     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8262       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8263       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8264       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8265       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8266                                          TemplateId->NumArgs);
8267       translateTemplateArguments(TemplateArgsPtr,
8268                                  TemplateArgs);
8269 
8270       HasExplicitTemplateArgs = true;
8271 
8272       if (NewFD->isInvalidDecl()) {
8273         HasExplicitTemplateArgs = false;
8274       } else if (FunctionTemplate) {
8275         // Function template with explicit template arguments.
8276         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8277           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8278 
8279         HasExplicitTemplateArgs = false;
8280       } else {
8281         assert((isFunctionTemplateSpecialization ||
8282                 D.getDeclSpec().isFriendSpecified()) &&
8283                "should have a 'template<>' for this decl");
8284         // "friend void foo<>(int);" is an implicit specialization decl.
8285         isFunctionTemplateSpecialization = true;
8286       }
8287     } else if (isFriend && isFunctionTemplateSpecialization) {
8288       // This combination is only possible in a recovery case;  the user
8289       // wrote something like:
8290       //   template <> friend void foo(int);
8291       // which we're recovering from as if the user had written:
8292       //   friend void foo<>(int);
8293       // Go ahead and fake up a template id.
8294       HasExplicitTemplateArgs = true;
8295       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8296       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8297     }
8298 
8299     // If it's a friend (and only if it's a friend), it's possible
8300     // that either the specialized function type or the specialized
8301     // template is dependent, and therefore matching will fail.  In
8302     // this case, don't check the specialization yet.
8303     bool InstantiationDependent = false;
8304     if (isFunctionTemplateSpecialization && isFriend &&
8305         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8306          TemplateSpecializationType::anyDependentTemplateArguments(
8307             TemplateArgs,
8308             InstantiationDependent))) {
8309       assert(HasExplicitTemplateArgs &&
8310              "friend function specialization without template args");
8311       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8312                                                        Previous))
8313         NewFD->setInvalidDecl();
8314     } else if (isFunctionTemplateSpecialization) {
8315       if (CurContext->isDependentContext() && CurContext->isRecord()
8316           && !isFriend) {
8317         isDependentClassScopeExplicitSpecialization = true;
8318         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8319           diag::ext_function_specialization_in_class :
8320           diag::err_function_specialization_in_class)
8321           << NewFD->getDeclName();
8322       } else if (CheckFunctionTemplateSpecialization(NewFD,
8323                                   (HasExplicitTemplateArgs ? &TemplateArgs
8324                                                            : nullptr),
8325                                                      Previous))
8326         NewFD->setInvalidDecl();
8327 
8328       // C++ [dcl.stc]p1:
8329       //   A storage-class-specifier shall not be specified in an explicit
8330       //   specialization (14.7.3)
8331       FunctionTemplateSpecializationInfo *Info =
8332           NewFD->getTemplateSpecializationInfo();
8333       if (Info && SC != SC_None) {
8334         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8335           Diag(NewFD->getLocation(),
8336                diag::err_explicit_specialization_inconsistent_storage_class)
8337             << SC
8338             << FixItHint::CreateRemoval(
8339                                       D.getDeclSpec().getStorageClassSpecLoc());
8340 
8341         else
8342           Diag(NewFD->getLocation(),
8343                diag::ext_explicit_specialization_storage_class)
8344             << FixItHint::CreateRemoval(
8345                                       D.getDeclSpec().getStorageClassSpecLoc());
8346       }
8347     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8348       if (CheckMemberSpecialization(NewFD, Previous))
8349           NewFD->setInvalidDecl();
8350     }
8351 
8352     // Perform semantic checking on the function declaration.
8353     if (!isDependentClassScopeExplicitSpecialization) {
8354       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8355         CheckMain(NewFD, D.getDeclSpec());
8356 
8357       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8358         CheckMSVCRTEntryPoint(NewFD);
8359 
8360       if (!NewFD->isInvalidDecl())
8361         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8362                                                     isExplicitSpecialization));
8363       else if (!Previous.empty())
8364         // Recover gracefully from an invalid redeclaration.
8365         D.setRedeclaration(true);
8366     }
8367 
8368     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8369             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8370            "previous declaration set still overloaded");
8371 
8372     NamedDecl *PrincipalDecl = (FunctionTemplate
8373                                 ? cast<NamedDecl>(FunctionTemplate)
8374                                 : NewFD);
8375 
8376     if (isFriend && D.isRedeclaration()) {
8377       AccessSpecifier Access = AS_public;
8378       if (!NewFD->isInvalidDecl())
8379         Access = NewFD->getPreviousDecl()->getAccess();
8380 
8381       NewFD->setAccess(Access);
8382       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8383     }
8384 
8385     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8386         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8387       PrincipalDecl->setNonMemberOperator();
8388 
8389     // If we have a function template, check the template parameter
8390     // list. This will check and merge default template arguments.
8391     if (FunctionTemplate) {
8392       FunctionTemplateDecl *PrevTemplate =
8393                                      FunctionTemplate->getPreviousDecl();
8394       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8395                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8396                                     : nullptr,
8397                             D.getDeclSpec().isFriendSpecified()
8398                               ? (D.isFunctionDefinition()
8399                                    ? TPC_FriendFunctionTemplateDefinition
8400                                    : TPC_FriendFunctionTemplate)
8401                               : (D.getCXXScopeSpec().isSet() &&
8402                                  DC && DC->isRecord() &&
8403                                  DC->isDependentContext())
8404                                   ? TPC_ClassTemplateMember
8405                                   : TPC_FunctionTemplate);
8406     }
8407 
8408     if (NewFD->isInvalidDecl()) {
8409       // Ignore all the rest of this.
8410     } else if (!D.isRedeclaration()) {
8411       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8412                                        AddToScope };
8413       // Fake up an access specifier if it's supposed to be a class member.
8414       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8415         NewFD->setAccess(AS_public);
8416 
8417       // Qualified decls generally require a previous declaration.
8418       if (D.getCXXScopeSpec().isSet()) {
8419         // ...with the major exception of templated-scope or
8420         // dependent-scope friend declarations.
8421 
8422         // TODO: we currently also suppress this check in dependent
8423         // contexts because (1) the parameter depth will be off when
8424         // matching friend templates and (2) we might actually be
8425         // selecting a friend based on a dependent factor.  But there
8426         // are situations where these conditions don't apply and we
8427         // can actually do this check immediately.
8428         if (isFriend &&
8429             (TemplateParamLists.size() ||
8430              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8431              CurContext->isDependentContext())) {
8432           // ignore these
8433         } else {
8434           // The user tried to provide an out-of-line definition for a
8435           // function that is a member of a class or namespace, but there
8436           // was no such member function declared (C++ [class.mfct]p2,
8437           // C++ [namespace.memdef]p2). For example:
8438           //
8439           // class X {
8440           //   void f() const;
8441           // };
8442           //
8443           // void X::f() { } // ill-formed
8444           //
8445           // Complain about this problem, and attempt to suggest close
8446           // matches (e.g., those that differ only in cv-qualifiers and
8447           // whether the parameter types are references).
8448 
8449           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8450                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8451             AddToScope = ExtraArgs.AddToScope;
8452             return Result;
8453           }
8454         }
8455 
8456         // Unqualified local friend declarations are required to resolve
8457         // to something.
8458       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8459         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8460                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8461           AddToScope = ExtraArgs.AddToScope;
8462           return Result;
8463         }
8464       }
8465     } else if (!D.isFunctionDefinition() &&
8466                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8467                !isFriend && !isFunctionTemplateSpecialization &&
8468                !isExplicitSpecialization) {
8469       // An out-of-line member function declaration must also be a
8470       // definition (C++ [class.mfct]p2).
8471       // Note that this is not the case for explicit specializations of
8472       // function templates or member functions of class templates, per
8473       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8474       // extension for compatibility with old SWIG code which likes to
8475       // generate them.
8476       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8477         << D.getCXXScopeSpec().getRange();
8478     }
8479   }
8480 
8481   ProcessPragmaWeak(S, NewFD);
8482   checkAttributesAfterMerging(*this, *NewFD);
8483 
8484   AddKnownFunctionAttributes(NewFD);
8485 
8486   if (NewFD->hasAttr<OverloadableAttr>() &&
8487       !NewFD->getType()->getAs<FunctionProtoType>()) {
8488     Diag(NewFD->getLocation(),
8489          diag::err_attribute_overloadable_no_prototype)
8490       << NewFD;
8491 
8492     // Turn this into a variadic function with no parameters.
8493     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8494     FunctionProtoType::ExtProtoInfo EPI(
8495         Context.getDefaultCallingConvention(true, false));
8496     EPI.Variadic = true;
8497     EPI.ExtInfo = FT->getExtInfo();
8498 
8499     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8500     NewFD->setType(R);
8501   }
8502 
8503   // If there's a #pragma GCC visibility in scope, and this isn't a class
8504   // member, set the visibility of this function.
8505   if (!DC->isRecord() && NewFD->isExternallyVisible())
8506     AddPushedVisibilityAttribute(NewFD);
8507 
8508   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8509   // marking the function.
8510   AddCFAuditedAttribute(NewFD);
8511 
8512   // If this is a function definition, check if we have to apply optnone due to
8513   // a pragma.
8514   if(D.isFunctionDefinition())
8515     AddRangeBasedOptnone(NewFD);
8516 
8517   // If this is the first declaration of an extern C variable, update
8518   // the map of such variables.
8519   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8520       isIncompleteDeclExternC(*this, NewFD))
8521     RegisterLocallyScopedExternCDecl(NewFD, S);
8522 
8523   // Set this FunctionDecl's range up to the right paren.
8524   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8525 
8526   if (D.isRedeclaration() && !Previous.empty()) {
8527     checkDLLAttributeRedeclaration(
8528         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8529         isExplicitSpecialization || isFunctionTemplateSpecialization,
8530         D.isFunctionDefinition());
8531   }
8532 
8533   if (getLangOpts().CUDA) {
8534     IdentifierInfo *II = NewFD->getIdentifier();
8535     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8536         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8537       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8538         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8539 
8540       Context.setcudaConfigureCallDecl(NewFD);
8541     }
8542 
8543     // Variadic functions, other than a *declaration* of printf, are not allowed
8544     // in device-side CUDA code, unless someone passed
8545     // -fcuda-allow-variadic-functions.
8546     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8547         (NewFD->hasAttr<CUDADeviceAttr>() ||
8548          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8549         !(II && II->isStr("printf") && NewFD->isExternC() &&
8550           !D.isFunctionDefinition())) {
8551       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8552     }
8553   }
8554 
8555   if (getLangOpts().CPlusPlus) {
8556     if (FunctionTemplate) {
8557       if (NewFD->isInvalidDecl())
8558         FunctionTemplate->setInvalidDecl();
8559       return FunctionTemplate;
8560     }
8561   }
8562 
8563   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8564     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8565     if ((getLangOpts().OpenCLVersion >= 120)
8566         && (SC == SC_Static)) {
8567       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8568       D.setInvalidType();
8569     }
8570 
8571     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8572     if (!NewFD->getReturnType()->isVoidType()) {
8573       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8574       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8575           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8576                                 : FixItHint());
8577       D.setInvalidType();
8578     }
8579 
8580     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8581     for (auto Param : NewFD->parameters())
8582       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8583   }
8584   for (const ParmVarDecl *Param : NewFD->parameters()) {
8585     QualType PT = Param->getType();
8586 
8587     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8588     // types.
8589     if (getLangOpts().OpenCLVersion >= 200) {
8590       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8591         QualType ElemTy = PipeTy->getElementType();
8592           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8593             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8594             D.setInvalidType();
8595           }
8596       }
8597     }
8598   }
8599 
8600   MarkUnusedFileScopedDecl(NewFD);
8601 
8602   // Here we have an function template explicit specialization at class scope.
8603   // The actually specialization will be postponed to template instatiation
8604   // time via the ClassScopeFunctionSpecializationDecl node.
8605   if (isDependentClassScopeExplicitSpecialization) {
8606     ClassScopeFunctionSpecializationDecl *NewSpec =
8607                          ClassScopeFunctionSpecializationDecl::Create(
8608                                 Context, CurContext, SourceLocation(),
8609                                 cast<CXXMethodDecl>(NewFD),
8610                                 HasExplicitTemplateArgs, TemplateArgs);
8611     CurContext->addDecl(NewSpec);
8612     AddToScope = false;
8613   }
8614 
8615   return NewFD;
8616 }
8617 
8618 /// \brief Perform semantic checking of a new function declaration.
8619 ///
8620 /// Performs semantic analysis of the new function declaration
8621 /// NewFD. This routine performs all semantic checking that does not
8622 /// require the actual declarator involved in the declaration, and is
8623 /// used both for the declaration of functions as they are parsed
8624 /// (called via ActOnDeclarator) and for the declaration of functions
8625 /// that have been instantiated via C++ template instantiation (called
8626 /// via InstantiateDecl).
8627 ///
8628 /// \param IsExplicitSpecialization whether this new function declaration is
8629 /// an explicit specialization of the previous declaration.
8630 ///
8631 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8632 ///
8633 /// \returns true if the function declaration is a redeclaration.
CheckFunctionDeclaration(Scope * S,FunctionDecl * NewFD,LookupResult & Previous,bool IsExplicitSpecialization)8634 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8635                                     LookupResult &Previous,
8636                                     bool IsExplicitSpecialization) {
8637   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8638          "Variably modified return types are not handled here");
8639 
8640   // Determine whether the type of this function should be merged with
8641   // a previous visible declaration. This never happens for functions in C++,
8642   // and always happens in C if the previous declaration was visible.
8643   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8644                                !Previous.isShadowed();
8645 
8646   bool Redeclaration = false;
8647   NamedDecl *OldDecl = nullptr;
8648 
8649   // Merge or overload the declaration with an existing declaration of
8650   // the same name, if appropriate.
8651   if (!Previous.empty()) {
8652     // Determine whether NewFD is an overload of PrevDecl or
8653     // a declaration that requires merging. If it's an overload,
8654     // there's no more work to do here; we'll just add the new
8655     // function to the scope.
8656     if (!AllowOverloadingOfFunction(Previous, Context)) {
8657       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8658       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8659         Redeclaration = true;
8660         OldDecl = Candidate;
8661       }
8662     } else {
8663       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8664                             /*NewIsUsingDecl*/ false)) {
8665       case Ovl_Match:
8666         Redeclaration = true;
8667         break;
8668 
8669       case Ovl_NonFunction:
8670         Redeclaration = true;
8671         break;
8672 
8673       case Ovl_Overload:
8674         Redeclaration = false;
8675         break;
8676       }
8677 
8678       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8679         // If a function name is overloadable in C, then every function
8680         // with that name must be marked "overloadable".
8681         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8682           << Redeclaration << NewFD;
8683         NamedDecl *OverloadedDecl = nullptr;
8684         if (Redeclaration)
8685           OverloadedDecl = OldDecl;
8686         else if (!Previous.empty())
8687           OverloadedDecl = Previous.getRepresentativeDecl();
8688         if (OverloadedDecl)
8689           Diag(OverloadedDecl->getLocation(),
8690                diag::note_attribute_overloadable_prev_overload);
8691         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8692       }
8693     }
8694   }
8695 
8696   // Check for a previous extern "C" declaration with this name.
8697   if (!Redeclaration &&
8698       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8699     if (!Previous.empty()) {
8700       // This is an extern "C" declaration with the same name as a previous
8701       // declaration, and thus redeclares that entity...
8702       Redeclaration = true;
8703       OldDecl = Previous.getFoundDecl();
8704       MergeTypeWithPrevious = false;
8705 
8706       // ... except in the presence of __attribute__((overloadable)).
8707       if (OldDecl->hasAttr<OverloadableAttr>()) {
8708         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8709           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8710             << Redeclaration << NewFD;
8711           Diag(Previous.getFoundDecl()->getLocation(),
8712                diag::note_attribute_overloadable_prev_overload);
8713           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8714         }
8715         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8716           Redeclaration = false;
8717           OldDecl = nullptr;
8718         }
8719       }
8720     }
8721   }
8722 
8723   // C++11 [dcl.constexpr]p8:
8724   //   A constexpr specifier for a non-static member function that is not
8725   //   a constructor declares that member function to be const.
8726   //
8727   // This needs to be delayed until we know whether this is an out-of-line
8728   // definition of a static member function.
8729   //
8730   // This rule is not present in C++1y, so we produce a backwards
8731   // compatibility warning whenever it happens in C++11.
8732   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8733   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8734       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8735       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8736     CXXMethodDecl *OldMD = nullptr;
8737     if (OldDecl)
8738       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8739     if (!OldMD || !OldMD->isStatic()) {
8740       const FunctionProtoType *FPT =
8741         MD->getType()->castAs<FunctionProtoType>();
8742       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8743       EPI.TypeQuals |= Qualifiers::Const;
8744       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8745                                           FPT->getParamTypes(), EPI));
8746 
8747       // Warn that we did this, if we're not performing template instantiation.
8748       // In that case, we'll have warned already when the template was defined.
8749       if (ActiveTemplateInstantiations.empty()) {
8750         SourceLocation AddConstLoc;
8751         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8752                 .IgnoreParens().getAs<FunctionTypeLoc>())
8753           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8754 
8755         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8756           << FixItHint::CreateInsertion(AddConstLoc, " const");
8757       }
8758     }
8759   }
8760 
8761   if (Redeclaration) {
8762     // NewFD and OldDecl represent declarations that need to be
8763     // merged.
8764     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8765       NewFD->setInvalidDecl();
8766       return Redeclaration;
8767     }
8768 
8769     Previous.clear();
8770     Previous.addDecl(OldDecl);
8771 
8772     if (FunctionTemplateDecl *OldTemplateDecl
8773                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8774       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8775       FunctionTemplateDecl *NewTemplateDecl
8776         = NewFD->getDescribedFunctionTemplate();
8777       assert(NewTemplateDecl && "Template/non-template mismatch");
8778       if (CXXMethodDecl *Method
8779             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8780         Method->setAccess(OldTemplateDecl->getAccess());
8781         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8782       }
8783 
8784       // If this is an explicit specialization of a member that is a function
8785       // template, mark it as a member specialization.
8786       if (IsExplicitSpecialization &&
8787           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8788         NewTemplateDecl->setMemberSpecialization();
8789         assert(OldTemplateDecl->isMemberSpecialization());
8790         // Explicit specializations of a member template do not inherit deleted
8791         // status from the parent member template that they are specializing.
8792         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8793           FunctionDecl *const OldTemplatedDecl =
8794               OldTemplateDecl->getTemplatedDecl();
8795           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8796           OldTemplatedDecl->setDeletedAsWritten(false);
8797         }
8798       }
8799 
8800     } else {
8801       // This needs to happen first so that 'inline' propagates.
8802       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8803 
8804       if (isa<CXXMethodDecl>(NewFD))
8805         NewFD->setAccess(OldDecl->getAccess());
8806     }
8807   }
8808 
8809   // Semantic checking for this function declaration (in isolation).
8810 
8811   if (getLangOpts().CPlusPlus) {
8812     // C++-specific checks.
8813     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8814       CheckConstructor(Constructor);
8815     } else if (CXXDestructorDecl *Destructor =
8816                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8817       CXXRecordDecl *Record = Destructor->getParent();
8818       QualType ClassType = Context.getTypeDeclType(Record);
8819 
8820       // FIXME: Shouldn't we be able to perform this check even when the class
8821       // type is dependent? Both gcc and edg can handle that.
8822       if (!ClassType->isDependentType()) {
8823         DeclarationName Name
8824           = Context.DeclarationNames.getCXXDestructorName(
8825                                         Context.getCanonicalType(ClassType));
8826         if (NewFD->getDeclName() != Name) {
8827           Diag(NewFD->getLocation(), diag::err_destructor_name);
8828           NewFD->setInvalidDecl();
8829           return Redeclaration;
8830         }
8831       }
8832     } else if (CXXConversionDecl *Conversion
8833                = dyn_cast<CXXConversionDecl>(NewFD)) {
8834       ActOnConversionDeclarator(Conversion);
8835     }
8836 
8837     // Find any virtual functions that this function overrides.
8838     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8839       if (!Method->isFunctionTemplateSpecialization() &&
8840           !Method->getDescribedFunctionTemplate() &&
8841           Method->isCanonicalDecl()) {
8842         if (AddOverriddenMethods(Method->getParent(), Method)) {
8843           // If the function was marked as "static", we have a problem.
8844           if (NewFD->getStorageClass() == SC_Static) {
8845             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8846           }
8847         }
8848       }
8849 
8850       if (Method->isStatic())
8851         checkThisInStaticMemberFunctionType(Method);
8852     }
8853 
8854     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8855     if (NewFD->isOverloadedOperator() &&
8856         CheckOverloadedOperatorDeclaration(NewFD)) {
8857       NewFD->setInvalidDecl();
8858       return Redeclaration;
8859     }
8860 
8861     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8862     if (NewFD->getLiteralIdentifier() &&
8863         CheckLiteralOperatorDeclaration(NewFD)) {
8864       NewFD->setInvalidDecl();
8865       return Redeclaration;
8866     }
8867 
8868     // In C++, check default arguments now that we have merged decls. Unless
8869     // the lexical context is the class, because in this case this is done
8870     // during delayed parsing anyway.
8871     if (!CurContext->isRecord())
8872       CheckCXXDefaultArguments(NewFD);
8873 
8874     // If this function declares a builtin function, check the type of this
8875     // declaration against the expected type for the builtin.
8876     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8877       ASTContext::GetBuiltinTypeError Error;
8878       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8879       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8880       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8881         // The type of this function differs from the type of the builtin,
8882         // so forget about the builtin entirely.
8883         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8884       }
8885     }
8886 
8887     // If this function is declared as being extern "C", then check to see if
8888     // the function returns a UDT (class, struct, or union type) that is not C
8889     // compatible, and if it does, warn the user.
8890     // But, issue any diagnostic on the first declaration only.
8891     if (Previous.empty() && NewFD->isExternC()) {
8892       QualType R = NewFD->getReturnType();
8893       if (R->isIncompleteType() && !R->isVoidType())
8894         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8895             << NewFD << R;
8896       else if (!R.isPODType(Context) && !R->isVoidType() &&
8897                !R->isObjCObjectPointerType())
8898         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8899     }
8900   }
8901   return Redeclaration;
8902 }
8903 
CheckMain(FunctionDecl * FD,const DeclSpec & DS)8904 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8905   // C++11 [basic.start.main]p3:
8906   //   A program that [...] declares main to be inline, static or
8907   //   constexpr is ill-formed.
8908   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8909   //   appear in a declaration of main.
8910   // static main is not an error under C99, but we should warn about it.
8911   // We accept _Noreturn main as an extension.
8912   if (FD->getStorageClass() == SC_Static)
8913     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8914          ? diag::err_static_main : diag::warn_static_main)
8915       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8916   if (FD->isInlineSpecified())
8917     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8918       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8919   if (DS.isNoreturnSpecified()) {
8920     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8921     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8922     Diag(NoreturnLoc, diag::ext_noreturn_main);
8923     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8924       << FixItHint::CreateRemoval(NoreturnRange);
8925   }
8926   if (FD->isConstexpr()) {
8927     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8928       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8929     FD->setConstexpr(false);
8930   }
8931 
8932   if (getLangOpts().OpenCL) {
8933     Diag(FD->getLocation(), diag::err_opencl_no_main)
8934         << FD->hasAttr<OpenCLKernelAttr>();
8935     FD->setInvalidDecl();
8936     return;
8937   }
8938 
8939   QualType T = FD->getType();
8940   assert(T->isFunctionType() && "function decl is not of function type");
8941   const FunctionType* FT = T->castAs<FunctionType>();
8942 
8943   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8944     // In C with GNU extensions we allow main() to have non-integer return
8945     // type, but we should warn about the extension, and we disable the
8946     // implicit-return-zero rule.
8947 
8948     // GCC in C mode accepts qualified 'int'.
8949     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8950       FD->setHasImplicitReturnZero(true);
8951     else {
8952       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8953       SourceRange RTRange = FD->getReturnTypeSourceRange();
8954       if (RTRange.isValid())
8955         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8956             << FixItHint::CreateReplacement(RTRange, "int");
8957     }
8958   } else {
8959     // In C and C++, main magically returns 0 if you fall off the end;
8960     // set the flag which tells us that.
8961     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8962 
8963     // All the standards say that main() should return 'int'.
8964     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8965       FD->setHasImplicitReturnZero(true);
8966     else {
8967       // Otherwise, this is just a flat-out error.
8968       SourceRange RTRange = FD->getReturnTypeSourceRange();
8969       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8970           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8971                                 : FixItHint());
8972       FD->setInvalidDecl(true);
8973     }
8974   }
8975 
8976   // Treat protoless main() as nullary.
8977   if (isa<FunctionNoProtoType>(FT)) return;
8978 
8979   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8980   unsigned nparams = FTP->getNumParams();
8981   assert(FD->getNumParams() == nparams);
8982 
8983   bool HasExtraParameters = (nparams > 3);
8984 
8985   if (FTP->isVariadic()) {
8986     Diag(FD->getLocation(), diag::ext_variadic_main);
8987     // FIXME: if we had information about the location of the ellipsis, we
8988     // could add a FixIt hint to remove it as a parameter.
8989   }
8990 
8991   // Darwin passes an undocumented fourth argument of type char**.  If
8992   // other platforms start sprouting these, the logic below will start
8993   // getting shifty.
8994   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8995     HasExtraParameters = false;
8996 
8997   if (HasExtraParameters) {
8998     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8999     FD->setInvalidDecl(true);
9000     nparams = 3;
9001   }
9002 
9003   // FIXME: a lot of the following diagnostics would be improved
9004   // if we had some location information about types.
9005 
9006   QualType CharPP =
9007     Context.getPointerType(Context.getPointerType(Context.CharTy));
9008   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9009 
9010   for (unsigned i = 0; i < nparams; ++i) {
9011     QualType AT = FTP->getParamType(i);
9012 
9013     bool mismatch = true;
9014 
9015     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9016       mismatch = false;
9017     else if (Expected[i] == CharPP) {
9018       // As an extension, the following forms are okay:
9019       //   char const **
9020       //   char const * const *
9021       //   char * const *
9022 
9023       QualifierCollector qs;
9024       const PointerType* PT;
9025       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9026           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9027           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9028                               Context.CharTy)) {
9029         qs.removeConst();
9030         mismatch = !qs.empty();
9031       }
9032     }
9033 
9034     if (mismatch) {
9035       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9036       // TODO: suggest replacing given type with expected type
9037       FD->setInvalidDecl(true);
9038     }
9039   }
9040 
9041   if (nparams == 1 && !FD->isInvalidDecl()) {
9042     Diag(FD->getLocation(), diag::warn_main_one_arg);
9043   }
9044 
9045   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9046     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9047     FD->setInvalidDecl();
9048   }
9049 }
9050 
CheckMSVCRTEntryPoint(FunctionDecl * FD)9051 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9052   QualType T = FD->getType();
9053   assert(T->isFunctionType() && "function decl is not of function type");
9054   const FunctionType *FT = T->castAs<FunctionType>();
9055 
9056   // Set an implicit return of 'zero' if the function can return some integral,
9057   // enumeration, pointer or nullptr type.
9058   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9059       FT->getReturnType()->isAnyPointerType() ||
9060       FT->getReturnType()->isNullPtrType())
9061     // DllMain is exempt because a return value of zero means it failed.
9062     if (FD->getName() != "DllMain")
9063       FD->setHasImplicitReturnZero(true);
9064 
9065   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9066     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9067     FD->setInvalidDecl();
9068   }
9069 }
9070 
CheckForConstantInitializer(Expr * Init,QualType DclT)9071 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9072   // FIXME: Need strict checking.  In C89, we need to check for
9073   // any assignment, increment, decrement, function-calls, or
9074   // commas outside of a sizeof.  In C99, it's the same list,
9075   // except that the aforementioned are allowed in unevaluated
9076   // expressions.  Everything else falls under the
9077   // "may accept other forms of constant expressions" exception.
9078   // (We never end up here for C++, so the constant expression
9079   // rules there don't matter.)
9080   const Expr *Culprit;
9081   if (Init->isConstantInitializer(Context, false, &Culprit))
9082     return false;
9083   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9084     << Culprit->getSourceRange();
9085   return true;
9086 }
9087 
9088 namespace {
9089   // Visits an initialization expression to see if OrigDecl is evaluated in
9090   // its own initialization and throws a warning if it does.
9091   class SelfReferenceChecker
9092       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9093     Sema &S;
9094     Decl *OrigDecl;
9095     bool isRecordType;
9096     bool isPODType;
9097     bool isReferenceType;
9098 
9099     bool isInitList;
9100     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9101 
9102   public:
9103     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9104 
SelfReferenceChecker(Sema & S,Decl * OrigDecl)9105     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9106                                                     S(S), OrigDecl(OrigDecl) {
9107       isPODType = false;
9108       isRecordType = false;
9109       isReferenceType = false;
9110       isInitList = false;
9111       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9112         isPODType = VD->getType().isPODType(S.Context);
9113         isRecordType = VD->getType()->isRecordType();
9114         isReferenceType = VD->getType()->isReferenceType();
9115       }
9116     }
9117 
9118     // For most expressions, just call the visitor.  For initializer lists,
9119     // track the index of the field being initialized since fields are
9120     // initialized in order allowing use of previously initialized fields.
CheckExpr(Expr * E)9121     void CheckExpr(Expr *E) {
9122       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9123       if (!InitList) {
9124         Visit(E);
9125         return;
9126       }
9127 
9128       // Track and increment the index here.
9129       isInitList = true;
9130       InitFieldIndex.push_back(0);
9131       for (auto Child : InitList->children()) {
9132         CheckExpr(cast<Expr>(Child));
9133         ++InitFieldIndex.back();
9134       }
9135       InitFieldIndex.pop_back();
9136     }
9137 
9138     // Returns true if MemberExpr is checked and no futher checking is needed.
9139     // Returns false if additional checking is required.
CheckInitListMemberExpr(MemberExpr * E,bool CheckReference)9140     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9141       llvm::SmallVector<FieldDecl*, 4> Fields;
9142       Expr *Base = E;
9143       bool ReferenceField = false;
9144 
9145       // Get the field memebers used.
9146       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9147         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9148         if (!FD)
9149           return false;
9150         Fields.push_back(FD);
9151         if (FD->getType()->isReferenceType())
9152           ReferenceField = true;
9153         Base = ME->getBase()->IgnoreParenImpCasts();
9154       }
9155 
9156       // Keep checking only if the base Decl is the same.
9157       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9158       if (!DRE || DRE->getDecl() != OrigDecl)
9159         return false;
9160 
9161       // A reference field can be bound to an unininitialized field.
9162       if (CheckReference && !ReferenceField)
9163         return true;
9164 
9165       // Convert FieldDecls to their index number.
9166       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9167       for (const FieldDecl *I : llvm::reverse(Fields))
9168         UsedFieldIndex.push_back(I->getFieldIndex());
9169 
9170       // See if a warning is needed by checking the first difference in index
9171       // numbers.  If field being used has index less than the field being
9172       // initialized, then the use is safe.
9173       for (auto UsedIter = UsedFieldIndex.begin(),
9174                 UsedEnd = UsedFieldIndex.end(),
9175                 OrigIter = InitFieldIndex.begin(),
9176                 OrigEnd = InitFieldIndex.end();
9177            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9178         if (*UsedIter < *OrigIter)
9179           return true;
9180         if (*UsedIter > *OrigIter)
9181           break;
9182       }
9183 
9184       // TODO: Add a different warning which will print the field names.
9185       HandleDeclRefExpr(DRE);
9186       return true;
9187     }
9188 
9189     // For most expressions, the cast is directly above the DeclRefExpr.
9190     // For conditional operators, the cast can be outside the conditional
9191     // operator if both expressions are DeclRefExpr's.
HandleValue(Expr * E)9192     void HandleValue(Expr *E) {
9193       E = E->IgnoreParens();
9194       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9195         HandleDeclRefExpr(DRE);
9196         return;
9197       }
9198 
9199       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9200         Visit(CO->getCond());
9201         HandleValue(CO->getTrueExpr());
9202         HandleValue(CO->getFalseExpr());
9203         return;
9204       }
9205 
9206       if (BinaryConditionalOperator *BCO =
9207               dyn_cast<BinaryConditionalOperator>(E)) {
9208         Visit(BCO->getCond());
9209         HandleValue(BCO->getFalseExpr());
9210         return;
9211       }
9212 
9213       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9214         HandleValue(OVE->getSourceExpr());
9215         return;
9216       }
9217 
9218       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9219         if (BO->getOpcode() == BO_Comma) {
9220           Visit(BO->getLHS());
9221           HandleValue(BO->getRHS());
9222           return;
9223         }
9224       }
9225 
9226       if (isa<MemberExpr>(E)) {
9227         if (isInitList) {
9228           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9229                                       false /*CheckReference*/))
9230             return;
9231         }
9232 
9233         Expr *Base = E->IgnoreParenImpCasts();
9234         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9235           // Check for static member variables and don't warn on them.
9236           if (!isa<FieldDecl>(ME->getMemberDecl()))
9237             return;
9238           Base = ME->getBase()->IgnoreParenImpCasts();
9239         }
9240         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9241           HandleDeclRefExpr(DRE);
9242         return;
9243       }
9244 
9245       Visit(E);
9246     }
9247 
9248     // Reference types not handled in HandleValue are handled here since all
9249     // uses of references are bad, not just r-value uses.
VisitDeclRefExpr(DeclRefExpr * E)9250     void VisitDeclRefExpr(DeclRefExpr *E) {
9251       if (isReferenceType)
9252         HandleDeclRefExpr(E);
9253     }
9254 
VisitImplicitCastExpr(ImplicitCastExpr * E)9255     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9256       if (E->getCastKind() == CK_LValueToRValue) {
9257         HandleValue(E->getSubExpr());
9258         return;
9259       }
9260 
9261       Inherited::VisitImplicitCastExpr(E);
9262     }
9263 
VisitMemberExpr(MemberExpr * E)9264     void VisitMemberExpr(MemberExpr *E) {
9265       if (isInitList) {
9266         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9267           return;
9268       }
9269 
9270       // Don't warn on arrays since they can be treated as pointers.
9271       if (E->getType()->canDecayToPointerType()) return;
9272 
9273       // Warn when a non-static method call is followed by non-static member
9274       // field accesses, which is followed by a DeclRefExpr.
9275       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9276       bool Warn = (MD && !MD->isStatic());
9277       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9278       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9279         if (!isa<FieldDecl>(ME->getMemberDecl()))
9280           Warn = false;
9281         Base = ME->getBase()->IgnoreParenImpCasts();
9282       }
9283 
9284       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9285         if (Warn)
9286           HandleDeclRefExpr(DRE);
9287         return;
9288       }
9289 
9290       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9291       // Visit that expression.
9292       Visit(Base);
9293     }
9294 
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)9295     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9296       Expr *Callee = E->getCallee();
9297 
9298       if (isa<UnresolvedLookupExpr>(Callee))
9299         return Inherited::VisitCXXOperatorCallExpr(E);
9300 
9301       Visit(Callee);
9302       for (auto Arg: E->arguments())
9303         HandleValue(Arg->IgnoreParenImpCasts());
9304     }
9305 
VisitUnaryOperator(UnaryOperator * E)9306     void VisitUnaryOperator(UnaryOperator *E) {
9307       // For POD record types, addresses of its own members are well-defined.
9308       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9309           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9310         if (!isPODType)
9311           HandleValue(E->getSubExpr());
9312         return;
9313       }
9314 
9315       if (E->isIncrementDecrementOp()) {
9316         HandleValue(E->getSubExpr());
9317         return;
9318       }
9319 
9320       Inherited::VisitUnaryOperator(E);
9321     }
9322 
VisitObjCMessageExpr(ObjCMessageExpr * E)9323     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9324 
VisitCXXConstructExpr(CXXConstructExpr * E)9325     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9326       if (E->getConstructor()->isCopyConstructor()) {
9327         Expr *ArgExpr = E->getArg(0);
9328         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9329           if (ILE->getNumInits() == 1)
9330             ArgExpr = ILE->getInit(0);
9331         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9332           if (ICE->getCastKind() == CK_NoOp)
9333             ArgExpr = ICE->getSubExpr();
9334         HandleValue(ArgExpr);
9335         return;
9336       }
9337       Inherited::VisitCXXConstructExpr(E);
9338     }
9339 
VisitCallExpr(CallExpr * E)9340     void VisitCallExpr(CallExpr *E) {
9341       // Treat std::move as a use.
9342       if (E->getNumArgs() == 1) {
9343         if (FunctionDecl *FD = E->getDirectCallee()) {
9344           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9345               FD->getIdentifier()->isStr("move")) {
9346             HandleValue(E->getArg(0));
9347             return;
9348           }
9349         }
9350       }
9351 
9352       Inherited::VisitCallExpr(E);
9353     }
9354 
VisitBinaryOperator(BinaryOperator * E)9355     void VisitBinaryOperator(BinaryOperator *E) {
9356       if (E->isCompoundAssignmentOp()) {
9357         HandleValue(E->getLHS());
9358         Visit(E->getRHS());
9359         return;
9360       }
9361 
9362       Inherited::VisitBinaryOperator(E);
9363     }
9364 
9365     // A custom visitor for BinaryConditionalOperator is needed because the
9366     // regular visitor would check the condition and true expression separately
9367     // but both point to the same place giving duplicate diagnostics.
VisitBinaryConditionalOperator(BinaryConditionalOperator * E)9368     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9369       Visit(E->getCond());
9370       Visit(E->getFalseExpr());
9371     }
9372 
HandleDeclRefExpr(DeclRefExpr * DRE)9373     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9374       Decl* ReferenceDecl = DRE->getDecl();
9375       if (OrigDecl != ReferenceDecl) return;
9376       unsigned diag;
9377       if (isReferenceType) {
9378         diag = diag::warn_uninit_self_reference_in_reference_init;
9379       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9380         diag = diag::warn_static_self_reference_in_init;
9381       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9382                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9383                  DRE->getDecl()->getType()->isRecordType()) {
9384         diag = diag::warn_uninit_self_reference_in_init;
9385       } else {
9386         // Local variables will be handled by the CFG analysis.
9387         return;
9388       }
9389 
9390       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9391                             S.PDiag(diag)
9392                               << DRE->getNameInfo().getName()
9393                               << OrigDecl->getLocation()
9394                               << DRE->getSourceRange());
9395     }
9396   };
9397 
9398   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
CheckSelfReference(Sema & S,Decl * OrigDecl,Expr * E,bool DirectInit)9399   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9400                                  bool DirectInit) {
9401     // Parameters arguments are occassionially constructed with itself,
9402     // for instance, in recursive functions.  Skip them.
9403     if (isa<ParmVarDecl>(OrigDecl))
9404       return;
9405 
9406     E = E->IgnoreParens();
9407 
9408     // Skip checking T a = a where T is not a record or reference type.
9409     // Doing so is a way to silence uninitialized warnings.
9410     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9411       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9412         if (ICE->getCastKind() == CK_LValueToRValue)
9413           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9414             if (DRE->getDecl() == OrigDecl)
9415               return;
9416 
9417     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9418   }
9419 } // end anonymous namespace
9420 
deduceVarTypeFromInitializer(VarDecl * VDecl,DeclarationName Name,QualType Type,TypeSourceInfo * TSI,SourceRange Range,bool DirectInit,Expr * Init)9421 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9422                                             DeclarationName Name, QualType Type,
9423                                             TypeSourceInfo *TSI,
9424                                             SourceRange Range, bool DirectInit,
9425                                             Expr *Init) {
9426   bool IsInitCapture = !VDecl;
9427   assert((!VDecl || !VDecl->isInitCapture()) &&
9428          "init captures are expected to be deduced prior to initialization");
9429 
9430   ArrayRef<Expr *> DeduceInits = Init;
9431   if (DirectInit) {
9432     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9433       DeduceInits = PL->exprs();
9434     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9435       DeduceInits = IL->inits();
9436   }
9437 
9438   // Deduction only works if we have exactly one source expression.
9439   if (DeduceInits.empty()) {
9440     // It isn't possible to write this directly, but it is possible to
9441     // end up in this situation with "auto x(some_pack...);"
9442     Diag(Init->getLocStart(), IsInitCapture
9443                                   ? diag::err_init_capture_no_expression
9444                                   : diag::err_auto_var_init_no_expression)
9445         << Name << Type << Range;
9446     return QualType();
9447   }
9448 
9449   if (DeduceInits.size() > 1) {
9450     Diag(DeduceInits[1]->getLocStart(),
9451          IsInitCapture ? diag::err_init_capture_multiple_expressions
9452                        : diag::err_auto_var_init_multiple_expressions)
9453         << Name << Type << Range;
9454     return QualType();
9455   }
9456 
9457   Expr *DeduceInit = DeduceInits[0];
9458   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9459     Diag(Init->getLocStart(), IsInitCapture
9460                                   ? diag::err_init_capture_paren_braces
9461                                   : diag::err_auto_var_init_paren_braces)
9462         << isa<InitListExpr>(Init) << Name << Type << Range;
9463     return QualType();
9464   }
9465 
9466   // Expressions default to 'id' when we're in a debugger.
9467   bool DefaultedAnyToId = false;
9468   if (getLangOpts().DebuggerCastResultToId &&
9469       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9470     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9471     if (Result.isInvalid()) {
9472       return QualType();
9473     }
9474     Init = Result.get();
9475     DefaultedAnyToId = true;
9476   }
9477 
9478   QualType DeducedType;
9479   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9480     if (!IsInitCapture)
9481       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9482     else if (isa<InitListExpr>(Init))
9483       Diag(Range.getBegin(),
9484            diag::err_init_capture_deduction_failure_from_init_list)
9485           << Name
9486           << (DeduceInit->getType().isNull() ? TSI->getType()
9487                                              : DeduceInit->getType())
9488           << DeduceInit->getSourceRange();
9489     else
9490       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9491           << Name << TSI->getType()
9492           << (DeduceInit->getType().isNull() ? TSI->getType()
9493                                              : DeduceInit->getType())
9494           << DeduceInit->getSourceRange();
9495   }
9496 
9497   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9498   // 'id' instead of a specific object type prevents most of our usual
9499   // checks.
9500   // We only want to warn outside of template instantiations, though:
9501   // inside a template, the 'id' could have come from a parameter.
9502   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9503       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9504     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9505     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9506   }
9507 
9508   return DeducedType;
9509 }
9510 
9511 /// AddInitializerToDecl - Adds the initializer Init to the
9512 /// declaration dcl. If DirectInit is true, this is C++ direct
9513 /// initialization rather than copy initialization.
AddInitializerToDecl(Decl * RealDecl,Expr * Init,bool DirectInit,bool TypeMayContainAuto)9514 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9515                                 bool DirectInit, bool TypeMayContainAuto) {
9516   // If there is no declaration, there was an error parsing it.  Just ignore
9517   // the initializer.
9518   if (!RealDecl || RealDecl->isInvalidDecl()) {
9519     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9520     return;
9521   }
9522 
9523   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9524     // Pure-specifiers are handled in ActOnPureSpecifier.
9525     Diag(Method->getLocation(), diag::err_member_function_initialization)
9526       << Method->getDeclName() << Init->getSourceRange();
9527     Method->setInvalidDecl();
9528     return;
9529   }
9530 
9531   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9532   if (!VDecl) {
9533     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9534     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9535     RealDecl->setInvalidDecl();
9536     return;
9537   }
9538 
9539   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9540   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9541     // Attempt typo correction early so that the type of the init expression can
9542     // be deduced based on the chosen correction if the original init contains a
9543     // TypoExpr.
9544     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9545     if (!Res.isUsable()) {
9546       RealDecl->setInvalidDecl();
9547       return;
9548     }
9549     Init = Res.get();
9550 
9551     QualType DeducedType = deduceVarTypeFromInitializer(
9552         VDecl, VDecl->getDeclName(), VDecl->getType(),
9553         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9554     if (DeducedType.isNull()) {
9555       RealDecl->setInvalidDecl();
9556       return;
9557     }
9558 
9559     VDecl->setType(DeducedType);
9560     assert(VDecl->isLinkageValid());
9561 
9562     // In ARC, infer lifetime.
9563     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9564       VDecl->setInvalidDecl();
9565 
9566     // If this is a redeclaration, check that the type we just deduced matches
9567     // the previously declared type.
9568     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9569       // We never need to merge the type, because we cannot form an incomplete
9570       // array of auto, nor deduce such a type.
9571       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9572     }
9573 
9574     // Check the deduced type is valid for a variable declaration.
9575     CheckVariableDeclarationType(VDecl);
9576     if (VDecl->isInvalidDecl())
9577       return;
9578   }
9579 
9580   // dllimport cannot be used on variable definitions.
9581   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9582     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9583     VDecl->setInvalidDecl();
9584     return;
9585   }
9586 
9587   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9588     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9589     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9590     VDecl->setInvalidDecl();
9591     return;
9592   }
9593 
9594   if (!VDecl->getType()->isDependentType()) {
9595     // A definition must end up with a complete type, which means it must be
9596     // complete with the restriction that an array type might be completed by
9597     // the initializer; note that later code assumes this restriction.
9598     QualType BaseDeclType = VDecl->getType();
9599     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9600       BaseDeclType = Array->getElementType();
9601     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9602                             diag::err_typecheck_decl_incomplete_type)) {
9603       RealDecl->setInvalidDecl();
9604       return;
9605     }
9606 
9607     // The variable can not have an abstract class type.
9608     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9609                                diag::err_abstract_type_in_decl,
9610                                AbstractVariableType))
9611       VDecl->setInvalidDecl();
9612   }
9613 
9614   VarDecl *Def;
9615   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9616     NamedDecl *Hidden = nullptr;
9617     if (!hasVisibleDefinition(Def, &Hidden) &&
9618         (VDecl->getFormalLinkage() == InternalLinkage ||
9619          VDecl->getDescribedVarTemplate() ||
9620          VDecl->getNumTemplateParameterLists() ||
9621          VDecl->getDeclContext()->isDependentContext())) {
9622       // The previous definition is hidden, and multiple definitions are
9623       // permitted (in separate TUs). Form another definition of it.
9624     } else {
9625       Diag(VDecl->getLocation(), diag::err_redefinition)
9626         << VDecl->getDeclName();
9627       Diag(Def->getLocation(), diag::note_previous_definition);
9628       VDecl->setInvalidDecl();
9629       return;
9630     }
9631   }
9632 
9633   if (getLangOpts().CPlusPlus) {
9634     // C++ [class.static.data]p4
9635     //   If a static data member is of const integral or const
9636     //   enumeration type, its declaration in the class definition can
9637     //   specify a constant-initializer which shall be an integral
9638     //   constant expression (5.19). In that case, the member can appear
9639     //   in integral constant expressions. The member shall still be
9640     //   defined in a namespace scope if it is used in the program and the
9641     //   namespace scope definition shall not contain an initializer.
9642     //
9643     // We already performed a redefinition check above, but for static
9644     // data members we also need to check whether there was an in-class
9645     // declaration with an initializer.
9646     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9647       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9648           << VDecl->getDeclName();
9649       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9650            diag::note_previous_initializer)
9651           << 0;
9652       return;
9653     }
9654 
9655     if (VDecl->hasLocalStorage())
9656       getCurFunction()->setHasBranchProtectedScope();
9657 
9658     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9659       VDecl->setInvalidDecl();
9660       return;
9661     }
9662   }
9663 
9664   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9665   // a kernel function cannot be initialized."
9666   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9667     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9668     VDecl->setInvalidDecl();
9669     return;
9670   }
9671 
9672   // Get the decls type and save a reference for later, since
9673   // CheckInitializerTypes may change it.
9674   QualType DclT = VDecl->getType(), SavT = DclT;
9675 
9676   // Expressions default to 'id' when we're in a debugger
9677   // and we are assigning it to a variable of Objective-C pointer type.
9678   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9679       Init->getType() == Context.UnknownAnyTy) {
9680     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9681     if (Result.isInvalid()) {
9682       VDecl->setInvalidDecl();
9683       return;
9684     }
9685     Init = Result.get();
9686   }
9687 
9688   // Perform the initialization.
9689   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9690   if (!VDecl->isInvalidDecl()) {
9691     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9692     InitializationKind Kind =
9693         DirectInit
9694             ? CXXDirectInit
9695                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9696                                                      Init->getLocStart(),
9697                                                      Init->getLocEnd())
9698                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9699             : InitializationKind::CreateCopy(VDecl->getLocation(),
9700                                              Init->getLocStart());
9701 
9702     MultiExprArg Args = Init;
9703     if (CXXDirectInit)
9704       Args = MultiExprArg(CXXDirectInit->getExprs(),
9705                           CXXDirectInit->getNumExprs());
9706 
9707     // Try to correct any TypoExprs in the initialization arguments.
9708     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9709       ExprResult Res = CorrectDelayedTyposInExpr(
9710           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9711             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9712             return Init.Failed() ? ExprError() : E;
9713           });
9714       if (Res.isInvalid()) {
9715         VDecl->setInvalidDecl();
9716       } else if (Res.get() != Args[Idx]) {
9717         Args[Idx] = Res.get();
9718       }
9719     }
9720     if (VDecl->isInvalidDecl())
9721       return;
9722 
9723     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9724                                    /*TopLevelOfInitList=*/false,
9725                                    /*TreatUnavailableAsInvalid=*/false);
9726     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9727     if (Result.isInvalid()) {
9728       VDecl->setInvalidDecl();
9729       return;
9730     }
9731 
9732     Init = Result.getAs<Expr>();
9733   }
9734 
9735   // Check for self-references within variable initializers.
9736   // Variables declared within a function/method body (except for references)
9737   // are handled by a dataflow analysis.
9738   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9739       VDecl->getType()->isReferenceType()) {
9740     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9741   }
9742 
9743   // If the type changed, it means we had an incomplete type that was
9744   // completed by the initializer. For example:
9745   //   int ary[] = { 1, 3, 5 };
9746   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9747   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9748     VDecl->setType(DclT);
9749 
9750   if (!VDecl->isInvalidDecl()) {
9751     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9752 
9753     if (VDecl->hasAttr<BlocksAttr>())
9754       checkRetainCycles(VDecl, Init);
9755 
9756     // It is safe to assign a weak reference into a strong variable.
9757     // Although this code can still have problems:
9758     //   id x = self.weakProp;
9759     //   id y = self.weakProp;
9760     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9761     // paths through the function. This should be revisited if
9762     // -Wrepeated-use-of-weak is made flow-sensitive.
9763     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9764         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9765                          Init->getLocStart()))
9766       getCurFunction()->markSafeWeakUse(Init);
9767   }
9768 
9769   // The initialization is usually a full-expression.
9770   //
9771   // FIXME: If this is a braced initialization of an aggregate, it is not
9772   // an expression, and each individual field initializer is a separate
9773   // full-expression. For instance, in:
9774   //
9775   //   struct Temp { ~Temp(); };
9776   //   struct S { S(Temp); };
9777   //   struct T { S a, b; } t = { Temp(), Temp() }
9778   //
9779   // we should destroy the first Temp before constructing the second.
9780   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9781                                           false,
9782                                           VDecl->isConstexpr());
9783   if (Result.isInvalid()) {
9784     VDecl->setInvalidDecl();
9785     return;
9786   }
9787   Init = Result.get();
9788 
9789   // Attach the initializer to the decl.
9790   VDecl->setInit(Init);
9791 
9792   if (VDecl->isLocalVarDecl()) {
9793     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9794     // static storage duration shall be constant expressions or string literals.
9795     // C++ does not have this restriction.
9796     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9797       const Expr *Culprit;
9798       if (VDecl->getStorageClass() == SC_Static)
9799         CheckForConstantInitializer(Init, DclT);
9800       // C89 is stricter than C99 for non-static aggregate types.
9801       // C89 6.5.7p3: All the expressions [...] in an initializer list
9802       // for an object that has aggregate or union type shall be
9803       // constant expressions.
9804       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9805                isa<InitListExpr>(Init) &&
9806                !Init->isConstantInitializer(Context, false, &Culprit))
9807         Diag(Culprit->getExprLoc(),
9808              diag::ext_aggregate_init_not_constant)
9809           << Culprit->getSourceRange();
9810     }
9811   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
9812              VDecl->getLexicalDeclContext()->isRecord()) {
9813     // This is an in-class initialization for a static data member, e.g.,
9814     //
9815     // struct S {
9816     //   static const int value = 17;
9817     // };
9818 
9819     // C++ [class.mem]p4:
9820     //   A member-declarator can contain a constant-initializer only
9821     //   if it declares a static member (9.4) of const integral or
9822     //   const enumeration type, see 9.4.2.
9823     //
9824     // C++11 [class.static.data]p3:
9825     //   If a non-volatile non-inline const static data member is of integral
9826     //   or enumeration type, its declaration in the class definition can
9827     //   specify a brace-or-equal-initializer in which every initalizer-clause
9828     //   that is an assignment-expression is a constant expression. A static
9829     //   data member of literal type can be declared in the class definition
9830     //   with the constexpr specifier; if so, its declaration shall specify a
9831     //   brace-or-equal-initializer in which every initializer-clause that is
9832     //   an assignment-expression is a constant expression.
9833 
9834     // Do nothing on dependent types.
9835     if (DclT->isDependentType()) {
9836 
9837     // Allow any 'static constexpr' members, whether or not they are of literal
9838     // type. We separately check that every constexpr variable is of literal
9839     // type.
9840     } else if (VDecl->isConstexpr()) {
9841 
9842     // Require constness.
9843     } else if (!DclT.isConstQualified()) {
9844       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9845         << Init->getSourceRange();
9846       VDecl->setInvalidDecl();
9847 
9848     // We allow integer constant expressions in all cases.
9849     } else if (DclT->isIntegralOrEnumerationType()) {
9850       // Check whether the expression is a constant expression.
9851       SourceLocation Loc;
9852       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9853         // In C++11, a non-constexpr const static data member with an
9854         // in-class initializer cannot be volatile.
9855         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9856       else if (Init->isValueDependent())
9857         ; // Nothing to check.
9858       else if (Init->isIntegerConstantExpr(Context, &Loc))
9859         ; // Ok, it's an ICE!
9860       else if (Init->isEvaluatable(Context)) {
9861         // If we can constant fold the initializer through heroics, accept it,
9862         // but report this as a use of an extension for -pedantic.
9863         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9864           << Init->getSourceRange();
9865       } else {
9866         // Otherwise, this is some crazy unknown case.  Report the issue at the
9867         // location provided by the isIntegerConstantExpr failed check.
9868         Diag(Loc, diag::err_in_class_initializer_non_constant)
9869           << Init->getSourceRange();
9870         VDecl->setInvalidDecl();
9871       }
9872 
9873     // We allow foldable floating-point constants as an extension.
9874     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9875       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9876       // it anyway and provide a fixit to add the 'constexpr'.
9877       if (getLangOpts().CPlusPlus11) {
9878         Diag(VDecl->getLocation(),
9879              diag::ext_in_class_initializer_float_type_cxx11)
9880             << DclT << Init->getSourceRange();
9881         Diag(VDecl->getLocStart(),
9882              diag::note_in_class_initializer_float_type_cxx11)
9883             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9884       } else {
9885         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9886           << DclT << Init->getSourceRange();
9887 
9888         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9889           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9890             << Init->getSourceRange();
9891           VDecl->setInvalidDecl();
9892         }
9893       }
9894 
9895     // Suggest adding 'constexpr' in C++11 for literal types.
9896     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9897       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9898         << DclT << Init->getSourceRange()
9899         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9900       VDecl->setConstexpr(true);
9901 
9902     } else {
9903       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9904         << DclT << Init->getSourceRange();
9905       VDecl->setInvalidDecl();
9906     }
9907   } else if (VDecl->isFileVarDecl()) {
9908     if (VDecl->getStorageClass() == SC_Extern &&
9909         (!getLangOpts().CPlusPlus ||
9910          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9911            VDecl->isExternC())) &&
9912         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9913       Diag(VDecl->getLocation(), diag::warn_extern_init);
9914 
9915     // C99 6.7.8p4. All file scoped initializers need to be constant.
9916     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9917       CheckForConstantInitializer(Init, DclT);
9918   }
9919 
9920   // We will represent direct-initialization similarly to copy-initialization:
9921   //    int x(1);  -as-> int x = 1;
9922   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9923   //
9924   // Clients that want to distinguish between the two forms, can check for
9925   // direct initializer using VarDecl::getInitStyle().
9926   // A major benefit is that clients that don't particularly care about which
9927   // exactly form was it (like the CodeGen) can handle both cases without
9928   // special case code.
9929 
9930   // C++ 8.5p11:
9931   // The form of initialization (using parentheses or '=') is generally
9932   // insignificant, but does matter when the entity being initialized has a
9933   // class type.
9934   if (CXXDirectInit) {
9935     assert(DirectInit && "Call-style initializer must be direct init.");
9936     VDecl->setInitStyle(VarDecl::CallInit);
9937   } else if (DirectInit) {
9938     // This must be list-initialization. No other way is direct-initialization.
9939     VDecl->setInitStyle(VarDecl::ListInit);
9940   }
9941 
9942   CheckCompleteVariableDeclaration(VDecl);
9943 }
9944 
9945 /// ActOnInitializerError - Given that there was an error parsing an
9946 /// initializer for the given declaration, try to return to some form
9947 /// of sanity.
ActOnInitializerError(Decl * D)9948 void Sema::ActOnInitializerError(Decl *D) {
9949   // Our main concern here is re-establishing invariants like "a
9950   // variable's type is either dependent or complete".
9951   if (!D || D->isInvalidDecl()) return;
9952 
9953   VarDecl *VD = dyn_cast<VarDecl>(D);
9954   if (!VD) return;
9955 
9956   // Auto types are meaningless if we can't make sense of the initializer.
9957   if (ParsingInitForAutoVars.count(D)) {
9958     D->setInvalidDecl();
9959     return;
9960   }
9961 
9962   QualType Ty = VD->getType();
9963   if (Ty->isDependentType()) return;
9964 
9965   // Require a complete type.
9966   if (RequireCompleteType(VD->getLocation(),
9967                           Context.getBaseElementType(Ty),
9968                           diag::err_typecheck_decl_incomplete_type)) {
9969     VD->setInvalidDecl();
9970     return;
9971   }
9972 
9973   // Require a non-abstract type.
9974   if (RequireNonAbstractType(VD->getLocation(), Ty,
9975                              diag::err_abstract_type_in_decl,
9976                              AbstractVariableType)) {
9977     VD->setInvalidDecl();
9978     return;
9979   }
9980 
9981   // Don't bother complaining about constructors or destructors,
9982   // though.
9983 }
9984 
ActOnUninitializedDecl(Decl * RealDecl,bool TypeMayContainAuto)9985 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9986                                   bool TypeMayContainAuto) {
9987   // If there is no declaration, there was an error parsing it. Just ignore it.
9988   if (!RealDecl)
9989     return;
9990 
9991   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9992     QualType Type = Var->getType();
9993 
9994     // C++11 [dcl.spec.auto]p3
9995     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9996       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9997         << Var->getDeclName() << Type;
9998       Var->setInvalidDecl();
9999       return;
10000     }
10001 
10002     // C++11 [class.static.data]p3: A static data member can be declared with
10003     // the constexpr specifier; if so, its declaration shall specify
10004     // a brace-or-equal-initializer.
10005     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10006     // the definition of a variable [...] or the declaration of a static data
10007     // member.
10008     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
10009       if (Var->isStaticDataMember()) {
10010         // C++1z removes the relevant rule; the in-class declaration is always
10011         // a definition there.
10012         if (!getLangOpts().CPlusPlus1z) {
10013           Diag(Var->getLocation(),
10014                diag::err_constexpr_static_mem_var_requires_init)
10015             << Var->getDeclName();
10016           Var->setInvalidDecl();
10017           return;
10018         }
10019       } else {
10020         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10021         Var->setInvalidDecl();
10022         return;
10023       }
10024     }
10025 
10026     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10027     // definition having the concept specifier is called a variable concept. A
10028     // concept definition refers to [...] a variable concept and its initializer.
10029     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10030       if (VTD->isConcept()) {
10031         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10032         Var->setInvalidDecl();
10033         return;
10034       }
10035     }
10036 
10037     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10038     // be initialized.
10039     if (!Var->isInvalidDecl() &&
10040         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10041         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10042       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10043       Var->setInvalidDecl();
10044       return;
10045     }
10046 
10047     switch (Var->isThisDeclarationADefinition()) {
10048     case VarDecl::Definition:
10049       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10050         break;
10051 
10052       // We have an out-of-line definition of a static data member
10053       // that has an in-class initializer, so we type-check this like
10054       // a declaration.
10055       //
10056       // Fall through
10057 
10058     case VarDecl::DeclarationOnly:
10059       // It's only a declaration.
10060 
10061       // Block scope. C99 6.7p7: If an identifier for an object is
10062       // declared with no linkage (C99 6.2.2p6), the type for the
10063       // object shall be complete.
10064       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10065           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10066           RequireCompleteType(Var->getLocation(), Type,
10067                               diag::err_typecheck_decl_incomplete_type))
10068         Var->setInvalidDecl();
10069 
10070       // Make sure that the type is not abstract.
10071       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10072           RequireNonAbstractType(Var->getLocation(), Type,
10073                                  diag::err_abstract_type_in_decl,
10074                                  AbstractVariableType))
10075         Var->setInvalidDecl();
10076       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10077           Var->getStorageClass() == SC_PrivateExtern) {
10078         Diag(Var->getLocation(), diag::warn_private_extern);
10079         Diag(Var->getLocation(), diag::note_private_extern);
10080       }
10081 
10082       return;
10083 
10084     case VarDecl::TentativeDefinition:
10085       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10086       // object that has file scope without an initializer, and without a
10087       // storage-class specifier or with the storage-class specifier "static",
10088       // constitutes a tentative definition. Note: A tentative definition with
10089       // external linkage is valid (C99 6.2.2p5).
10090       if (!Var->isInvalidDecl()) {
10091         if (const IncompleteArrayType *ArrayT
10092                                     = Context.getAsIncompleteArrayType(Type)) {
10093           if (RequireCompleteType(Var->getLocation(),
10094                                   ArrayT->getElementType(),
10095                                   diag::err_illegal_decl_array_incomplete_type))
10096             Var->setInvalidDecl();
10097         } else if (Var->getStorageClass() == SC_Static) {
10098           // C99 6.9.2p3: If the declaration of an identifier for an object is
10099           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10100           // declared type shall not be an incomplete type.
10101           // NOTE: code such as the following
10102           //     static struct s;
10103           //     struct s { int a; };
10104           // is accepted by gcc. Hence here we issue a warning instead of
10105           // an error and we do not invalidate the static declaration.
10106           // NOTE: to avoid multiple warnings, only check the first declaration.
10107           if (Var->isFirstDecl())
10108             RequireCompleteType(Var->getLocation(), Type,
10109                                 diag::ext_typecheck_decl_incomplete_type);
10110         }
10111       }
10112 
10113       // Record the tentative definition; we're done.
10114       if (!Var->isInvalidDecl())
10115         TentativeDefinitions.push_back(Var);
10116       return;
10117     }
10118 
10119     // Provide a specific diagnostic for uninitialized variable
10120     // definitions with incomplete array type.
10121     if (Type->isIncompleteArrayType()) {
10122       Diag(Var->getLocation(),
10123            diag::err_typecheck_incomplete_array_needs_initializer);
10124       Var->setInvalidDecl();
10125       return;
10126     }
10127 
10128     // Provide a specific diagnostic for uninitialized variable
10129     // definitions with reference type.
10130     if (Type->isReferenceType()) {
10131       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10132         << Var->getDeclName()
10133         << SourceRange(Var->getLocation(), Var->getLocation());
10134       Var->setInvalidDecl();
10135       return;
10136     }
10137 
10138     // Do not attempt to type-check the default initializer for a
10139     // variable with dependent type.
10140     if (Type->isDependentType())
10141       return;
10142 
10143     if (Var->isInvalidDecl())
10144       return;
10145 
10146     if (!Var->hasAttr<AliasAttr>()) {
10147       if (RequireCompleteType(Var->getLocation(),
10148                               Context.getBaseElementType(Type),
10149                               diag::err_typecheck_decl_incomplete_type)) {
10150         Var->setInvalidDecl();
10151         return;
10152       }
10153     } else {
10154       return;
10155     }
10156 
10157     // The variable can not have an abstract class type.
10158     if (RequireNonAbstractType(Var->getLocation(), Type,
10159                                diag::err_abstract_type_in_decl,
10160                                AbstractVariableType)) {
10161       Var->setInvalidDecl();
10162       return;
10163     }
10164 
10165     // Check for jumps past the implicit initializer.  C++0x
10166     // clarifies that this applies to a "variable with automatic
10167     // storage duration", not a "local variable".
10168     // C++11 [stmt.dcl]p3
10169     //   A program that jumps from a point where a variable with automatic
10170     //   storage duration is not in scope to a point where it is in scope is
10171     //   ill-formed unless the variable has scalar type, class type with a
10172     //   trivial default constructor and a trivial destructor, a cv-qualified
10173     //   version of one of these types, or an array of one of the preceding
10174     //   types and is declared without an initializer.
10175     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10176       if (const RecordType *Record
10177             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10178         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10179         // Mark the function for further checking even if the looser rules of
10180         // C++11 do not require such checks, so that we can diagnose
10181         // incompatibilities with C++98.
10182         if (!CXXRecord->isPOD())
10183           getCurFunction()->setHasBranchProtectedScope();
10184       }
10185     }
10186 
10187     // C++03 [dcl.init]p9:
10188     //   If no initializer is specified for an object, and the
10189     //   object is of (possibly cv-qualified) non-POD class type (or
10190     //   array thereof), the object shall be default-initialized; if
10191     //   the object is of const-qualified type, the underlying class
10192     //   type shall have a user-declared default
10193     //   constructor. Otherwise, if no initializer is specified for
10194     //   a non- static object, the object and its subobjects, if
10195     //   any, have an indeterminate initial value); if the object
10196     //   or any of its subobjects are of const-qualified type, the
10197     //   program is ill-formed.
10198     // C++0x [dcl.init]p11:
10199     //   If no initializer is specified for an object, the object is
10200     //   default-initialized; [...].
10201     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10202     InitializationKind Kind
10203       = InitializationKind::CreateDefault(Var->getLocation());
10204 
10205     InitializationSequence InitSeq(*this, Entity, Kind, None);
10206     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10207     if (Init.isInvalid())
10208       Var->setInvalidDecl();
10209     else if (Init.get()) {
10210       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10211       // This is important for template substitution.
10212       Var->setInitStyle(VarDecl::CallInit);
10213     }
10214 
10215     CheckCompleteVariableDeclaration(Var);
10216   }
10217 }
10218 
ActOnCXXForRangeDecl(Decl * D)10219 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10220   // If there is no declaration, there was an error parsing it. Ignore it.
10221   if (!D)
10222     return;
10223 
10224   VarDecl *VD = dyn_cast<VarDecl>(D);
10225   if (!VD) {
10226     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10227     D->setInvalidDecl();
10228     return;
10229   }
10230 
10231   VD->setCXXForRangeDecl(true);
10232 
10233   // for-range-declaration cannot be given a storage class specifier.
10234   int Error = -1;
10235   switch (VD->getStorageClass()) {
10236   case SC_None:
10237     break;
10238   case SC_Extern:
10239     Error = 0;
10240     break;
10241   case SC_Static:
10242     Error = 1;
10243     break;
10244   case SC_PrivateExtern:
10245     Error = 2;
10246     break;
10247   case SC_Auto:
10248     Error = 3;
10249     break;
10250   case SC_Register:
10251     Error = 4;
10252     break;
10253   }
10254   if (Error != -1) {
10255     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10256       << VD->getDeclName() << Error;
10257     D->setInvalidDecl();
10258   }
10259 }
10260 
10261 StmtResult
ActOnCXXForRangeIdentifier(Scope * S,SourceLocation IdentLoc,IdentifierInfo * Ident,ParsedAttributes & Attrs,SourceLocation AttrEnd)10262 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10263                                  IdentifierInfo *Ident,
10264                                  ParsedAttributes &Attrs,
10265                                  SourceLocation AttrEnd) {
10266   // C++1y [stmt.iter]p1:
10267   //   A range-based for statement of the form
10268   //      for ( for-range-identifier : for-range-initializer ) statement
10269   //   is equivalent to
10270   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10271   DeclSpec DS(Attrs.getPool().getFactory());
10272 
10273   const char *PrevSpec;
10274   unsigned DiagID;
10275   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10276                      getPrintingPolicy());
10277 
10278   Declarator D(DS, Declarator::ForContext);
10279   D.SetIdentifier(Ident, IdentLoc);
10280   D.takeAttributes(Attrs, AttrEnd);
10281 
10282   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10283   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10284                 EmptyAttrs, IdentLoc);
10285   Decl *Var = ActOnDeclarator(S, D);
10286   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10287   FinalizeDeclaration(Var);
10288   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10289                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10290 }
10291 
CheckCompleteVariableDeclaration(VarDecl * var)10292 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10293   if (var->isInvalidDecl()) return;
10294 
10295   if (getLangOpts().OpenCL) {
10296     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10297     // initialiser
10298     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10299         !var->hasInit()) {
10300       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10301           << 1 /*Init*/;
10302       var->setInvalidDecl();
10303       return;
10304     }
10305   }
10306 
10307   // In Objective-C, don't allow jumps past the implicit initialization of a
10308   // local retaining variable.
10309   if (getLangOpts().ObjC1 &&
10310       var->hasLocalStorage()) {
10311     switch (var->getType().getObjCLifetime()) {
10312     case Qualifiers::OCL_None:
10313     case Qualifiers::OCL_ExplicitNone:
10314     case Qualifiers::OCL_Autoreleasing:
10315       break;
10316 
10317     case Qualifiers::OCL_Weak:
10318     case Qualifiers::OCL_Strong:
10319       getCurFunction()->setHasBranchProtectedScope();
10320       break;
10321     }
10322   }
10323 
10324   // Warn about externally-visible variables being defined without a
10325   // prior declaration.  We only want to do this for global
10326   // declarations, but we also specifically need to avoid doing it for
10327   // class members because the linkage of an anonymous class can
10328   // change if it's later given a typedef name.
10329   if (var->isThisDeclarationADefinition() &&
10330       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10331       var->isExternallyVisible() && var->hasLinkage() &&
10332       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10333                                   var->getLocation())) {
10334     // Find a previous declaration that's not a definition.
10335     VarDecl *prev = var->getPreviousDecl();
10336     while (prev && prev->isThisDeclarationADefinition())
10337       prev = prev->getPreviousDecl();
10338 
10339     if (!prev)
10340       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10341   }
10342 
10343   if (var->getTLSKind() == VarDecl::TLS_Static) {
10344     const Expr *Culprit;
10345     if (var->getType().isDestructedType()) {
10346       // GNU C++98 edits for __thread, [basic.start.term]p3:
10347       //   The type of an object with thread storage duration shall not
10348       //   have a non-trivial destructor.
10349       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10350       if (getLangOpts().CPlusPlus11)
10351         Diag(var->getLocation(), diag::note_use_thread_local);
10352     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10353                !var->getInit()->isConstantInitializer(
10354                    Context, var->getType()->isReferenceType(), &Culprit)) {
10355       // GNU C++98 edits for __thread, [basic.start.init]p4:
10356       //   An object of thread storage duration shall not require dynamic
10357       //   initialization.
10358       // FIXME: Need strict checking here.
10359       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10360         << Culprit->getSourceRange();
10361       if (getLangOpts().CPlusPlus11)
10362         Diag(var->getLocation(), diag::note_use_thread_local);
10363     }
10364   }
10365 
10366   // Apply section attributes and pragmas to global variables.
10367   bool GlobalStorage = var->hasGlobalStorage();
10368   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10369       ActiveTemplateInstantiations.empty()) {
10370     PragmaStack<StringLiteral *> *Stack = nullptr;
10371     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10372     if (var->getType().isConstQualified())
10373       Stack = &ConstSegStack;
10374     else if (!var->getInit()) {
10375       Stack = &BSSSegStack;
10376       SectionFlags |= ASTContext::PSF_Write;
10377     } else {
10378       Stack = &DataSegStack;
10379       SectionFlags |= ASTContext::PSF_Write;
10380     }
10381     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10382       var->addAttr(SectionAttr::CreateImplicit(
10383           Context, SectionAttr::Declspec_allocate,
10384           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10385     }
10386     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10387       if (UnifySection(SA->getName(), SectionFlags, var))
10388         var->dropAttr<SectionAttr>();
10389 
10390     // Apply the init_seg attribute if this has an initializer.  If the
10391     // initializer turns out to not be dynamic, we'll end up ignoring this
10392     // attribute.
10393     if (CurInitSeg && var->getInit())
10394       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10395                                                CurInitSegLoc));
10396   }
10397 
10398   // All the following checks are C++ only.
10399   if (!getLangOpts().CPlusPlus) return;
10400 
10401   QualType type = var->getType();
10402   if (type->isDependentType()) return;
10403 
10404   // __block variables might require us to capture a copy-initializer.
10405   if (var->hasAttr<BlocksAttr>()) {
10406     // It's currently invalid to ever have a __block variable with an
10407     // array type; should we diagnose that here?
10408 
10409     // Regardless, we don't want to ignore array nesting when
10410     // constructing this copy.
10411     if (type->isStructureOrClassType()) {
10412       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10413       SourceLocation poi = var->getLocation();
10414       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10415       ExprResult result
10416         = PerformMoveOrCopyInitialization(
10417             InitializedEntity::InitializeBlock(poi, type, false),
10418             var, var->getType(), varRef, /*AllowNRVO=*/true);
10419       if (!result.isInvalid()) {
10420         result = MaybeCreateExprWithCleanups(result);
10421         Expr *init = result.getAs<Expr>();
10422         Context.setBlockVarCopyInits(var, init);
10423       }
10424     }
10425   }
10426 
10427   Expr *Init = var->getInit();
10428   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10429   QualType baseType = Context.getBaseElementType(type);
10430 
10431   if (!var->getDeclContext()->isDependentContext() &&
10432       Init && !Init->isValueDependent()) {
10433     if (IsGlobal && !var->isConstexpr() &&
10434         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10435                                     var->getLocation())) {
10436       // Warn about globals which don't have a constant initializer.  Don't
10437       // warn about globals with a non-trivial destructor because we already
10438       // warned about them.
10439       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10440       if (!(RD && !RD->hasTrivialDestructor()) &&
10441           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10442         Diag(var->getLocation(), diag::warn_global_constructor)
10443           << Init->getSourceRange();
10444     }
10445 
10446     if (var->isConstexpr()) {
10447       SmallVector<PartialDiagnosticAt, 8> Notes;
10448       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10449         SourceLocation DiagLoc = var->getLocation();
10450         // If the note doesn't add any useful information other than a source
10451         // location, fold it into the primary diagnostic.
10452         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10453               diag::note_invalid_subexpr_in_const_expr) {
10454           DiagLoc = Notes[0].first;
10455           Notes.clear();
10456         }
10457         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10458           << var << Init->getSourceRange();
10459         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10460           Diag(Notes[I].first, Notes[I].second);
10461       }
10462     } else if (var->isUsableInConstantExpressions(Context)) {
10463       // Check whether the initializer of a const variable of integral or
10464       // enumeration type is an ICE now, since we can't tell whether it was
10465       // initialized by a constant expression if we check later.
10466       var->checkInitIsICE();
10467     }
10468   }
10469 
10470   // Require the destructor.
10471   if (const RecordType *recordType = baseType->getAs<RecordType>())
10472     FinalizeVarWithDestructor(var, recordType);
10473 }
10474 
10475 /// \brief Determines if a variable's alignment is dependent.
hasDependentAlignment(VarDecl * VD)10476 static bool hasDependentAlignment(VarDecl *VD) {
10477   if (VD->getType()->isDependentType())
10478     return true;
10479   for (auto *I : VD->specific_attrs<AlignedAttr>())
10480     if (I->isAlignmentDependent())
10481       return true;
10482   return false;
10483 }
10484 
10485 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10486 /// any semantic actions necessary after any initializer has been attached.
10487 void
FinalizeDeclaration(Decl * ThisDecl)10488 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10489   // Note that we are no longer parsing the initializer for this declaration.
10490   ParsingInitForAutoVars.erase(ThisDecl);
10491 
10492   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10493   if (!VD)
10494     return;
10495 
10496   checkAttributesAfterMerging(*this, *VD);
10497 
10498   // Perform TLS alignment check here after attributes attached to the variable
10499   // which may affect the alignment have been processed. Only perform the check
10500   // if the target has a maximum TLS alignment (zero means no constraints).
10501   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10502     // Protect the check so that it's not performed on dependent types and
10503     // dependent alignments (we can't determine the alignment in that case).
10504     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10505       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10506       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10507         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10508           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10509           << (unsigned)MaxAlignChars.getQuantity();
10510       }
10511     }
10512   }
10513 
10514   if (VD->isStaticLocal()) {
10515     if (FunctionDecl *FD =
10516             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10517       // Static locals inherit dll attributes from their function.
10518       if (Attr *A = getDLLAttr(FD)) {
10519         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10520         NewAttr->setInherited(true);
10521         VD->addAttr(NewAttr);
10522       }
10523       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10524       // function, only __shared__ variables may be declared with
10525       // static storage class.
10526       if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
10527           (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) &&
10528           !VD->hasAttr<CUDASharedAttr>()) {
10529         Diag(VD->getLocation(), diag::err_device_static_local_var);
10530         VD->setInvalidDecl();
10531       }
10532     }
10533   }
10534 
10535   // Perform check for initializers of device-side global variables.
10536   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10537   // 7.5). We must also apply the same checks to all __shared__
10538   // variables whether they are local or not. CUDA also allows
10539   // constant initializers for __constant__ and __device__ variables.
10540   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10541     const Expr *Init = VD->getInit();
10542     if (Init && VD->hasGlobalStorage() &&
10543         (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10544          VD->hasAttr<CUDASharedAttr>())) {
10545       assert((!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()));
10546       bool AllowedInit = false;
10547       if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10548         AllowedInit =
10549             isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10550       // We'll allow constant initializers even if it's a non-empty
10551       // constructor according to CUDA rules. This deviates from NVCC,
10552       // but allows us to handle things like constexpr constructors.
10553       if (!AllowedInit &&
10554           (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10555         AllowedInit = VD->getInit()->isConstantInitializer(
10556             Context, VD->getType()->isReferenceType());
10557 
10558       // Also make sure that destructor, if there is one, is empty.
10559       if (AllowedInit)
10560         if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10561           AllowedInit =
10562               isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10563 
10564       if (!AllowedInit) {
10565         Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10566                                     ? diag::err_shared_var_init
10567                                     : diag::err_dynamic_var_init)
10568             << Init->getSourceRange();
10569         VD->setInvalidDecl();
10570       }
10571     }
10572   }
10573 
10574   // Grab the dllimport or dllexport attribute off of the VarDecl.
10575   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10576 
10577   // Imported static data members cannot be defined out-of-line.
10578   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10579     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10580         VD->isThisDeclarationADefinition()) {
10581       // We allow definitions of dllimport class template static data members
10582       // with a warning.
10583       CXXRecordDecl *Context =
10584         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10585       bool IsClassTemplateMember =
10586           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10587           Context->getDescribedClassTemplate();
10588 
10589       Diag(VD->getLocation(),
10590            IsClassTemplateMember
10591                ? diag::warn_attribute_dllimport_static_field_definition
10592                : diag::err_attribute_dllimport_static_field_definition);
10593       Diag(IA->getLocation(), diag::note_attribute);
10594       if (!IsClassTemplateMember)
10595         VD->setInvalidDecl();
10596     }
10597   }
10598 
10599   // dllimport/dllexport variables cannot be thread local, their TLS index
10600   // isn't exported with the variable.
10601   if (DLLAttr && VD->getTLSKind()) {
10602     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10603     if (F && getDLLAttr(F)) {
10604       assert(VD->isStaticLocal());
10605       // But if this is a static local in a dlimport/dllexport function, the
10606       // function will never be inlined, which means the var would never be
10607       // imported, so having it marked import/export is safe.
10608     } else {
10609       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10610                                                                     << DLLAttr;
10611       VD->setInvalidDecl();
10612     }
10613   }
10614 
10615   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10616     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10617       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10618       VD->dropAttr<UsedAttr>();
10619     }
10620   }
10621 
10622   const DeclContext *DC = VD->getDeclContext();
10623   // If there's a #pragma GCC visibility in scope, and this isn't a class
10624   // member, set the visibility of this variable.
10625   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10626     AddPushedVisibilityAttribute(VD);
10627 
10628   // FIXME: Warn on unused templates.
10629   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10630       !isa<VarTemplatePartialSpecializationDecl>(VD))
10631     MarkUnusedFileScopedDecl(VD);
10632 
10633   // Now we have parsed the initializer and can update the table of magic
10634   // tag values.
10635   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10636       !VD->getType()->isIntegralOrEnumerationType())
10637     return;
10638 
10639   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10640     const Expr *MagicValueExpr = VD->getInit();
10641     if (!MagicValueExpr) {
10642       continue;
10643     }
10644     llvm::APSInt MagicValueInt;
10645     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10646       Diag(I->getRange().getBegin(),
10647            diag::err_type_tag_for_datatype_not_ice)
10648         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10649       continue;
10650     }
10651     if (MagicValueInt.getActiveBits() > 64) {
10652       Diag(I->getRange().getBegin(),
10653            diag::err_type_tag_for_datatype_too_large)
10654         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10655       continue;
10656     }
10657     uint64_t MagicValue = MagicValueInt.getZExtValue();
10658     RegisterTypeTagForDatatype(I->getArgumentKind(),
10659                                MagicValue,
10660                                I->getMatchingCType(),
10661                                I->getLayoutCompatible(),
10662                                I->getMustBeNull());
10663   }
10664 }
10665 
FinalizeDeclaratorGroup(Scope * S,const DeclSpec & DS,ArrayRef<Decl * > Group)10666 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10667                                                    ArrayRef<Decl *> Group) {
10668   SmallVector<Decl*, 8> Decls;
10669 
10670   if (DS.isTypeSpecOwned())
10671     Decls.push_back(DS.getRepAsDecl());
10672 
10673   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10674   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10675     if (Decl *D = Group[i]) {
10676       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10677         if (!FirstDeclaratorInGroup)
10678           FirstDeclaratorInGroup = DD;
10679       Decls.push_back(D);
10680     }
10681 
10682   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10683     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10684       handleTagNumbering(Tag, S);
10685       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10686           getLangOpts().CPlusPlus)
10687         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10688     }
10689   }
10690 
10691   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10692 }
10693 
10694 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10695 /// group, performing any necessary semantic checking.
10696 Sema::DeclGroupPtrTy
BuildDeclaratorGroup(MutableArrayRef<Decl * > Group,bool TypeMayContainAuto)10697 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10698                            bool TypeMayContainAuto) {
10699   // C++0x [dcl.spec.auto]p7:
10700   //   If the type deduced for the template parameter U is not the same in each
10701   //   deduction, the program is ill-formed.
10702   // FIXME: When initializer-list support is added, a distinction is needed
10703   // between the deduced type U and the deduced type which 'auto' stands for.
10704   //   auto a = 0, b = { 1, 2, 3 };
10705   // is legal because the deduced type U is 'int' in both cases.
10706   if (TypeMayContainAuto && Group.size() > 1) {
10707     QualType Deduced;
10708     CanQualType DeducedCanon;
10709     VarDecl *DeducedDecl = nullptr;
10710     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10711       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10712         AutoType *AT = D->getType()->getContainedAutoType();
10713         // Don't reissue diagnostics when instantiating a template.
10714         if (AT && D->isInvalidDecl())
10715           break;
10716         QualType U = AT ? AT->getDeducedType() : QualType();
10717         if (!U.isNull()) {
10718           CanQualType UCanon = Context.getCanonicalType(U);
10719           if (Deduced.isNull()) {
10720             Deduced = U;
10721             DeducedCanon = UCanon;
10722             DeducedDecl = D;
10723           } else if (DeducedCanon != UCanon) {
10724             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10725                  diag::err_auto_different_deductions)
10726               << (unsigned)AT->getKeyword()
10727               << Deduced << DeducedDecl->getDeclName()
10728               << U << D->getDeclName()
10729               << DeducedDecl->getInit()->getSourceRange()
10730               << D->getInit()->getSourceRange();
10731             D->setInvalidDecl();
10732             break;
10733           }
10734         }
10735       }
10736     }
10737   }
10738 
10739   ActOnDocumentableDecls(Group);
10740 
10741   return DeclGroupPtrTy::make(
10742       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10743 }
10744 
ActOnDocumentableDecl(Decl * D)10745 void Sema::ActOnDocumentableDecl(Decl *D) {
10746   ActOnDocumentableDecls(D);
10747 }
10748 
ActOnDocumentableDecls(ArrayRef<Decl * > Group)10749 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10750   // Don't parse the comment if Doxygen diagnostics are ignored.
10751   if (Group.empty() || !Group[0])
10752     return;
10753 
10754   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10755                       Group[0]->getLocation()) &&
10756       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10757                       Group[0]->getLocation()))
10758     return;
10759 
10760   if (Group.size() >= 2) {
10761     // This is a decl group.  Normally it will contain only declarations
10762     // produced from declarator list.  But in case we have any definitions or
10763     // additional declaration references:
10764     //   'typedef struct S {} S;'
10765     //   'typedef struct S *S;'
10766     //   'struct S *pS;'
10767     // FinalizeDeclaratorGroup adds these as separate declarations.
10768     Decl *MaybeTagDecl = Group[0];
10769     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10770       Group = Group.slice(1);
10771     }
10772   }
10773 
10774   // See if there are any new comments that are not attached to a decl.
10775   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10776   if (!Comments.empty() &&
10777       !Comments.back()->isAttached()) {
10778     // There is at least one comment that not attached to a decl.
10779     // Maybe it should be attached to one of these decls?
10780     //
10781     // Note that this way we pick up not only comments that precede the
10782     // declaration, but also comments that *follow* the declaration -- thanks to
10783     // the lookahead in the lexer: we've consumed the semicolon and looked
10784     // ahead through comments.
10785     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10786       Context.getCommentForDecl(Group[i], &PP);
10787   }
10788 }
10789 
10790 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10791 /// to introduce parameters into function prototype scope.
ActOnParamDeclarator(Scope * S,Declarator & D)10792 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10793   const DeclSpec &DS = D.getDeclSpec();
10794 
10795   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10796 
10797   // C++03 [dcl.stc]p2 also permits 'auto'.
10798   StorageClass SC = SC_None;
10799   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10800     SC = SC_Register;
10801   } else if (getLangOpts().CPlusPlus &&
10802              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10803     SC = SC_Auto;
10804   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10805     Diag(DS.getStorageClassSpecLoc(),
10806          diag::err_invalid_storage_class_in_func_decl);
10807     D.getMutableDeclSpec().ClearStorageClassSpecs();
10808   }
10809 
10810   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10811     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10812       << DeclSpec::getSpecifierName(TSCS);
10813   if (DS.isInlineSpecified())
10814     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
10815         << getLangOpts().CPlusPlus1z;
10816   if (DS.isConstexprSpecified())
10817     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10818       << 0;
10819   if (DS.isConceptSpecified())
10820     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10821 
10822   DiagnoseFunctionSpecifiers(DS);
10823 
10824   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10825   QualType parmDeclType = TInfo->getType();
10826 
10827   if (getLangOpts().CPlusPlus) {
10828     // Check that there are no default arguments inside the type of this
10829     // parameter.
10830     CheckExtraCXXDefaultArguments(D);
10831 
10832     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10833     if (D.getCXXScopeSpec().isSet()) {
10834       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10835         << D.getCXXScopeSpec().getRange();
10836       D.getCXXScopeSpec().clear();
10837     }
10838   }
10839 
10840   // Ensure we have a valid name
10841   IdentifierInfo *II = nullptr;
10842   if (D.hasName()) {
10843     II = D.getIdentifier();
10844     if (!II) {
10845       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10846         << GetNameForDeclarator(D).getName();
10847       D.setInvalidType(true);
10848     }
10849   }
10850 
10851   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10852   if (II) {
10853     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10854                    ForRedeclaration);
10855     LookupName(R, S);
10856     if (R.isSingleResult()) {
10857       NamedDecl *PrevDecl = R.getFoundDecl();
10858       if (PrevDecl->isTemplateParameter()) {
10859         // Maybe we will complain about the shadowed template parameter.
10860         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10861         // Just pretend that we didn't see the previous declaration.
10862         PrevDecl = nullptr;
10863       } else if (S->isDeclScope(PrevDecl)) {
10864         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10865         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10866 
10867         // Recover by removing the name
10868         II = nullptr;
10869         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10870         D.setInvalidType(true);
10871       }
10872     }
10873   }
10874 
10875   // Temporarily put parameter variables in the translation unit, not
10876   // the enclosing context.  This prevents them from accidentally
10877   // looking like class members in C++.
10878   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10879                                     D.getLocStart(),
10880                                     D.getIdentifierLoc(), II,
10881                                     parmDeclType, TInfo,
10882                                     SC);
10883 
10884   if (D.isInvalidType())
10885     New->setInvalidDecl();
10886 
10887   assert(S->isFunctionPrototypeScope());
10888   assert(S->getFunctionPrototypeDepth() >= 1);
10889   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10890                     S->getNextFunctionPrototypeIndex());
10891 
10892   // Add the parameter declaration into this scope.
10893   S->AddDecl(New);
10894   if (II)
10895     IdResolver.AddDecl(New);
10896 
10897   ProcessDeclAttributes(S, New, D);
10898 
10899   if (D.getDeclSpec().isModulePrivateSpecified())
10900     Diag(New->getLocation(), diag::err_module_private_local)
10901       << 1 << New->getDeclName()
10902       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10903       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10904 
10905   if (New->hasAttr<BlocksAttr>()) {
10906     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10907   }
10908   return New;
10909 }
10910 
10911 /// \brief Synthesizes a variable for a parameter arising from a
10912 /// typedef.
BuildParmVarDeclForTypedef(DeclContext * DC,SourceLocation Loc,QualType T)10913 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10914                                               SourceLocation Loc,
10915                                               QualType T) {
10916   /* FIXME: setting StartLoc == Loc.
10917      Would it be worth to modify callers so as to provide proper source
10918      location for the unnamed parameters, embedding the parameter's type? */
10919   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10920                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10921                                            SC_None, nullptr);
10922   Param->setImplicit();
10923   return Param;
10924 }
10925 
DiagnoseUnusedParameters(ArrayRef<ParmVarDecl * > Parameters)10926 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
10927   // Don't diagnose unused-parameter errors in template instantiations; we
10928   // will already have done so in the template itself.
10929   if (!ActiveTemplateInstantiations.empty())
10930     return;
10931 
10932   for (const ParmVarDecl *Parameter : Parameters) {
10933     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
10934         !Parameter->hasAttr<UnusedAttr>()) {
10935       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
10936         << Parameter->getDeclName();
10937     }
10938   }
10939 }
10940 
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl * > Parameters,QualType ReturnTy,NamedDecl * D)10941 void Sema::DiagnoseSizeOfParametersAndReturnValue(
10942     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
10943   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10944     return;
10945 
10946   // Warn if the return value is pass-by-value and larger than the specified
10947   // threshold.
10948   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10949     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10950     if (Size > LangOpts.NumLargeByValueCopy)
10951       Diag(D->getLocation(), diag::warn_return_value_size)
10952           << D->getDeclName() << Size;
10953   }
10954 
10955   // Warn if any parameter is pass-by-value and larger than the specified
10956   // threshold.
10957   for (const ParmVarDecl *Parameter : Parameters) {
10958     QualType T = Parameter->getType();
10959     if (T->isDependentType() || !T.isPODType(Context))
10960       continue;
10961     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10962     if (Size > LangOpts.NumLargeByValueCopy)
10963       Diag(Parameter->getLocation(), diag::warn_parameter_size)
10964           << Parameter->getDeclName() << Size;
10965   }
10966 }
10967 
CheckParameter(DeclContext * DC,SourceLocation StartLoc,SourceLocation NameLoc,IdentifierInfo * Name,QualType T,TypeSourceInfo * TSInfo,StorageClass SC)10968 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10969                                   SourceLocation NameLoc, IdentifierInfo *Name,
10970                                   QualType T, TypeSourceInfo *TSInfo,
10971                                   StorageClass SC) {
10972   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10973   if (getLangOpts().ObjCAutoRefCount &&
10974       T.getObjCLifetime() == Qualifiers::OCL_None &&
10975       T->isObjCLifetimeType()) {
10976 
10977     Qualifiers::ObjCLifetime lifetime;
10978 
10979     // Special cases for arrays:
10980     //   - if it's const, use __unsafe_unretained
10981     //   - otherwise, it's an error
10982     if (T->isArrayType()) {
10983       if (!T.isConstQualified()) {
10984         DelayedDiagnostics.add(
10985             sema::DelayedDiagnostic::makeForbiddenType(
10986             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10987       }
10988       lifetime = Qualifiers::OCL_ExplicitNone;
10989     } else {
10990       lifetime = T->getObjCARCImplicitLifetime();
10991     }
10992     T = Context.getLifetimeQualifiedType(T, lifetime);
10993   }
10994 
10995   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10996                                          Context.getAdjustedParameterType(T),
10997                                          TSInfo, SC, nullptr);
10998 
10999   // Parameters can not be abstract class types.
11000   // For record types, this is done by the AbstractClassUsageDiagnoser once
11001   // the class has been completely parsed.
11002   if (!CurContext->isRecord() &&
11003       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11004                              AbstractParamType))
11005     New->setInvalidDecl();
11006 
11007   // Parameter declarators cannot be interface types. All ObjC objects are
11008   // passed by reference.
11009   if (T->isObjCObjectType()) {
11010     SourceLocation TypeEndLoc =
11011         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11012     Diag(NameLoc,
11013          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11014       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11015     T = Context.getObjCObjectPointerType(T);
11016     New->setType(T);
11017   }
11018 
11019   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11020   // duration shall not be qualified by an address-space qualifier."
11021   // Since all parameters have automatic store duration, they can not have
11022   // an address space.
11023   if (T.getAddressSpace() != 0) {
11024     // OpenCL allows function arguments declared to be an array of a type
11025     // to be qualified with an address space.
11026     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11027       Diag(NameLoc, diag::err_arg_with_address_space);
11028       New->setInvalidDecl();
11029     }
11030   }
11031 
11032   return New;
11033 }
11034 
ActOnFinishKNRParamDeclarations(Scope * S,Declarator & D,SourceLocation LocAfterDecls)11035 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11036                                            SourceLocation LocAfterDecls) {
11037   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11038 
11039   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11040   // for a K&R function.
11041   if (!FTI.hasPrototype) {
11042     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11043       --i;
11044       if (FTI.Params[i].Param == nullptr) {
11045         SmallString<256> Code;
11046         llvm::raw_svector_ostream(Code)
11047             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11048         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11049             << FTI.Params[i].Ident
11050             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11051 
11052         // Implicitly declare the argument as type 'int' for lack of a better
11053         // type.
11054         AttributeFactory attrs;
11055         DeclSpec DS(attrs);
11056         const char* PrevSpec; // unused
11057         unsigned DiagID; // unused
11058         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11059                            DiagID, Context.getPrintingPolicy());
11060         // Use the identifier location for the type source range.
11061         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11062         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11063         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11064         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11065         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11066       }
11067     }
11068   }
11069 }
11070 
11071 Decl *
ActOnStartOfFunctionDef(Scope * FnBodyScope,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,SkipBodyInfo * SkipBody)11072 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11073                               MultiTemplateParamsArg TemplateParameterLists,
11074                               SkipBodyInfo *SkipBody) {
11075   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11076   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11077   Scope *ParentScope = FnBodyScope->getParent();
11078 
11079   D.setFunctionDefinitionKind(FDK_Definition);
11080   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11081   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11082 }
11083 
ActOnFinishInlineFunctionDef(FunctionDecl * D)11084 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11085   Consumer.HandleInlineFunctionDefinition(D);
11086 }
11087 
ShouldWarnAboutMissingPrototype(const FunctionDecl * FD,const FunctionDecl * & PossibleZeroParamPrototype)11088 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11089                              const FunctionDecl*& PossibleZeroParamPrototype) {
11090   // Don't warn about invalid declarations.
11091   if (FD->isInvalidDecl())
11092     return false;
11093 
11094   // Or declarations that aren't global.
11095   if (!FD->isGlobal())
11096     return false;
11097 
11098   // Don't warn about C++ member functions.
11099   if (isa<CXXMethodDecl>(FD))
11100     return false;
11101 
11102   // Don't warn about 'main'.
11103   if (FD->isMain())
11104     return false;
11105 
11106   // Don't warn about inline functions.
11107   if (FD->isInlined())
11108     return false;
11109 
11110   // Don't warn about function templates.
11111   if (FD->getDescribedFunctionTemplate())
11112     return false;
11113 
11114   // Don't warn about function template specializations.
11115   if (FD->isFunctionTemplateSpecialization())
11116     return false;
11117 
11118   // Don't warn for OpenCL kernels.
11119   if (FD->hasAttr<OpenCLKernelAttr>())
11120     return false;
11121 
11122   // Don't warn on explicitly deleted functions.
11123   if (FD->isDeleted())
11124     return false;
11125 
11126   bool MissingPrototype = true;
11127   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11128        Prev; Prev = Prev->getPreviousDecl()) {
11129     // Ignore any declarations that occur in function or method
11130     // scope, because they aren't visible from the header.
11131     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11132       continue;
11133 
11134     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11135     if (FD->getNumParams() == 0)
11136       PossibleZeroParamPrototype = Prev;
11137     break;
11138   }
11139 
11140   return MissingPrototype;
11141 }
11142 
11143 void
CheckForFunctionRedefinition(FunctionDecl * FD,const FunctionDecl * EffectiveDefinition,SkipBodyInfo * SkipBody)11144 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11145                                    const FunctionDecl *EffectiveDefinition,
11146                                    SkipBodyInfo *SkipBody) {
11147   // Don't complain if we're in GNU89 mode and the previous definition
11148   // was an extern inline function.
11149   const FunctionDecl *Definition = EffectiveDefinition;
11150   if (!Definition)
11151     if (!FD->isDefined(Definition))
11152       return;
11153 
11154   if (canRedefineFunction(Definition, getLangOpts()))
11155     return;
11156 
11157   // If we don't have a visible definition of the function, and it's inline or
11158   // a template, skip the new definition.
11159   if (SkipBody && !hasVisibleDefinition(Definition) &&
11160       (Definition->getFormalLinkage() == InternalLinkage ||
11161        Definition->isInlined() ||
11162        Definition->getDescribedFunctionTemplate() ||
11163        Definition->getNumTemplateParameterLists())) {
11164     SkipBody->ShouldSkip = true;
11165     if (auto *TD = Definition->getDescribedFunctionTemplate())
11166       makeMergedDefinitionVisible(TD, FD->getLocation());
11167     else
11168       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11169                                   FD->getLocation());
11170     return;
11171   }
11172 
11173   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11174       Definition->getStorageClass() == SC_Extern)
11175     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11176         << FD->getDeclName() << getLangOpts().CPlusPlus;
11177   else
11178     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11179 
11180   Diag(Definition->getLocation(), diag::note_previous_definition);
11181   FD->setInvalidDecl();
11182 }
11183 
RebuildLambdaScopeInfo(CXXMethodDecl * CallOperator,Sema & S)11184 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11185                                    Sema &S) {
11186   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11187 
11188   LambdaScopeInfo *LSI = S.PushLambdaScope();
11189   LSI->CallOperator = CallOperator;
11190   LSI->Lambda = LambdaClass;
11191   LSI->ReturnType = CallOperator->getReturnType();
11192   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11193 
11194   if (LCD == LCD_None)
11195     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11196   else if (LCD == LCD_ByCopy)
11197     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11198   else if (LCD == LCD_ByRef)
11199     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11200   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11201 
11202   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11203   LSI->Mutable = !CallOperator->isConst();
11204 
11205   // Add the captures to the LSI so they can be noted as already
11206   // captured within tryCaptureVar.
11207   auto I = LambdaClass->field_begin();
11208   for (const auto &C : LambdaClass->captures()) {
11209     if (C.capturesVariable()) {
11210       VarDecl *VD = C.getCapturedVar();
11211       if (VD->isInitCapture())
11212         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11213       QualType CaptureType = VD->getType();
11214       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11215       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11216           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11217           /*EllipsisLoc*/C.isPackExpansion()
11218                          ? C.getEllipsisLoc() : SourceLocation(),
11219           CaptureType, /*Expr*/ nullptr);
11220 
11221     } else if (C.capturesThis()) {
11222       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11223                               /*Expr*/ nullptr,
11224                               C.getCaptureKind() == LCK_StarThis);
11225     } else {
11226       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11227     }
11228     ++I;
11229   }
11230 }
11231 
ActOnStartOfFunctionDef(Scope * FnBodyScope,Decl * D,SkipBodyInfo * SkipBody)11232 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11233                                     SkipBodyInfo *SkipBody) {
11234   // Clear the last template instantiation error context.
11235   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11236 
11237   if (!D)
11238     return D;
11239   FunctionDecl *FD = nullptr;
11240 
11241   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11242     FD = FunTmpl->getTemplatedDecl();
11243   else
11244     FD = cast<FunctionDecl>(D);
11245 
11246   // See if this is a redefinition.
11247   if (!FD->isLateTemplateParsed()) {
11248     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11249 
11250     // If we're skipping the body, we're done. Don't enter the scope.
11251     if (SkipBody && SkipBody->ShouldSkip)
11252       return D;
11253   }
11254 
11255   // If we are instantiating a generic lambda call operator, push
11256   // a LambdaScopeInfo onto the function stack.  But use the information
11257   // that's already been calculated (ActOnLambdaExpr) to prime the current
11258   // LambdaScopeInfo.
11259   // When the template operator is being specialized, the LambdaScopeInfo,
11260   // has to be properly restored so that tryCaptureVariable doesn't try
11261   // and capture any new variables. In addition when calculating potential
11262   // captures during transformation of nested lambdas, it is necessary to
11263   // have the LSI properly restored.
11264   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11265     assert(ActiveTemplateInstantiations.size() &&
11266       "There should be an active template instantiation on the stack "
11267       "when instantiating a generic lambda!");
11268     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11269   }
11270   else
11271     // Enter a new function scope
11272     PushFunctionScope();
11273 
11274   // Builtin functions cannot be defined.
11275   if (unsigned BuiltinID = FD->getBuiltinID()) {
11276     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11277         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11278       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11279       FD->setInvalidDecl();
11280     }
11281   }
11282 
11283   // The return type of a function definition must be complete
11284   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11285   QualType ResultType = FD->getReturnType();
11286   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11287       !FD->isInvalidDecl() &&
11288       RequireCompleteType(FD->getLocation(), ResultType,
11289                           diag::err_func_def_incomplete_result))
11290     FD->setInvalidDecl();
11291 
11292   if (FnBodyScope)
11293     PushDeclContext(FnBodyScope, FD);
11294 
11295   // Check the validity of our function parameters
11296   CheckParmsForFunctionDef(FD->parameters(),
11297                            /*CheckParameterNames=*/true);
11298 
11299   // Introduce our parameters into the function scope
11300   for (auto Param : FD->parameters()) {
11301     Param->setOwningFunction(FD);
11302 
11303     // If this has an identifier, add it to the scope stack.
11304     if (Param->getIdentifier() && FnBodyScope) {
11305       CheckShadow(FnBodyScope, Param);
11306 
11307       PushOnScopeChains(Param, FnBodyScope);
11308     }
11309   }
11310 
11311   // If we had any tags defined in the function prototype,
11312   // introduce them into the function scope.
11313   if (FnBodyScope) {
11314     for (ArrayRef<NamedDecl *>::iterator
11315              I = FD->getDeclsInPrototypeScope().begin(),
11316              E = FD->getDeclsInPrototypeScope().end();
11317          I != E; ++I) {
11318       NamedDecl *D = *I;
11319 
11320       // Some of these decls (like enums) may have been pinned to the
11321       // translation unit for lack of a real context earlier. If so, remove
11322       // from the translation unit and reattach to the current context.
11323       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11324         // Is the decl actually in the context?
11325         if (Context.getTranslationUnitDecl()->containsDecl(D))
11326           Context.getTranslationUnitDecl()->removeDecl(D);
11327         // Either way, reassign the lexical decl context to our FunctionDecl.
11328         D->setLexicalDeclContext(CurContext);
11329       }
11330 
11331       // If the decl has a non-null name, make accessible in the current scope.
11332       if (!D->getName().empty())
11333         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11334 
11335       // Similarly, dive into enums and fish their constants out, making them
11336       // accessible in this scope.
11337       if (auto *ED = dyn_cast<EnumDecl>(D)) {
11338         for (auto *EI : ED->enumerators())
11339           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11340       }
11341     }
11342   }
11343 
11344   // Ensure that the function's exception specification is instantiated.
11345   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11346     ResolveExceptionSpec(D->getLocation(), FPT);
11347 
11348   // dllimport cannot be applied to non-inline function definitions.
11349   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11350       !FD->isTemplateInstantiation()) {
11351     assert(!FD->hasAttr<DLLExportAttr>());
11352     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11353     FD->setInvalidDecl();
11354     return D;
11355   }
11356   // We want to attach documentation to original Decl (which might be
11357   // a function template).
11358   ActOnDocumentableDecl(D);
11359   if (getCurLexicalContext()->isObjCContainer() &&
11360       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11361       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11362     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11363 
11364   return D;
11365 }
11366 
11367 /// \brief Given the set of return statements within a function body,
11368 /// compute the variables that are subject to the named return value
11369 /// optimization.
11370 ///
11371 /// Each of the variables that is subject to the named return value
11372 /// optimization will be marked as NRVO variables in the AST, and any
11373 /// return statement that has a marked NRVO variable as its NRVO candidate can
11374 /// use the named return value optimization.
11375 ///
11376 /// This function applies a very simplistic algorithm for NRVO: if every return
11377 /// statement in the scope of a variable has the same NRVO candidate, that
11378 /// candidate is an NRVO variable.
computeNRVO(Stmt * Body,FunctionScopeInfo * Scope)11379 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11380   ReturnStmt **Returns = Scope->Returns.data();
11381 
11382   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11383     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11384       if (!NRVOCandidate->isNRVOVariable())
11385         Returns[I]->setNRVOCandidate(nullptr);
11386     }
11387   }
11388 }
11389 
canDelayFunctionBody(const Declarator & D)11390 bool Sema::canDelayFunctionBody(const Declarator &D) {
11391   // We can't delay parsing the body of a constexpr function template (yet).
11392   if (D.getDeclSpec().isConstexprSpecified())
11393     return false;
11394 
11395   // We can't delay parsing the body of a function template with a deduced
11396   // return type (yet).
11397   if (D.getDeclSpec().containsPlaceholderType()) {
11398     // If the placeholder introduces a non-deduced trailing return type,
11399     // we can still delay parsing it.
11400     if (D.getNumTypeObjects()) {
11401       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11402       if (Outer.Kind == DeclaratorChunk::Function &&
11403           Outer.Fun.hasTrailingReturnType()) {
11404         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11405         return Ty.isNull() || !Ty->isUndeducedType();
11406       }
11407     }
11408     return false;
11409   }
11410 
11411   return true;
11412 }
11413 
canSkipFunctionBody(Decl * D)11414 bool Sema::canSkipFunctionBody(Decl *D) {
11415   // We cannot skip the body of a function (or function template) which is
11416   // constexpr, since we may need to evaluate its body in order to parse the
11417   // rest of the file.
11418   // We cannot skip the body of a function with an undeduced return type,
11419   // because any callers of that function need to know the type.
11420   if (const FunctionDecl *FD = D->getAsFunction())
11421     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11422       return false;
11423   return Consumer.shouldSkipFunctionBody(D);
11424 }
11425 
ActOnSkippedFunctionBody(Decl * Decl)11426 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11427   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11428     FD->setHasSkippedBody();
11429   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11430     MD->setHasSkippedBody();
11431   return Decl;
11432 }
11433 
ActOnFinishFunctionBody(Decl * D,Stmt * BodyArg)11434 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11435   return ActOnFinishFunctionBody(D, BodyArg, false);
11436 }
11437 
ActOnFinishFunctionBody(Decl * dcl,Stmt * Body,bool IsInstantiation)11438 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11439                                     bool IsInstantiation) {
11440   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11441 
11442   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11443   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11444 
11445   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11446     CheckCompletedCoroutineBody(FD, Body);
11447 
11448   if (FD) {
11449     FD->setBody(Body);
11450 
11451     if (getLangOpts().CPlusPlus14) {
11452       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11453           FD->getReturnType()->isUndeducedType()) {
11454         // If the function has a deduced result type but contains no 'return'
11455         // statements, the result type as written must be exactly 'auto', and
11456         // the deduced result type is 'void'.
11457         if (!FD->getReturnType()->getAs<AutoType>()) {
11458           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11459               << FD->getReturnType();
11460           FD->setInvalidDecl();
11461         } else {
11462           // Substitute 'void' for the 'auto' in the type.
11463           TypeLoc ResultType = getReturnTypeLoc(FD);
11464           Context.adjustDeducedFunctionResultType(
11465               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11466         }
11467       }
11468     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11469       // In C++11, we don't use 'auto' deduction rules for lambda call
11470       // operators because we don't support return type deduction.
11471       auto *LSI = getCurLambda();
11472       if (LSI->HasImplicitReturnType) {
11473         deduceClosureReturnType(*LSI);
11474 
11475         // C++11 [expr.prim.lambda]p4:
11476         //   [...] if there are no return statements in the compound-statement
11477         //   [the deduced type is] the type void
11478         QualType RetType =
11479             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11480 
11481         // Update the return type to the deduced type.
11482         const FunctionProtoType *Proto =
11483             FD->getType()->getAs<FunctionProtoType>();
11484         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11485                                             Proto->getExtProtoInfo()));
11486       }
11487     }
11488 
11489     // The only way to be included in UndefinedButUsed is if there is an
11490     // ODR use before the definition. Avoid the expensive map lookup if this
11491     // is the first declaration.
11492     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11493       if (!FD->isExternallyVisible())
11494         UndefinedButUsed.erase(FD);
11495       else if (FD->isInlined() &&
11496                !LangOpts.GNUInline &&
11497                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11498         UndefinedButUsed.erase(FD);
11499     }
11500 
11501     // If the function implicitly returns zero (like 'main') or is naked,
11502     // don't complain about missing return statements.
11503     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11504       WP.disableCheckFallThrough();
11505 
11506     // MSVC permits the use of pure specifier (=0) on function definition,
11507     // defined at class scope, warn about this non-standard construct.
11508     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11509       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11510 
11511     if (!FD->isInvalidDecl()) {
11512       // Don't diagnose unused parameters of defaulted or deleted functions.
11513       if (!FD->isDeleted() && !FD->isDefaulted())
11514         DiagnoseUnusedParameters(FD->parameters());
11515       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
11516                                              FD->getReturnType(), FD);
11517 
11518       // If this is a structor, we need a vtable.
11519       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11520         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11521       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11522         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11523 
11524       // Try to apply the named return value optimization. We have to check
11525       // if we can do this here because lambdas keep return statements around
11526       // to deduce an implicit return type.
11527       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11528           !FD->isDependentContext())
11529         computeNRVO(Body, getCurFunction());
11530     }
11531 
11532     // GNU warning -Wmissing-prototypes:
11533     //   Warn if a global function is defined without a previous
11534     //   prototype declaration. This warning is issued even if the
11535     //   definition itself provides a prototype. The aim is to detect
11536     //   global functions that fail to be declared in header files.
11537     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11538     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11539       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11540 
11541       if (PossibleZeroParamPrototype) {
11542         // We found a declaration that is not a prototype,
11543         // but that could be a zero-parameter prototype
11544         if (TypeSourceInfo *TI =
11545                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11546           TypeLoc TL = TI->getTypeLoc();
11547           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11548             Diag(PossibleZeroParamPrototype->getLocation(),
11549                  diag::note_declaration_not_a_prototype)
11550                 << PossibleZeroParamPrototype
11551                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11552         }
11553       }
11554     }
11555 
11556     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11557       const CXXMethodDecl *KeyFunction;
11558       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11559           MD->isVirtual() &&
11560           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11561           MD == KeyFunction->getCanonicalDecl()) {
11562         // Update the key-function state if necessary for this ABI.
11563         if (FD->isInlined() &&
11564             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11565           Context.setNonKeyFunction(MD);
11566 
11567           // If the newly-chosen key function is already defined, then we
11568           // need to mark the vtable as used retroactively.
11569           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11570           const FunctionDecl *Definition;
11571           if (KeyFunction && KeyFunction->isDefined(Definition))
11572             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11573         } else {
11574           // We just defined they key function; mark the vtable as used.
11575           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11576         }
11577       }
11578     }
11579 
11580     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11581            "Function parsing confused");
11582   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11583     assert(MD == getCurMethodDecl() && "Method parsing confused");
11584     MD->setBody(Body);
11585     if (!MD->isInvalidDecl()) {
11586       DiagnoseUnusedParameters(MD->parameters());
11587       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
11588                                              MD->getReturnType(), MD);
11589 
11590       if (Body)
11591         computeNRVO(Body, getCurFunction());
11592     }
11593     if (getCurFunction()->ObjCShouldCallSuper) {
11594       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11595         << MD->getSelector().getAsString();
11596       getCurFunction()->ObjCShouldCallSuper = false;
11597     }
11598     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11599       const ObjCMethodDecl *InitMethod = nullptr;
11600       bool isDesignated =
11601           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11602       assert(isDesignated && InitMethod);
11603       (void)isDesignated;
11604 
11605       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11606         auto IFace = MD->getClassInterface();
11607         if (!IFace)
11608           return false;
11609         auto SuperD = IFace->getSuperClass();
11610         if (!SuperD)
11611           return false;
11612         return SuperD->getIdentifier() ==
11613             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11614       };
11615       // Don't issue this warning for unavailable inits or direct subclasses
11616       // of NSObject.
11617       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11618         Diag(MD->getLocation(),
11619              diag::warn_objc_designated_init_missing_super_call);
11620         Diag(InitMethod->getLocation(),
11621              diag::note_objc_designated_init_marked_here);
11622       }
11623       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11624     }
11625     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11626       // Don't issue this warning for unavaialable inits.
11627       if (!MD->isUnavailable())
11628         Diag(MD->getLocation(),
11629              diag::warn_objc_secondary_init_missing_init_call);
11630       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11631     }
11632   } else {
11633     return nullptr;
11634   }
11635 
11636   assert(!getCurFunction()->ObjCShouldCallSuper &&
11637          "This should only be set for ObjC methods, which should have been "
11638          "handled in the block above.");
11639 
11640   // Verify and clean out per-function state.
11641   if (Body && (!FD || !FD->isDefaulted())) {
11642     // C++ constructors that have function-try-blocks can't have return
11643     // statements in the handlers of that block. (C++ [except.handle]p14)
11644     // Verify this.
11645     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11646       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11647 
11648     // Verify that gotos and switch cases don't jump into scopes illegally.
11649     if (getCurFunction()->NeedsScopeChecking() &&
11650         !PP.isCodeCompletionEnabled())
11651       DiagnoseInvalidJumps(Body);
11652 
11653     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11654       if (!Destructor->getParent()->isDependentType())
11655         CheckDestructor(Destructor);
11656 
11657       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11658                                              Destructor->getParent());
11659     }
11660 
11661     // If any errors have occurred, clear out any temporaries that may have
11662     // been leftover. This ensures that these temporaries won't be picked up for
11663     // deletion in some later function.
11664     if (getDiagnostics().hasErrorOccurred() ||
11665         getDiagnostics().getSuppressAllDiagnostics()) {
11666       DiscardCleanupsInEvaluationContext();
11667     }
11668     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11669         !isa<FunctionTemplateDecl>(dcl)) {
11670       // Since the body is valid, issue any analysis-based warnings that are
11671       // enabled.
11672       ActivePolicy = &WP;
11673     }
11674 
11675     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11676         (!CheckConstexprFunctionDecl(FD) ||
11677          !CheckConstexprFunctionBody(FD, Body)))
11678       FD->setInvalidDecl();
11679 
11680     if (FD && FD->hasAttr<NakedAttr>()) {
11681       for (const Stmt *S : Body->children()) {
11682         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11683           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11684           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11685           FD->setInvalidDecl();
11686           break;
11687         }
11688       }
11689     }
11690 
11691     assert(ExprCleanupObjects.size() ==
11692                ExprEvalContexts.back().NumCleanupObjects &&
11693            "Leftover temporaries in function");
11694     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
11695     assert(MaybeODRUseExprs.empty() &&
11696            "Leftover expressions for odr-use checking");
11697   }
11698 
11699   if (!IsInstantiation)
11700     PopDeclContext();
11701 
11702   PopFunctionScopeInfo(ActivePolicy, dcl);
11703   // If any errors have occurred, clear out any temporaries that may have
11704   // been leftover. This ensures that these temporaries won't be picked up for
11705   // deletion in some later function.
11706   if (getDiagnostics().hasErrorOccurred()) {
11707     DiscardCleanupsInEvaluationContext();
11708   }
11709 
11710   return dcl;
11711 }
11712 
11713 /// When we finish delayed parsing of an attribute, we must attach it to the
11714 /// relevant Decl.
ActOnFinishDelayedAttribute(Scope * S,Decl * D,ParsedAttributes & Attrs)11715 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11716                                        ParsedAttributes &Attrs) {
11717   // Always attach attributes to the underlying decl.
11718   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11719     D = TD->getTemplatedDecl();
11720   ProcessDeclAttributeList(S, D, Attrs.getList());
11721 
11722   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11723     if (Method->isStatic())
11724       checkThisInStaticMemberFunctionAttributes(Method);
11725 }
11726 
11727 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11728 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
ImplicitlyDefineFunction(SourceLocation Loc,IdentifierInfo & II,Scope * S)11729 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11730                                           IdentifierInfo &II, Scope *S) {
11731   // Before we produce a declaration for an implicitly defined
11732   // function, see whether there was a locally-scoped declaration of
11733   // this name as a function or variable. If so, use that
11734   // (non-visible) declaration, and complain about it.
11735   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11736     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11737     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11738     return ExternCPrev;
11739   }
11740 
11741   // Extension in C99.  Legal in C90, but warn about it.
11742   unsigned diag_id;
11743   if (II.getName().startswith("__builtin_"))
11744     diag_id = diag::warn_builtin_unknown;
11745   else if (getLangOpts().C99)
11746     diag_id = diag::ext_implicit_function_decl;
11747   else
11748     diag_id = diag::warn_implicit_function_decl;
11749   Diag(Loc, diag_id) << &II;
11750 
11751   // Because typo correction is expensive, only do it if the implicit
11752   // function declaration is going to be treated as an error.
11753   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11754     TypoCorrection Corrected;
11755     if (S &&
11756         (Corrected = CorrectTypo(
11757              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11758              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11759       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11760                    /*ErrorRecovery*/false);
11761   }
11762 
11763   // Set a Declarator for the implicit definition: int foo();
11764   const char *Dummy;
11765   AttributeFactory attrFactory;
11766   DeclSpec DS(attrFactory);
11767   unsigned DiagID;
11768   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11769                                   Context.getPrintingPolicy());
11770   (void)Error; // Silence warning.
11771   assert(!Error && "Error setting up implicit decl!");
11772   SourceLocation NoLoc;
11773   Declarator D(DS, Declarator::BlockContext);
11774   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11775                                              /*IsAmbiguous=*/false,
11776                                              /*LParenLoc=*/NoLoc,
11777                                              /*Params=*/nullptr,
11778                                              /*NumParams=*/0,
11779                                              /*EllipsisLoc=*/NoLoc,
11780                                              /*RParenLoc=*/NoLoc,
11781                                              /*TypeQuals=*/0,
11782                                              /*RefQualifierIsLvalueRef=*/true,
11783                                              /*RefQualifierLoc=*/NoLoc,
11784                                              /*ConstQualifierLoc=*/NoLoc,
11785                                              /*VolatileQualifierLoc=*/NoLoc,
11786                                              /*RestrictQualifierLoc=*/NoLoc,
11787                                              /*MutableLoc=*/NoLoc,
11788                                              EST_None,
11789                                              /*ESpecRange=*/SourceRange(),
11790                                              /*Exceptions=*/nullptr,
11791                                              /*ExceptionRanges=*/nullptr,
11792                                              /*NumExceptions=*/0,
11793                                              /*NoexceptExpr=*/nullptr,
11794                                              /*ExceptionSpecTokens=*/nullptr,
11795                                              Loc, Loc, D),
11796                 DS.getAttributes(),
11797                 SourceLocation());
11798   D.SetIdentifier(&II, Loc);
11799 
11800   // Insert this function into translation-unit scope.
11801 
11802   DeclContext *PrevDC = CurContext;
11803   CurContext = Context.getTranslationUnitDecl();
11804 
11805   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11806   FD->setImplicit();
11807 
11808   CurContext = PrevDC;
11809 
11810   AddKnownFunctionAttributes(FD);
11811 
11812   return FD;
11813 }
11814 
11815 /// \brief Adds any function attributes that we know a priori based on
11816 /// the declaration of this function.
11817 ///
11818 /// These attributes can apply both to implicitly-declared builtins
11819 /// (like __builtin___printf_chk) or to library-declared functions
11820 /// like NSLog or printf.
11821 ///
11822 /// We need to check for duplicate attributes both here and where user-written
11823 /// attributes are applied to declarations.
AddKnownFunctionAttributes(FunctionDecl * FD)11824 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11825   if (FD->isInvalidDecl())
11826     return;
11827 
11828   // If this is a built-in function, map its builtin attributes to
11829   // actual attributes.
11830   if (unsigned BuiltinID = FD->getBuiltinID()) {
11831     // Handle printf-formatting attributes.
11832     unsigned FormatIdx;
11833     bool HasVAListArg;
11834     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11835       if (!FD->hasAttr<FormatAttr>()) {
11836         const char *fmt = "printf";
11837         unsigned int NumParams = FD->getNumParams();
11838         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11839             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11840           fmt = "NSString";
11841         FD->addAttr(FormatAttr::CreateImplicit(Context,
11842                                                &Context.Idents.get(fmt),
11843                                                FormatIdx+1,
11844                                                HasVAListArg ? 0 : FormatIdx+2,
11845                                                FD->getLocation()));
11846       }
11847     }
11848     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11849                                              HasVAListArg)) {
11850      if (!FD->hasAttr<FormatAttr>())
11851        FD->addAttr(FormatAttr::CreateImplicit(Context,
11852                                               &Context.Idents.get("scanf"),
11853                                               FormatIdx+1,
11854                                               HasVAListArg ? 0 : FormatIdx+2,
11855                                               FD->getLocation()));
11856     }
11857 
11858     // Mark const if we don't care about errno and that is the only
11859     // thing preventing the function from being const. This allows
11860     // IRgen to use LLVM intrinsics for such functions.
11861     if (!getLangOpts().MathErrno &&
11862         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11863       if (!FD->hasAttr<ConstAttr>())
11864         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11865     }
11866 
11867     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11868         !FD->hasAttr<ReturnsTwiceAttr>())
11869       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11870                                          FD->getLocation()));
11871     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11872       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11873     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
11874       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
11875     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11876       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11877     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11878         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11879       // Add the appropriate attribute, depending on the CUDA compilation mode
11880       // and which target the builtin belongs to. For example, during host
11881       // compilation, aux builtins are __device__, while the rest are __host__.
11882       if (getLangOpts().CUDAIsDevice !=
11883           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11884         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11885       else
11886         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11887     }
11888   }
11889 
11890   // If C++ exceptions are enabled but we are told extern "C" functions cannot
11891   // throw, add an implicit nothrow attribute to any extern "C" function we come
11892   // across.
11893   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11894       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
11895     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
11896     if (!FPT || FPT->getExceptionSpecType() == EST_None)
11897       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11898   }
11899 
11900   IdentifierInfo *Name = FD->getIdentifier();
11901   if (!Name)
11902     return;
11903   if ((!getLangOpts().CPlusPlus &&
11904        FD->getDeclContext()->isTranslationUnit()) ||
11905       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11906        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11907        LinkageSpecDecl::lang_c)) {
11908     // Okay: this could be a libc/libm/Objective-C function we know
11909     // about.
11910   } else
11911     return;
11912 
11913   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11914     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11915     // target-specific builtins, perhaps?
11916     if (!FD->hasAttr<FormatAttr>())
11917       FD->addAttr(FormatAttr::CreateImplicit(Context,
11918                                              &Context.Idents.get("printf"), 2,
11919                                              Name->isStr("vasprintf") ? 0 : 3,
11920                                              FD->getLocation()));
11921   }
11922 
11923   if (Name->isStr("__CFStringMakeConstantString")) {
11924     // We already have a __builtin___CFStringMakeConstantString,
11925     // but builds that use -fno-constant-cfstrings don't go through that.
11926     if (!FD->hasAttr<FormatArgAttr>())
11927       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11928                                                 FD->getLocation()));
11929   }
11930 }
11931 
ParseTypedefDecl(Scope * S,Declarator & D,QualType T,TypeSourceInfo * TInfo)11932 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11933                                     TypeSourceInfo *TInfo) {
11934   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11935   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11936 
11937   if (!TInfo) {
11938     assert(D.isInvalidType() && "no declarator info for valid type");
11939     TInfo = Context.getTrivialTypeSourceInfo(T);
11940   }
11941 
11942   // Scope manipulation handled by caller.
11943   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11944                                            D.getLocStart(),
11945                                            D.getIdentifierLoc(),
11946                                            D.getIdentifier(),
11947                                            TInfo);
11948 
11949   // Bail out immediately if we have an invalid declaration.
11950   if (D.isInvalidType()) {
11951     NewTD->setInvalidDecl();
11952     return NewTD;
11953   }
11954 
11955   if (D.getDeclSpec().isModulePrivateSpecified()) {
11956     if (CurContext->isFunctionOrMethod())
11957       Diag(NewTD->getLocation(), diag::err_module_private_local)
11958         << 2 << NewTD->getDeclName()
11959         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11960         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11961     else
11962       NewTD->setModulePrivate();
11963   }
11964 
11965   // C++ [dcl.typedef]p8:
11966   //   If the typedef declaration defines an unnamed class (or
11967   //   enum), the first typedef-name declared by the declaration
11968   //   to be that class type (or enum type) is used to denote the
11969   //   class type (or enum type) for linkage purposes only.
11970   // We need to check whether the type was declared in the declaration.
11971   switch (D.getDeclSpec().getTypeSpecType()) {
11972   case TST_enum:
11973   case TST_struct:
11974   case TST_interface:
11975   case TST_union:
11976   case TST_class: {
11977     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11978     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11979     break;
11980   }
11981 
11982   default:
11983     break;
11984   }
11985 
11986   return NewTD;
11987 }
11988 
11989 /// \brief Check that this is a valid underlying type for an enum declaration.
CheckEnumUnderlyingType(TypeSourceInfo * TI)11990 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11991   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11992   QualType T = TI->getType();
11993 
11994   if (T->isDependentType())
11995     return false;
11996 
11997   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11998     if (BT->isInteger())
11999       return false;
12000 
12001   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12002   return true;
12003 }
12004 
12005 /// Check whether this is a valid redeclaration of a previous enumeration.
12006 /// \return true if the redeclaration was invalid.
CheckEnumRedeclaration(SourceLocation EnumLoc,bool IsScoped,QualType EnumUnderlyingTy,bool EnumUnderlyingIsImplicit,const EnumDecl * Prev)12007 bool Sema::CheckEnumRedeclaration(
12008     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12009     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12010   bool IsFixed = !EnumUnderlyingTy.isNull();
12011 
12012   if (IsScoped != Prev->isScoped()) {
12013     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12014       << Prev->isScoped();
12015     Diag(Prev->getLocation(), diag::note_previous_declaration);
12016     return true;
12017   }
12018 
12019   if (IsFixed && Prev->isFixed()) {
12020     if (!EnumUnderlyingTy->isDependentType() &&
12021         !Prev->getIntegerType()->isDependentType() &&
12022         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12023                                         Prev->getIntegerType())) {
12024       // TODO: Highlight the underlying type of the redeclaration.
12025       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12026         << EnumUnderlyingTy << Prev->getIntegerType();
12027       Diag(Prev->getLocation(), diag::note_previous_declaration)
12028           << Prev->getIntegerTypeRange();
12029       return true;
12030     }
12031   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12032     ;
12033   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12034     ;
12035   } else if (IsFixed != Prev->isFixed()) {
12036     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12037       << Prev->isFixed();
12038     Diag(Prev->getLocation(), diag::note_previous_declaration);
12039     return true;
12040   }
12041 
12042   return false;
12043 }
12044 
12045 /// \brief Get diagnostic %select index for tag kind for
12046 /// redeclaration diagnostic message.
12047 /// WARNING: Indexes apply to particular diagnostics only!
12048 ///
12049 /// \returns diagnostic %select index.
getRedeclDiagFromTagKind(TagTypeKind Tag)12050 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12051   switch (Tag) {
12052   case TTK_Struct: return 0;
12053   case TTK_Interface: return 1;
12054   case TTK_Class:  return 2;
12055   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12056   }
12057 }
12058 
12059 /// \brief Determine if tag kind is a class-key compatible with
12060 /// class for redeclaration (class, struct, or __interface).
12061 ///
12062 /// \returns true iff the tag kind is compatible.
isClassCompatTagKind(TagTypeKind Tag)12063 static bool isClassCompatTagKind(TagTypeKind Tag)
12064 {
12065   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12066 }
12067 
12068 /// \brief Determine whether a tag with a given kind is acceptable
12069 /// as a redeclaration of the given tag declaration.
12070 ///
12071 /// \returns true if the new tag kind is acceptable, false otherwise.
isAcceptableTagRedeclaration(const TagDecl * Previous,TagTypeKind NewTag,bool isDefinition,SourceLocation NewTagLoc,const IdentifierInfo * Name)12072 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12073                                         TagTypeKind NewTag, bool isDefinition,
12074                                         SourceLocation NewTagLoc,
12075                                         const IdentifierInfo *Name) {
12076   // C++ [dcl.type.elab]p3:
12077   //   The class-key or enum keyword present in the
12078   //   elaborated-type-specifier shall agree in kind with the
12079   //   declaration to which the name in the elaborated-type-specifier
12080   //   refers. This rule also applies to the form of
12081   //   elaborated-type-specifier that declares a class-name or
12082   //   friend class since it can be construed as referring to the
12083   //   definition of the class. Thus, in any
12084   //   elaborated-type-specifier, the enum keyword shall be used to
12085   //   refer to an enumeration (7.2), the union class-key shall be
12086   //   used to refer to a union (clause 9), and either the class or
12087   //   struct class-key shall be used to refer to a class (clause 9)
12088   //   declared using the class or struct class-key.
12089   TagTypeKind OldTag = Previous->getTagKind();
12090   if (!isDefinition || !isClassCompatTagKind(NewTag))
12091     if (OldTag == NewTag)
12092       return true;
12093 
12094   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12095     // Warn about the struct/class tag mismatch.
12096     bool isTemplate = false;
12097     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12098       isTemplate = Record->getDescribedClassTemplate();
12099 
12100     if (!ActiveTemplateInstantiations.empty()) {
12101       // In a template instantiation, do not offer fix-its for tag mismatches
12102       // since they usually mess up the template instead of fixing the problem.
12103       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12104         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12105         << getRedeclDiagFromTagKind(OldTag);
12106       return true;
12107     }
12108 
12109     if (isDefinition) {
12110       // On definitions, check previous tags and issue a fix-it for each
12111       // one that doesn't match the current tag.
12112       if (Previous->getDefinition()) {
12113         // Don't suggest fix-its for redefinitions.
12114         return true;
12115       }
12116 
12117       bool previousMismatch = false;
12118       for (auto I : Previous->redecls()) {
12119         if (I->getTagKind() != NewTag) {
12120           if (!previousMismatch) {
12121             previousMismatch = true;
12122             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12123               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12124               << getRedeclDiagFromTagKind(I->getTagKind());
12125           }
12126           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12127             << getRedeclDiagFromTagKind(NewTag)
12128             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12129                  TypeWithKeyword::getTagTypeKindName(NewTag));
12130         }
12131       }
12132       return true;
12133     }
12134 
12135     // Check for a previous definition.  If current tag and definition
12136     // are same type, do nothing.  If no definition, but disagree with
12137     // with previous tag type, give a warning, but no fix-it.
12138     const TagDecl *Redecl = Previous->getDefinition() ?
12139                             Previous->getDefinition() : Previous;
12140     if (Redecl->getTagKind() == NewTag) {
12141       return true;
12142     }
12143 
12144     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12145       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12146       << getRedeclDiagFromTagKind(OldTag);
12147     Diag(Redecl->getLocation(), diag::note_previous_use);
12148 
12149     // If there is a previous definition, suggest a fix-it.
12150     if (Previous->getDefinition()) {
12151         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12152           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12153           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12154                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12155     }
12156 
12157     return true;
12158   }
12159   return false;
12160 }
12161 
12162 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12163 /// from an outer enclosing namespace or file scope inside a friend declaration.
12164 /// This should provide the commented out code in the following snippet:
12165 ///   namespace N {
12166 ///     struct X;
12167 ///     namespace M {
12168 ///       struct Y { friend struct /*N::*/ X; };
12169 ///     }
12170 ///   }
createFriendTagNNSFixIt(Sema & SemaRef,NamedDecl * ND,Scope * S,SourceLocation NameLoc)12171 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12172                                          SourceLocation NameLoc) {
12173   // While the decl is in a namespace, do repeated lookup of that name and see
12174   // if we get the same namespace back.  If we do not, continue until
12175   // translation unit scope, at which point we have a fully qualified NNS.
12176   SmallVector<IdentifierInfo *, 4> Namespaces;
12177   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12178   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12179     // This tag should be declared in a namespace, which can only be enclosed by
12180     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12181     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12182     if (!Namespace || Namespace->isAnonymousNamespace())
12183       return FixItHint();
12184     IdentifierInfo *II = Namespace->getIdentifier();
12185     Namespaces.push_back(II);
12186     NamedDecl *Lookup = SemaRef.LookupSingleName(
12187         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12188     if (Lookup == Namespace)
12189       break;
12190   }
12191 
12192   // Once we have all the namespaces, reverse them to go outermost first, and
12193   // build an NNS.
12194   SmallString<64> Insertion;
12195   llvm::raw_svector_ostream OS(Insertion);
12196   if (DC->isTranslationUnit())
12197     OS << "::";
12198   std::reverse(Namespaces.begin(), Namespaces.end());
12199   for (auto *II : Namespaces)
12200     OS << II->getName() << "::";
12201   return FixItHint::CreateInsertion(NameLoc, Insertion);
12202 }
12203 
12204 /// \brief Determine whether a tag originally declared in context \p OldDC can
12205 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12206 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12207 /// using-declaration).
isAcceptableTagRedeclContext(Sema & S,DeclContext * OldDC,DeclContext * NewDC)12208 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12209                                          DeclContext *NewDC) {
12210   OldDC = OldDC->getRedeclContext();
12211   NewDC = NewDC->getRedeclContext();
12212 
12213   if (OldDC->Equals(NewDC))
12214     return true;
12215 
12216   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12217   // encloses the other).
12218   if (S.getLangOpts().MSVCCompat &&
12219       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12220     return true;
12221 
12222   return false;
12223 }
12224 
12225 /// Find the DeclContext in which a tag is implicitly declared if we see an
12226 /// elaborated type specifier in the specified context, and lookup finds
12227 /// nothing.
getTagInjectionContext(DeclContext * DC)12228 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12229   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12230     DC = DC->getParent();
12231   return DC;
12232 }
12233 
12234 /// Find the Scope in which a tag is implicitly declared if we see an
12235 /// elaborated type specifier in the specified context, and lookup finds
12236 /// nothing.
getTagInjectionScope(Scope * S,const LangOptions & LangOpts)12237 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12238   while (S->isClassScope() ||
12239          (LangOpts.CPlusPlus &&
12240           S->isFunctionPrototypeScope()) ||
12241          ((S->getFlags() & Scope::DeclScope) == 0) ||
12242          (S->getEntity() && S->getEntity()->isTransparentContext()))
12243     S = S->getParent();
12244   return S;
12245 }
12246 
12247 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12248 /// former case, Name will be non-null.  In the later case, Name will be null.
12249 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12250 /// reference/declaration/definition of a tag.
12251 ///
12252 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12253 /// trailing-type-specifier) other than one in an alias-declaration.
12254 ///
12255 /// \param SkipBody If non-null, will be set to indicate if the caller should
12256 /// skip the definition of this tag and treat it as if it were a declaration.
ActOnTag(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr,AccessSpecifier AS,SourceLocation ModulePrivateLoc,MultiTemplateParamsArg TemplateParameterLists,bool & OwnedDecl,bool & IsDependent,SourceLocation ScopedEnumKWLoc,bool ScopedEnumUsesClassTag,TypeResult UnderlyingType,bool IsTypeSpecifier,SkipBodyInfo * SkipBody)12257 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12258                      SourceLocation KWLoc, CXXScopeSpec &SS,
12259                      IdentifierInfo *Name, SourceLocation NameLoc,
12260                      AttributeList *Attr, AccessSpecifier AS,
12261                      SourceLocation ModulePrivateLoc,
12262                      MultiTemplateParamsArg TemplateParameterLists,
12263                      bool &OwnedDecl, bool &IsDependent,
12264                      SourceLocation ScopedEnumKWLoc,
12265                      bool ScopedEnumUsesClassTag,
12266                      TypeResult UnderlyingType,
12267                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12268   // If this is not a definition, it must have a name.
12269   IdentifierInfo *OrigName = Name;
12270   assert((Name != nullptr || TUK == TUK_Definition) &&
12271          "Nameless record must be a definition!");
12272   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12273 
12274   OwnedDecl = false;
12275   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12276   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12277 
12278   // FIXME: Check explicit specializations more carefully.
12279   bool isExplicitSpecialization = false;
12280   bool Invalid = false;
12281 
12282   // We only need to do this matching if we have template parameters
12283   // or a scope specifier, which also conveniently avoids this work
12284   // for non-C++ cases.
12285   if (TemplateParameterLists.size() > 0 ||
12286       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12287     if (TemplateParameterList *TemplateParams =
12288             MatchTemplateParametersToScopeSpecifier(
12289                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12290                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12291       if (Kind == TTK_Enum) {
12292         Diag(KWLoc, diag::err_enum_template);
12293         return nullptr;
12294       }
12295 
12296       if (TemplateParams->size() > 0) {
12297         // This is a declaration or definition of a class template (which may
12298         // be a member of another template).
12299 
12300         if (Invalid)
12301           return nullptr;
12302 
12303         OwnedDecl = false;
12304         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12305                                                SS, Name, NameLoc, Attr,
12306                                                TemplateParams, AS,
12307                                                ModulePrivateLoc,
12308                                                /*FriendLoc*/SourceLocation(),
12309                                                TemplateParameterLists.size()-1,
12310                                                TemplateParameterLists.data(),
12311                                                SkipBody);
12312         return Result.get();
12313       } else {
12314         // The "template<>" header is extraneous.
12315         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12316           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12317         isExplicitSpecialization = true;
12318       }
12319     }
12320   }
12321 
12322   // Figure out the underlying type if this a enum declaration. We need to do
12323   // this early, because it's needed to detect if this is an incompatible
12324   // redeclaration.
12325   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12326   bool EnumUnderlyingIsImplicit = false;
12327 
12328   if (Kind == TTK_Enum) {
12329     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12330       // No underlying type explicitly specified, or we failed to parse the
12331       // type, default to int.
12332       EnumUnderlying = Context.IntTy.getTypePtr();
12333     else if (UnderlyingType.get()) {
12334       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12335       // integral type; any cv-qualification is ignored.
12336       TypeSourceInfo *TI = nullptr;
12337       GetTypeFromParser(UnderlyingType.get(), &TI);
12338       EnumUnderlying = TI;
12339 
12340       if (CheckEnumUnderlyingType(TI))
12341         // Recover by falling back to int.
12342         EnumUnderlying = Context.IntTy.getTypePtr();
12343 
12344       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12345                                           UPPC_FixedUnderlyingType))
12346         EnumUnderlying = Context.IntTy.getTypePtr();
12347 
12348     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12349       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12350         // Microsoft enums are always of int type.
12351         EnumUnderlying = Context.IntTy.getTypePtr();
12352         EnumUnderlyingIsImplicit = true;
12353       }
12354     }
12355   }
12356 
12357   DeclContext *SearchDC = CurContext;
12358   DeclContext *DC = CurContext;
12359   bool isStdBadAlloc = false;
12360 
12361   RedeclarationKind Redecl = ForRedeclaration;
12362   if (TUK == TUK_Friend || TUK == TUK_Reference)
12363     Redecl = NotForRedeclaration;
12364 
12365   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12366   if (Name && SS.isNotEmpty()) {
12367     // We have a nested-name tag ('struct foo::bar').
12368 
12369     // Check for invalid 'foo::'.
12370     if (SS.isInvalid()) {
12371       Name = nullptr;
12372       goto CreateNewDecl;
12373     }
12374 
12375     // If this is a friend or a reference to a class in a dependent
12376     // context, don't try to make a decl for it.
12377     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12378       DC = computeDeclContext(SS, false);
12379       if (!DC) {
12380         IsDependent = true;
12381         return nullptr;
12382       }
12383     } else {
12384       DC = computeDeclContext(SS, true);
12385       if (!DC) {
12386         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12387           << SS.getRange();
12388         return nullptr;
12389       }
12390     }
12391 
12392     if (RequireCompleteDeclContext(SS, DC))
12393       return nullptr;
12394 
12395     SearchDC = DC;
12396     // Look-up name inside 'foo::'.
12397     LookupQualifiedName(Previous, DC);
12398 
12399     if (Previous.isAmbiguous())
12400       return nullptr;
12401 
12402     if (Previous.empty()) {
12403       // Name lookup did not find anything. However, if the
12404       // nested-name-specifier refers to the current instantiation,
12405       // and that current instantiation has any dependent base
12406       // classes, we might find something at instantiation time: treat
12407       // this as a dependent elaborated-type-specifier.
12408       // But this only makes any sense for reference-like lookups.
12409       if (Previous.wasNotFoundInCurrentInstantiation() &&
12410           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12411         IsDependent = true;
12412         return nullptr;
12413       }
12414 
12415       // A tag 'foo::bar' must already exist.
12416       Diag(NameLoc, diag::err_not_tag_in_scope)
12417         << Kind << Name << DC << SS.getRange();
12418       Name = nullptr;
12419       Invalid = true;
12420       goto CreateNewDecl;
12421     }
12422   } else if (Name) {
12423     // C++14 [class.mem]p14:
12424     //   If T is the name of a class, then each of the following shall have a
12425     //   name different from T:
12426     //    -- every member of class T that is itself a type
12427     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12428         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12429       return nullptr;
12430 
12431     // If this is a named struct, check to see if there was a previous forward
12432     // declaration or definition.
12433     // FIXME: We're looking into outer scopes here, even when we
12434     // shouldn't be. Doing so can result in ambiguities that we
12435     // shouldn't be diagnosing.
12436     LookupName(Previous, S);
12437 
12438     // When declaring or defining a tag, ignore ambiguities introduced
12439     // by types using'ed into this scope.
12440     if (Previous.isAmbiguous() &&
12441         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12442       LookupResult::Filter F = Previous.makeFilter();
12443       while (F.hasNext()) {
12444         NamedDecl *ND = F.next();
12445         if (!ND->getDeclContext()->getRedeclContext()->Equals(
12446                 SearchDC->getRedeclContext()))
12447           F.erase();
12448       }
12449       F.done();
12450     }
12451 
12452     // C++11 [namespace.memdef]p3:
12453     //   If the name in a friend declaration is neither qualified nor
12454     //   a template-id and the declaration is a function or an
12455     //   elaborated-type-specifier, the lookup to determine whether
12456     //   the entity has been previously declared shall not consider
12457     //   any scopes outside the innermost enclosing namespace.
12458     //
12459     // MSVC doesn't implement the above rule for types, so a friend tag
12460     // declaration may be a redeclaration of a type declared in an enclosing
12461     // scope.  They do implement this rule for friend functions.
12462     //
12463     // Does it matter that this should be by scope instead of by
12464     // semantic context?
12465     if (!Previous.empty() && TUK == TUK_Friend) {
12466       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12467       LookupResult::Filter F = Previous.makeFilter();
12468       bool FriendSawTagOutsideEnclosingNamespace = false;
12469       while (F.hasNext()) {
12470         NamedDecl *ND = F.next();
12471         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12472         if (DC->isFileContext() &&
12473             !EnclosingNS->Encloses(ND->getDeclContext())) {
12474           if (getLangOpts().MSVCCompat)
12475             FriendSawTagOutsideEnclosingNamespace = true;
12476           else
12477             F.erase();
12478         }
12479       }
12480       F.done();
12481 
12482       // Diagnose this MSVC extension in the easy case where lookup would have
12483       // unambiguously found something outside the enclosing namespace.
12484       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12485         NamedDecl *ND = Previous.getFoundDecl();
12486         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12487             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12488       }
12489     }
12490 
12491     // Note:  there used to be some attempt at recovery here.
12492     if (Previous.isAmbiguous())
12493       return nullptr;
12494 
12495     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12496       // FIXME: This makes sure that we ignore the contexts associated
12497       // with C structs, unions, and enums when looking for a matching
12498       // tag declaration or definition. See the similar lookup tweak
12499       // in Sema::LookupName; is there a better way to deal with this?
12500       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12501         SearchDC = SearchDC->getParent();
12502     }
12503   }
12504 
12505   if (Previous.isSingleResult() &&
12506       Previous.getFoundDecl()->isTemplateParameter()) {
12507     // Maybe we will complain about the shadowed template parameter.
12508     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12509     // Just pretend that we didn't see the previous declaration.
12510     Previous.clear();
12511   }
12512 
12513   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12514       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12515     // This is a declaration of or a reference to "std::bad_alloc".
12516     isStdBadAlloc = true;
12517 
12518     if (Previous.empty() && StdBadAlloc) {
12519       // std::bad_alloc has been implicitly declared (but made invisible to
12520       // name lookup). Fill in this implicit declaration as the previous
12521       // declaration, so that the declarations get chained appropriately.
12522       Previous.addDecl(getStdBadAlloc());
12523     }
12524   }
12525 
12526   // If we didn't find a previous declaration, and this is a reference
12527   // (or friend reference), move to the correct scope.  In C++, we
12528   // also need to do a redeclaration lookup there, just in case
12529   // there's a shadow friend decl.
12530   if (Name && Previous.empty() &&
12531       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12532     if (Invalid) goto CreateNewDecl;
12533     assert(SS.isEmpty());
12534 
12535     if (TUK == TUK_Reference) {
12536       // C++ [basic.scope.pdecl]p5:
12537       //   -- for an elaborated-type-specifier of the form
12538       //
12539       //          class-key identifier
12540       //
12541       //      if the elaborated-type-specifier is used in the
12542       //      decl-specifier-seq or parameter-declaration-clause of a
12543       //      function defined in namespace scope, the identifier is
12544       //      declared as a class-name in the namespace that contains
12545       //      the declaration; otherwise, except as a friend
12546       //      declaration, the identifier is declared in the smallest
12547       //      non-class, non-function-prototype scope that contains the
12548       //      declaration.
12549       //
12550       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12551       // C structs and unions.
12552       //
12553       // It is an error in C++ to declare (rather than define) an enum
12554       // type, including via an elaborated type specifier.  We'll
12555       // diagnose that later; for now, declare the enum in the same
12556       // scope as we would have picked for any other tag type.
12557       //
12558       // GNU C also supports this behavior as part of its incomplete
12559       // enum types extension, while GNU C++ does not.
12560       //
12561       // Find the context where we'll be declaring the tag.
12562       // FIXME: We would like to maintain the current DeclContext as the
12563       // lexical context,
12564       SearchDC = getTagInjectionContext(SearchDC);
12565 
12566       // Find the scope where we'll be declaring the tag.
12567       S = getTagInjectionScope(S, getLangOpts());
12568     } else {
12569       assert(TUK == TUK_Friend);
12570       // C++ [namespace.memdef]p3:
12571       //   If a friend declaration in a non-local class first declares a
12572       //   class or function, the friend class or function is a member of
12573       //   the innermost enclosing namespace.
12574       SearchDC = SearchDC->getEnclosingNamespaceContext();
12575     }
12576 
12577     // In C++, we need to do a redeclaration lookup to properly
12578     // diagnose some problems.
12579     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12580     // hidden declaration so that we don't get ambiguity errors when using a
12581     // type declared by an elaborated-type-specifier.  In C that is not correct
12582     // and we should instead merge compatible types found by lookup.
12583     if (getLangOpts().CPlusPlus) {
12584       Previous.setRedeclarationKind(ForRedeclaration);
12585       LookupQualifiedName(Previous, SearchDC);
12586     } else {
12587       Previous.setRedeclarationKind(ForRedeclaration);
12588       LookupName(Previous, S);
12589     }
12590   }
12591 
12592   // If we have a known previous declaration to use, then use it.
12593   if (Previous.empty() && SkipBody && SkipBody->Previous)
12594     Previous.addDecl(SkipBody->Previous);
12595 
12596   if (!Previous.empty()) {
12597     NamedDecl *PrevDecl = Previous.getFoundDecl();
12598     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12599 
12600     // It's okay to have a tag decl in the same scope as a typedef
12601     // which hides a tag decl in the same scope.  Finding this
12602     // insanity with a redeclaration lookup can only actually happen
12603     // in C++.
12604     //
12605     // This is also okay for elaborated-type-specifiers, which is
12606     // technically forbidden by the current standard but which is
12607     // okay according to the likely resolution of an open issue;
12608     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12609     if (getLangOpts().CPlusPlus) {
12610       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12611         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12612           TagDecl *Tag = TT->getDecl();
12613           if (Tag->getDeclName() == Name &&
12614               Tag->getDeclContext()->getRedeclContext()
12615                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12616             PrevDecl = Tag;
12617             Previous.clear();
12618             Previous.addDecl(Tag);
12619             Previous.resolveKind();
12620           }
12621         }
12622       }
12623     }
12624 
12625     // If this is a redeclaration of a using shadow declaration, it must
12626     // declare a tag in the same context. In MSVC mode, we allow a
12627     // redefinition if either context is within the other.
12628     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12629       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12630       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12631           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12632           !(OldTag && isAcceptableTagRedeclContext(
12633                           *this, OldTag->getDeclContext(), SearchDC))) {
12634         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12635         Diag(Shadow->getTargetDecl()->getLocation(),
12636              diag::note_using_decl_target);
12637         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12638             << 0;
12639         // Recover by ignoring the old declaration.
12640         Previous.clear();
12641         goto CreateNewDecl;
12642       }
12643     }
12644 
12645     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12646       // If this is a use of a previous tag, or if the tag is already declared
12647       // in the same scope (so that the definition/declaration completes or
12648       // rementions the tag), reuse the decl.
12649       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12650           isDeclInScope(DirectPrevDecl, SearchDC, S,
12651                         SS.isNotEmpty() || isExplicitSpecialization)) {
12652         // Make sure that this wasn't declared as an enum and now used as a
12653         // struct or something similar.
12654         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12655                                           TUK == TUK_Definition, KWLoc,
12656                                           Name)) {
12657           bool SafeToContinue
12658             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12659                Kind != TTK_Enum);
12660           if (SafeToContinue)
12661             Diag(KWLoc, diag::err_use_with_wrong_tag)
12662               << Name
12663               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12664                                               PrevTagDecl->getKindName());
12665           else
12666             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12667           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12668 
12669           if (SafeToContinue)
12670             Kind = PrevTagDecl->getTagKind();
12671           else {
12672             // Recover by making this an anonymous redefinition.
12673             Name = nullptr;
12674             Previous.clear();
12675             Invalid = true;
12676           }
12677         }
12678 
12679         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12680           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12681 
12682           // If this is an elaborated-type-specifier for a scoped enumeration,
12683           // the 'class' keyword is not necessary and not permitted.
12684           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12685             if (ScopedEnum)
12686               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12687                 << PrevEnum->isScoped()
12688                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12689             return PrevTagDecl;
12690           }
12691 
12692           QualType EnumUnderlyingTy;
12693           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12694             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12695           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12696             EnumUnderlyingTy = QualType(T, 0);
12697 
12698           // All conflicts with previous declarations are recovered by
12699           // returning the previous declaration, unless this is a definition,
12700           // in which case we want the caller to bail out.
12701           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12702                                      ScopedEnum, EnumUnderlyingTy,
12703                                      EnumUnderlyingIsImplicit, PrevEnum))
12704             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12705         }
12706 
12707         // C++11 [class.mem]p1:
12708         //   A member shall not be declared twice in the member-specification,
12709         //   except that a nested class or member class template can be declared
12710         //   and then later defined.
12711         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12712             S->isDeclScope(PrevDecl)) {
12713           Diag(NameLoc, diag::ext_member_redeclared);
12714           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12715         }
12716 
12717         if (!Invalid) {
12718           // If this is a use, just return the declaration we found, unless
12719           // we have attributes.
12720           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12721             if (Attr) {
12722               // FIXME: Diagnose these attributes. For now, we create a new
12723               // declaration to hold them.
12724             } else if (TUK == TUK_Reference &&
12725                        (PrevTagDecl->getFriendObjectKind() ==
12726                             Decl::FOK_Undeclared ||
12727                         PP.getModuleContainingLocation(
12728                             PrevDecl->getLocation()) !=
12729                             PP.getModuleContainingLocation(KWLoc)) &&
12730                        SS.isEmpty()) {
12731               // This declaration is a reference to an existing entity, but
12732               // has different visibility from that entity: it either makes
12733               // a friend visible or it makes a type visible in a new module.
12734               // In either case, create a new declaration. We only do this if
12735               // the declaration would have meant the same thing if no prior
12736               // declaration were found, that is, if it was found in the same
12737               // scope where we would have injected a declaration.
12738               if (!getTagInjectionContext(CurContext)->getRedeclContext()
12739                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12740                 return PrevTagDecl;
12741               // This is in the injected scope, create a new declaration in
12742               // that scope.
12743               S = getTagInjectionScope(S, getLangOpts());
12744             } else {
12745               return PrevTagDecl;
12746             }
12747           }
12748 
12749           // Diagnose attempts to redefine a tag.
12750           if (TUK == TUK_Definition) {
12751             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12752               // If we're defining a specialization and the previous definition
12753               // is from an implicit instantiation, don't emit an error
12754               // here; we'll catch this in the general case below.
12755               bool IsExplicitSpecializationAfterInstantiation = false;
12756               if (isExplicitSpecialization) {
12757                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12758                   IsExplicitSpecializationAfterInstantiation =
12759                     RD->getTemplateSpecializationKind() !=
12760                     TSK_ExplicitSpecialization;
12761                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12762                   IsExplicitSpecializationAfterInstantiation =
12763                     ED->getTemplateSpecializationKind() !=
12764                     TSK_ExplicitSpecialization;
12765               }
12766 
12767               NamedDecl *Hidden = nullptr;
12768               if (SkipBody && getLangOpts().CPlusPlus &&
12769                   !hasVisibleDefinition(Def, &Hidden)) {
12770                 // There is a definition of this tag, but it is not visible. We
12771                 // explicitly make use of C++'s one definition rule here, and
12772                 // assume that this definition is identical to the hidden one
12773                 // we already have. Make the existing definition visible and
12774                 // use it in place of this one.
12775                 SkipBody->ShouldSkip = true;
12776                 makeMergedDefinitionVisible(Hidden, KWLoc);
12777                 return Def;
12778               } else if (!IsExplicitSpecializationAfterInstantiation) {
12779                 // A redeclaration in function prototype scope in C isn't
12780                 // visible elsewhere, so merely issue a warning.
12781                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12782                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12783                 else
12784                   Diag(NameLoc, diag::err_redefinition) << Name;
12785                 Diag(Def->getLocation(), diag::note_previous_definition);
12786                 // If this is a redefinition, recover by making this
12787                 // struct be anonymous, which will make any later
12788                 // references get the previous definition.
12789                 Name = nullptr;
12790                 Previous.clear();
12791                 Invalid = true;
12792               }
12793             } else {
12794               // If the type is currently being defined, complain
12795               // about a nested redefinition.
12796               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12797               if (TD->isBeingDefined()) {
12798                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12799                 Diag(PrevTagDecl->getLocation(),
12800                      diag::note_previous_definition);
12801                 Name = nullptr;
12802                 Previous.clear();
12803                 Invalid = true;
12804               }
12805             }
12806 
12807             // Okay, this is definition of a previously declared or referenced
12808             // tag. We're going to create a new Decl for it.
12809           }
12810 
12811           // Okay, we're going to make a redeclaration.  If this is some kind
12812           // of reference, make sure we build the redeclaration in the same DC
12813           // as the original, and ignore the current access specifier.
12814           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12815             SearchDC = PrevTagDecl->getDeclContext();
12816             AS = AS_none;
12817           }
12818         }
12819         // If we get here we have (another) forward declaration or we
12820         // have a definition.  Just create a new decl.
12821 
12822       } else {
12823         // If we get here, this is a definition of a new tag type in a nested
12824         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12825         // new decl/type.  We set PrevDecl to NULL so that the entities
12826         // have distinct types.
12827         Previous.clear();
12828       }
12829       // If we get here, we're going to create a new Decl. If PrevDecl
12830       // is non-NULL, it's a definition of the tag declared by
12831       // PrevDecl. If it's NULL, we have a new definition.
12832 
12833     // Otherwise, PrevDecl is not a tag, but was found with tag
12834     // lookup.  This is only actually possible in C++, where a few
12835     // things like templates still live in the tag namespace.
12836     } else {
12837       // Use a better diagnostic if an elaborated-type-specifier
12838       // found the wrong kind of type on the first
12839       // (non-redeclaration) lookup.
12840       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12841           !Previous.isForRedeclaration()) {
12842         unsigned Kind = 0;
12843         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12844         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12845         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12846         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12847         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12848         Invalid = true;
12849 
12850       // Otherwise, only diagnose if the declaration is in scope.
12851       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12852                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12853         // do nothing
12854 
12855       // Diagnose implicit declarations introduced by elaborated types.
12856       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12857         unsigned Kind = 0;
12858         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12859         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12860         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12861         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12862         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12863         Invalid = true;
12864 
12865       // Otherwise it's a declaration.  Call out a particularly common
12866       // case here.
12867       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12868         unsigned Kind = 0;
12869         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12870         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12871           << Name << Kind << TND->getUnderlyingType();
12872         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12873         Invalid = true;
12874 
12875       // Otherwise, diagnose.
12876       } else {
12877         // The tag name clashes with something else in the target scope,
12878         // issue an error and recover by making this tag be anonymous.
12879         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12880         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12881         Name = nullptr;
12882         Invalid = true;
12883       }
12884 
12885       // The existing declaration isn't relevant to us; we're in a
12886       // new scope, so clear out the previous declaration.
12887       Previous.clear();
12888     }
12889   }
12890 
12891 CreateNewDecl:
12892 
12893   TagDecl *PrevDecl = nullptr;
12894   if (Previous.isSingleResult())
12895     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12896 
12897   // If there is an identifier, use the location of the identifier as the
12898   // location of the decl, otherwise use the location of the struct/union
12899   // keyword.
12900   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12901 
12902   // Otherwise, create a new declaration. If there is a previous
12903   // declaration of the same entity, the two will be linked via
12904   // PrevDecl.
12905   TagDecl *New;
12906 
12907   bool IsForwardReference = false;
12908   if (Kind == TTK_Enum) {
12909     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12910     // enum X { A, B, C } D;    D should chain to X.
12911     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12912                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12913                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12914     // If this is an undefined enum, warn.
12915     if (TUK != TUK_Definition && !Invalid) {
12916       TagDecl *Def;
12917       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12918           cast<EnumDecl>(New)->isFixed()) {
12919         // C++0x: 7.2p2: opaque-enum-declaration.
12920         // Conflicts are diagnosed above. Do nothing.
12921       }
12922       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12923         Diag(Loc, diag::ext_forward_ref_enum_def)
12924           << New;
12925         Diag(Def->getLocation(), diag::note_previous_definition);
12926       } else {
12927         unsigned DiagID = diag::ext_forward_ref_enum;
12928         if (getLangOpts().MSVCCompat)
12929           DiagID = diag::ext_ms_forward_ref_enum;
12930         else if (getLangOpts().CPlusPlus)
12931           DiagID = diag::err_forward_ref_enum;
12932         Diag(Loc, DiagID);
12933 
12934         // If this is a forward-declared reference to an enumeration, make a
12935         // note of it; we won't actually be introducing the declaration into
12936         // the declaration context.
12937         if (TUK == TUK_Reference)
12938           IsForwardReference = true;
12939       }
12940     }
12941 
12942     if (EnumUnderlying) {
12943       EnumDecl *ED = cast<EnumDecl>(New);
12944       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12945         ED->setIntegerTypeSourceInfo(TI);
12946       else
12947         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12948       ED->setPromotionType(ED->getIntegerType());
12949     }
12950   } else {
12951     // struct/union/class
12952 
12953     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12954     // struct X { int A; } D;    D should chain to X.
12955     if (getLangOpts().CPlusPlus) {
12956       // FIXME: Look for a way to use RecordDecl for simple structs.
12957       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12958                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12959 
12960       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12961         StdBadAlloc = cast<CXXRecordDecl>(New);
12962     } else
12963       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12964                                cast_or_null<RecordDecl>(PrevDecl));
12965   }
12966 
12967   // C++11 [dcl.type]p3:
12968   //   A type-specifier-seq shall not define a class or enumeration [...].
12969   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12970     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12971       << Context.getTagDeclType(New);
12972     Invalid = true;
12973   }
12974 
12975   // Maybe add qualifier info.
12976   if (SS.isNotEmpty()) {
12977     if (SS.isSet()) {
12978       // If this is either a declaration or a definition, check the
12979       // nested-name-specifier against the current context. We don't do this
12980       // for explicit specializations, because they have similar checking
12981       // (with more specific diagnostics) in the call to
12982       // CheckMemberSpecialization, below.
12983       if (!isExplicitSpecialization &&
12984           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12985           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12986         Invalid = true;
12987 
12988       New->setQualifierInfo(SS.getWithLocInContext(Context));
12989       if (TemplateParameterLists.size() > 0) {
12990         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12991       }
12992     }
12993     else
12994       Invalid = true;
12995   }
12996 
12997   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12998     // Add alignment attributes if necessary; these attributes are checked when
12999     // the ASTContext lays out the structure.
13000     //
13001     // It is important for implementing the correct semantics that this
13002     // happen here (in act on tag decl). The #pragma pack stack is
13003     // maintained as a result of parser callbacks which can occur at
13004     // many points during the parsing of a struct declaration (because
13005     // the #pragma tokens are effectively skipped over during the
13006     // parsing of the struct).
13007     if (TUK == TUK_Definition) {
13008       AddAlignmentAttributesForRecord(RD);
13009       AddMsStructLayoutForRecord(RD);
13010     }
13011   }
13012 
13013   if (ModulePrivateLoc.isValid()) {
13014     if (isExplicitSpecialization)
13015       Diag(New->getLocation(), diag::err_module_private_specialization)
13016         << 2
13017         << FixItHint::CreateRemoval(ModulePrivateLoc);
13018     // __module_private__ does not apply to local classes. However, we only
13019     // diagnose this as an error when the declaration specifiers are
13020     // freestanding. Here, we just ignore the __module_private__.
13021     else if (!SearchDC->isFunctionOrMethod())
13022       New->setModulePrivate();
13023   }
13024 
13025   // If this is a specialization of a member class (of a class template),
13026   // check the specialization.
13027   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
13028     Invalid = true;
13029 
13030   // If we're declaring or defining a tag in function prototype scope in C,
13031   // note that this type can only be used within the function and add it to
13032   // the list of decls to inject into the function definition scope.
13033   if ((Name || Kind == TTK_Enum) &&
13034       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13035     if (getLangOpts().CPlusPlus) {
13036       // C++ [dcl.fct]p6:
13037       //   Types shall not be defined in return or parameter types.
13038       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13039         Diag(Loc, diag::err_type_defined_in_param_type)
13040             << Name;
13041         Invalid = true;
13042       }
13043     } else if (!PrevDecl) {
13044       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13045     }
13046     DeclsInPrototypeScope.push_back(New);
13047   }
13048 
13049   if (Invalid)
13050     New->setInvalidDecl();
13051 
13052   if (Attr)
13053     ProcessDeclAttributeList(S, New, Attr);
13054 
13055   // Set the lexical context. If the tag has a C++ scope specifier, the
13056   // lexical context will be different from the semantic context.
13057   New->setLexicalDeclContext(CurContext);
13058 
13059   // Mark this as a friend decl if applicable.
13060   // In Microsoft mode, a friend declaration also acts as a forward
13061   // declaration so we always pass true to setObjectOfFriendDecl to make
13062   // the tag name visible.
13063   if (TUK == TUK_Friend)
13064     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13065 
13066   // Set the access specifier.
13067   if (!Invalid && SearchDC->isRecord())
13068     SetMemberAccessSpecifier(New, PrevDecl, AS);
13069 
13070   if (TUK == TUK_Definition)
13071     New->startDefinition();
13072 
13073   // If this has an identifier, add it to the scope stack.
13074   if (TUK == TUK_Friend) {
13075     // We might be replacing an existing declaration in the lookup tables;
13076     // if so, borrow its access specifier.
13077     if (PrevDecl)
13078       New->setAccess(PrevDecl->getAccess());
13079 
13080     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13081     DC->makeDeclVisibleInContext(New);
13082     if (Name) // can be null along some error paths
13083       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13084         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13085   } else if (Name) {
13086     S = getNonFieldDeclScope(S);
13087     PushOnScopeChains(New, S, !IsForwardReference);
13088     if (IsForwardReference)
13089       SearchDC->makeDeclVisibleInContext(New);
13090   } else {
13091     CurContext->addDecl(New);
13092   }
13093 
13094   // If this is the C FILE type, notify the AST context.
13095   if (IdentifierInfo *II = New->getIdentifier())
13096     if (!New->isInvalidDecl() &&
13097         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13098         II->isStr("FILE"))
13099       Context.setFILEDecl(New);
13100 
13101   if (PrevDecl)
13102     mergeDeclAttributes(New, PrevDecl);
13103 
13104   // If there's a #pragma GCC visibility in scope, set the visibility of this
13105   // record.
13106   AddPushedVisibilityAttribute(New);
13107 
13108   OwnedDecl = true;
13109   // In C++, don't return an invalid declaration. We can't recover well from
13110   // the cases where we make the type anonymous.
13111   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
13112 }
13113 
ActOnTagStartDefinition(Scope * S,Decl * TagD)13114 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13115   AdjustDeclIfTemplate(TagD);
13116   TagDecl *Tag = cast<TagDecl>(TagD);
13117 
13118   // Enter the tag context.
13119   PushDeclContext(S, Tag);
13120 
13121   ActOnDocumentableDecl(TagD);
13122 
13123   // If there's a #pragma GCC visibility in scope, set the visibility of this
13124   // record.
13125   AddPushedVisibilityAttribute(Tag);
13126 }
13127 
ActOnObjCContainerStartDefinition(Decl * IDecl)13128 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13129   assert(isa<ObjCContainerDecl>(IDecl) &&
13130          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13131   DeclContext *OCD = cast<DeclContext>(IDecl);
13132   assert(getContainingDC(OCD) == CurContext &&
13133       "The next DeclContext should be lexically contained in the current one.");
13134   CurContext = OCD;
13135   return IDecl;
13136 }
13137 
ActOnStartCXXMemberDeclarations(Scope * S,Decl * TagD,SourceLocation FinalLoc,bool IsFinalSpelledSealed,SourceLocation LBraceLoc)13138 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13139                                            SourceLocation FinalLoc,
13140                                            bool IsFinalSpelledSealed,
13141                                            SourceLocation LBraceLoc) {
13142   AdjustDeclIfTemplate(TagD);
13143   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13144 
13145   FieldCollector->StartClass();
13146 
13147   if (!Record->getIdentifier())
13148     return;
13149 
13150   if (FinalLoc.isValid())
13151     Record->addAttr(new (Context)
13152                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13153 
13154   // C++ [class]p2:
13155   //   [...] The class-name is also inserted into the scope of the
13156   //   class itself; this is known as the injected-class-name. For
13157   //   purposes of access checking, the injected-class-name is treated
13158   //   as if it were a public member name.
13159   CXXRecordDecl *InjectedClassName
13160     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13161                             Record->getLocStart(), Record->getLocation(),
13162                             Record->getIdentifier(),
13163                             /*PrevDecl=*/nullptr,
13164                             /*DelayTypeCreation=*/true);
13165   Context.getTypeDeclType(InjectedClassName, Record);
13166   InjectedClassName->setImplicit();
13167   InjectedClassName->setAccess(AS_public);
13168   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13169       InjectedClassName->setDescribedClassTemplate(Template);
13170   PushOnScopeChains(InjectedClassName, S);
13171   assert(InjectedClassName->isInjectedClassName() &&
13172          "Broken injected-class-name");
13173 }
13174 
ActOnTagFinishDefinition(Scope * S,Decl * TagD,SourceLocation RBraceLoc)13175 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13176                                     SourceLocation RBraceLoc) {
13177   AdjustDeclIfTemplate(TagD);
13178   TagDecl *Tag = cast<TagDecl>(TagD);
13179   Tag->setRBraceLoc(RBraceLoc);
13180 
13181   // Make sure we "complete" the definition even it is invalid.
13182   if (Tag->isBeingDefined()) {
13183     assert(Tag->isInvalidDecl() && "We should already have completed it");
13184     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13185       RD->completeDefinition();
13186   }
13187 
13188   if (isa<CXXRecordDecl>(Tag))
13189     FieldCollector->FinishClass();
13190 
13191   // Exit this scope of this tag's definition.
13192   PopDeclContext();
13193 
13194   if (getCurLexicalContext()->isObjCContainer() &&
13195       Tag->getDeclContext()->isFileContext())
13196     Tag->setTopLevelDeclInObjCContainer();
13197 
13198   // Notify the consumer that we've defined a tag.
13199   if (!Tag->isInvalidDecl())
13200     Consumer.HandleTagDeclDefinition(Tag);
13201 }
13202 
ActOnObjCContainerFinishDefinition()13203 void Sema::ActOnObjCContainerFinishDefinition() {
13204   // Exit this scope of this interface definition.
13205   PopDeclContext();
13206 }
13207 
ActOnObjCTemporaryExitContainerContext(DeclContext * DC)13208 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13209   assert(DC == CurContext && "Mismatch of container contexts");
13210   OriginalLexicalContext = DC;
13211   ActOnObjCContainerFinishDefinition();
13212 }
13213 
ActOnObjCReenterContainerContext(DeclContext * DC)13214 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13215   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13216   OriginalLexicalContext = nullptr;
13217 }
13218 
ActOnTagDefinitionError(Scope * S,Decl * TagD)13219 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13220   AdjustDeclIfTemplate(TagD);
13221   TagDecl *Tag = cast<TagDecl>(TagD);
13222   Tag->setInvalidDecl();
13223 
13224   // Make sure we "complete" the definition even it is invalid.
13225   if (Tag->isBeingDefined()) {
13226     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13227       RD->completeDefinition();
13228   }
13229 
13230   // We're undoing ActOnTagStartDefinition here, not
13231   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13232   // the FieldCollector.
13233 
13234   PopDeclContext();
13235 }
13236 
13237 // Note that FieldName may be null for anonymous bitfields.
VerifyBitField(SourceLocation FieldLoc,IdentifierInfo * FieldName,QualType FieldTy,bool IsMsStruct,Expr * BitWidth,bool * ZeroWidth)13238 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13239                                 IdentifierInfo *FieldName,
13240                                 QualType FieldTy, bool IsMsStruct,
13241                                 Expr *BitWidth, bool *ZeroWidth) {
13242   // Default to true; that shouldn't confuse checks for emptiness
13243   if (ZeroWidth)
13244     *ZeroWidth = true;
13245 
13246   // C99 6.7.2.1p4 - verify the field type.
13247   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13248   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13249     // Handle incomplete types with specific error.
13250     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13251       return ExprError();
13252     if (FieldName)
13253       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13254         << FieldName << FieldTy << BitWidth->getSourceRange();
13255     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13256       << FieldTy << BitWidth->getSourceRange();
13257   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13258                                              UPPC_BitFieldWidth))
13259     return ExprError();
13260 
13261   // If the bit-width is type- or value-dependent, don't try to check
13262   // it now.
13263   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13264     return BitWidth;
13265 
13266   llvm::APSInt Value;
13267   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13268   if (ICE.isInvalid())
13269     return ICE;
13270   BitWidth = ICE.get();
13271 
13272   if (Value != 0 && ZeroWidth)
13273     *ZeroWidth = false;
13274 
13275   // Zero-width bitfield is ok for anonymous field.
13276   if (Value == 0 && FieldName)
13277     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13278 
13279   if (Value.isSigned() && Value.isNegative()) {
13280     if (FieldName)
13281       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13282                << FieldName << Value.toString(10);
13283     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13284       << Value.toString(10);
13285   }
13286 
13287   if (!FieldTy->isDependentType()) {
13288     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13289     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13290     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13291 
13292     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13293     // ABI.
13294     bool CStdConstraintViolation =
13295         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13296     bool MSBitfieldViolation =
13297         Value.ugt(TypeStorageSize) &&
13298         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13299     if (CStdConstraintViolation || MSBitfieldViolation) {
13300       unsigned DiagWidth =
13301           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13302       if (FieldName)
13303         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13304                << FieldName << (unsigned)Value.getZExtValue()
13305                << !CStdConstraintViolation << DiagWidth;
13306 
13307       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13308              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13309              << DiagWidth;
13310     }
13311 
13312     // Warn on types where the user might conceivably expect to get all
13313     // specified bits as value bits: that's all integral types other than
13314     // 'bool'.
13315     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13316       if (FieldName)
13317         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13318             << FieldName << (unsigned)Value.getZExtValue()
13319             << (unsigned)TypeWidth;
13320       else
13321         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13322             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13323     }
13324   }
13325 
13326   return BitWidth;
13327 }
13328 
13329 /// ActOnField - Each field of a C struct/union is passed into this in order
13330 /// to create a FieldDecl object for it.
ActOnField(Scope * S,Decl * TagD,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth)13331 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13332                        Declarator &D, Expr *BitfieldWidth) {
13333   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13334                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13335                                /*InitStyle=*/ICIS_NoInit, AS_public);
13336   return Res;
13337 }
13338 
13339 /// HandleField - Analyze a field of a C struct or a C++ data member.
13340 ///
HandleField(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS)13341 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13342                              SourceLocation DeclStart,
13343                              Declarator &D, Expr *BitWidth,
13344                              InClassInitStyle InitStyle,
13345                              AccessSpecifier AS) {
13346   IdentifierInfo *II = D.getIdentifier();
13347   SourceLocation Loc = DeclStart;
13348   if (II) Loc = D.getIdentifierLoc();
13349 
13350   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13351   QualType T = TInfo->getType();
13352   if (getLangOpts().CPlusPlus) {
13353     CheckExtraCXXDefaultArguments(D);
13354 
13355     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13356                                         UPPC_DataMemberType)) {
13357       D.setInvalidType();
13358       T = Context.IntTy;
13359       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13360     }
13361   }
13362 
13363   // TR 18037 does not allow fields to be declared with address spaces.
13364   if (T.getQualifiers().hasAddressSpace()) {
13365     Diag(Loc, diag::err_field_with_address_space);
13366     D.setInvalidType();
13367   }
13368 
13369   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13370   // used as structure or union field: image, sampler, event or block types.
13371   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13372                           T->isSamplerT() || T->isBlockPointerType())) {
13373     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13374     D.setInvalidType();
13375   }
13376 
13377   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13378 
13379   if (D.getDeclSpec().isInlineSpecified())
13380     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13381         << getLangOpts().CPlusPlus1z;
13382   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13383     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13384          diag::err_invalid_thread)
13385       << DeclSpec::getSpecifierName(TSCS);
13386 
13387   // Check to see if this name was declared as a member previously
13388   NamedDecl *PrevDecl = nullptr;
13389   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13390   LookupName(Previous, S);
13391   switch (Previous.getResultKind()) {
13392     case LookupResult::Found:
13393     case LookupResult::FoundUnresolvedValue:
13394       PrevDecl = Previous.getAsSingle<NamedDecl>();
13395       break;
13396 
13397     case LookupResult::FoundOverloaded:
13398       PrevDecl = Previous.getRepresentativeDecl();
13399       break;
13400 
13401     case LookupResult::NotFound:
13402     case LookupResult::NotFoundInCurrentInstantiation:
13403     case LookupResult::Ambiguous:
13404       break;
13405   }
13406   Previous.suppressDiagnostics();
13407 
13408   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13409     // Maybe we will complain about the shadowed template parameter.
13410     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13411     // Just pretend that we didn't see the previous declaration.
13412     PrevDecl = nullptr;
13413   }
13414 
13415   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13416     PrevDecl = nullptr;
13417 
13418   bool Mutable
13419     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13420   SourceLocation TSSL = D.getLocStart();
13421   FieldDecl *NewFD
13422     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13423                      TSSL, AS, PrevDecl, &D);
13424 
13425   if (NewFD->isInvalidDecl())
13426     Record->setInvalidDecl();
13427 
13428   if (D.getDeclSpec().isModulePrivateSpecified())
13429     NewFD->setModulePrivate();
13430 
13431   if (NewFD->isInvalidDecl() && PrevDecl) {
13432     // Don't introduce NewFD into scope; there's already something
13433     // with the same name in the same scope.
13434   } else if (II) {
13435     PushOnScopeChains(NewFD, S);
13436   } else
13437     Record->addDecl(NewFD);
13438 
13439   return NewFD;
13440 }
13441 
13442 /// \brief Build a new FieldDecl and check its well-formedness.
13443 ///
13444 /// This routine builds a new FieldDecl given the fields name, type,
13445 /// record, etc. \p PrevDecl should refer to any previous declaration
13446 /// with the same name and in the same scope as the field to be
13447 /// created.
13448 ///
13449 /// \returns a new FieldDecl.
13450 ///
13451 /// \todo The Declarator argument is a hack. It will be removed once
CheckFieldDecl(DeclarationName Name,QualType T,TypeSourceInfo * TInfo,RecordDecl * Record,SourceLocation Loc,bool Mutable,Expr * BitWidth,InClassInitStyle InitStyle,SourceLocation TSSL,AccessSpecifier AS,NamedDecl * PrevDecl,Declarator * D)13452 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13453                                 TypeSourceInfo *TInfo,
13454                                 RecordDecl *Record, SourceLocation Loc,
13455                                 bool Mutable, Expr *BitWidth,
13456                                 InClassInitStyle InitStyle,
13457                                 SourceLocation TSSL,
13458                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13459                                 Declarator *D) {
13460   IdentifierInfo *II = Name.getAsIdentifierInfo();
13461   bool InvalidDecl = false;
13462   if (D) InvalidDecl = D->isInvalidType();
13463 
13464   // If we receive a broken type, recover by assuming 'int' and
13465   // marking this declaration as invalid.
13466   if (T.isNull()) {
13467     InvalidDecl = true;
13468     T = Context.IntTy;
13469   }
13470 
13471   QualType EltTy = Context.getBaseElementType(T);
13472   if (!EltTy->isDependentType()) {
13473     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13474       // Fields of incomplete type force their record to be invalid.
13475       Record->setInvalidDecl();
13476       InvalidDecl = true;
13477     } else {
13478       NamedDecl *Def;
13479       EltTy->isIncompleteType(&Def);
13480       if (Def && Def->isInvalidDecl()) {
13481         Record->setInvalidDecl();
13482         InvalidDecl = true;
13483       }
13484     }
13485   }
13486 
13487   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13488   if (BitWidth && getLangOpts().OpenCL) {
13489     Diag(Loc, diag::err_opencl_bitfields);
13490     InvalidDecl = true;
13491   }
13492 
13493   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13494   // than a variably modified type.
13495   if (!InvalidDecl && T->isVariablyModifiedType()) {
13496     bool SizeIsNegative;
13497     llvm::APSInt Oversized;
13498 
13499     TypeSourceInfo *FixedTInfo =
13500       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13501                                                     SizeIsNegative,
13502                                                     Oversized);
13503     if (FixedTInfo) {
13504       Diag(Loc, diag::warn_illegal_constant_array_size);
13505       TInfo = FixedTInfo;
13506       T = FixedTInfo->getType();
13507     } else {
13508       if (SizeIsNegative)
13509         Diag(Loc, diag::err_typecheck_negative_array_size);
13510       else if (Oversized.getBoolValue())
13511         Diag(Loc, diag::err_array_too_large)
13512           << Oversized.toString(10);
13513       else
13514         Diag(Loc, diag::err_typecheck_field_variable_size);
13515       InvalidDecl = true;
13516     }
13517   }
13518 
13519   // Fields can not have abstract class types
13520   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13521                                              diag::err_abstract_type_in_decl,
13522                                              AbstractFieldType))
13523     InvalidDecl = true;
13524 
13525   bool ZeroWidth = false;
13526   if (InvalidDecl)
13527     BitWidth = nullptr;
13528   // If this is declared as a bit-field, check the bit-field.
13529   if (BitWidth) {
13530     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13531                               &ZeroWidth).get();
13532     if (!BitWidth) {
13533       InvalidDecl = true;
13534       BitWidth = nullptr;
13535       ZeroWidth = false;
13536     }
13537   }
13538 
13539   // Check that 'mutable' is consistent with the type of the declaration.
13540   if (!InvalidDecl && Mutable) {
13541     unsigned DiagID = 0;
13542     if (T->isReferenceType())
13543       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13544                                         : diag::err_mutable_reference;
13545     else if (T.isConstQualified())
13546       DiagID = diag::err_mutable_const;
13547 
13548     if (DiagID) {
13549       SourceLocation ErrLoc = Loc;
13550       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13551         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13552       Diag(ErrLoc, DiagID);
13553       if (DiagID != diag::ext_mutable_reference) {
13554         Mutable = false;
13555         InvalidDecl = true;
13556       }
13557     }
13558   }
13559 
13560   // C++11 [class.union]p8 (DR1460):
13561   //   At most one variant member of a union may have a
13562   //   brace-or-equal-initializer.
13563   if (InitStyle != ICIS_NoInit)
13564     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13565 
13566   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13567                                        BitWidth, Mutable, InitStyle);
13568   if (InvalidDecl)
13569     NewFD->setInvalidDecl();
13570 
13571   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13572     Diag(Loc, diag::err_duplicate_member) << II;
13573     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13574     NewFD->setInvalidDecl();
13575   }
13576 
13577   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13578     if (Record->isUnion()) {
13579       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13580         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13581         if (RDecl->getDefinition()) {
13582           // C++ [class.union]p1: An object of a class with a non-trivial
13583           // constructor, a non-trivial copy constructor, a non-trivial
13584           // destructor, or a non-trivial copy assignment operator
13585           // cannot be a member of a union, nor can an array of such
13586           // objects.
13587           if (CheckNontrivialField(NewFD))
13588             NewFD->setInvalidDecl();
13589         }
13590       }
13591 
13592       // C++ [class.union]p1: If a union contains a member of reference type,
13593       // the program is ill-formed, except when compiling with MSVC extensions
13594       // enabled.
13595       if (EltTy->isReferenceType()) {
13596         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13597                                     diag::ext_union_member_of_reference_type :
13598                                     diag::err_union_member_of_reference_type)
13599           << NewFD->getDeclName() << EltTy;
13600         if (!getLangOpts().MicrosoftExt)
13601           NewFD->setInvalidDecl();
13602       }
13603     }
13604   }
13605 
13606   // FIXME: We need to pass in the attributes given an AST
13607   // representation, not a parser representation.
13608   if (D) {
13609     // FIXME: The current scope is almost... but not entirely... correct here.
13610     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13611 
13612     if (NewFD->hasAttrs())
13613       CheckAlignasUnderalignment(NewFD);
13614   }
13615 
13616   // In auto-retain/release, infer strong retension for fields of
13617   // retainable type.
13618   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13619     NewFD->setInvalidDecl();
13620 
13621   if (T.isObjCGCWeak())
13622     Diag(Loc, diag::warn_attribute_weak_on_field);
13623 
13624   NewFD->setAccess(AS);
13625   return NewFD;
13626 }
13627 
CheckNontrivialField(FieldDecl * FD)13628 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13629   assert(FD);
13630   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13631 
13632   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13633     return false;
13634 
13635   QualType EltTy = Context.getBaseElementType(FD->getType());
13636   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13637     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13638     if (RDecl->getDefinition()) {
13639       // We check for copy constructors before constructors
13640       // because otherwise we'll never get complaints about
13641       // copy constructors.
13642 
13643       CXXSpecialMember member = CXXInvalid;
13644       // We're required to check for any non-trivial constructors. Since the
13645       // implicit default constructor is suppressed if there are any
13646       // user-declared constructors, we just need to check that there is a
13647       // trivial default constructor and a trivial copy constructor. (We don't
13648       // worry about move constructors here, since this is a C++98 check.)
13649       if (RDecl->hasNonTrivialCopyConstructor())
13650         member = CXXCopyConstructor;
13651       else if (!RDecl->hasTrivialDefaultConstructor())
13652         member = CXXDefaultConstructor;
13653       else if (RDecl->hasNonTrivialCopyAssignment())
13654         member = CXXCopyAssignment;
13655       else if (RDecl->hasNonTrivialDestructor())
13656         member = CXXDestructor;
13657 
13658       if (member != CXXInvalid) {
13659         if (!getLangOpts().CPlusPlus11 &&
13660             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13661           // Objective-C++ ARC: it is an error to have a non-trivial field of
13662           // a union. However, system headers in Objective-C programs
13663           // occasionally have Objective-C lifetime objects within unions,
13664           // and rather than cause the program to fail, we make those
13665           // members unavailable.
13666           SourceLocation Loc = FD->getLocation();
13667           if (getSourceManager().isInSystemHeader(Loc)) {
13668             if (!FD->hasAttr<UnavailableAttr>())
13669               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13670                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13671             return false;
13672           }
13673         }
13674 
13675         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13676                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13677                diag::err_illegal_union_or_anon_struct_member)
13678           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13679         DiagnoseNontrivial(RDecl, member);
13680         return !getLangOpts().CPlusPlus11;
13681       }
13682     }
13683   }
13684 
13685   return false;
13686 }
13687 
13688 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13689 ///  AST enum value.
13690 static ObjCIvarDecl::AccessControl
TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)13691 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13692   switch (ivarVisibility) {
13693   default: llvm_unreachable("Unknown visitibility kind");
13694   case tok::objc_private: return ObjCIvarDecl::Private;
13695   case tok::objc_public: return ObjCIvarDecl::Public;
13696   case tok::objc_protected: return ObjCIvarDecl::Protected;
13697   case tok::objc_package: return ObjCIvarDecl::Package;
13698   }
13699 }
13700 
13701 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13702 /// in order to create an IvarDecl object for it.
ActOnIvar(Scope * S,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth,tok::ObjCKeywordKind Visibility)13703 Decl *Sema::ActOnIvar(Scope *S,
13704                                 SourceLocation DeclStart,
13705                                 Declarator &D, Expr *BitfieldWidth,
13706                                 tok::ObjCKeywordKind Visibility) {
13707 
13708   IdentifierInfo *II = D.getIdentifier();
13709   Expr *BitWidth = (Expr*)BitfieldWidth;
13710   SourceLocation Loc = DeclStart;
13711   if (II) Loc = D.getIdentifierLoc();
13712 
13713   // FIXME: Unnamed fields can be handled in various different ways, for
13714   // example, unnamed unions inject all members into the struct namespace!
13715 
13716   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13717   QualType T = TInfo->getType();
13718 
13719   if (BitWidth) {
13720     // 6.7.2.1p3, 6.7.2.1p4
13721     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13722     if (!BitWidth)
13723       D.setInvalidType();
13724   } else {
13725     // Not a bitfield.
13726 
13727     // validate II.
13728 
13729   }
13730   if (T->isReferenceType()) {
13731     Diag(Loc, diag::err_ivar_reference_type);
13732     D.setInvalidType();
13733   }
13734   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13735   // than a variably modified type.
13736   else if (T->isVariablyModifiedType()) {
13737     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13738     D.setInvalidType();
13739   }
13740 
13741   // Get the visibility (access control) for this ivar.
13742   ObjCIvarDecl::AccessControl ac =
13743     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13744                                         : ObjCIvarDecl::None;
13745   // Must set ivar's DeclContext to its enclosing interface.
13746   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13747   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13748     return nullptr;
13749   ObjCContainerDecl *EnclosingContext;
13750   if (ObjCImplementationDecl *IMPDecl =
13751       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13752     if (LangOpts.ObjCRuntime.isFragile()) {
13753     // Case of ivar declared in an implementation. Context is that of its class.
13754       EnclosingContext = IMPDecl->getClassInterface();
13755       assert(EnclosingContext && "Implementation has no class interface!");
13756     }
13757     else
13758       EnclosingContext = EnclosingDecl;
13759   } else {
13760     if (ObjCCategoryDecl *CDecl =
13761         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13762       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13763         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13764         return nullptr;
13765       }
13766     }
13767     EnclosingContext = EnclosingDecl;
13768   }
13769 
13770   // Construct the decl.
13771   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13772                                              DeclStart, Loc, II, T,
13773                                              TInfo, ac, (Expr *)BitfieldWidth);
13774 
13775   if (II) {
13776     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13777                                            ForRedeclaration);
13778     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13779         && !isa<TagDecl>(PrevDecl)) {
13780       Diag(Loc, diag::err_duplicate_member) << II;
13781       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13782       NewID->setInvalidDecl();
13783     }
13784   }
13785 
13786   // Process attributes attached to the ivar.
13787   ProcessDeclAttributes(S, NewID, D);
13788 
13789   if (D.isInvalidType())
13790     NewID->setInvalidDecl();
13791 
13792   // In ARC, infer 'retaining' for ivars of retainable type.
13793   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13794     NewID->setInvalidDecl();
13795 
13796   if (D.getDeclSpec().isModulePrivateSpecified())
13797     NewID->setModulePrivate();
13798 
13799   if (II) {
13800     // FIXME: When interfaces are DeclContexts, we'll need to add
13801     // these to the interface.
13802     S->AddDecl(NewID);
13803     IdResolver.AddDecl(NewID);
13804   }
13805 
13806   if (LangOpts.ObjCRuntime.isNonFragile() &&
13807       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13808     Diag(Loc, diag::warn_ivars_in_interface);
13809 
13810   return NewID;
13811 }
13812 
13813 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13814 /// class and class extensions. For every class \@interface and class
13815 /// extension \@interface, if the last ivar is a bitfield of any type,
13816 /// then add an implicit `char :0` ivar to the end of that interface.
ActOnLastBitfield(SourceLocation DeclLoc,SmallVectorImpl<Decl * > & AllIvarDecls)13817 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13818                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13819   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13820     return;
13821 
13822   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13823   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13824 
13825   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13826     return;
13827   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13828   if (!ID) {
13829     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13830       if (!CD->IsClassExtension())
13831         return;
13832     }
13833     // No need to add this to end of @implementation.
13834     else
13835       return;
13836   }
13837   // All conditions are met. Add a new bitfield to the tail end of ivars.
13838   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13839   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13840 
13841   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13842                               DeclLoc, DeclLoc, nullptr,
13843                               Context.CharTy,
13844                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13845                                                                DeclLoc),
13846                               ObjCIvarDecl::Private, BW,
13847                               true);
13848   AllIvarDecls.push_back(Ivar);
13849 }
13850 
ActOnFields(Scope * S,SourceLocation RecLoc,Decl * EnclosingDecl,ArrayRef<Decl * > Fields,SourceLocation LBrac,SourceLocation RBrac,AttributeList * Attr)13851 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13852                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13853                        SourceLocation RBrac, AttributeList *Attr) {
13854   assert(EnclosingDecl && "missing record or interface decl");
13855 
13856   // If this is an Objective-C @implementation or category and we have
13857   // new fields here we should reset the layout of the interface since
13858   // it will now change.
13859   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13860     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13861     switch (DC->getKind()) {
13862     default: break;
13863     case Decl::ObjCCategory:
13864       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13865       break;
13866     case Decl::ObjCImplementation:
13867       Context.
13868         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13869       break;
13870     }
13871   }
13872 
13873   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13874 
13875   // Start counting up the number of named members; make sure to include
13876   // members of anonymous structs and unions in the total.
13877   unsigned NumNamedMembers = 0;
13878   if (Record) {
13879     for (const auto *I : Record->decls()) {
13880       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13881         if (IFD->getDeclName())
13882           ++NumNamedMembers;
13883     }
13884   }
13885 
13886   // Verify that all the fields are okay.
13887   SmallVector<FieldDecl*, 32> RecFields;
13888 
13889   bool ARCErrReported = false;
13890   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13891        i != end; ++i) {
13892     FieldDecl *FD = cast<FieldDecl>(*i);
13893 
13894     // Get the type for the field.
13895     const Type *FDTy = FD->getType().getTypePtr();
13896 
13897     if (!FD->isAnonymousStructOrUnion()) {
13898       // Remember all fields written by the user.
13899       RecFields.push_back(FD);
13900     }
13901 
13902     // If the field is already invalid for some reason, don't emit more
13903     // diagnostics about it.
13904     if (FD->isInvalidDecl()) {
13905       EnclosingDecl->setInvalidDecl();
13906       continue;
13907     }
13908 
13909     // C99 6.7.2.1p2:
13910     //   A structure or union shall not contain a member with
13911     //   incomplete or function type (hence, a structure shall not
13912     //   contain an instance of itself, but may contain a pointer to
13913     //   an instance of itself), except that the last member of a
13914     //   structure with more than one named member may have incomplete
13915     //   array type; such a structure (and any union containing,
13916     //   possibly recursively, a member that is such a structure)
13917     //   shall not be a member of a structure or an element of an
13918     //   array.
13919     if (FDTy->isFunctionType()) {
13920       // Field declared as a function.
13921       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13922         << FD->getDeclName();
13923       FD->setInvalidDecl();
13924       EnclosingDecl->setInvalidDecl();
13925       continue;
13926     } else if (FDTy->isIncompleteArrayType() && Record &&
13927                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13928                 ((getLangOpts().MicrosoftExt ||
13929                   getLangOpts().CPlusPlus) &&
13930                  (i + 1 == Fields.end() || Record->isUnion())))) {
13931       // Flexible array member.
13932       // Microsoft and g++ is more permissive regarding flexible array.
13933       // It will accept flexible array in union and also
13934       // as the sole element of a struct/class.
13935       unsigned DiagID = 0;
13936       if (Record->isUnion())
13937         DiagID = getLangOpts().MicrosoftExt
13938                      ? diag::ext_flexible_array_union_ms
13939                      : getLangOpts().CPlusPlus
13940                            ? diag::ext_flexible_array_union_gnu
13941                            : diag::err_flexible_array_union;
13942       else if (NumNamedMembers < 1)
13943         DiagID = getLangOpts().MicrosoftExt
13944                      ? diag::ext_flexible_array_empty_aggregate_ms
13945                      : getLangOpts().CPlusPlus
13946                            ? diag::ext_flexible_array_empty_aggregate_gnu
13947                            : diag::err_flexible_array_empty_aggregate;
13948 
13949       if (DiagID)
13950         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13951                                         << Record->getTagKind();
13952       // While the layout of types that contain virtual bases is not specified
13953       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13954       // virtual bases after the derived members.  This would make a flexible
13955       // array member declared at the end of an object not adjacent to the end
13956       // of the type.
13957       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13958         if (RD->getNumVBases() != 0)
13959           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13960             << FD->getDeclName() << Record->getTagKind();
13961       if (!getLangOpts().C99)
13962         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13963           << FD->getDeclName() << Record->getTagKind();
13964 
13965       // If the element type has a non-trivial destructor, we would not
13966       // implicitly destroy the elements, so disallow it for now.
13967       //
13968       // FIXME: GCC allows this. We should probably either implicitly delete
13969       // the destructor of the containing class, or just allow this.
13970       QualType BaseElem = Context.getBaseElementType(FD->getType());
13971       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13972         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13973           << FD->getDeclName() << FD->getType();
13974         FD->setInvalidDecl();
13975         EnclosingDecl->setInvalidDecl();
13976         continue;
13977       }
13978       // Okay, we have a legal flexible array member at the end of the struct.
13979       Record->setHasFlexibleArrayMember(true);
13980     } else if (!FDTy->isDependentType() &&
13981                RequireCompleteType(FD->getLocation(), FD->getType(),
13982                                    diag::err_field_incomplete)) {
13983       // Incomplete type
13984       FD->setInvalidDecl();
13985       EnclosingDecl->setInvalidDecl();
13986       continue;
13987     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13988       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13989         // A type which contains a flexible array member is considered to be a
13990         // flexible array member.
13991         Record->setHasFlexibleArrayMember(true);
13992         if (!Record->isUnion()) {
13993           // If this is a struct/class and this is not the last element, reject
13994           // it.  Note that GCC supports variable sized arrays in the middle of
13995           // structures.
13996           if (i + 1 != Fields.end())
13997             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13998               << FD->getDeclName() << FD->getType();
13999           else {
14000             // We support flexible arrays at the end of structs in
14001             // other structs as an extension.
14002             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14003               << FD->getDeclName();
14004           }
14005         }
14006       }
14007       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14008           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14009                                  diag::err_abstract_type_in_decl,
14010                                  AbstractIvarType)) {
14011         // Ivars can not have abstract class types
14012         FD->setInvalidDecl();
14013       }
14014       if (Record && FDTTy->getDecl()->hasObjectMember())
14015         Record->setHasObjectMember(true);
14016       if (Record && FDTTy->getDecl()->hasVolatileMember())
14017         Record->setHasVolatileMember(true);
14018     } else if (FDTy->isObjCObjectType()) {
14019       /// A field cannot be an Objective-c object
14020       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14021         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14022       QualType T = Context.getObjCObjectPointerType(FD->getType());
14023       FD->setType(T);
14024     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14025                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14026       // It's an error in ARC if a field has lifetime.
14027       // We don't want to report this in a system header, though,
14028       // so we just make the field unavailable.
14029       // FIXME: that's really not sufficient; we need to make the type
14030       // itself invalid to, say, initialize or copy.
14031       QualType T = FD->getType();
14032       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14033       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
14034         SourceLocation loc = FD->getLocation();
14035         if (getSourceManager().isInSystemHeader(loc)) {
14036           if (!FD->hasAttr<UnavailableAttr>()) {
14037             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14038                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14039           }
14040         } else {
14041           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14042             << T->isBlockPointerType() << Record->getTagKind();
14043         }
14044         ARCErrReported = true;
14045       }
14046     } else if (getLangOpts().ObjC1 &&
14047                getLangOpts().getGC() != LangOptions::NonGC &&
14048                Record && !Record->hasObjectMember()) {
14049       if (FD->getType()->isObjCObjectPointerType() ||
14050           FD->getType().isObjCGCStrong())
14051         Record->setHasObjectMember(true);
14052       else if (Context.getAsArrayType(FD->getType())) {
14053         QualType BaseType = Context.getBaseElementType(FD->getType());
14054         if (BaseType->isRecordType() &&
14055             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14056           Record->setHasObjectMember(true);
14057         else if (BaseType->isObjCObjectPointerType() ||
14058                  BaseType.isObjCGCStrong())
14059                Record->setHasObjectMember(true);
14060       }
14061     }
14062     if (Record && FD->getType().isVolatileQualified())
14063       Record->setHasVolatileMember(true);
14064     // Keep track of the number of named members.
14065     if (FD->getIdentifier())
14066       ++NumNamedMembers;
14067   }
14068 
14069   // Okay, we successfully defined 'Record'.
14070   if (Record) {
14071     bool Completed = false;
14072     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14073       if (!CXXRecord->isInvalidDecl()) {
14074         // Set access bits correctly on the directly-declared conversions.
14075         for (CXXRecordDecl::conversion_iterator
14076                I = CXXRecord->conversion_begin(),
14077                E = CXXRecord->conversion_end(); I != E; ++I)
14078           I.setAccess((*I)->getAccess());
14079       }
14080 
14081       if (!CXXRecord->isDependentType()) {
14082         if (CXXRecord->hasUserDeclaredDestructor()) {
14083           // Adjust user-defined destructor exception spec.
14084           if (getLangOpts().CPlusPlus11)
14085             AdjustDestructorExceptionSpec(CXXRecord,
14086                                           CXXRecord->getDestructor());
14087         }
14088 
14089         if (!CXXRecord->isInvalidDecl()) {
14090           // Add any implicitly-declared members to this class.
14091           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14092 
14093           // If we have virtual base classes, we may end up finding multiple
14094           // final overriders for a given virtual function. Check for this
14095           // problem now.
14096           if (CXXRecord->getNumVBases()) {
14097             CXXFinalOverriderMap FinalOverriders;
14098             CXXRecord->getFinalOverriders(FinalOverriders);
14099 
14100             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14101                                              MEnd = FinalOverriders.end();
14102                  M != MEnd; ++M) {
14103               for (OverridingMethods::iterator SO = M->second.begin(),
14104                                             SOEnd = M->second.end();
14105                    SO != SOEnd; ++SO) {
14106                 assert(SO->second.size() > 0 &&
14107                        "Virtual function without overridding functions?");
14108                 if (SO->second.size() == 1)
14109                   continue;
14110 
14111                 // C++ [class.virtual]p2:
14112                 //   In a derived class, if a virtual member function of a base
14113                 //   class subobject has more than one final overrider the
14114                 //   program is ill-formed.
14115                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14116                   << (const NamedDecl *)M->first << Record;
14117                 Diag(M->first->getLocation(),
14118                      diag::note_overridden_virtual_function);
14119                 for (OverridingMethods::overriding_iterator
14120                           OM = SO->second.begin(),
14121                        OMEnd = SO->second.end();
14122                      OM != OMEnd; ++OM)
14123                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14124                     << (const NamedDecl *)M->first << OM->Method->getParent();
14125 
14126                 Record->setInvalidDecl();
14127               }
14128             }
14129             CXXRecord->completeDefinition(&FinalOverriders);
14130             Completed = true;
14131           }
14132         }
14133       }
14134     }
14135 
14136     if (!Completed)
14137       Record->completeDefinition();
14138 
14139     if (Record->hasAttrs()) {
14140       CheckAlignasUnderalignment(Record);
14141 
14142       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14143         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14144                                            IA->getRange(), IA->getBestCase(),
14145                                            IA->getSemanticSpelling());
14146     }
14147 
14148     // Check if the structure/union declaration is a type that can have zero
14149     // size in C. For C this is a language extension, for C++ it may cause
14150     // compatibility problems.
14151     bool CheckForZeroSize;
14152     if (!getLangOpts().CPlusPlus) {
14153       CheckForZeroSize = true;
14154     } else {
14155       // For C++ filter out types that cannot be referenced in C code.
14156       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14157       CheckForZeroSize =
14158           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14159           !CXXRecord->isDependentType() &&
14160           CXXRecord->isCLike();
14161     }
14162     if (CheckForZeroSize) {
14163       bool ZeroSize = true;
14164       bool IsEmpty = true;
14165       unsigned NonBitFields = 0;
14166       for (RecordDecl::field_iterator I = Record->field_begin(),
14167                                       E = Record->field_end();
14168            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14169         IsEmpty = false;
14170         if (I->isUnnamedBitfield()) {
14171           if (I->getBitWidthValue(Context) > 0)
14172             ZeroSize = false;
14173         } else {
14174           ++NonBitFields;
14175           QualType FieldType = I->getType();
14176           if (FieldType->isIncompleteType() ||
14177               !Context.getTypeSizeInChars(FieldType).isZero())
14178             ZeroSize = false;
14179         }
14180       }
14181 
14182       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14183       // allowed in C++, but warn if its declaration is inside
14184       // extern "C" block.
14185       if (ZeroSize) {
14186         Diag(RecLoc, getLangOpts().CPlusPlus ?
14187                          diag::warn_zero_size_struct_union_in_extern_c :
14188                          diag::warn_zero_size_struct_union_compat)
14189           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14190       }
14191 
14192       // Structs without named members are extension in C (C99 6.7.2.1p7),
14193       // but are accepted by GCC.
14194       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14195         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14196                                diag::ext_no_named_members_in_struct_union)
14197           << Record->isUnion();
14198       }
14199     }
14200   } else {
14201     ObjCIvarDecl **ClsFields =
14202       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14203     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14204       ID->setEndOfDefinitionLoc(RBrac);
14205       // Add ivar's to class's DeclContext.
14206       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14207         ClsFields[i]->setLexicalDeclContext(ID);
14208         ID->addDecl(ClsFields[i]);
14209       }
14210       // Must enforce the rule that ivars in the base classes may not be
14211       // duplicates.
14212       if (ID->getSuperClass())
14213         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14214     } else if (ObjCImplementationDecl *IMPDecl =
14215                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14216       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14217       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14218         // Ivar declared in @implementation never belongs to the implementation.
14219         // Only it is in implementation's lexical context.
14220         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14221       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14222       IMPDecl->setIvarLBraceLoc(LBrac);
14223       IMPDecl->setIvarRBraceLoc(RBrac);
14224     } else if (ObjCCategoryDecl *CDecl =
14225                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14226       // case of ivars in class extension; all other cases have been
14227       // reported as errors elsewhere.
14228       // FIXME. Class extension does not have a LocEnd field.
14229       // CDecl->setLocEnd(RBrac);
14230       // Add ivar's to class extension's DeclContext.
14231       // Diagnose redeclaration of private ivars.
14232       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14233       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14234         if (IDecl) {
14235           if (const ObjCIvarDecl *ClsIvar =
14236               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14237             Diag(ClsFields[i]->getLocation(),
14238                  diag::err_duplicate_ivar_declaration);
14239             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14240             continue;
14241           }
14242           for (const auto *Ext : IDecl->known_extensions()) {
14243             if (const ObjCIvarDecl *ClsExtIvar
14244                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14245               Diag(ClsFields[i]->getLocation(),
14246                    diag::err_duplicate_ivar_declaration);
14247               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14248               continue;
14249             }
14250           }
14251         }
14252         ClsFields[i]->setLexicalDeclContext(CDecl);
14253         CDecl->addDecl(ClsFields[i]);
14254       }
14255       CDecl->setIvarLBraceLoc(LBrac);
14256       CDecl->setIvarRBraceLoc(RBrac);
14257     }
14258   }
14259 
14260   if (Attr)
14261     ProcessDeclAttributeList(S, Record, Attr);
14262 }
14263 
14264 /// \brief Determine whether the given integral value is representable within
14265 /// the given type T.
isRepresentableIntegerValue(ASTContext & Context,llvm::APSInt & Value,QualType T)14266 static bool isRepresentableIntegerValue(ASTContext &Context,
14267                                         llvm::APSInt &Value,
14268                                         QualType T) {
14269   assert(T->isIntegralType(Context) && "Integral type required!");
14270   unsigned BitWidth = Context.getIntWidth(T);
14271 
14272   if (Value.isUnsigned() || Value.isNonNegative()) {
14273     if (T->isSignedIntegerOrEnumerationType())
14274       --BitWidth;
14275     return Value.getActiveBits() <= BitWidth;
14276   }
14277   return Value.getMinSignedBits() <= BitWidth;
14278 }
14279 
14280 // \brief Given an integral type, return the next larger integral type
14281 // (or a NULL type of no such type exists).
getNextLargerIntegralType(ASTContext & Context,QualType T)14282 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14283   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14284   // enum checking below.
14285   assert(T->isIntegralType(Context) && "Integral type required!");
14286   const unsigned NumTypes = 4;
14287   QualType SignedIntegralTypes[NumTypes] = {
14288     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14289   };
14290   QualType UnsignedIntegralTypes[NumTypes] = {
14291     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14292     Context.UnsignedLongLongTy
14293   };
14294 
14295   unsigned BitWidth = Context.getTypeSize(T);
14296   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14297                                                         : UnsignedIntegralTypes;
14298   for (unsigned I = 0; I != NumTypes; ++I)
14299     if (Context.getTypeSize(Types[I]) > BitWidth)
14300       return Types[I];
14301 
14302   return QualType();
14303 }
14304 
CheckEnumConstant(EnumDecl * Enum,EnumConstantDecl * LastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,Expr * Val)14305 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14306                                           EnumConstantDecl *LastEnumConst,
14307                                           SourceLocation IdLoc,
14308                                           IdentifierInfo *Id,
14309                                           Expr *Val) {
14310   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14311   llvm::APSInt EnumVal(IntWidth);
14312   QualType EltTy;
14313 
14314   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14315     Val = nullptr;
14316 
14317   if (Val)
14318     Val = DefaultLvalueConversion(Val).get();
14319 
14320   if (Val) {
14321     if (Enum->isDependentType() || Val->isTypeDependent())
14322       EltTy = Context.DependentTy;
14323     else {
14324       SourceLocation ExpLoc;
14325       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14326           !getLangOpts().MSVCCompat) {
14327         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14328         // constant-expression in the enumerator-definition shall be a converted
14329         // constant expression of the underlying type.
14330         EltTy = Enum->getIntegerType();
14331         ExprResult Converted =
14332           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14333                                            CCEK_Enumerator);
14334         if (Converted.isInvalid())
14335           Val = nullptr;
14336         else
14337           Val = Converted.get();
14338       } else if (!Val->isValueDependent() &&
14339                  !(Val = VerifyIntegerConstantExpression(Val,
14340                                                          &EnumVal).get())) {
14341         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14342       } else {
14343         if (Enum->isFixed()) {
14344           EltTy = Enum->getIntegerType();
14345 
14346           // In Obj-C and Microsoft mode, require the enumeration value to be
14347           // representable in the underlying type of the enumeration. In C++11,
14348           // we perform a non-narrowing conversion as part of converted constant
14349           // expression checking.
14350           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14351             if (getLangOpts().MSVCCompat) {
14352               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14353               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14354             } else
14355               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14356           } else
14357             Val = ImpCastExprToType(Val, EltTy,
14358                                     EltTy->isBooleanType() ?
14359                                     CK_IntegralToBoolean : CK_IntegralCast)
14360                     .get();
14361         } else if (getLangOpts().CPlusPlus) {
14362           // C++11 [dcl.enum]p5:
14363           //   If the underlying type is not fixed, the type of each enumerator
14364           //   is the type of its initializing value:
14365           //     - If an initializer is specified for an enumerator, the
14366           //       initializing value has the same type as the expression.
14367           EltTy = Val->getType();
14368         } else {
14369           // C99 6.7.2.2p2:
14370           //   The expression that defines the value of an enumeration constant
14371           //   shall be an integer constant expression that has a value
14372           //   representable as an int.
14373 
14374           // Complain if the value is not representable in an int.
14375           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14376             Diag(IdLoc, diag::ext_enum_value_not_int)
14377               << EnumVal.toString(10) << Val->getSourceRange()
14378               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14379           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14380             // Force the type of the expression to 'int'.
14381             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14382           }
14383           EltTy = Val->getType();
14384         }
14385       }
14386     }
14387   }
14388 
14389   if (!Val) {
14390     if (Enum->isDependentType())
14391       EltTy = Context.DependentTy;
14392     else if (!LastEnumConst) {
14393       // C++0x [dcl.enum]p5:
14394       //   If the underlying type is not fixed, the type of each enumerator
14395       //   is the type of its initializing value:
14396       //     - If no initializer is specified for the first enumerator, the
14397       //       initializing value has an unspecified integral type.
14398       //
14399       // GCC uses 'int' for its unspecified integral type, as does
14400       // C99 6.7.2.2p3.
14401       if (Enum->isFixed()) {
14402         EltTy = Enum->getIntegerType();
14403       }
14404       else {
14405         EltTy = Context.IntTy;
14406       }
14407     } else {
14408       // Assign the last value + 1.
14409       EnumVal = LastEnumConst->getInitVal();
14410       ++EnumVal;
14411       EltTy = LastEnumConst->getType();
14412 
14413       // Check for overflow on increment.
14414       if (EnumVal < LastEnumConst->getInitVal()) {
14415         // C++0x [dcl.enum]p5:
14416         //   If the underlying type is not fixed, the type of each enumerator
14417         //   is the type of its initializing value:
14418         //
14419         //     - Otherwise the type of the initializing value is the same as
14420         //       the type of the initializing value of the preceding enumerator
14421         //       unless the incremented value is not representable in that type,
14422         //       in which case the type is an unspecified integral type
14423         //       sufficient to contain the incremented value. If no such type
14424         //       exists, the program is ill-formed.
14425         QualType T = getNextLargerIntegralType(Context, EltTy);
14426         if (T.isNull() || Enum->isFixed()) {
14427           // There is no integral type larger enough to represent this
14428           // value. Complain, then allow the value to wrap around.
14429           EnumVal = LastEnumConst->getInitVal();
14430           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14431           ++EnumVal;
14432           if (Enum->isFixed())
14433             // When the underlying type is fixed, this is ill-formed.
14434             Diag(IdLoc, diag::err_enumerator_wrapped)
14435               << EnumVal.toString(10)
14436               << EltTy;
14437           else
14438             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14439               << EnumVal.toString(10);
14440         } else {
14441           EltTy = T;
14442         }
14443 
14444         // Retrieve the last enumerator's value, extent that type to the
14445         // type that is supposed to be large enough to represent the incremented
14446         // value, then increment.
14447         EnumVal = LastEnumConst->getInitVal();
14448         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14449         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14450         ++EnumVal;
14451 
14452         // If we're not in C++, diagnose the overflow of enumerator values,
14453         // which in C99 means that the enumerator value is not representable in
14454         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14455         // permits enumerator values that are representable in some larger
14456         // integral type.
14457         if (!getLangOpts().CPlusPlus && !T.isNull())
14458           Diag(IdLoc, diag::warn_enum_value_overflow);
14459       } else if (!getLangOpts().CPlusPlus &&
14460                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14461         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14462         Diag(IdLoc, diag::ext_enum_value_not_int)
14463           << EnumVal.toString(10) << 1;
14464       }
14465     }
14466   }
14467 
14468   if (!EltTy->isDependentType()) {
14469     // Make the enumerator value match the signedness and size of the
14470     // enumerator's type.
14471     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14472     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14473   }
14474 
14475   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14476                                   Val, EnumVal);
14477 }
14478 
shouldSkipAnonEnumBody(Scope * S,IdentifierInfo * II,SourceLocation IILoc)14479 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14480                                                 SourceLocation IILoc) {
14481   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14482       !getLangOpts().CPlusPlus)
14483     return SkipBodyInfo();
14484 
14485   // We have an anonymous enum definition. Look up the first enumerator to
14486   // determine if we should merge the definition with an existing one and
14487   // skip the body.
14488   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14489                                          ForRedeclaration);
14490   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14491   if (!PrevECD)
14492     return SkipBodyInfo();
14493 
14494   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14495   NamedDecl *Hidden;
14496   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14497     SkipBodyInfo Skip;
14498     Skip.Previous = Hidden;
14499     return Skip;
14500   }
14501 
14502   return SkipBodyInfo();
14503 }
14504 
ActOnEnumConstant(Scope * S,Decl * theEnumDecl,Decl * lastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,AttributeList * Attr,SourceLocation EqualLoc,Expr * Val)14505 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14506                               SourceLocation IdLoc, IdentifierInfo *Id,
14507                               AttributeList *Attr,
14508                               SourceLocation EqualLoc, Expr *Val) {
14509   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14510   EnumConstantDecl *LastEnumConst =
14511     cast_or_null<EnumConstantDecl>(lastEnumConst);
14512 
14513   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14514   // we find one that is.
14515   S = getNonFieldDeclScope(S);
14516 
14517   // Verify that there isn't already something declared with this name in this
14518   // scope.
14519   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14520                                          ForRedeclaration);
14521   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14522     // Maybe we will complain about the shadowed template parameter.
14523     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14524     // Just pretend that we didn't see the previous declaration.
14525     PrevDecl = nullptr;
14526   }
14527 
14528   // C++ [class.mem]p15:
14529   // If T is the name of a class, then each of the following shall have a name
14530   // different from T:
14531   // - every enumerator of every member of class T that is an unscoped
14532   // enumerated type
14533   if (!TheEnumDecl->isScoped())
14534     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14535                             DeclarationNameInfo(Id, IdLoc));
14536 
14537   EnumConstantDecl *New =
14538     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14539   if (!New)
14540     return nullptr;
14541 
14542   if (PrevDecl) {
14543     // When in C++, we may get a TagDecl with the same name; in this case the
14544     // enum constant will 'hide' the tag.
14545     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14546            "Received TagDecl when not in C++!");
14547     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14548         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14549       if (isa<EnumConstantDecl>(PrevDecl))
14550         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14551       else
14552         Diag(IdLoc, diag::err_redefinition) << Id;
14553       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14554       return nullptr;
14555     }
14556   }
14557 
14558   // Process attributes.
14559   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14560 
14561   // Register this decl in the current scope stack.
14562   New->setAccess(TheEnumDecl->getAccess());
14563   PushOnScopeChains(New, S);
14564 
14565   ActOnDocumentableDecl(New);
14566 
14567   return New;
14568 }
14569 
14570 // Returns true when the enum initial expression does not trigger the
14571 // duplicate enum warning.  A few common cases are exempted as follows:
14572 // Element2 = Element1
14573 // Element2 = Element1 + 1
14574 // Element2 = Element1 - 1
14575 // Where Element2 and Element1 are from the same enum.
ValidDuplicateEnum(EnumConstantDecl * ECD,EnumDecl * Enum)14576 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14577   Expr *InitExpr = ECD->getInitExpr();
14578   if (!InitExpr)
14579     return true;
14580   InitExpr = InitExpr->IgnoreImpCasts();
14581 
14582   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14583     if (!BO->isAdditiveOp())
14584       return true;
14585     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14586     if (!IL)
14587       return true;
14588     if (IL->getValue() != 1)
14589       return true;
14590 
14591     InitExpr = BO->getLHS();
14592   }
14593 
14594   // This checks if the elements are from the same enum.
14595   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14596   if (!DRE)
14597     return true;
14598 
14599   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14600   if (!EnumConstant)
14601     return true;
14602 
14603   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14604       Enum)
14605     return true;
14606 
14607   return false;
14608 }
14609 
14610 namespace {
14611 struct DupKey {
14612   int64_t val;
14613   bool isTombstoneOrEmptyKey;
DupKey__anon9ef05b340b11::DupKey14614   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14615     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14616 };
14617 
GetDupKey(const llvm::APSInt & Val)14618 static DupKey GetDupKey(const llvm::APSInt& Val) {
14619   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14620                 false);
14621 }
14622 
14623 struct DenseMapInfoDupKey {
getEmptyKey__anon9ef05b340b11::DenseMapInfoDupKey14624   static DupKey getEmptyKey() { return DupKey(0, true); }
getTombstoneKey__anon9ef05b340b11::DenseMapInfoDupKey14625   static DupKey getTombstoneKey() { return DupKey(1, true); }
getHashValue__anon9ef05b340b11::DenseMapInfoDupKey14626   static unsigned getHashValue(const DupKey Key) {
14627     return (unsigned)(Key.val * 37);
14628   }
isEqual__anon9ef05b340b11::DenseMapInfoDupKey14629   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14630     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14631            LHS.val == RHS.val;
14632   }
14633 };
14634 } // end anonymous namespace
14635 
14636 // Emits a warning when an element is implicitly set a value that
14637 // a previous element has already been set to.
CheckForDuplicateEnumValues(Sema & S,ArrayRef<Decl * > Elements,EnumDecl * Enum,QualType EnumType)14638 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14639                                         EnumDecl *Enum,
14640                                         QualType EnumType) {
14641   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14642     return;
14643   // Avoid anonymous enums
14644   if (!Enum->getIdentifier())
14645     return;
14646 
14647   // Only check for small enums.
14648   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14649     return;
14650 
14651   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14652   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14653 
14654   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14655   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14656           ValueToVectorMap;
14657 
14658   DuplicatesVector DupVector;
14659   ValueToVectorMap EnumMap;
14660 
14661   // Populate the EnumMap with all values represented by enum constants without
14662   // an initialier.
14663   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14664     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14665 
14666     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14667     // this constant.  Skip this enum since it may be ill-formed.
14668     if (!ECD) {
14669       return;
14670     }
14671 
14672     if (ECD->getInitExpr())
14673       continue;
14674 
14675     DupKey Key = GetDupKey(ECD->getInitVal());
14676     DeclOrVector &Entry = EnumMap[Key];
14677 
14678     // First time encountering this value.
14679     if (Entry.isNull())
14680       Entry = ECD;
14681   }
14682 
14683   // Create vectors for any values that has duplicates.
14684   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14685     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14686     if (!ValidDuplicateEnum(ECD, Enum))
14687       continue;
14688 
14689     DupKey Key = GetDupKey(ECD->getInitVal());
14690 
14691     DeclOrVector& Entry = EnumMap[Key];
14692     if (Entry.isNull())
14693       continue;
14694 
14695     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14696       // Ensure constants are different.
14697       if (D == ECD)
14698         continue;
14699 
14700       // Create new vector and push values onto it.
14701       ECDVector *Vec = new ECDVector();
14702       Vec->push_back(D);
14703       Vec->push_back(ECD);
14704 
14705       // Update entry to point to the duplicates vector.
14706       Entry = Vec;
14707 
14708       // Store the vector somewhere we can consult later for quick emission of
14709       // diagnostics.
14710       DupVector.push_back(Vec);
14711       continue;
14712     }
14713 
14714     ECDVector *Vec = Entry.get<ECDVector*>();
14715     // Make sure constants are not added more than once.
14716     if (*Vec->begin() == ECD)
14717       continue;
14718 
14719     Vec->push_back(ECD);
14720   }
14721 
14722   // Emit diagnostics.
14723   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14724                                   DupVectorEnd = DupVector.end();
14725        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14726     ECDVector *Vec = *DupVectorIter;
14727     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14728 
14729     // Emit warning for one enum constant.
14730     ECDVector::iterator I = Vec->begin();
14731     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14732       << (*I)->getName() << (*I)->getInitVal().toString(10)
14733       << (*I)->getSourceRange();
14734     ++I;
14735 
14736     // Emit one note for each of the remaining enum constants with
14737     // the same value.
14738     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14739       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14740         << (*I)->getName() << (*I)->getInitVal().toString(10)
14741         << (*I)->getSourceRange();
14742     delete Vec;
14743   }
14744 }
14745 
IsValueInFlagEnum(const EnumDecl * ED,const llvm::APInt & Val,bool AllowMask) const14746 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14747                              bool AllowMask) const {
14748   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14749   assert(ED->isCompleteDefinition() && "expected enum definition");
14750 
14751   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14752   llvm::APInt &FlagBits = R.first->second;
14753 
14754   if (R.second) {
14755     for (auto *E : ED->enumerators()) {
14756       const auto &EVal = E->getInitVal();
14757       // Only single-bit enumerators introduce new flag values.
14758       if (EVal.isPowerOf2())
14759         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14760     }
14761   }
14762 
14763   // A value is in a flag enum if either its bits are a subset of the enum's
14764   // flag bits (the first condition) or we are allowing masks and the same is
14765   // true of its complement (the second condition). When masks are allowed, we
14766   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14767   //
14768   // While it's true that any value could be used as a mask, the assumption is
14769   // that a mask will have all of the insignificant bits set. Anything else is
14770   // likely a logic error.
14771   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14772   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14773 }
14774 
ActOnEnumBody(SourceLocation EnumLoc,SourceLocation LBraceLoc,SourceLocation RBraceLoc,Decl * EnumDeclX,ArrayRef<Decl * > Elements,Scope * S,AttributeList * Attr)14775 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14776                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14777                          ArrayRef<Decl *> Elements,
14778                          Scope *S, AttributeList *Attr) {
14779   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14780   QualType EnumType = Context.getTypeDeclType(Enum);
14781 
14782   if (Attr)
14783     ProcessDeclAttributeList(S, Enum, Attr);
14784 
14785   if (Enum->isDependentType()) {
14786     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14787       EnumConstantDecl *ECD =
14788         cast_or_null<EnumConstantDecl>(Elements[i]);
14789       if (!ECD) continue;
14790 
14791       ECD->setType(EnumType);
14792     }
14793 
14794     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14795     return;
14796   }
14797 
14798   // TODO: If the result value doesn't fit in an int, it must be a long or long
14799   // long value.  ISO C does not support this, but GCC does as an extension,
14800   // emit a warning.
14801   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14802   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14803   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14804 
14805   // Verify that all the values are okay, compute the size of the values, and
14806   // reverse the list.
14807   unsigned NumNegativeBits = 0;
14808   unsigned NumPositiveBits = 0;
14809 
14810   // Keep track of whether all elements have type int.
14811   bool AllElementsInt = true;
14812 
14813   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14814     EnumConstantDecl *ECD =
14815       cast_or_null<EnumConstantDecl>(Elements[i]);
14816     if (!ECD) continue;  // Already issued a diagnostic.
14817 
14818     const llvm::APSInt &InitVal = ECD->getInitVal();
14819 
14820     // Keep track of the size of positive and negative values.
14821     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14822       NumPositiveBits = std::max(NumPositiveBits,
14823                                  (unsigned)InitVal.getActiveBits());
14824     else
14825       NumNegativeBits = std::max(NumNegativeBits,
14826                                  (unsigned)InitVal.getMinSignedBits());
14827 
14828     // Keep track of whether every enum element has type int (very commmon).
14829     if (AllElementsInt)
14830       AllElementsInt = ECD->getType() == Context.IntTy;
14831   }
14832 
14833   // Figure out the type that should be used for this enum.
14834   QualType BestType;
14835   unsigned BestWidth;
14836 
14837   // C++0x N3000 [conv.prom]p3:
14838   //   An rvalue of an unscoped enumeration type whose underlying
14839   //   type is not fixed can be converted to an rvalue of the first
14840   //   of the following types that can represent all the values of
14841   //   the enumeration: int, unsigned int, long int, unsigned long
14842   //   int, long long int, or unsigned long long int.
14843   // C99 6.4.4.3p2:
14844   //   An identifier declared as an enumeration constant has type int.
14845   // The C99 rule is modified by a gcc extension
14846   QualType BestPromotionType;
14847 
14848   bool Packed = Enum->hasAttr<PackedAttr>();
14849   // -fshort-enums is the equivalent to specifying the packed attribute on all
14850   // enum definitions.
14851   if (LangOpts.ShortEnums)
14852     Packed = true;
14853 
14854   if (Enum->isFixed()) {
14855     BestType = Enum->getIntegerType();
14856     if (BestType->isPromotableIntegerType())
14857       BestPromotionType = Context.getPromotedIntegerType(BestType);
14858     else
14859       BestPromotionType = BestType;
14860 
14861     BestWidth = Context.getIntWidth(BestType);
14862   }
14863   else if (NumNegativeBits) {
14864     // If there is a negative value, figure out the smallest integer type (of
14865     // int/long/longlong) that fits.
14866     // If it's packed, check also if it fits a char or a short.
14867     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14868       BestType = Context.SignedCharTy;
14869       BestWidth = CharWidth;
14870     } else if (Packed && NumNegativeBits <= ShortWidth &&
14871                NumPositiveBits < ShortWidth) {
14872       BestType = Context.ShortTy;
14873       BestWidth = ShortWidth;
14874     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14875       BestType = Context.IntTy;
14876       BestWidth = IntWidth;
14877     } else {
14878       BestWidth = Context.getTargetInfo().getLongWidth();
14879 
14880       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14881         BestType = Context.LongTy;
14882       } else {
14883         BestWidth = Context.getTargetInfo().getLongLongWidth();
14884 
14885         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14886           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14887         BestType = Context.LongLongTy;
14888       }
14889     }
14890     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14891   } else {
14892     // If there is no negative value, figure out the smallest type that fits
14893     // all of the enumerator values.
14894     // If it's packed, check also if it fits a char or a short.
14895     if (Packed && NumPositiveBits <= CharWidth) {
14896       BestType = Context.UnsignedCharTy;
14897       BestPromotionType = Context.IntTy;
14898       BestWidth = CharWidth;
14899     } else if (Packed && NumPositiveBits <= ShortWidth) {
14900       BestType = Context.UnsignedShortTy;
14901       BestPromotionType = Context.IntTy;
14902       BestWidth = ShortWidth;
14903     } else if (NumPositiveBits <= IntWidth) {
14904       BestType = Context.UnsignedIntTy;
14905       BestWidth = IntWidth;
14906       BestPromotionType
14907         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14908                            ? Context.UnsignedIntTy : Context.IntTy;
14909     } else if (NumPositiveBits <=
14910                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14911       BestType = Context.UnsignedLongTy;
14912       BestPromotionType
14913         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14914                            ? Context.UnsignedLongTy : Context.LongTy;
14915     } else {
14916       BestWidth = Context.getTargetInfo().getLongLongWidth();
14917       assert(NumPositiveBits <= BestWidth &&
14918              "How could an initializer get larger than ULL?");
14919       BestType = Context.UnsignedLongLongTy;
14920       BestPromotionType
14921         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14922                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14923     }
14924   }
14925 
14926   // Loop over all of the enumerator constants, changing their types to match
14927   // the type of the enum if needed.
14928   for (auto *D : Elements) {
14929     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14930     if (!ECD) continue;  // Already issued a diagnostic.
14931 
14932     // Standard C says the enumerators have int type, but we allow, as an
14933     // extension, the enumerators to be larger than int size.  If each
14934     // enumerator value fits in an int, type it as an int, otherwise type it the
14935     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14936     // that X has type 'int', not 'unsigned'.
14937 
14938     // Determine whether the value fits into an int.
14939     llvm::APSInt InitVal = ECD->getInitVal();
14940 
14941     // If it fits into an integer type, force it.  Otherwise force it to match
14942     // the enum decl type.
14943     QualType NewTy;
14944     unsigned NewWidth;
14945     bool NewSign;
14946     if (!getLangOpts().CPlusPlus &&
14947         !Enum->isFixed() &&
14948         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14949       NewTy = Context.IntTy;
14950       NewWidth = IntWidth;
14951       NewSign = true;
14952     } else if (ECD->getType() == BestType) {
14953       // Already the right type!
14954       if (getLangOpts().CPlusPlus)
14955         // C++ [dcl.enum]p4: Following the closing brace of an
14956         // enum-specifier, each enumerator has the type of its
14957         // enumeration.
14958         ECD->setType(EnumType);
14959       continue;
14960     } else {
14961       NewTy = BestType;
14962       NewWidth = BestWidth;
14963       NewSign = BestType->isSignedIntegerOrEnumerationType();
14964     }
14965 
14966     // Adjust the APSInt value.
14967     InitVal = InitVal.extOrTrunc(NewWidth);
14968     InitVal.setIsSigned(NewSign);
14969     ECD->setInitVal(InitVal);
14970 
14971     // Adjust the Expr initializer and type.
14972     if (ECD->getInitExpr() &&
14973         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14974       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14975                                                 CK_IntegralCast,
14976                                                 ECD->getInitExpr(),
14977                                                 /*base paths*/ nullptr,
14978                                                 VK_RValue));
14979     if (getLangOpts().CPlusPlus)
14980       // C++ [dcl.enum]p4: Following the closing brace of an
14981       // enum-specifier, each enumerator has the type of its
14982       // enumeration.
14983       ECD->setType(EnumType);
14984     else
14985       ECD->setType(NewTy);
14986   }
14987 
14988   Enum->completeDefinition(BestType, BestPromotionType,
14989                            NumPositiveBits, NumNegativeBits);
14990 
14991   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14992 
14993   if (Enum->hasAttr<FlagEnumAttr>()) {
14994     for (Decl *D : Elements) {
14995       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14996       if (!ECD) continue;  // Already issued a diagnostic.
14997 
14998       llvm::APSInt InitVal = ECD->getInitVal();
14999       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15000           !IsValueInFlagEnum(Enum, InitVal, true))
15001         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15002           << ECD << Enum;
15003     }
15004   }
15005 
15006   // Now that the enum type is defined, ensure it's not been underaligned.
15007   if (Enum->hasAttrs())
15008     CheckAlignasUnderalignment(Enum);
15009 }
15010 
ActOnFileScopeAsmDecl(Expr * expr,SourceLocation StartLoc,SourceLocation EndLoc)15011 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15012                                   SourceLocation StartLoc,
15013                                   SourceLocation EndLoc) {
15014   StringLiteral *AsmString = cast<StringLiteral>(expr);
15015 
15016   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15017                                                    AsmString, StartLoc,
15018                                                    EndLoc);
15019   CurContext->addDecl(New);
15020   return New;
15021 }
15022 
checkModuleImportContext(Sema & S,Module * M,SourceLocation ImportLoc,DeclContext * DC,bool FromInclude=false)15023 static void checkModuleImportContext(Sema &S, Module *M,
15024                                      SourceLocation ImportLoc, DeclContext *DC,
15025                                      bool FromInclude = false) {
15026   SourceLocation ExternCLoc;
15027 
15028   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15029     switch (LSD->getLanguage()) {
15030     case LinkageSpecDecl::lang_c:
15031       if (ExternCLoc.isInvalid())
15032         ExternCLoc = LSD->getLocStart();
15033       break;
15034     case LinkageSpecDecl::lang_cxx:
15035       break;
15036     }
15037     DC = LSD->getParent();
15038   }
15039 
15040   while (isa<LinkageSpecDecl>(DC))
15041     DC = DC->getParent();
15042 
15043   if (!isa<TranslationUnitDecl>(DC)) {
15044     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15045                           ? diag::ext_module_import_not_at_top_level_noop
15046                           : diag::err_module_import_not_at_top_level_fatal)
15047         << M->getFullModuleName() << DC;
15048     S.Diag(cast<Decl>(DC)->getLocStart(),
15049            diag::note_module_import_not_at_top_level) << DC;
15050   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15051     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15052       << M->getFullModuleName();
15053     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
15054   }
15055 }
15056 
diagnoseMisplacedModuleImport(Module * M,SourceLocation ImportLoc)15057 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
15058   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
15059 }
15060 
ActOnModuleImport(SourceLocation AtLoc,SourceLocation ImportLoc,ModuleIdPath Path)15061 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
15062                                    SourceLocation ImportLoc,
15063                                    ModuleIdPath Path) {
15064   Module *Mod =
15065       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15066                                    /*IsIncludeDirective=*/false);
15067   if (!Mod)
15068     return true;
15069 
15070   VisibleModules.setVisible(Mod, ImportLoc);
15071 
15072   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15073 
15074   // FIXME: we should support importing a submodule within a different submodule
15075   // of the same top-level module. Until we do, make it an error rather than
15076   // silently ignoring the import.
15077   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
15078     Diag(ImportLoc, getLangOpts().CompilingModule
15079                         ? diag::err_module_self_import
15080                         : diag::err_module_import_in_implementation)
15081         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15082 
15083   SmallVector<SourceLocation, 2> IdentifierLocs;
15084   Module *ModCheck = Mod;
15085   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15086     // If we've run out of module parents, just drop the remaining identifiers.
15087     // We need the length to be consistent.
15088     if (!ModCheck)
15089       break;
15090     ModCheck = ModCheck->Parent;
15091 
15092     IdentifierLocs.push_back(Path[I].second);
15093   }
15094 
15095   ImportDecl *Import = ImportDecl::Create(Context,
15096                                           Context.getTranslationUnitDecl(),
15097                                           AtLoc.isValid()? AtLoc : ImportLoc,
15098                                           Mod, IdentifierLocs);
15099   Context.getTranslationUnitDecl()->addDecl(Import);
15100   return Import;
15101 }
15102 
ActOnModuleInclude(SourceLocation DirectiveLoc,Module * Mod)15103 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15104   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15105 
15106   // Determine whether we're in the #include buffer for a module. The #includes
15107   // in that buffer do not qualify as module imports; they're just an
15108   // implementation detail of us building the module.
15109   //
15110   // FIXME: Should we even get ActOnModuleInclude calls for those?
15111   bool IsInModuleIncludes =
15112       TUKind == TU_Module &&
15113       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15114 
15115   // Similarly, if we're in the implementation of a module, don't
15116   // synthesize an illegal module import. FIXME: Why not?
15117   bool ShouldAddImport =
15118       !IsInModuleIncludes &&
15119       (getLangOpts().CompilingModule ||
15120        getLangOpts().CurrentModule.empty() ||
15121        getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
15122 
15123   // If this module import was due to an inclusion directive, create an
15124   // implicit import declaration to capture it in the AST.
15125   if (ShouldAddImport) {
15126     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15127     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15128                                                      DirectiveLoc, Mod,
15129                                                      DirectiveLoc);
15130     TU->addDecl(ImportD);
15131     Consumer.HandleImplicitImportDecl(ImportD);
15132   }
15133 
15134   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15135   VisibleModules.setVisible(Mod, DirectiveLoc);
15136 }
15137 
ActOnModuleBegin(SourceLocation DirectiveLoc,Module * Mod)15138 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15139   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15140 
15141   if (getLangOpts().ModulesLocalVisibility)
15142     VisibleModulesStack.push_back(std::move(VisibleModules));
15143   VisibleModules.setVisible(Mod, DirectiveLoc);
15144 }
15145 
ActOnModuleEnd(SourceLocation DirectiveLoc,Module * Mod)15146 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
15147   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15148 
15149   if (getLangOpts().ModulesLocalVisibility) {
15150     VisibleModules = std::move(VisibleModulesStack.back());
15151     VisibleModulesStack.pop_back();
15152     VisibleModules.setVisible(Mod, DirectiveLoc);
15153     // Leaving a module hides namespace names, so our visible namespace cache
15154     // is now out of date.
15155     VisibleNamespaceCache.clear();
15156   }
15157 }
15158 
createImplicitModuleImportForErrorRecovery(SourceLocation Loc,Module * Mod)15159 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15160                                                       Module *Mod) {
15161   // Bail if we're not allowed to implicitly import a module here.
15162   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15163     return;
15164 
15165   // Create the implicit import declaration.
15166   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15167   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15168                                                    Loc, Mod, Loc);
15169   TU->addDecl(ImportD);
15170   Consumer.HandleImplicitImportDecl(ImportD);
15171 
15172   // Make the module visible.
15173   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15174   VisibleModules.setVisible(Mod, Loc);
15175 }
15176 
ActOnPragmaRedefineExtname(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)15177 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15178                                       IdentifierInfo* AliasName,
15179                                       SourceLocation PragmaLoc,
15180                                       SourceLocation NameLoc,
15181                                       SourceLocation AliasNameLoc) {
15182   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15183                                          LookupOrdinaryName);
15184   AsmLabelAttr *Attr =
15185       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15186 
15187   // If a declaration that:
15188   // 1) declares a function or a variable
15189   // 2) has external linkage
15190   // already exists, add a label attribute to it.
15191   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15192     if (isDeclExternC(PrevDecl))
15193       PrevDecl->addAttr(Attr);
15194     else
15195       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15196           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15197   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15198   } else
15199     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15200 }
15201 
ActOnPragmaWeakID(IdentifierInfo * Name,SourceLocation PragmaLoc,SourceLocation NameLoc)15202 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15203                              SourceLocation PragmaLoc,
15204                              SourceLocation NameLoc) {
15205   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15206 
15207   if (PrevDecl) {
15208     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15209   } else {
15210     (void)WeakUndeclaredIdentifiers.insert(
15211       std::pair<IdentifierInfo*,WeakInfo>
15212         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15213   }
15214 }
15215 
ActOnPragmaWeakAlias(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)15216 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15217                                 IdentifierInfo* AliasName,
15218                                 SourceLocation PragmaLoc,
15219                                 SourceLocation NameLoc,
15220                                 SourceLocation AliasNameLoc) {
15221   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15222                                     LookupOrdinaryName);
15223   WeakInfo W = WeakInfo(Name, NameLoc);
15224 
15225   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15226     if (!PrevDecl->hasAttr<AliasAttr>())
15227       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15228         DeclApplyPragmaWeak(TUScope, ND, W);
15229   } else {
15230     (void)WeakUndeclaredIdentifiers.insert(
15231       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15232   }
15233 }
15234 
getObjCDeclContext() const15235 Decl *Sema::getObjCDeclContext() const {
15236   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15237 }
15238 
getCurContextAvailability() const15239 AvailabilityResult Sema::getCurContextAvailability() const {
15240   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15241   if (!D)
15242     return AR_Available;
15243 
15244   // If we are within an Objective-C method, we should consult
15245   // both the availability of the method as well as the
15246   // enclosing class.  If the class is (say) deprecated,
15247   // the entire method is considered deprecated from the
15248   // purpose of checking if the current context is deprecated.
15249   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15250     AvailabilityResult R = MD->getAvailability();
15251     if (R != AR_Available)
15252       return R;
15253     D = MD->getClassInterface();
15254   }
15255   // If we are within an Objective-c @implementation, it
15256   // gets the same availability context as the @interface.
15257   else if (const ObjCImplementationDecl *ID =
15258             dyn_cast<ObjCImplementationDecl>(D)) {
15259     D = ID->getClassInterface();
15260   }
15261   // Recover from user error.
15262   return D ? D->getAvailability() : AR_Available;
15263 }
15264