Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaDecl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements semantic analysis for declarations.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TypeLocBuilder.h"
14
#include "clang/AST/ASTConsumer.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/ASTLambda.h"
17
#include "clang/AST/CXXInheritance.h"
18
#include "clang/AST/CharUnits.h"
19
#include "clang/AST/CommentDiagnostic.h"
20
#include "clang/AST/DeclCXX.h"
21
#include "clang/AST/DeclObjC.h"
22
#include "clang/AST/DeclTemplate.h"
23
#include "clang/AST/EvaluatedExprVisitor.h"
24
#include "clang/AST/Expr.h"
25
#include "clang/AST/ExprCXX.h"
26
#include "clang/AST/NonTrivialTypeVisitor.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/SemaInternal.h"
45
#include "clang/Sema/Template.h"
46
#include "llvm/ADT/SmallString.h"
47
#include "llvm/ADT/Triple.h"
48
#include <algorithm>
49
#include <cstring>
50
#include <functional>
51
#include <unordered_map>
52
53
using namespace clang;
54
using namespace sema;
55
56
5.06M
Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57
5.06M
  if (OwnedType) {
58
1.76k
    Decl *Group[2] = { OwnedType, Ptr };
59
1.76k
    return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60
1.76k
  }
61
62
5.06M
  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63
5.06M
}
64
65
namespace {
66
67
class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68
 public:
69
   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70
                        bool AllowTemplates = false,
71
                        bool AllowNonTemplates = true)
72
       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73
1.32k
         AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74
1.32k
     WantExpressionKeywords = false;
75
1.32k
     WantCXXNamedCasts = false;
76
1.32k
     WantRemainingKeywords = false;
77
1.32k
  }
78
79
821
  bool ValidateCandidate(const TypoCorrection &candidate) override {
80
821
    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81
780
      if (!AllowInvalidDecl && 
ND->isInvalidDecl()774
)
82
11
        return false;
83
84
769
      if (getAsTypeTemplateDecl(ND))
85
98
        return AllowTemplates;
86
87
671
      bool IsType = isa<TypeDecl>(ND) || 
isa<ObjCInterfaceDecl>(ND)110
;
88
671
      if (!IsType)
89
107
        return false;
90
91
564
      if (AllowNonTemplates)
92
564
        return true;
93
94
      // An injected-class-name of a class template (specialization) is valid
95
      // as a template or as a non-template.
96
0
      if (AllowTemplates) {
97
0
        auto *RD = dyn_cast<CXXRecordDecl>(ND);
98
0
        if (!RD || !RD->isInjectedClassName())
99
0
          return false;
100
0
        RD = cast<CXXRecordDecl>(RD->getDeclContext());
101
0
        return RD->getDescribedClassTemplate() ||
102
0
               isa<ClassTemplateSpecializationDecl>(RD);
103
0
      }
104
105
0
      return false;
106
0
    }
107
108
41
    return !WantClassName && 
candidate.isKeyword()39
;
109
821
  }
110
111
958
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
112
958
    return std::make_unique<TypeNameValidatorCCC>(*this);
113
958
  }
114
115
 private:
116
  bool AllowInvalidDecl;
117
  bool WantClassName;
118
  bool AllowTemplates;
119
  bool AllowNonTemplates;
120
};
121
122
} // end anonymous namespace
123
124
/// Determine whether the token kind starts a simple-type-specifier.
125
29.2k
bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126
29.2k
  switch (Kind) {
127
  // FIXME: Take into account the current language when deciding whether a
128
  // token kind is a valid type specifier
129
0
  case tok::kw_short:
130
0
  case tok::kw_long:
131
0
  case tok::kw___int64:
132
0
  case tok::kw___int128:
133
0
  case tok::kw_signed:
134
0
  case tok::kw_unsigned:
135
0
  case tok::kw_void:
136
0
  case tok::kw_char:
137
1
  case tok::kw_int:
138
1
  case tok::kw_half:
139
1
  case tok::kw_float:
140
1
  case tok::kw_double:
141
1
  case tok::kw___bf16:
142
1
  case tok::kw__Float16:
143
1
  case tok::kw___float128:
144
1
  case tok::kw_wchar_t:
145
1
  case tok::kw_bool:
146
1
  case tok::kw___underlying_type:
147
1
  case tok::kw___auto_type:
148
1
    return true;
149
150
27.2k
  case tok::annot_typename:
151
27.2k
  case tok::kw_char16_t:
152
27.2k
  case tok::kw_char32_t:
153
27.2k
  case tok::kw_typeof:
154
27.2k
  case tok::annot_decltype:
155
27.2k
  case tok::kw_decltype:
156
27.2k
    return getLangOpts().CPlusPlus;
157
158
0
  case tok::kw_char8_t:
159
0
    return getLangOpts().Char8;
160
161
1.95k
  default:
162
1.95k
    break;
163
29.2k
  }
164
165
1.95k
  return false;
166
29.2k
}
167
168
namespace {
169
enum class UnqualifiedTypeNameLookupResult {
170
  NotFound,
171
  FoundNonType,
172
  FoundType
173
};
174
} // end anonymous namespace
175
176
/// Tries to perform unqualified lookup of the type decls in bases for
177
/// dependent class.
178
/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179
/// type decl, \a FoundType if only type decls are found.
180
static UnqualifiedTypeNameLookupResult
181
lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182
                                SourceLocation NameLoc,
183
128
                                const CXXRecordDecl *RD) {
184
128
  if (!RD->hasDefinition())
185
2
    return UnqualifiedTypeNameLookupResult::NotFound;
186
  // Look for type decls in base classes.
187
126
  UnqualifiedTypeNameLookupResult FoundTypeDecl =
188
126
      UnqualifiedTypeNameLookupResult::NotFound;
189
126
  for (const auto &Base : RD->bases()) {
190
124
    const CXXRecordDecl *BaseRD = nullptr;
191
124
    if (auto *BaseTT = Base.getType()->getAs<TagType>())
192
10
      BaseRD = BaseTT->getAsCXXRecordDecl();
193
114
    else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194
      // Look for type decls in dependent base classes that have known primary
195
      // templates.
196
88
      if (!TST || !TST->isDependentType())
197
0
        continue;
198
88
      auto *TD = TST->getTemplateName().getAsTemplateDecl();
199
88
      if (!TD)
200
0
        continue;
201
88
      if (auto *BasePrimaryTemplate =
202
88
          dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203
84
        if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204
82
          BaseRD = BasePrimaryTemplate;
205
2
        else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206
2
          if (const ClassTemplatePartialSpecializationDecl *PS =
207
2
                  CTD->findPartialSpecialization(Base.getType()))
208
2
            if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209
2
              BaseRD = PS;
210
2
        }
211
84
      }
212
88
    }
213
124
    if (BaseRD) {
214
94
      for (NamedDecl *ND : BaseRD->lookup(&II)) {
215
76
        if (!isa<TypeDecl>(ND))
216
24
          return UnqualifiedTypeNameLookupResult::FoundNonType;
217
52
        FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218
52
      }
219
70
      if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220
18
        switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221
0
        case UnqualifiedTypeNameLookupResult::FoundNonType:
222
0
          return UnqualifiedTypeNameLookupResult::FoundNonType;
223
10
        case UnqualifiedTypeNameLookupResult::FoundType:
224
10
          FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225
10
          break;
226
8
        case UnqualifiedTypeNameLookupResult::NotFound:
227
8
          break;
228
18
        }
229
18
      }
230
70
    }
231
124
  }
232
233
102
  return FoundTypeDecl;
234
126
}
235
236
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237
                                                      const IdentifierInfo &II,
238
185
                                                      SourceLocation NameLoc) {
239
  // Lookup in the parent class template context, if any.
240
185
  const CXXRecordDecl *RD = nullptr;
241
185
  UnqualifiedTypeNameLookupResult FoundTypeDecl =
242
185
      UnqualifiedTypeNameLookupResult::NotFound;
243
185
  for (DeclContext *DC = S.CurContext;
244
585
       DC && 
FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound468
;
245
400
       DC = DC->getParent()) {
246
    // Look for type decls in dependent base classes that have known primary
247
    // templates.
248
400
    RD = dyn_cast<CXXRecordDecl>(DC);
249
400
    if (RD && 
RD->getDescribedClassTemplate()127
)
250
110
      FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251
400
  }
252
185
  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253
141
    return nullptr;
254
255
  // We found some types in dependent base classes.  Recover as if the user
256
  // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
257
  // lookup during template instantiation.
258
44
  S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259
260
44
  ASTContext &Context = S.Context;
261
44
  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262
44
                                          cast<Type>(Context.getRecordType(RD)));
263
44
  QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264
265
44
  CXXScopeSpec SS;
266
44
  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268
44
  TypeLocBuilder Builder;
269
44
  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270
44
  DepTL.setNameLoc(NameLoc);
271
44
  DepTL.setElaboratedKeywordLoc(SourceLocation());
272
44
  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273
44
  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274
185
}
275
276
/// If the identifier refers to a type name within this scope,
277
/// return the declaration of that type.
278
///
279
/// This routine performs ordinary name lookup of the identifier II
280
/// within the given scope, with optional C++ scope specifier SS, to
281
/// determine whether the name refers to a type. If so, returns an
282
/// opaque pointer (actually a QualType) corresponding to that
283
/// type. Otherwise, returns NULL.
284
ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285
                             Scope *S, CXXScopeSpec *SS,
286
                             bool isClassName, bool HasTrailingDot,
287
                             ParsedType ObjectTypePtr,
288
                             bool IsCtorOrDtorName,
289
                             bool WantNontrivialTypeSourceInfo,
290
                             bool IsClassTemplateDeductionContext,
291
120M
                             IdentifierInfo **CorrectedII) {
292
  // FIXME: Consider allowing this outside C++1z mode as an extension.
293
120M
  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294
120M
                              
getLangOpts().CPlusPlus17120M
&&
!IsCtorOrDtorName278k
&&
295
120M
                              
!isClassName278k
&&
!HasTrailingDot278k
;
296
297
  // Determine where we will perform name lookup.
298
120M
  DeclContext *LookupCtx = nullptr;
299
120M
  if (ObjectTypePtr) {
300
7.02k
    QualType ObjectType = ObjectTypePtr.get();
301
7.02k
    if (ObjectType->isRecordType())
302
417
      LookupCtx = computeDeclContext(ObjectType);
303
120M
  } else if (SS && 
SS->isNotEmpty()29.9M
) {
304
2.31M
    LookupCtx = computeDeclContext(*SS, false);
305
306
2.31M
    if (!LookupCtx) {
307
1.47M
      if (isDependentScopeSpecifier(*SS)) {
308
        // C++ [temp.res]p3:
309
        //   A qualified-id that refers to a type and in which the
310
        //   nested-name-specifier depends on a template-parameter (14.6.2)
311
        //   shall be prefixed by the keyword typename to indicate that the
312
        //   qualified-id denotes a type, forming an
313
        //   elaborated-type-specifier (7.1.5.3).
314
        //
315
        // We therefore do not perform any name lookup if the result would
316
        // refer to a member of an unknown specialization.
317
1.47M
        if (!isClassName && 
!IsCtorOrDtorName1.47M
)
318
1.47M
          return nullptr;
319
320
        // We know from the grammar that this name refers to a type,
321
        // so build a dependent node to describe the type.
322
2.41k
        if (WantNontrivialTypeSourceInfo)
323
2.40k
          return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324
325
12
        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326
12
        QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327
12
                                       II, NameLoc);
328
12
        return ParsedType::make(T);
329
2.41k
      }
330
331
682
      return nullptr;
332
1.47M
    }
333
334
834k
    if (!LookupCtx->isDependentContext() &&
335
834k
        
RequireCompleteDeclContext(*SS, LookupCtx)833k
)
336
130
      return nullptr;
337
834k
  }
338
339
  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340
  // lookup for class-names.
341
119M
  LookupNameKind Kind = isClassName ? 
LookupNestedNameSpecifierName90.9k
:
342
119M
                                      
LookupOrdinaryName118M
;
343
119M
  LookupResult Result(*this, &II, NameLoc, Kind);
344
119M
  if (LookupCtx) {
345
    // Perform "qualified" name lookup into the declaration context we
346
    // computed, which is either the type of the base of a member access
347
    // expression or the declaration context associated with a prior
348
    // nested-name-specifier.
349
834k
    LookupQualifiedName(Result, LookupCtx);
350
351
834k
    if (ObjectTypePtr && 
Result.empty()0
) {
352
      // C++ [basic.lookup.classref]p3:
353
      //   If the unqualified-id is ~type-name, the type-name is looked up
354
      //   in the context of the entire postfix-expression. If the type T of
355
      //   the object expression is of a class type C, the type-name is also
356
      //   looked up in the scope of class C. At least one of the lookups shall
357
      //   find a name that refers to (possibly cv-qualified) T.
358
0
      LookupName(Result, S);
359
0
    }
360
118M
  } else {
361
    // Perform unqualified name lookup.
362
118M
    LookupName(Result, S);
363
364
    // For unqualified lookup in a class template in MSVC mode, look into
365
    // dependent base classes where the primary class template is known.
366
118M
    if (Result.empty() && 
getLangOpts().MSVCCompat120k
&&
(108
!SS108
||
SS->isEmpty()30
)) {
367
108
      if (ParsedType TypeInBase =
368
108
              recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369
30
        return TypeInBase;
370
108
    }
371
118M
  }
372
373
119M
  NamedDecl *IIDecl = nullptr;
374
119M
  switch (Result.getResultKind()) {
375
121k
  case LookupResult::NotFound:
376
121k
  case LookupResult::NotFoundInCurrentInstantiation:
377
121k
    if (CorrectedII) {
378
8
      TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379
8
                               AllowDeducedTemplate);
380
8
      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381
8
                                              S, SS, CCC, CTK_ErrorRecovery);
382
8
      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383
8
      TemplateTy Template;
384
8
      bool MemberOfUnknownSpecialization;
385
8
      UnqualifiedId TemplateName;
386
8
      TemplateName.setIdentifier(NewII, NameLoc);
387
8
      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388
8
      CXXScopeSpec NewSS, *NewSSPtr = SS;
389
8
      if (SS && NNS) {
390
0
        NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391
0
        NewSSPtr = &NewSS;
392
0
      }
393
8
      if (Correction && 
(2
NNS2
||
NewII != &II2
) &&
394
          // Ignore a correction to a template type as the to-be-corrected
395
          // identifier is not a template (typo correction for template names
396
          // is handled elsewhere).
397
8
          
!(2
getLangOpts().CPlusPlus2
&&
NewSSPtr2
&&
398
2
            isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399
2
                           Template, MemberOfUnknownSpecialization))) {
400
2
        ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401
2
                                    isClassName, HasTrailingDot, ObjectTypePtr,
402
2
                                    IsCtorOrDtorName,
403
2
                                    WantNontrivialTypeSourceInfo,
404
2
                                    IsClassTemplateDeductionContext);
405
2
        if (Ty) {
406
2
          diagnoseTypo(Correction,
407
2
                       PDiag(diag::err_unknown_type_or_class_name_suggest)
408
2
                         << Result.getLookupName() << isClassName);
409
2
          if (SS && NNS)
410
0
            SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411
2
          *CorrectedII = NewII;
412
2
          return Ty;
413
2
        }
414
2
      }
415
8
    }
416
    // If typo correction failed or was not performed, fall through
417
121k
    
LLVM_FALLTHROUGH121k
;121k
418
832k
  case LookupResult::FoundOverloaded:
419
832k
  case LookupResult::FoundUnresolvedValue:
420
832k
    Result.suppressDiagnostics();
421
832k
    return nullptr;
422
423
70
  case LookupResult::Ambiguous:
424
    // Recover from type-hiding ambiguities by hiding the type.  We'll
425
    // do the lookup again when looking for an object, and we can
426
    // diagnose the error then.  If we don't do this, then the error
427
    // about hiding the type will be immediately followed by an error
428
    // that only makes sense if the identifier was treated like a type.
429
70
    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430
2
      Result.suppressDiagnostics();
431
2
      return nullptr;
432
2
    }
433
434
    // Look to see if we have a type anywhere in the list of results.
435
68
    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436
192
         Res != ResEnd; 
++Res124
) {
437
124
      NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
438
124
      if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
439
124
              RealRes) ||
440
124
          
(61
AllowDeducedTemplate61
&&
getAsTypeTemplateDecl(RealRes)4
)) {
441
63
        if (!IIDecl ||
442
            // Make the selection of the recovery decl deterministic.
443
63
            
RealRes->getLocation() < IIDecl->getLocation()31
)
444
43
          IIDecl = RealRes;
445
63
      }
446
124
    }
447
448
68
    if (!IIDecl) {
449
      // None of the entities we found is a type, so there is no way
450
      // to even assume that the result is a type. In this case, don't
451
      // complain about the ambiguity. The parser will either try to
452
      // perform this lookup again (e.g., as an object name), which
453
      // will produce the ambiguity, or will complain that it expected
454
      // a type name.
455
36
      Result.suppressDiagnostics();
456
36
      return nullptr;
457
36
    }
458
459
    // We found a type within the ambiguous lookup; diagnose the
460
    // ambiguity and then return that type. This might be the right
461
    // answer, or it might not be, but it suppresses any attempt to
462
    // perform the name lookup again.
463
32
    break;
464
465
118M
  case LookupResult::Found:
466
118M
    IIDecl = Result.getFoundDecl();
467
118M
    break;
468
119M
  }
469
470
118M
  assert(IIDecl && "Didn't find decl");
471
472
0
  QualType T;
473
118M
  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
474
    // C++ [class.qual]p2: A lookup that would find the injected-class-name
475
    // instead names the constructors of the class, except when naming a class.
476
    // This is ill-formed when we're not actually forming a ctor or dtor name.
477
115M
    auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
478
115M
    auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
479
115M
    if (!isClassName && 
!IsCtorOrDtorName115M
&&
LookupRD115M
&&
FoundRD37.0k
&&
480
115M
        
FoundRD->isInjectedClassName()4.46k
&&
481
115M
        
declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))76
)
482
52
      Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
483
52
          << &II << /*Type*/1;
484
485
115M
    DiagnoseUseOfDecl(IIDecl, NameLoc);
486
487
115M
    T = Context.getTypeDeclType(TD);
488
115M
    MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
489
115M
  } else 
if (ObjCInterfaceDecl *2.71M
IDecl2.71M
= dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
490
1.14M
    (void)DiagnoseUseOfDecl(IDecl, NameLoc);
491
1.14M
    if (!HasTrailingDot)
492
1.14M
      T = Context.getObjCInterfaceType(IDecl);
493
1.57M
  } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
494
604
    (void)DiagnoseUseOfDecl(UD, NameLoc);
495
    // Recover with 'int'
496
604
    T = Context.IntTy;
497
1.57M
  } else if (AllowDeducedTemplate) {
498
33.7k
    if (auto *TD = getAsTypeTemplateDecl(IIDecl))
499
1.26k
      T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
500
1.26k
                                                       QualType(), false);
501
33.7k
  }
502
503
118M
  if (T.isNull()) {
504
    // If it's not plausibly a type, suppress diagnostics.
505
1.57M
    Result.suppressDiagnostics();
506
1.57M
    return nullptr;
507
1.57M
  }
508
509
  // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
510
  // constructor or destructor name (in such a case, the scope specifier
511
  // will be attached to the enclosing Expr or Decl node).
512
116M
  if (SS && 
SS->isNotEmpty()26.0M
&&
!IsCtorOrDtorName102k
&&
513
116M
      
!isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)102k
) {
514
102k
    if (WantNontrivialTypeSourceInfo) {
515
      // Construct a type with type-source information.
516
102k
      TypeLocBuilder Builder;
517
102k
      Builder.pushTypeSpec(T).setNameLoc(NameLoc);
518
519
102k
      T = getElaboratedType(ETK_None, *SS, T);
520
102k
      ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
521
102k
      ElabTL.setElaboratedKeywordLoc(SourceLocation());
522
102k
      ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
523
102k
      return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
524
102k
    } else {
525
0
      T = getElaboratedType(ETK_None, *SS, T);
526
0
    }
527
102k
  }
528
529
116M
  return ParsedType::make(T);
530
116M
}
531
532
// Builds a fake NNS for the given decl context.
533
static NestedNameSpecifier *
534
3
synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
535
3
  for (;; 
DC = DC->getLookupParent()0
) {
536
3
    DC = DC->getPrimaryContext();
537
3
    auto *ND = dyn_cast<NamespaceDecl>(DC);
538
3
    if (ND && 
!ND->isInline()2
&&
!ND->isAnonymousNamespace()2
)
539
2
      return NestedNameSpecifier::Create(Context, nullptr, ND);
540
1
    else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
541
1
      return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
542
1
                                         RD->getTypeForDecl());
543
0
    else if (isa<TranslationUnitDecl>(DC))
544
0
      return NestedNameSpecifier::GlobalSpecifier(Context);
545
3
  }
546
0
  llvm_unreachable("something isn't in TU scope?");
547
0
}
548
549
/// Find the parent class with dependent bases of the innermost enclosing method
550
/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
551
/// up allowing unqualified dependent type names at class-level, which MSVC
552
/// correctly rejects.
553
static const CXXRecordDecl *
554
38
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
555
52
  for (; DC && DC->isDependentContext(); 
DC = DC->getLookupParent()14
) {
556
26
    DC = DC->getPrimaryContext();
557
26
    if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
558
12
      if (MD->getParent()->hasAnyDependentBases())
559
12
        return MD->getParent();
560
26
  }
561
26
  return nullptr;
562
38
}
563
564
ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
565
                                          SourceLocation NameLoc,
566
41
                                          bool IsTemplateTypeArg) {
567
41
  assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
568
569
0
  NestedNameSpecifier *NNS = nullptr;
570
41
  if (IsTemplateTypeArg && 
getCurScope()->isTemplateParamScope()3
) {
571
    // If we weren't able to parse a default template argument, delay lookup
572
    // until instantiation time by making a non-dependent DependentTypeName. We
573
    // pretend we saw a NestedNameSpecifier referring to the current scope, and
574
    // lookup is retried.
575
    // FIXME: This hurts our diagnostic quality, since we get errors like "no
576
    // type named 'Foo' in 'current_namespace'" when the user didn't write any
577
    // name specifiers.
578
3
    NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
579
3
    Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
580
38
  } else if (const CXXRecordDecl *RD =
581
38
                 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
582
    // Build a DependentNameType that will perform lookup into RD at
583
    // instantiation time.
584
12
    NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
585
12
                                      RD->getTypeForDecl());
586
587
    // Diagnose that this identifier was undeclared, and retry the lookup during
588
    // template instantiation.
589
12
    Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
590
12
                                                                      << RD;
591
26
  } else {
592
    // This is not a situation that we should recover from.
593
26
    return ParsedType();
594
26
  }
595
596
15
  QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
597
598
  // Build type location information.  We synthesized the qualifier, so we have
599
  // to build a fake NestedNameSpecifierLoc.
600
15
  NestedNameSpecifierLocBuilder NNSLocBuilder;
601
15
  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
602
15
  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
603
604
15
  TypeLocBuilder Builder;
605
15
  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
606
15
  DepTL.setNameLoc(NameLoc);
607
15
  DepTL.setElaboratedKeywordLoc(SourceLocation());
608
15
  DepTL.setQualifierLoc(QualifierLoc);
609
15
  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
610
41
}
611
612
/// isTagName() - This method is called *for error recovery purposes only*
613
/// to determine if the specified name is a valid tag name ("struct foo").  If
614
/// so, this returns the TST for the tag corresponding to it (TST_enum,
615
/// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
616
/// cases in C where the user forgot to specify the tag.
617
1.02k
DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
618
  // Do a tag name lookup in this scope.
619
1.02k
  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
620
1.02k
  LookupName(R, S, false);
621
1.02k
  R.suppressDiagnostics();
622
1.02k
  if (R.getResultKind() == LookupResult::Found)
623
76
    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
624
38
      switch (TD->getTagKind()) {
625
18
      case TTK_Struct: return DeclSpec::TST_struct;
626
0
      case TTK_Interface: return DeclSpec::TST_interface;
627
0
      case TTK_Union:  return DeclSpec::TST_union;
628
9
      case TTK_Class:  return DeclSpec::TST_class;
629
11
      case TTK_Enum:   return DeclSpec::TST_enum;
630
38
      }
631
38
    }
632
633
983
  return DeclSpec::TST_unspecified;
634
1.02k
}
635
636
/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
637
/// if a CXXScopeSpec's type is equal to the type of one of the base classes
638
/// then downgrade the missing typename error to a warning.
639
/// This is needed for MSVC compatibility; Example:
640
/// @code
641
/// template<class T> class A {
642
/// public:
643
///   typedef int TYPE;
644
/// };
645
/// template<class T> class B : public A<T> {
646
/// public:
647
///   A<T>::TYPE a; // no typename required because A<T> is a base class.
648
/// };
649
/// @endcode
650
35
bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
651
35
  if (CurContext->isRecord()) {
652
25
    if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
653
0
      return true;
654
655
25
    const Type *Ty = SS->getScopeRep()->getAsType();
656
657
25
    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
658
25
    for (const auto &Base : RD->bases())
659
41
      if (Ty && 
Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())40
)
660
16
        return true;
661
9
    return S->isFunctionPrototypeScope();
662
25
  }
663
10
  return CurContext->isFunctionOrMethod() || 
S->isFunctionPrototypeScope()4
;
664
35
}
665
666
void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
667
                                   SourceLocation IILoc,
668
                                   Scope *S,
669
                                   CXXScopeSpec *SS,
670
                                   ParsedType &SuggestedType,
671
1.32k
                                   bool IsTemplateName) {
672
  // Don't report typename errors for editor placeholders.
673
1.32k
  if (II->isEditorPlaceholder())
674
7
    return;
675
  // We don't have anything to suggest (yet).
676
1.31k
  SuggestedType = nullptr;
677
678
  // There may have been a typo in the name of the type. Look up typo
679
  // results, in case we have something that we can suggest.
680
1.31k
  TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
681
1.31k
                           /*AllowTemplates=*/IsTemplateName,
682
1.31k
                           /*AllowNonTemplates=*/!IsTemplateName);
683
1.31k
  if (TypoCorrection Corrected =
684
1.31k
          CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
685
1.31k
                      CCC, CTK_ErrorRecovery)) {
686
    // FIXME: Support error recovery for the template-name case.
687
279
    bool CanRecover = !IsTemplateName;
688
279
    if (Corrected.isKeyword()) {
689
      // We corrected to a keyword.
690
12
      diagnoseTypo(Corrected,
691
12
                   PDiag(IsTemplateName ? 
diag::err_no_template_suggest0
692
12
                                        : diag::err_unknown_typename_suggest)
693
12
                       << II);
694
12
      II = Corrected.getCorrectionAsIdentifierInfo();
695
267
    } else {
696
      // We found a similarly-named type or interface; suggest that.
697
267
      if (!SS || 
!SS->isSet()71
) {
698
196
        diagnoseTypo(Corrected,
699
196
                     PDiag(IsTemplateName ? 
diag::err_no_template_suggest2
700
196
                                          : 
diag::err_unknown_typename_suggest194
)
701
196
                         << II, CanRecover);
702
196
      } else 
if (DeclContext *71
DC71
= computeDeclContext(*SS, false)) {
703
71
        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
704
71
        bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
705
71
                                
II->getName().equals(CorrectedStr)43
;
706
71
        diagnoseTypo(Corrected,
707
71
                     PDiag(IsTemplateName
708
71
                               ? 
diag::err_no_member_template_suggest0
709
71
                               : diag::err_unknown_nested_typename_suggest)
710
71
                         << II << DC << DroppedSpecifier << SS->getRange(),
711
71
                     CanRecover);
712
71
      } else {
713
0
        llvm_unreachable("could not have corrected a typo here");
714
0
      }
715
716
267
      if (!CanRecover)
717
2
        return;
718
719
265
      CXXScopeSpec tmpSS;
720
265
      if (Corrected.getCorrectionSpecifier())
721
39
        tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
722
39
                          SourceRange(IILoc));
723
      // FIXME: Support class template argument deduction here.
724
265
      SuggestedType =
725
265
          getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
726
265
                      tmpSS.isSet() ? 
&tmpSS39
:
SS226
, false, false, nullptr,
727
265
                      /*IsCtorOrDtorName=*/false,
728
265
                      /*WantNontrivialTypeSourceInfo=*/true);
729
265
    }
730
277
    return;
731
279
  }
732
733
1.03k
  if (getLangOpts().CPlusPlus && 
!IsTemplateName834
) {
734
    // See if II is a class template that the user forgot to pass arguments to.
735
828
    UnqualifiedId Name;
736
828
    Name.setIdentifier(II, IILoc);
737
828
    CXXScopeSpec EmptySS;
738
828
    TemplateTy TemplateResult;
739
828
    bool MemberOfUnknownSpecialization;
740
828
    if (isTemplateName(S, SS ? 
*SS394
:
EmptySS434
, /*hasTemplateKeyword=*/false,
741
828
                       Name, nullptr, true, TemplateResult,
742
828
                       MemberOfUnknownSpecialization) == TNK_Type_template) {
743
42
      diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
744
42
      return;
745
42
    }
746
828
  }
747
748
  // FIXME: Should we move the logic that tries to recover from a missing tag
749
  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
750
751
996
  if (!SS || 
(380
!SS->isSet()380
&&
!SS->isInvalid()151
))
752
616
    Diag(IILoc, IsTemplateName ? 
diag::err_no_template0
753
616
                               : diag::err_unknown_typename)
754
616
        << II;
755
380
  else if (DeclContext *DC = computeDeclContext(*SS, false))
756
49
    Diag(IILoc, IsTemplateName ? 
diag::err_no_member_template6
757
49
                               : 
diag::err_typename_nested_not_found43
)
758
49
        << II << DC << SS->getRange();
759
331
  else if (SS->isValid() && 
SS->getScopeRep()->containsErrors()180
) {
760
3
    SuggestedType =
761
3
        ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
762
328
  } else if (isDependentScopeSpecifier(*SS)) {
763
177
    unsigned DiagID = diag::err_typename_missing;
764
177
    if (getLangOpts().MSVCCompat && 
isMicrosoftMissingTypename(SS, S)35
)
765
26
      DiagID = diag::ext_typename_missing;
766
767
177
    Diag(SS->getRange().getBegin(), DiagID)
768
177
      << SS->getScopeRep() << II->getName()
769
177
      << SourceRange(SS->getRange().getBegin(), IILoc)
770
177
      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
771
177
    SuggestedType = ActOnTypenameType(S, SourceLocation(),
772
177
                                      *SS, *II, IILoc).get();
773
177
  } else {
774
151
    assert(SS && SS->isInvalid() &&
775
151
           "Invalid scope specifier has already been diagnosed");
776
151
  }
777
996
}
778
779
/// Determine whether the given result set contains either a type name
780
/// or
781
5.02k
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
782
5.02k
  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
783
5.02k
                       
NextToken.is(tok::less)1.23k
;
784
785
8.01k
  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; 
++I2.99k
) {
786
4.12k
    if (isa<TypeDecl>(*I) || 
isa<ObjCInterfaceDecl>(*I)3.54k
)
787
1.13k
      return true;
788
789
2.99k
    if (CheckTemplate && 
isa<TemplateDecl>(*I)0
)
790
0
      return true;
791
2.99k
  }
792
793
3.89k
  return false;
794
5.02k
}
795
796
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
797
                                    Scope *S, CXXScopeSpec &SS,
798
                                    IdentifierInfo *&Name,
799
8.60k
                                    SourceLocation NameLoc) {
800
8.60k
  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
801
8.60k
  SemaRef.LookupParsedName(R, S, &SS);
802
8.60k
  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
803
36
    StringRef FixItTagName;
804
36
    switch (Tag->getTagKind()) {
805
12
      case TTK_Class:
806
12
        FixItTagName = "class ";
807
12
        break;
808
809
10
      case TTK_Enum:
810
10
        FixItTagName = "enum ";
811
10
        break;
812
813
14
      case TTK_Struct:
814
14
        FixItTagName = "struct ";
815
14
        break;
816
817
0
      case TTK_Interface:
818
0
        FixItTagName = "__interface ";
819
0
        break;
820
821
0
      case TTK_Union:
822
0
        FixItTagName = "union ";
823
0
        break;
824
36
    }
825
826
36
    StringRef TagName = FixItTagName.drop_back();
827
36
    SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
828
36
      << Name << TagName << SemaRef.getLangOpts().CPlusPlus
829
36
      << FixItHint::CreateInsertion(NameLoc, FixItTagName);
830
831
36
    for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
832
68
         I != IEnd; 
++I32
)
833
32
      SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
834
32
        << Name << TagName;
835
836
    // Replace lookup results with just the tag decl.
837
36
    Result.clear(Sema::LookupTagName);
838
36
    SemaRef.LookupParsedName(Result, S, &SS);
839
36
    return true;
840
36
  }
841
842
8.56k
  return false;
843
8.60k
}
844
845
/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
846
static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
847
219
                                  QualType T, SourceLocation NameLoc) {
848
219
  ASTContext &Context = S.Context;
849
850
219
  TypeLocBuilder Builder;
851
219
  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
852
853
219
  T = S.getElaboratedType(ETK_None, SS, T);
854
219
  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
855
219
  ElabTL.setElaboratedKeywordLoc(SourceLocation());
856
219
  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
857
219
  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
858
219
}
859
860
Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
861
                                            IdentifierInfo *&Name,
862
                                            SourceLocation NameLoc,
863
                                            const Token &NextToken,
864
14.4M
                                            CorrectionCandidateCallback *CCC) {
865
14.4M
  DeclarationNameInfo NameInfo(Name, NameLoc);
866
14.4M
  ObjCMethodDecl *CurMethod = getCurMethodDecl();
867
868
14.4M
  assert(NextToken.isNot(tok::coloncolon) &&
869
14.4M
         "parse nested name specifiers before calling ClassifyName");
870
14.4M
  if (getLangOpts().CPlusPlus && 
SS.isSet()13.4M
&&
871
14.4M
      
isCurrentClassName(*Name, S, &SS)76.3k
) {
872
    // Per [class.qual]p2, this names the constructors of SS, not the
873
    // injected-class-name. We don't have a classification for that.
874
    // There's not much point caching this result, since the parser
875
    // will reject it later.
876
8
    return NameClassification::Unknown();
877
8
  }
878
879
14.4M
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
880
14.4M
  LookupParsedName(Result, S, &SS, !CurMethod);
881
882
14.4M
  if (SS.isInvalid())
883
7
    return NameClassification::Error();
884
885
  // For unqualified lookup in a class template in MSVC mode, look into
886
  // dependent base classes where the primary class template is known.
887
14.4M
  if (Result.empty() && 
SS.isEmpty()30.7k
&&
getLangOpts().MSVCCompat28.4k
) {
888
77
    if (ParsedType TypeInBase =
889
77
            recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
890
14
      return TypeInBase;
891
77
  }
892
893
  // Perform lookup for Objective-C instance variables (including automatically
894
  // synthesized instance variables), if we're in an Objective-C method.
895
  // FIXME: This lookup really, really needs to be folded in to the normal
896
  // unqualified lookup mechanism.
897
14.4M
  if (SS.isEmpty() && 
CurMethod14.3M
&&
!isResultTypeOrTemplate(Result, NextToken)5.02k
) {
898
3.89k
    DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
899
3.89k
    if (Ivar.isInvalid())
900
6
      return NameClassification::Error();
901
3.88k
    if (Ivar.isUsable())
902
898
      return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
903
904
    // We defer builtin creation until after ivar lookup inside ObjC methods.
905
2.98k
    if (Result.empty())
906
165
      LookupBuiltin(Result);
907
2.98k
  }
908
909
14.4M
  bool SecondTry = false;
910
14.4M
  bool IsFilteredTemplateName = false;
911
912
14.4M
Corrected:
913
14.4M
  switch (Result.getResultKind()) {
914
27.8k
  case LookupResult::NotFound:
915
    // If an unqualified-id is followed by a '(', then we have a function
916
    // call.
917
27.8k
    if (SS.isEmpty() && 
NextToken.is(tok::l_paren)27.7k
) {
918
      // In C++, this is an ADL-only call.
919
      // FIXME: Reference?
920
792
      if (getLangOpts().CPlusPlus)
921
613
        return NameClassification::UndeclaredNonType();
922
923
      // C90 6.3.2.2:
924
      //   If the expression that precedes the parenthesized argument list in a
925
      //   function call consists solely of an identifier, and if no
926
      //   declaration is visible for this identifier, the identifier is
927
      //   implicitly declared exactly as if, in the innermost block containing
928
      //   the function call, the declaration
929
      //
930
      //     extern int identifier ();
931
      //
932
      //   appeared.
933
      //
934
      // We also allow this in C99 as an extension.
935
179
      if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
936
179
        return NameClassification::NonType(D);
937
179
    }
938
939
27.0k
    if (getLangOpts().CPlusPlus20 && 
SS.isEmpty()95
&&
NextToken.is(tok::less)87
) {
940
      // In C++20 onwards, this could be an ADL-only call to a function
941
      // template, and we're required to assume that this is a template name.
942
      //
943
      // FIXME: Find a way to still do typo correction in this case.
944
2
      TemplateName Template =
945
2
          Context.getAssumedTemplateName(NameInfo.getName());
946
2
      return NameClassification::UndeclaredTemplate(Template);
947
2
    }
948
949
    // In C, we first see whether there is a tag type by the same name, in
950
    // which case it's likely that the user just forgot to write "enum",
951
    // "struct", or "union".
952
27.0k
    if (!getLangOpts().CPlusPlus && 
!SecondTry8.37k
&&
953
27.0k
        
isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)8.37k
) {
954
4
      break;
955
4
    }
956
957
    // Perform typo correction to determine if there is another name that is
958
    // close to this name.
959
27.0k
    if (!SecondTry && CCC) {
960
26.9k
      SecondTry = true;
961
26.9k
      if (TypoCorrection Corrected =
962
26.9k
              CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
963
26.9k
                          &SS, *CCC, CTK_ErrorRecovery)) {
964
94
        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
965
94
        unsigned QualifiedDiag = diag::err_no_member_suggest;
966
967
94
        NamedDecl *FirstDecl = Corrected.getFoundDecl();
968
94
        NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
969
94
        if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)79
&&
970
94
            
UnderlyingFirstDecl0
&&
isa<TemplateDecl>(UnderlyingFirstDecl)0
) {
971
0
          UnqualifiedDiag = diag::err_no_template_suggest;
972
0
          QualifiedDiag = diag::err_no_member_template_suggest;
973
94
        } else if (UnderlyingFirstDecl &&
974
94
                   
(77
isa<TypeDecl>(UnderlyingFirstDecl)77
||
975
77
                    
isa<ObjCInterfaceDecl>(UnderlyingFirstDecl)56
||
976
77
                    
isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl)54
)) {
977
23
          UnqualifiedDiag = diag::err_unknown_typename_suggest;
978
23
          QualifiedDiag = diag::err_unknown_nested_typename_suggest;
979
23
        }
980
981
94
        if (SS.isEmpty()) {
982
94
          diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
983
94
        } else {// FIXME: is this even reachable? Test it.
984
0
          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
985
0
          bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
986
0
                                  Name->getName().equals(CorrectedStr);
987
0
          diagnoseTypo(Corrected, PDiag(QualifiedDiag)
988
0
                                    << Name << computeDeclContext(SS, false)
989
0
                                    << DroppedSpecifier << SS.getRange());
990
0
        }
991
992
        // Update the name, so that the caller has the new name.
993
94
        Name = Corrected.getCorrectionAsIdentifierInfo();
994
995
        // Typo correction corrected to a keyword.
996
94
        if (Corrected.isKeyword())
997
17
          return Name;
998
999
        // Also update the LookupResult...
1000
        // FIXME: This should probably go away at some point
1001
77
        Result.clear();
1002
77
        Result.setLookupName(Corrected.getCorrection());
1003
77
        if (FirstDecl)
1004
77
          Result.addDecl(FirstDecl);
1005
1006
        // If we found an Objective-C instance variable, let
1007
        // LookupInObjCMethod build the appropriate expression to
1008
        // reference the ivar.
1009
        // FIXME: This is a gross hack.
1010
77
        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1011
5
          DeclResult R =
1012
5
              LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1013
5
          if (R.isInvalid())
1014
0
            return NameClassification::Error();
1015
5
          if (R.isUsable())
1016
5
            return NameClassification::NonType(Ivar);
1017
5
        }
1018
1019
72
        goto Corrected;
1020
77
      }
1021
26.9k
    }
1022
1023
    // We failed to correct; just fall through and let the parser deal with it.
1024
26.9k
    Result.suppressDiagnostics();
1025
26.9k
    return NameClassification::Unknown();
1026
1027
2.15k
  case LookupResult::NotFoundInCurrentInstantiation: {
1028
    // We performed name lookup into the current instantiation, and there were
1029
    // dependent bases, so we treat this result the same way as any other
1030
    // dependent nested-name-specifier.
1031
1032
    // C++ [temp.res]p2:
1033
    //   A name used in a template declaration or definition and that is
1034
    //   dependent on a template-parameter is assumed not to name a type
1035
    //   unless the applicable name lookup finds a type name or the name is
1036
    //   qualified by the keyword typename.
1037
    //
1038
    // FIXME: If the next token is '<', we might want to ask the parser to
1039
    // perform some heroics to see if we actually have a
1040
    // template-argument-list, which would indicate a missing 'template'
1041
    // keyword here.
1042
2.15k
    return NameClassification::DependentNonType();
1043
27.0k
  }
1044
1045
14.2M
  case LookupResult::Found:
1046
14.4M
  case LookupResult::FoundOverloaded:
1047
14.4M
  case LookupResult::FoundUnresolvedValue:
1048
14.4M
    break;
1049
1050
29
  case LookupResult::Ambiguous:
1051
29
    if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)26
&&
1052
29
        hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1053
0
                                      /*AllowDependent=*/false)) {
1054
      // C++ [temp.local]p3:
1055
      //   A lookup that finds an injected-class-name (10.2) can result in an
1056
      //   ambiguity in certain cases (for example, if it is found in more than
1057
      //   one base class). If all of the injected-class-names that are found
1058
      //   refer to specializations of the same class template, and if the name
1059
      //   is followed by a template-argument-list, the reference refers to the
1060
      //   class template itself and not a specialization thereof, and is not
1061
      //   ambiguous.
1062
      //
1063
      // This filtering can make an ambiguous result into an unambiguous one,
1064
      // so try again after filtering out template names.
1065
0
      FilterAcceptableTemplateNames(Result);
1066
0
      if (!Result.isAmbiguous()) {
1067
0
        IsFilteredTemplateName = true;
1068
0
        break;
1069
0
      }
1070
0
    }
1071
1072
    // Diagnose the ambiguity and return an error.
1073
29
    return NameClassification::Error();
1074
14.4M
  }
1075
1076
14.4M
  if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)13.4M
&&
1077
14.4M
      
(149
IsFilteredTemplateName149
||
1078
149
       hasAnyAcceptableTemplateNames(
1079
149
           Result, /*AllowFunctionTemplates=*/true,
1080
149
           /*AllowDependent=*/false,
1081
149
           /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1082
149
               
getLangOpts().CPlusPlus20128
))) {
1083
    // C++ [temp.names]p3:
1084
    //   After name lookup (3.4) finds that a name is a template-name or that
1085
    //   an operator-function-id or a literal- operator-id refers to a set of
1086
    //   overloaded functions any member of which is a function template if
1087
    //   this is followed by a <, the < is always taken as the delimiter of a
1088
    //   template-argument-list and never as the less-than operator.
1089
    // C++2a [temp.names]p2:
1090
    //   A name is also considered to refer to a template if it is an
1091
    //   unqualified-id followed by a < and name lookup finds either one
1092
    //   or more functions or finds nothing.
1093
0
    if (!IsFilteredTemplateName)
1094
0
      FilterAcceptableTemplateNames(Result);
1095
1096
0
    bool IsFunctionTemplate;
1097
0
    bool IsVarTemplate;
1098
0
    TemplateName Template;
1099
0
    if (Result.end() - Result.begin() > 1) {
1100
0
      IsFunctionTemplate = true;
1101
0
      Template = Context.getOverloadedTemplateName(Result.begin(),
1102
0
                                                   Result.end());
1103
0
    } else if (!Result.empty()) {
1104
0
      auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1105
0
          *Result.begin(), /*AllowFunctionTemplates=*/true,
1106
0
          /*AllowDependent=*/false));
1107
0
      IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1108
0
      IsVarTemplate = isa<VarTemplateDecl>(TD);
1109
1110
0
      if (SS.isNotEmpty())
1111
0
        Template =
1112
0
            Context.getQualifiedTemplateName(SS.getScopeRep(),
1113
0
                                             /*TemplateKeyword=*/false, TD);
1114
0
      else
1115
0
        Template = TemplateName(TD);
1116
0
    } else {
1117
      // All results were non-template functions. This is a function template
1118
      // name.
1119
0
      IsFunctionTemplate = true;
1120
0
      Template = Context.getAssumedTemplateName(NameInfo.getName());
1121
0
    }
1122
1123
0
    if (IsFunctionTemplate) {
1124
      // Function templates always go through overload resolution, at which
1125
      // point we'll perform the various checks (e.g., accessibility) we need
1126
      // to based on which function we selected.
1127
0
      Result.suppressDiagnostics();
1128
1129
0
      return NameClassification::FunctionTemplate(Template);
1130
0
    }
1131
1132
0
    return IsVarTemplate ? NameClassification::VarTemplate(Template)
1133
0
                         : NameClassification::TypeTemplate(Template);
1134
0
  }
1135
1136
14.4M
  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1137
14.4M
  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1138
11.8M
    DiagnoseUseOfDecl(Type, NameLoc);
1139
11.8M
    MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1140
11.8M
    QualType T = Context.getTypeDeclType(Type);
1141
11.8M
    if (SS.isNotEmpty())
1142
219
      return buildNestedType(*this, SS, T, NameLoc);
1143
11.8M
    return ParsedType::make(T);
1144
11.8M
  }
1145
1146
2.60M
  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1147
2.60M
  if (!Class) {
1148
    // FIXME: It's unfortunate that we don't have a Type node for handling this.
1149
2.60M
    if (ObjCCompatibleAliasDecl *Alias =
1150
2.60M
            dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1151
0
      Class = Alias->getClassInterface();
1152
2.60M
  }
1153
1154
2.60M
  if (Class) {
1155
9.62k
    DiagnoseUseOfDecl(Class, NameLoc);
1156
1157
9.62k
    if (NextToken.is(tok::period)) {
1158
      // Interface. <something> is parsed as a property reference expression.
1159
      // Just return "unknown" as a fall-through for now.
1160
70
      Result.suppressDiagnostics();
1161
70
      return NameClassification::Unknown();
1162
70
    }
1163
1164
9.55k
    QualType T = Context.getObjCInterfaceType(Class);
1165
9.55k
    return ParsedType::make(T);
1166
9.62k
  }
1167
1168
2.60M
  if (isa<ConceptDecl>(FirstDecl))
1169
37
    return NameClassification::Concept(
1170
37
        TemplateName(cast<TemplateDecl>(FirstDecl)));
1171
1172
2.60M
  if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1173
109
    (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1174
109
    return NameClassification::Error();
1175
109
  }
1176
1177
  // We can have a type template here if we're classifying a template argument.
1178
2.59M
  if (isa<TemplateDecl>(FirstDecl) && 
!isa<FunctionTemplateDecl>(FirstDecl)112k
&&
1179
2.59M
      
!isa<VarTemplateDecl>(FirstDecl)9.50k
)
1180
9.49k
    return NameClassification::TypeTemplate(
1181
9.49k
        TemplateName(cast<TemplateDecl>(FirstDecl)));
1182
1183
  // Check for a tag type hidden by a non-type decl in a few cases where it
1184
  // seems likely a type is wanted instead of the non-type that was found.
1185
2.59M
  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1186
2.59M
  if ((NextToken.is(tok::identifier) ||
1187
2.59M
       
(2.59M
NextIsOp2.59M
&&
1188
2.59M
        
FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate()13.3k
)) &&
1189
2.59M
      
isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)226
) {
1190
32
    TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1191
32
    DiagnoseUseOfDecl(Type, NameLoc);
1192
32
    QualType T = Context.getTypeDeclType(Type);
1193
32
    if (SS.isNotEmpty())
1194
0
      return buildNestedType(*this, SS, T, NameLoc);
1195
32
    return ParsedType::make(T);
1196
32
  }
1197
1198
  // If we already know which single declaration is referenced, just annotate
1199
  // that declaration directly. Defer resolving even non-overloaded class
1200
  // member accesses, as we need to defer certain access checks until we know
1201
  // the context.
1202
2.59M
  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1203
2.59M
  if (Result.isSingleResult() && 
!ADL2.43M
&&
!FirstDecl->isCXXClassMember()2.21M
)
1204
1.91M
    return NameClassification::NonType(Result.getRepresentativeDecl());
1205
1206
  // Otherwise, this is an overload set that we will need to resolve later.
1207
676k
  Result.suppressDiagnostics();
1208
676k
  return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1209
676k
      Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1210
676k
      Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1211
676k
      Result.begin(), Result.end()));
1212
2.59M
}
1213
1214
ExprResult
1215
Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1216
613
                                             SourceLocation NameLoc) {
1217
613
  assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1218
0
  CXXScopeSpec SS;
1219
613
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1220
613
  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1221
613
}
1222
1223
ExprResult
1224
Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1225
                                            IdentifierInfo *Name,
1226
                                            SourceLocation NameLoc,
1227
2.15k
                                            bool IsAddressOfOperand) {
1228
2.15k
  DeclarationNameInfo NameInfo(Name, NameLoc);
1229
2.15k
  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1230
2.15k
                                    NameInfo, IsAddressOfOperand,
1231
2.15k
                                    /*TemplateArgs=*/nullptr);
1232
2.15k
}
1233
1234
ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1235
                                              NamedDecl *Found,
1236
                                              SourceLocation NameLoc,
1237
1.91M
                                              const Token &NextToken) {
1238
1.91M
  if (getCurMethodDecl() && 
SS.isEmpty()3.58k
)
1239
3.58k
    if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1240
903
      return BuildIvarRefExpr(S, NameLoc, Ivar);
1241
1242
  // Reconstruct the lookup result.
1243
1.91M
  LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1244
1.91M
  Result.addDecl(Found);
1245
1.91M
  Result.resolveKind();
1246
1247
1.91M
  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1248
1.91M
  return BuildDeclarationNameExpr(SS, Result, ADL);
1249
1.91M
}
1250
1251
676k
ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1252
  // For an implicit class member access, transform the result into a member
1253
  // access expression if necessary.
1254
676k
  auto *ULE = cast<UnresolvedLookupExpr>(E);
1255
676k
  if ((*ULE->decls_begin())->isCXXClassMember()) {
1256
360k
    CXXScopeSpec SS;
1257
360k
    SS.Adopt(ULE->getQualifierLoc());
1258
1259
    // Reconstruct the lookup result.
1260
360k
    LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1261
360k
                        LookupOrdinaryName);
1262
360k
    Result.setNamingClass(ULE->getNamingClass());
1263
833k
    for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; 
++I473k
)
1264
473k
      Result.addDecl(*I, I.getAccess());
1265
360k
    Result.resolveKind();
1266
360k
    return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1267
360k
                                           nullptr, S);
1268
360k
  }
1269
1270
  // Otherwise, this is already in the form we needed, and no further checks
1271
  // are necessary.
1272
315k
  return ULE;
1273
676k
}
1274
1275
Sema::TemplateNameKindForDiagnostics
1276
1.40k
Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1277
1.40k
  auto *TD = Name.getAsTemplateDecl();
1278
1.40k
  if (!TD)
1279
116
    return TemplateNameKindForDiagnostics::DependentTemplate;
1280
1.28k
  if (isa<ClassTemplateDecl>(TD))
1281
282
    return TemplateNameKindForDiagnostics::ClassTemplate;
1282
1.00k
  if (isa<FunctionTemplateDecl>(TD))
1283
943
    return TemplateNameKindForDiagnostics::FunctionTemplate;
1284
63
  if (isa<VarTemplateDecl>(TD))
1285
23
    return TemplateNameKindForDiagnostics::VarTemplate;
1286
40
  if (isa<TypeAliasTemplateDecl>(TD))
1287
28
    return TemplateNameKindForDiagnostics::AliasTemplate;
1288
12
  if (isa<TemplateTemplateParmDecl>(TD))
1289
11
    return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1290
1
  if (isa<ConceptDecl>(TD))
1291
1
    return TemplateNameKindForDiagnostics::Concept;
1292
0
  return TemplateNameKindForDiagnostics::DependentTemplate;
1293
1
}
1294
1295
5.97M
void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1296
5.97M
  assert(DC->getLexicalParent() == CurContext &&
1297
5.97M
      "The next DeclContext should be lexically contained in the current one.");
1298
0
  CurContext = DC;
1299
5.97M
  S->setEntity(DC);
1300
5.97M
}
1301
1302
8.06M
void Sema::PopDeclContext() {
1303
8.06M
  assert(CurContext && "DeclContext imbalance!");
1304
1305
0
  CurContext = CurContext->getLexicalParent();
1306
8.06M
  assert(CurContext && "Popped translation unit!");
1307
8.06M
}
1308
1309
Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1310
47
                                                                    Decl *D) {
1311
  // Unlike PushDeclContext, the context to which we return is not necessarily
1312
  // the containing DC of TD, because the new context will be some pre-existing
1313
  // TagDecl definition instead of a fresh one.
1314
47
  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1315
47
  CurContext = cast<TagDecl>(D)->getDefinition();
1316
47
  assert(CurContext && "skipping definition of undefined tag");
1317
  // Start lookups from the parent of the current context; we don't want to look
1318
  // into the pre-existing complete definition.
1319
0
  S->setEntity(CurContext->getLookupParent());
1320
47
  return Result;
1321
47
}
1322
1323
47
void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1324
47
  CurContext = static_cast<decltype(CurContext)>(Context);
1325
47
}
1326
1327
/// EnterDeclaratorContext - Used when we must lookup names in the context
1328
/// of a declarator's nested name specifier.
1329
///
1330
276k
void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1331
  // C++0x [basic.lookup.unqual]p13:
1332
  //   A name used in the definition of a static data member of class
1333
  //   X (after the qualified-id of the static member) is looked up as
1334
  //   if the name was used in a member function of X.
1335
  // C++0x [basic.lookup.unqual]p14:
1336
  //   If a variable member of a namespace is defined outside of the
1337
  //   scope of its namespace then any name used in the definition of
1338
  //   the variable member (after the declarator-id) is looked up as
1339
  //   if the definition of the variable member occurred in its
1340
  //   namespace.
1341
  // Both of these imply that we should push a scope whose context
1342
  // is the semantic context of the declaration.  We can't use
1343
  // PushDeclContext here because that context is not necessarily
1344
  // lexically contained in the current context.  Fortunately,
1345
  // the containing scope should have the appropriate information.
1346
1347
276k
  assert(!S->getEntity() && "scope already has entity");
1348
1349
0
#ifndef NDEBUG
1350
0
  Scope *Ancestor = S->getParent();
1351
545k
  while (!Ancestor->getEntity()) 
Ancestor = Ancestor->getParent()268k
;
1352
276k
  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1353
0
#endif
1354
1355
0
  CurContext = DC;
1356
276k
  S->setEntity(DC);
1357
1358
276k
  if (S->getParent()->isTemplateParamScope()) {
1359
    // Also set the corresponding entities for all immediately-enclosing
1360
    // template parameter scopes.
1361
221k
    EnterTemplatedContext(S->getParent(), DC);
1362
221k
  }
1363
276k
}
1364
1365
276k
void Sema::ExitDeclaratorContext(Scope *S) {
1366
276k
  assert(S->getEntity() == CurContext && "Context imbalance!");
1367
1368
  // Switch back to the lexical context.  The safety of this is
1369
  // enforced by an assert in EnterDeclaratorContext.
1370
0
  Scope *Ancestor = S->getParent();
1371
545k
  while (!Ancestor->getEntity()) 
Ancestor = Ancestor->getParent()268k
;
1372
276k
  CurContext = Ancestor->getEntity();
1373
1374
  // We don't need to do anything with the scope, which is going to
1375
  // disappear.
1376
276k
}
1377
1378
355k
void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1379
355k
  assert(S->isTemplateParamScope() &&
1380
355k
         "expected to be initializing a template parameter scope");
1381
1382
  // C++20 [temp.local]p7:
1383
  //   In the definition of a member of a class template that appears outside
1384
  //   of the class template definition, the name of a member of the class
1385
  //   template hides the name of a template-parameter of any enclosing class
1386
  //   templates (but not a template-parameter of the member if the member is a
1387
  //   class or function template).
1388
  // C++20 [temp.local]p9:
1389
  //   In the definition of a class template or in the definition of a member
1390
  //   of such a template that appears outside of the template definition, for
1391
  //   each non-dependent base class (13.8.2.1), if the name of the base class
1392
  //   or the name of a member of the base class is the same as the name of a
1393
  //   template-parameter, the base class name or member name hides the
1394
  //   template-parameter name (6.4.10).
1395
  //
1396
  // This means that a template parameter scope should be searched immediately
1397
  // after searching the DeclContext for which it is a template parameter
1398
  // scope. For example, for
1399
  //   template<typename T> template<typename U> template<typename V>
1400
  //     void N::A<T>::B<U>::f(...)
1401
  // we search V then B<U> (and base classes) then U then A<T> (and base
1402
  // classes) then T then N then ::.
1403
0
  unsigned ScopeDepth = getTemplateDepth(S);
1404
757k
  for (; S && S->isTemplateParamScope(); 
S = S->getParent(), --ScopeDepth402k
) {
1405
402k
    DeclContext *SearchDCAfterScope = DC;
1406
416k
    for (; DC; 
DC = DC->getLookupParent()14.3k
) {
1407
412k
      if (const TemplateParameterList *TPL =
1408
412k
              cast<Decl>(DC)->getDescribedTemplateParams()) {
1409
398k
        unsigned DCDepth = TPL->getDepth() + 1;
1410
398k
        if (DCDepth > ScopeDepth)
1411
0
          continue;
1412
398k
        if (ScopeDepth == DCDepth)
1413
352k
          SearchDCAfterScope = DC = DC->getLookupParent();
1414
398k
        break;
1415
398k
      }
1416
412k
    }
1417
402k
    S->setLookupEntity(SearchDCAfterScope);
1418
402k
  }
1419
355k
}
1420
1421
7.66k
void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1422
  // We assume that the caller has already called
1423
  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1424
7.66k
  FunctionDecl *FD = D->getAsFunction();
1425
7.66k
  if (!FD)
1426
0
    return;
1427
1428
  // Same implementation as PushDeclContext, but enters the context
1429
  // from the lexical parent, rather than the top-level class.
1430
7.66k
  assert(CurContext == FD->getLexicalParent() &&
1431
7.66k
    "The next DeclContext should be lexically contained in the current one.");
1432
0
  CurContext = FD;
1433
7.66k
  S->setEntity(CurContext);
1434
1435
18.4k
  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; 
++P10.7k
) {
1436
10.7k
    ParmVarDecl *Param = FD->getParamDecl(P);
1437
    // If the parameter has an identifier, then add it to the scope
1438
10.7k
    if (Param->getIdentifier()) {
1439
10.6k
      S->AddDecl(Param);
1440
10.6k
      IdResolver.AddDecl(Param);
1441
10.6k
    }
1442
10.7k
  }
1443
7.66k
}
1444
1445
7.66k
void Sema::ActOnExitFunctionContext() {
1446
  // Same implementation as PopDeclContext, but returns to the lexical parent,
1447
  // rather than the top-level class.
1448
7.66k
  assert(CurContext && "DeclContext imbalance!");
1449
0
  CurContext = CurContext->getLexicalParent();
1450
7.66k
  assert(CurContext && "Popped translation unit!");
1451
7.66k
}
1452
1453
/// Determine whether we allow overloading of the function
1454
/// PrevDecl with another declaration.
1455
///
1456
/// This routine determines whether overloading is possible, not
1457
/// whether some new function is actually an overload. It will return
1458
/// true in C++ (where we can always provide overloads) or, as an
1459
/// extension, in C when the previous function is already an
1460
/// overloaded function declaration or has the "overloadable"
1461
/// attribute.
1462
static bool AllowOverloadingOfFunction(LookupResult &Previous,
1463
                                       ASTContext &Context,
1464
14.8M
                                       const FunctionDecl *New) {
1465
14.8M
  if (Context.getLangOpts().CPlusPlus)
1466
4.58M
    return true;
1467
1468
10.2M
  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1469
9.19M
    return true;
1470
1471
1.06M
  return Previous.getResultKind() == LookupResult::Found &&
1472
1.06M
         
(1.06M
Previous.getFoundDecl()->hasAttr<OverloadableAttr>()1.06M
||
1473
1.06M
          
New->hasAttr<OverloadableAttr>()19.2k
);
1474
10.2M
}
1475
1476
/// Add this decl to the scope shadowed decl chains.
1477
53.9M
void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1478
  // Move up the scope chain until we find the nearest enclosing
1479
  // non-transparent context. The declaration will be introduced into this
1480
  // scope.
1481
62.4M
  while (S->getEntity() && 
S->getEntity()->isTransparentContext()62.0M
)
1482
8.55M
    S = S->getParent();
1483
1484
  // Add scoped declarations into their context, so that they can be
1485
  // found later. Declarations without a context won't be inserted
1486
  // into any context.
1487
53.9M
  if (AddToContext)
1488
53.6M
    CurContext->addDecl(D);
1489
1490
  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1491
  // are function-local declarations.
1492
53.9M
  if (getLangOpts().CPlusPlus && 
D->isOutOfLine()18.9M
&&
!S->getFnParent()235k
)
1493
234k
    return;
1494
1495
  // Template instantiations should also not be pushed into scope.
1496
53.6M
  if (isa<FunctionDecl>(D) &&
1497
53.6M
      
cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()32.1M
)
1498
1.50k
    return;
1499
1500
  // If this replaces anything in the current scope,
1501
53.6M
  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1502
53.6M
                               IEnd = IdResolver.end();
1503
302M
  for (; I != IEnd; 
++I249M
) {
1504
249M
    if (S->isDeclScope(*I) && 
D->declarationReplaces(*I)248M
) {
1505
394k
      S->RemoveDecl(*I);
1506
394k
      IdResolver.RemoveDecl(*I);
1507
1508
      // Should only need to replace one decl.
1509
394k
      break;
1510
394k
    }
1511
249M
  }
1512
1513
53.6M
  S->AddDecl(D);
1514
1515
53.6M
  if (isa<LabelDecl>(D) && 
!cast<LabelDecl>(D)->isGnuLocal()3.72k
) {
1516
    // Implicitly-generated labels may end up getting generated in an order that
1517
    // isn't strictly lexical, which breaks name lookup. Be careful to insert
1518
    // the label at the appropriate place in the identifier chain.
1519
3.73k
    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; 
++I17
) {
1520
312
      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1521
312
      if (IDC == CurContext) {
1522
17
        if (!S->isDeclScope(*I))
1523
3
          continue;
1524
295
      } else if (IDC->Encloses(CurContext))
1525
295
        break;
1526
312
    }
1527
1528
3.71k
    IdResolver.InsertDeclAfter(I, D);
1529
53.6M
  } else {
1530
53.6M
    IdResolver.AddDecl(D);
1531
53.6M
  }
1532
53.6M
  warnOnReservedIdentifier(D);
1533
53.6M
}
1534
1535
bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1536
250M
                         bool AllowInlineNamespace) {
1537
250M
  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1538
250M
}
1539
1540
37.1k
Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1541
37.1k
  DeclContext *TargetDC = DC->getPrimaryContext();
1542
108k
  do {
1543
108k
    if (DeclContext *ScopeDC = S->getEntity())
1544
77.4k
      if (ScopeDC->getPrimaryContext() == TargetDC)
1545
36.3k
        return S;
1546
108k
  } while (
(S = S->getParent())72.3k
);
1547
1548
788
  return nullptr;
1549
37.1k
}
1550
1551
static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1552
                                            DeclContext*,
1553
                                            ASTContext&);
1554
1555
/// Filters out lookup results that don't fall within the given scope
1556
/// as determined by isDeclInScope.
1557
void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1558
                                bool ConsiderLinkage,
1559
36.7M
                                bool AllowInlineNamespace) {
1560
36.7M
  LookupResult::Filter F = R.makeFilter();
1561
286M
  while (F.hasNext()) {
1562
250M
    NamedDecl *D = F.next();
1563
1564
250M
    if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1565
249M
      continue;
1566
1567
304k
    if (ConsiderLinkage && 
isOutOfScopePreviousDeclaration(D, Ctx, Context)1.17k
)
1568
515
      continue;
1569
1570
303k
    F.erase();
1571
303k
  }
1572
1573
36.7M
  F.done();
1574
36.7M
}
1575
1576
/// We've determined that \p New is a redeclaration of \p Old. Check that they
1577
/// have compatible owning modules.
1578
419k
bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1579
  // FIXME: The Modules TS is not clear about how friend declarations are
1580
  // to be treated. It's not meaningful to have different owning modules for
1581
  // linkage in redeclarations of the same entity, so for now allow the
1582
  // redeclaration and change the owning modules to match.
1583
419k
  if (New->getFriendObjectKind() &&
1584
419k
      
Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()19.8k
) {
1585
0
    New->setLocalOwningModule(Old->getOwningModule());
1586
0
    makeMergedDefinitionVisible(New);
1587
0
    return false;
1588
0
  }
1589
1590
419k
  Module *NewM = New->getOwningModule();
1591
419k
  Module *OldM = Old->getOwningModule();
1592
1593
419k
  if (NewM && 
NewM->Kind == Module::PrivateModuleFragment35.3k
)
1594
3
    NewM = NewM->Parent;
1595
419k
  if (OldM && 
OldM->Kind == Module::PrivateModuleFragment37.1k
)
1596
0
    OldM = OldM->Parent;
1597
1598
419k
  if (NewM == OldM)
1599
410k
    return false;
1600
1601
9.25k
  bool NewIsModuleInterface = NewM && 
NewM->isModulePurview()7.51k
;
1602
9.25k
  bool OldIsModuleInterface = OldM && 
OldM->isModulePurview()9.25k
;
1603
9.25k
  if (NewIsModuleInterface || 
OldIsModuleInterface9.21k
) {
1604
    // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1605
    //   if a declaration of D [...] appears in the purview of a module, all
1606
    //   other such declarations shall appear in the purview of the same module
1607
54
    Diag(New->getLocation(), diag::err_mismatched_owning_module)
1608
54
      << New
1609
54
      << NewIsModuleInterface
1610
54
      << (NewIsModuleInterface ? 
NewM->getFullModuleName()47
:
""7
)
1611
54
      << OldIsModuleInterface
1612
54
      << (OldIsModuleInterface ? 
OldM->getFullModuleName()28
:
""26
);
1613
54
    Diag(Old->getLocation(), diag::note_previous_declaration);
1614
54
    New->setInvalidDecl();
1615
54
    return true;
1616
54
  }
1617
1618
9.20k
  return false;
1619
9.25k
}
1620
1621
922k
static bool isUsingDecl(NamedDecl *D) {
1622
922k
  return isa<UsingShadowDecl>(D) ||
1623
922k
         
isa<UnresolvedUsingTypenameDecl>(D)922k
||
1624
922k
         
isa<UnresolvedUsingValueDecl>(D)922k
;
1625
922k
}
1626
1627
/// Removes using shadow declarations from the lookup results.
1628
210k
static void RemoveUsingDecls(LookupResult &R) {
1629
210k
  LookupResult::Filter F = R.makeFilter();
1630
1.13M
  while (F.hasNext())
1631
922k
    if (isUsingDecl(F.next()))
1632
8
      F.erase();
1633
1634
210k
  F.done();
1635
210k
}
1636
1637
/// Check for this common pattern:
1638
/// @code
1639
/// class S {
1640
///   S(const S&); // DO NOT IMPLEMENT
1641
///   void operator=(const S&); // DO NOT IMPLEMENT
1642
/// };
1643
/// @endcode
1644
317k
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1645
  // FIXME: Should check for private access too but access is set after we get
1646
  // the decl here.
1647
317k
  if (D->doesThisDeclarationHaveABody())
1648
558
    return false;
1649
1650
316k
  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1651
85.9k
    return CD->isCopyConstructor();
1652
230k
  return D->isCopyAssignmentOperator();
1653
316k
}
1654
1655
// We need this to handle
1656
//
1657
// typedef struct {
1658
//   void *foo() { return 0; }
1659
// } A;
1660
//
1661
// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1662
// for example. If 'A', foo will have external linkage. If we have '*A',
1663
// foo will have no linkage. Since we can't know until we get to the end
1664
// of the typedef, this function finds out if D might have non-external linkage.
1665
// Callers should verify at the end of the TU if it D has external linkage or
1666
// not.
1667
4.19M
bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1668
4.19M
  const DeclContext *DC = D->getDeclContext();
1669
6.65M
  while (!DC->isTranslationUnit()) {
1670
2.45M
    if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1671
436k
      if (!RD->hasNameForLinkage())
1672
745
        return true;
1673
436k
    }
1674
2.45M
    DC = DC->getParent();
1675
2.45M
  }
1676
1677
4.19M
  return !D->isExternallyVisible();
1678
4.19M
}
1679
1680
// FIXME: This needs to be refactored; some other isInMainFile users want
1681
// these semantics.
1682
29.2M
static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1683
29.2M
  if (S.TUKind != TU_Complete)
1684
110k
    return false;
1685
29.1M
  return S.SourceMgr.isInMainFile(Loc);
1686
29.2M
}
1687
1688
33.5M
bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1689
33.5M
  assert(D);
1690
1691
33.5M
  if (D->isInvalidDecl() || 
D->isUsed()33.5M
||
D->hasAttr<UnusedAttr>()33.5M
)
1692
17.3k
    return false;
1693
1694
  // Ignore all entities declared within templates, and out-of-line definitions
1695
  // of members of class templates.
1696
33.5M
  if (D->getDeclContext()->isDependentContext() ||
1697
33.5M
      
D->getLexicalDeclContext()->isDependentContext()32.3M
)
1698
1.19M
    return false;
1699
1700
32.3M
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1701
31.2M
    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1702
2.84k
      return false;
1703
    // A non-out-of-line declaration of a member specialization was implicitly
1704
    // instantiated; it's the out-of-line declaration that we're interested in.
1705
31.2M
    if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1706
31.2M
        
FD->getMemberSpecializationInfo()9.10k
&&
!FD->isOutOfLine()2.73k
)
1707
43
      return false;
1708
1709
31.2M
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1710
354k
      if (MD->isVirtual() || 
IsDisallowedCopyOrAssign(MD)317k
)
1711
66.8k
        return false;
1712
30.8M
    } else {
1713
      // 'static inline' functions are defined in headers; don't warn.
1714
30.8M
      if (FD->isInlined() && 
!isMainFileLoc(*this, FD->getLocation())28.1M
)
1715
28.1M
        return false;
1716
30.8M
    }
1717
1718
2.98M
    if (FD->doesThisDeclarationHaveABody() &&
1719
2.98M
        
Context.DeclMustBeEmitted(FD)33.3k
)
1720
211
      return false;
1721
2.98M
  } else 
if (const VarDecl *1.08M
VD1.08M
= dyn_cast<VarDecl>(D)) {
1722
    // Constants and utility variables are defined in headers with internal
1723
    // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1724
    // like "inline".)
1725
1.08M
    if (!isMainFileLoc(*this, VD->getLocation()))
1726
998k
      return false;
1727
1728
89.8k
    if (Context.DeclMustBeEmitted(VD))
1729
57.0k
      return false;
1730
1731
32.8k
    if (VD->isStaticDataMember() &&
1732
32.8k
        
VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation5.82k
)
1733
0
      return false;
1734
32.8k
    if (VD->isStaticDataMember() &&
1735
32.8k
        
VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization5.82k
&&
1736
32.8k
        
VD->getMemberSpecializationInfo()237
&&
!VD->isOutOfLine()161
)
1737
114
      return false;
1738
1739
32.6k
    if (VD->isInline() && 
!isMainFileLoc(*this, VD->getLocation())255
)
1740
0
      return false;
1741
32.6k
  } else {
1742
0
    return false;
1743
0
  }
1744
1745
  // Only warn for unused decls internal to the translation unit.
1746
  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1747
  // for inline functions defined in the main source file, for instance.
1748
3.01M
  return mightHaveNonExternalLinkage(D);
1749
32.3M
}
1750
1751
33.2M
void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1752
33.2M
  if (!D)
1753
0
    return;
1754
1755
33.2M
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1756
31.9M
    const FunctionDecl *First = FD->getFirstDecl();
1757
31.9M
    if (FD != First && 
ShouldWarnIfUnusedFileScopedDecl(First)233k
)
1758
381
      return; // First should already be in the vector.
1759
31.9M
  }
1760
1761
33.2M
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1762
1.24M
    const VarDecl *First = VD->getFirstDecl();
1763
1.24M
    if (VD != First && 
ShouldWarnIfUnusedFileScopedDecl(First)49.9k
)
1764
104
      return; // First should already be in the vector.
1765
1.24M
  }
1766
1767
33.2M
  if (ShouldWarnIfUnusedFileScopedDecl(D))
1768
41.5k
    UnusedFileScopedDecls.push_back(D);
1769
33.2M
}
1770
1771
108M
static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1772
108M
  if (D->isInvalidDecl())
1773
489
    return false;
1774
1775
108M
  if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1776
    // For a decomposition declaration, warn if none of the bindings are
1777
    // referenced, instead of if the variable itself is referenced (which
1778
    // it is, by the bindings' expressions).
1779
213
    for (auto *BD : DD->bindings())
1780
308
      if (BD->isReferenced())
1781
121
        return false;
1782
108M
  } else if (!D->getDeclName()) {
1783
63.5M
    return false;
1784
63.5M
  } else 
if (45.3M
D->isReferenced()45.3M
||
D->isUsed()35.2M
) {
1785
10.1M
    return false;
1786
10.1M
  }
1787
1788
35.2M
  if (D->hasAttr<UnusedAttr>() || 
D->hasAttr<ObjCPreciseLifetimeAttr>()35.2M
)
1789
751
    return false;
1790
1791
35.2M
  if (isa<LabelDecl>(D))
1792
236
    return true;
1793
1794
  // Except for labels, we only care about unused decls that are local to
1795
  // functions.
1796
35.2M
  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1797
35.2M
  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1798
    // For dependent types, the diagnostic is deferred.
1799
3.09M
    WithinFunction =
1800
3.09M
        WithinFunction || (R->isLocalClass() && 
!R->isDependentType()41.2k
);
1801
35.2M
  if (!WithinFunction)
1802
33.8M
    return false;
1803
1804
1.35M
  if (isa<TypedefNameDecl>(D))
1805
596
    return true;
1806
1807
  // White-list anything that isn't a local variable.
1808
1.35M
  if (!isa<VarDecl>(D) || 
isa<ParmVarDecl>(D)1.20M
||
isa<ImplicitParamDecl>(D)53.6k
)
1809
1.31M
    return false;
1810
1811
  // Types of valid local variables should be complete, so this should succeed.
1812
42.4k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1813
1814
    // White-list anything with an __attribute__((unused)) type.
1815
42.4k
    const auto *Ty = VD->getType().getTypePtr();
1816
1817
    // Only look at the outermost level of typedef.
1818
42.4k
    if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1819
3.23k
      if (TT->getDecl()->hasAttr<UnusedAttr>())
1820
5
        return false;
1821
3.23k
    }
1822
1823
    // If we failed to complete the type for some reason, or if the type is
1824
    // dependent, don't diagnose the variable.
1825
42.4k
    if (Ty->isIncompleteType() || 
Ty->isDependentType()42.2k
)
1826
5.99k
      return false;
1827
1828
    // Look at the element type to ensure that the warning behaviour is
1829
    // consistent for both scalars and arrays.
1830
36.4k
    Ty = Ty->getBaseElementTypeUnsafe();
1831
1832
36.4k
    if (const TagType *TT = Ty->getAs<TagType>()) {
1833
10.6k
      const TagDecl *Tag = TT->getDecl();
1834
10.6k
      if (Tag->hasAttr<UnusedAttr>())
1835
4
        return false;
1836
1837
10.6k
      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1838
9.58k
        if (!RD->hasTrivialDestructor() && 
!RD->hasAttr<WarnUnusedAttr>()3.14k
)
1839
3.14k
          return false;
1840
1841
6.43k
        if (const Expr *Init = VD->getInit()) {
1842
6.42k
          if (const ExprWithCleanups *Cleanups =
1843
6.42k
                  dyn_cast<ExprWithCleanups>(Init))
1844
1.77k
            Init = Cleanups->getSubExpr();
1845
6.42k
          const CXXConstructExpr *Construct =
1846
6.42k
            dyn_cast<CXXConstructExpr>(Init);
1847
6.42k
          if (Construct && 
!Construct->isElidable()5.43k
) {
1848
3.95k
            CXXConstructorDecl *CD = Construct->getConstructor();
1849
3.95k
            if (!CD->isTrivial() && 
!RD->hasAttr<WarnUnusedAttr>()2.26k
&&
1850
3.95k
                
(2.26k
VD->getInit()->isValueDependent()2.26k
||
!VD->evaluateValue()2.26k
))
1851
2.12k
              return false;
1852
3.95k
          }
1853
1854
          // Suppress the warning if we don't know how this is constructed, and
1855
          // it could possibly be non-trivial constructor.
1856
4.30k
          if (Init->isTypeDependent())
1857
76
            for (const CXXConstructorDecl *Ctor : RD->ctors())
1858
74
              if (!Ctor->isTrivial())
1859
18
                return false;
1860
4.30k
        }
1861
6.43k
      }
1862
10.6k
    }
1863
1864
    // TODO: __attribute__((unused)) templates?
1865
36.4k
  }
1866
1867
31.1k
  return true;
1868
42.4k
}
1869
1870
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1871
31.3k
                                     FixItHint &Hint) {
1872
31.3k
  if (isa<LabelDecl>(D)) {
1873
236
    SourceLocation AfterColon = Lexer::findLocationAfterToken(
1874
236
        D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1875
236
        true);
1876
236
    if (AfterColon.isInvalid())
1877
8
      return;
1878
228
    Hint = FixItHint::CreateRemoval(
1879
228
        CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1880
228
  }
1881
31.3k
}
1882
1883
1.58M
void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1884
1.58M
  if (D->getTypeForDecl()->isDependentType())
1885
390k
    return;
1886
1887
1.19M
  for (auto *TmpD : D->decls()) {
1888
486k
    if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1889
13.2k
      DiagnoseUnusedDecl(T);
1890
473k
    else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1891
72.0k
      DiagnoseUnusedNestedTypedefs(R);
1892
486k
  }
1893
1.19M
}
1894
1895
/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1896
/// unless they are marked attr(unused).
1897
108M
void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1898
108M
  if (!ShouldDiagnoseUnusedDecl(D))
1899
108M
    return;
1900
1901
31.9k
  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1902
    // typedefs can be referenced later on, so the diagnostics are emitted
1903
    // at end-of-translation-unit.
1904
596
    UnusedLocalTypedefNameCandidates.insert(TD);
1905
596
    return;
1906
596
  }
1907
1908
31.3k
  FixItHint Hint;
1909
31.3k
  GenerateFixForUnusedDecl(D, Context, Hint);
1910
1911
31.3k
  unsigned DiagID;
1912
31.3k
  if (isa<VarDecl>(D) && 
cast<VarDecl>(D)->isExceptionVariable()31.1k
)
1913
362
    DiagID = diag::warn_unused_exception_param;
1914
31.0k
  else if (isa<LabelDecl>(D))
1915
236
    DiagID = diag::warn_unused_label;
1916
30.7k
  else
1917
30.7k
    DiagID = diag::warn_unused_variable;
1918
1919
31.3k
  Diag(D->getLocation(), DiagID) << D << Hint;
1920
31.3k
}
1921
1922
100M
void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1923
  // If it's not referenced, it can't be set.
1924
100M
  if (!VD->isReferenced() || 
!VD->getDeclName()7.51M
||
VD->hasAttr<UnusedAttr>()7.51M
)
1925
92.6M
    return;
1926
1927
7.51M
  const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1928
1929
7.51M
  if (Ty->isReferenceType() || 
Ty->isDependentType()6.95M
)
1930
1.64M
    return;
1931
1932
5.87M
  if (const TagType *TT = Ty->getAs<TagType>()) {
1933
157k
    const TagDecl *Tag = TT->getDecl();
1934
157k
    if (Tag->hasAttr<UnusedAttr>())
1935
0
      return;
1936
    // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1937
    // mimic gcc's behavior.
1938
157k
    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1939
59.2k
      if (!RD->hasAttr<WarnUnusedAttr>())
1940
59.2k
        return;
1941
59.2k
    }
1942
157k
  }
1943
1944
5.81M
  auto iter = RefsMinusAssignments.find(VD);
1945
5.81M
  if (iter == RefsMinusAssignments.end())
1946
33.6k
    return;
1947
1948
5.78M
  assert(iter->getSecond() >= 0 &&
1949
5.78M
         "Found a negative number of references to a VarDecl");
1950
5.78M
  if (iter->getSecond() != 0)
1951
5.77M
    return;
1952
3.11k
  unsigned DiagID = isa<ParmVarDecl>(VD) ? 
diag::warn_unused_but_set_parameter677
1953
3.11k
                                         : 
diag::warn_unused_but_set_variable2.43k
;
1954
3.11k
  Diag(VD->getLocation(), DiagID) << VD;
1955
3.11k
}
1956
1957
3.72k
static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1958
  // Verify that we have no forward references left.  If so, there was a goto
1959
  // or address of a label taken, but no definition of it.  Label fwd
1960
  // definitions are indicated with a null substmt which is also not a resolved
1961
  // MS inline assembly label name.
1962
3.72k
  bool Diagnose = false;
1963
3.72k
  if (L->isMSAsmLabel())
1964
28
    Diagnose = !L->isResolvedMSAsmLabel();
1965
3.69k
  else
1966
3.69k
    Diagnose = L->getStmt() == nullptr;
1967
3.72k
  if (Diagnose)
1968
358
    S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1969
3.72k
}
1970
1971
42.4M
void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1972
42.4M
  S->mergeNRVOIntoParent();
1973
1974
42.4M
  if (S->decl_empty()) 
return4.09M
;
1975
38.3M
  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1976
38.3M
         "Scope shouldn't contain decls!");
1977
1978
109M
  for (auto *TmpD : S->decls()) {
1979
109M
    assert(TmpD && "This decl didn't get pushed??");
1980
1981
0
    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1982
0
    NamedDecl *D = cast<NamedDecl>(TmpD);
1983
1984
    // Diagnose unused variables in this scope.
1985
109M
    if (!S->hasUnrecoverableErrorOccurred()) {
1986
108M
      DiagnoseUnusedDecl(D);
1987
108M
      if (const auto *RD = dyn_cast<RecordDecl>(D))
1988
747k
        DiagnoseUnusedNestedTypedefs(RD);
1989
108M
      if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1990
100M
        DiagnoseUnusedButSetDecl(VD);
1991
100M
        RefsMinusAssignments.erase(VD);
1992
100M
      }
1993
108M
    }
1994
1995
109M
    if (!D->getDeclName()) 
continue63.5M
;
1996
1997
    // If this was a forward reference to a label, verify it was defined.
1998
45.4M
    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1999
3.72k
      CheckPoppedLabel(LD, *this);
2000
2001
    // Remove this name from our lexical scope, and warn on it if we haven't
2002
    // already.
2003
45.4M
    IdResolver.RemoveDecl(D);
2004
45.4M
    auto ShadowI = ShadowingDecls.find(D);
2005
45.4M
    if (ShadowI != ShadowingDecls.end()) {
2006
4
      if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2007
4
        Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2008
4
            << D << FD << FD->getParent();
2009
4
        Diag(FD->getLocation(), diag::note_previous_declaration);
2010
4
      }
2011
4
      ShadowingDecls.erase(ShadowI);
2012
4
    }
2013
45.4M
  }
2014
38.3M
}
2015
2016
/// Look for an Objective-C class in the translation unit.
2017
///
2018
/// \param Id The name of the Objective-C class we're looking for. If
2019
/// typo-correction fixes this name, the Id will be updated
2020
/// to the fixed name.
2021
///
2022
/// \param IdLoc The location of the name in the translation unit.
2023
///
2024
/// \param DoTypoCorrection If true, this routine will attempt typo correction
2025
/// if there is no class with the given name.
2026
///
2027
/// \returns The declaration of the named Objective-C class, or NULL if the
2028
/// class could not be found.
2029
ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2030
                                              SourceLocation IdLoc,
2031
41.5k
                                              bool DoTypoCorrection) {
2032
  // The third "scope" argument is 0 since we aren't enabling lazy built-in
2033
  // creation from this context.
2034
41.5k
  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2035
2036
41.5k
  if (!IDecl && 
DoTypoCorrection112
) {
2037
    // Perform typo correction at the given location, but only if we
2038
    // find an Objective-C class name.
2039
35
    DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2040
35
    if (TypoCorrection C =
2041
35
            CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2042
35
                        TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2043
1
      diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2044
1
      IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2045
1
      Id = IDecl->getIdentifier();
2046
1
    }
2047
35
  }
2048
41.5k
  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2049
  // This routine must always return a class definition, if any.
2050
41.5k
  if (Def && 
Def->getDefinition()41.4k
)
2051
41.3k
      Def = Def->getDefinition();
2052
41.5k
  return Def;
2053
41.5k
}
2054
2055
/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2056
/// from S, where a non-field would be declared. This routine copes
2057
/// with the difference between C and C++ scoping rules in structs and
2058
/// unions. For example, the following code is well-formed in C but
2059
/// ill-formed in C++:
2060
/// @code
2061
/// struct S6 {
2062
///   enum { BAR } e;
2063
/// };
2064
///
2065
/// void test_S6() {
2066
///   struct S6 a;
2067
///   a.e = BAR;
2068
/// }
2069
/// @endcode
2070
/// For the declaration of BAR, this routine will return a different
2071
/// scope. The scope S will be the scope of the unnamed enumeration
2072
/// within S6. In C++, this routine will return the scope associated
2073
/// with S6, because the enumeration's scope is a transparent
2074
/// context but structures can contain non-field names. In C, this
2075
/// routine will return the translation unit scope, since the
2076
/// enumeration's scope is a transparent context and structures cannot
2077
/// contain non-field names.
2078
5.63M
Scope *Sema::getNonFieldDeclScope(Scope *S) {
2079
9.99M
  while (((S->getFlags() & Scope::DeclScope) == 0) ||
2080
9.99M
         
(9.99M
S->getEntity()9.99M
&&
S->getEntity()->isTransparentContext()9.98M
) ||
2081
9.99M
         
(5.63M
S->isClassScope()5.63M
&&
!getLangOpts().CPlusPlus83.8k
))
2082
4.35M
    S = S->getParent();
2083
5.63M
  return S;
2084
5.63M
}
2085
2086
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2087
5
                               ASTContext::GetBuiltinTypeError Error) {
2088
5
  switch (Error) {
2089
0
  case ASTContext::GE_None:
2090
0
    return "";
2091
0
  case ASTContext::GE_Missing_type:
2092
0
    return BuiltinInfo.getHeaderName(ID);
2093
5
  case ASTContext::GE_Missing_stdio:
2094
5
    return "stdio.h";
2095
0
  case ASTContext::GE_Missing_setjmp:
2096
0
    return "setjmp.h";
2097
0
  case ASTContext::GE_Missing_ucontext:
2098
0
    return "ucontext.h";
2099
5
  }
2100
0
  llvm_unreachable("unhandled error kind");
2101
0
}
2102
2103
FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2104
851k
                                  unsigned ID, SourceLocation Loc) {
2105
851k
  DeclContext *Parent = Context.getTranslationUnitDecl();
2106
2107
851k
  if (getLangOpts().CPlusPlus) {
2108
185k
    LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2109
185k
        Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2110
185k
    CLinkageDecl->setImplicit();
2111
185k
    Parent->addDecl(CLinkageDecl);
2112
185k
    Parent = CLinkageDecl;
2113
185k
  }
2114
2115
851k
  FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2116
851k
                                           /*TInfo=*/nullptr, SC_Extern,
2117
851k
                                           getCurFPFeatures().isFPConstrained(),
2118
851k
                                           false, Type->isFunctionProtoType());
2119
851k
  New->setImplicit();
2120
851k
  New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2121
2122
  // Create Decl objects for each parameter, adding them to the
2123
  // FunctionDecl.
2124
851k
  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2125
848k
    SmallVector<ParmVarDecl *, 16> Params;
2126
2.41M
    for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i1.56M
) {
2127
1.56M
      ParmVarDecl *parm = ParmVarDecl::Create(
2128
1.56M
          Context, New, SourceLocation(), SourceLocation(), nullptr,
2129
1.56M
          FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2130
1.56M
      parm->setScopeInfo(0, i);
2131
1.56M
      Params.push_back(parm);
2132
1.56M
    }
2133
848k
    New->setParams(Params);
2134
848k
  }
2135
2136
851k
  AddKnownFunctionAttributes(New);
2137
851k
  return New;
2138
851k
}
2139
2140
/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2141
/// file scope.  lazily create a decl for it. ForRedeclaration is true
2142
/// if we're creating this built-in in anticipation of redeclaring the
2143
/// built-in.
2144
NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2145
                                     Scope *S, bool ForRedeclaration,
2146
851k
                                     SourceLocation Loc) {
2147
851k
  LookupNecessaryTypesForBuiltin(S, ID);
2148
2149
851k
  ASTContext::GetBuiltinTypeError Error;
2150
851k
  QualType R = Context.GetBuiltinType(ID, Error);
2151
851k
  if (Error) {
2152
26
    if (!ForRedeclaration)
2153
4
      return nullptr;
2154
2155
    // If we have a builtin without an associated type we should not emit a
2156
    // warning when we were not able to find a type for it.
2157
22
    if (Error == ASTContext::GE_Missing_type ||
2158
22
        
Context.BuiltinInfo.allowTypeMismatch(ID)15
)
2159
17
      return nullptr;
2160
2161
    // If we could not find a type for setjmp it is because the jmp_buf type was
2162
    // not defined prior to the setjmp declaration.
2163
5
    if (Error == ASTContext::GE_Missing_setjmp) {
2164
0
      Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2165
0
          << Context.BuiltinInfo.getName(ID);
2166
0
      return nullptr;
2167
0
    }
2168
2169
    // Generally, we emit a warning that the declaration requires the
2170
    // appropriate header.
2171
5
    Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2172
5
        << getHeaderName(Context.BuiltinInfo, ID, Error)
2173
5
        << Context.BuiltinInfo.getName(ID);
2174
5
    return nullptr;
2175
5
  }
2176
2177
851k
  if (!ForRedeclaration &&
2178
851k
      
(840k
Context.BuiltinInfo.isPredefinedLibFunction(ID)840k
||
2179
840k
       
Context.BuiltinInfo.isHeaderDependentFunction(ID)839k
)) {
2180
1.20k
    Diag(Loc, diag::ext_implicit_lib_function_decl)
2181
1.20k
        << Context.BuiltinInfo.getName(ID) << R;
2182
1.20k
    if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2183
1.20k
      Diag(Loc, diag::note_include_header_or_declare)
2184
1.20k
          << Header << Context.BuiltinInfo.getName(ID);
2185
1.20k
  }
2186
2187
851k
  if (R.isNull())
2188
8
    return nullptr;
2189
2190
851k
  FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2191
851k
  RegisterLocallyScopedExternCDecl(New, S);
2192
2193
  // TUScope is the translation-unit scope to insert this function into.
2194
  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2195
  // relate Scopes to DeclContexts, and probably eliminate CurContext
2196
  // entirely, but we're not there yet.
2197
851k
  DeclContext *SavedContext = CurContext;
2198
851k
  CurContext = New->getDeclContext();
2199
851k
  PushOnScopeChains(New, TUScope);
2200
851k
  CurContext = SavedContext;
2201
851k
  return New;
2202
851k
}
2203
2204
/// Typedef declarations don't have linkage, but they still denote the same
2205
/// entity if their types are the same.
2206
/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2207
/// isSameEntity.
2208
static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2209
                                                     TypedefNameDecl *Decl,
2210
2.32M
                                                     LookupResult &Previous) {
2211
  // This is only interesting when modules are enabled.
2212
2.32M
  if (!S.getLangOpts().Modules && 
!S.getLangOpts().ModulesLocalVisibility2.21M
)
2213
2.21M
    return;
2214
2215
  // Empty sets are uninteresting.
2216
116k
  if (Previous.empty())
2217
109k
    return;
2218
2219
6.78k
  LookupResult::Filter Filter = Previous.makeFilter();
2220
13.5k
  while (Filter.hasNext()) {
2221
6.78k
    NamedDecl *Old = Filter.next();
2222
2223
    // Non-hidden declarations are never ignored.
2224
6.78k
    if (S.isVisible(Old))
2225
6.77k
      continue;
2226
2227
    // Declarations of the same entity are not ignored, even if they have
2228
    // different linkages.
2229
17
    if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2230
16
      if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2231
16
                                Decl->getUnderlyingType()))
2232
5
        continue;
2233
2234
      // If both declarations give a tag declaration a typedef name for linkage
2235
      // purposes, then they declare the same entity.
2236
11
      if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2237
11
          Decl->getAnonDeclWithTypedefName())
2238
11
        continue;
2239
11
    }
2240
2241
1
    Filter.erase();
2242
1
  }
2243
2244
6.78k
  Filter.done();
2245
6.78k
}
2246
2247
33.3k
bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2248
33.3k
  QualType OldType;
2249
33.3k
  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2250
6.29k
    OldType = OldTypedef->getUnderlyingType();
2251
27.0k
  else
2252
27.0k
    OldType = Context.getTypeDeclType(Old);
2253
33.3k
  QualType NewType = New->getUnderlyingType();
2254
2255
33.3k
  if (NewType->isVariablyModifiedType()) {
2256
    // Must not redefine a typedef with a variably-modified type.
2257
2
    int Kind = isa<TypeAliasDecl>(Old) ? 
10
: 0;
2258
2
    Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2259
2
      << Kind << NewType;
2260
2
    if (Old->getLocation().isValid())
2261
2
      notePreviousDefinition(Old, New->getLocation());
2262
2
    New->setInvalidDecl();
2263
2
    return true;
2264
2
  }
2265
2266
33.3k
  if (OldType != NewType &&
2267
33.3k
      
!OldType->isDependentType()31.1k
&&
2268
33.3k
      
!NewType->isDependentType()31.0k
&&
2269
33.3k
      
!Context.hasSameType(OldType, NewType)30.9k
) {
2270
91
    int Kind = isa<TypeAliasDecl>(Old) ? 
145
:
046
;
2271
91
    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2272
91
      << Kind << NewType << OldType;
2273
91
    if (Old->getLocation().isValid())
2274
86
      notePreviousDefinition(Old, New->getLocation());
2275
91
    New->setInvalidDecl();
2276
91
    return true;
2277
91
  }
2278
33.2k
  return false;
2279
33.3k
}
2280
2281
/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2282
/// same name and scope as a previous declaration 'Old'.  Figure out
2283
/// how to resolve this situation, merging decls or emitting
2284
/// diagnostics as appropriate. If there was an error, set New to be invalid.
2285
///
2286
void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2287
33.8k
                                LookupResult &OldDecls) {
2288
  // If the new decl is known invalid already, don't bother doing any
2289
  // merging checks.
2290
33.8k
  if (New->isInvalidDecl()) 
return10
;
2291
2292
  // Allow multiple definitions for ObjC built-in typedefs.
2293
  // FIXME: Verify the underlying types are equivalent!
2294
33.8k
  if (getLangOpts().ObjC) {
2295
22.7k
    const IdentifierInfo *TypeID = New->getIdentifier();
2296
22.7k
    switch (TypeID->getLength()) {
2297
21.5k
    default: break;
2298
21.5k
    case 2:
2299
344
      {
2300
344
        if (!TypeID->isStr("id"))
2301
4
          break;
2302
340
        QualType T = New->getUnderlyingType();
2303
340
        if (!T->isPointerType())
2304
3
          break;
2305
337
        if (!T->isVoidPointerType()) {
2306
332
          QualType PT = T->castAs<PointerType>()->getPointeeType();
2307
332
          if (!PT->isStructureType())
2308
2
            break;
2309
332
        }
2310
335
        Context.setObjCIdRedefinitionType(T);
2311
        // Install the built-in type for 'id', ignoring the current definition.
2312
335
        New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2313
335
        return;
2314
337
      }
2315
469
    case 5:
2316
469
      if (!TypeID->isStr("Class"))
2317
145
        break;
2318
324
      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2319
      // Install the built-in type for 'Class', ignoring the current definition.
2320
324
      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2321
324
      return;
2322
322
    case 3:
2323
322
      if (!TypeID->isStr("SEL"))
2324
2
        break;
2325
320
      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2326
      // Install the built-in type for 'SEL', ignoring the current definition.
2327
320
      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2328
320
      return;
2329
22.7k
    }
2330
    // Fall through - the typedef name was not a builtin type.
2331
22.7k
  }
2332
2333
  // Verify the old decl was also a type.
2334
32.8k
  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2335
32.8k
  if (!Old) {
2336
14
    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2337
14
      << New->getDeclName();
2338
2339
14
    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2340
14
    if (OldD->getLocation().isValid())
2341
14
      notePreviousDefinition(OldD, New->getLocation());
2342
2343
14
    return New->setInvalidDecl();
2344
14
  }
2345
2346
  // If the old declaration is invalid, just give up here.
2347
32.8k
  if (Old->isInvalidDecl())
2348
15
    return New->setInvalidDecl();
2349
2350
32.8k
  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2351
5.82k
    auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2352
5.82k
    auto *NewTag = New->getAnonDeclWithTypedefName();
2353
5.82k
    NamedDecl *Hidden = nullptr;
2354
5.82k
    if (OldTag && 
NewTag18
&&
2355
5.82k
        
OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl()12
&&
2356
5.82k
        
!hasVisibleDefinition(OldTag, &Hidden)12
) {
2357
      // There is a definition of this tag, but it is not visible. Use it
2358
      // instead of our tag.
2359
11
      New->setTypeForDecl(OldTD->getTypeForDecl());
2360
11
      if (OldTD->isModed())
2361
0
        New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2362
0
                                    OldTD->getUnderlyingType());
2363
11
      else
2364
11
        New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2365
2366
      // Make the old tag definition visible.
2367
11
      makeMergedDefinitionVisible(Hidden);
2368
2369
      // If this was an unscoped enumeration, yank all of its enumerators
2370
      // out of the scope.
2371
11
      if (isa<EnumDecl>(NewTag)) {
2372
5
        Scope *EnumScope = getNonFieldDeclScope(S);
2373
5
        for (auto *D : NewTag->decls()) {
2374
0
          auto *ED = cast<EnumConstantDecl>(D);
2375
0
          assert(EnumScope->isDeclScope(ED));
2376
0
          EnumScope->RemoveDecl(ED);
2377
0
          IdResolver.RemoveDecl(ED);
2378
0
          ED->getLexicalDeclContext()->removeDecl(ED);
2379
0
        }
2380
5
      }
2381
11
    }
2382
5.82k
  }
2383
2384
  // If the typedef types are not identical, reject them in all languages and
2385
  // with any extensions enabled.
2386
32.8k
  if (isIncompatibleTypedef(Old, New))
2387
56
    return;
2388
2389
  // The types match.  Link up the redeclaration chain and merge attributes if
2390
  // the old declaration was a typedef.
2391
32.7k
  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2392
5.76k
    New->setPreviousDecl(Typedef);
2393
5.76k
    mergeDeclAttributes(New, Old);
2394
5.76k
  }
2395
2396
32.7k
  if (getLangOpts().MicrosoftExt)
2397
42
    return;
2398
2399
32.7k
  if (getLangOpts().CPlusPlus) {
2400
    // C++ [dcl.typedef]p2:
2401
    //   In a given non-class scope, a typedef specifier can be used to
2402
    //   redefine the name of any type declared in that scope to refer
2403
    //   to the type to which it already refers.
2404
29.8k
    if (!isa<CXXRecordDecl>(CurContext))
2405
29.7k
      return;
2406
2407
    // C++0x [dcl.typedef]p4:
2408
    //   In a given class scope, a typedef specifier can be used to redefine
2409
    //   any class-name declared in that scope that is not also a typedef-name
2410
    //   to refer to the type to which it already refers.
2411
    //
2412
    // This wording came in via DR424, which was a correction to the
2413
    // wording in DR56, which accidentally banned code like:
2414
    //
2415
    //   struct S {
2416
    //     typedef struct A { } A;
2417
    //   };
2418
    //
2419
    // in the C++03 standard. We implement the C++0x semantics, which
2420
    // allow the above but disallow
2421
    //
2422
    //   struct S {
2423
    //     typedef int I;
2424
    //     typedef int I;
2425
    //   };
2426
    //
2427
    // since that was the intent of DR56.
2428
34
    if (!isa<TypedefNameDecl>(Old))
2429
12
      return;
2430
2431
22
    Diag(New->getLocation(), diag::err_redefinition)
2432
22
      << New->getDeclName();
2433
22
    notePreviousDefinition(Old, New->getLocation());
2434
22
    return New->setInvalidDecl();
2435
34
  }
2436
2437
  // Modules always permit redefinition of typedefs, as does C11.
2438
2.91k
  if (getLangOpts().Modules || 
getLangOpts().C11531
)
2439
2.87k
    return;
2440
2441
  // If we have a redefinition of a typedef in C, emit a warning.  This warning
2442
  // is normally mapped to an error, but can be controlled with
2443
  // -Wtypedef-redefinition.  If either the original or the redefinition is
2444
  // in a system header, don't emit this for compatibility with GCC.
2445
39
  if (getDiagnostics().getSuppressSystemWarnings() &&
2446
      // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2447
39
      (Old->isImplicit() ||
2448
39
       
Context.getSourceManager().isInSystemHeader(Old->getLocation())38
||
2449
39
       
Context.getSourceManager().isInSystemHeader(New->getLocation())15
))
2450
24
    return;
2451
2452
15
  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2453
15
    << New->getDeclName();
2454
15
  notePreviousDefinition(Old, New->getLocation());
2455
15
}
2456
2457
/// DeclhasAttr - returns true if decl Declaration already has the target
2458
/// attribute.
2459
218k
static bool DeclHasAttr(const Decl *D, const Attr *A) {
2460
218k
  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2461
218k
  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2462
218k
  for (const auto *i : D->attrs())
2463
159k
    if (i->getKind() == A->getKind()) {
2464
21.3k
      if (Ann) {
2465
39
        if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2466
28
          return true;
2467
11
        continue;
2468
39
      }
2469
      // FIXME: Don't hardcode this check
2470
21.3k
      if (OA && 
isa<OwnershipAttr>(i)0
)
2471
0
        return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2472
21.3k
      return true;
2473
21.3k
    }
2474
2475
196k
  return false;
2476
218k
}
2477
2478
10
static bool isAttributeTargetADefinition(Decl *D) {
2479
10
  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2480
5
    return VD->isThisDeclarationADefinition();
2481
5
  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2482
5
    return TD->isCompleteDefinition() || TD->isBeingDefined();
2483
0
  return true;
2484
5
}
2485
2486
/// Merge alignment attributes from \p Old to \p New, taking into account the
2487
/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2488
///
2489
/// \return \c true if any attributes were added to \p New.
2490
291k
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2491
  // Look for alignas attributes on Old, and pick out whichever attribute
2492
  // specifies the strictest alignment requirement.
2493
291k
  AlignedAttr *OldAlignasAttr = nullptr;
2494
291k
  AlignedAttr *OldStrictestAlignAttr = nullptr;
2495
291k
  unsigned OldAlign = 0;
2496
291k
  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2497
    // FIXME: We have no way of representing inherited dependent alignments
2498
    // in a case like:
2499
    //   template<int A, int B> struct alignas(A) X;
2500
    //   template<int A, int B> struct alignas(B) X {};
2501
    // For now, we just ignore any alignas attributes which are not on the
2502
    // definition in such a case.
2503
68
    if (I->isAlignmentDependent())
2504
3
      return false;
2505
2506
65
    if (I->isAlignas())
2507
21
      OldAlignasAttr = I;
2508
2509
65
    unsigned Align = I->getAlignment(S.Context);
2510
65
    if (Align > OldAlign) {
2511
64
      OldAlign = Align;
2512
64
      OldStrictestAlignAttr = I;
2513
64
    }
2514
65
  }
2515
2516
  // Look for alignas attributes on New.
2517
291k
  AlignedAttr *NewAlignasAttr = nullptr;
2518
291k
  unsigned NewAlign = 0;
2519
291k
  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2520
49
    if (I->isAlignmentDependent())
2521
0
      return false;
2522
2523
49
    if (I->isAlignas())
2524
11
      NewAlignasAttr = I;
2525
2526
49
    unsigned Align = I->getAlignment(S.Context);
2527
49
    if (Align > NewAlign)
2528
48
      NewAlign = Align;
2529
49
  }
2530
2531
291k
  if (OldAlignasAttr && 
NewAlignasAttr19
&&
OldAlign != NewAlign9
) {
2532
    // Both declarations have 'alignas' attributes. We require them to match.
2533
    // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2534
    // fall short. (If two declarations both have alignas, they must both match
2535
    // every definition, and so must match each other if there is a definition.)
2536
2537
    // If either declaration only contains 'alignas(0)' specifiers, then it
2538
    // specifies the natural alignment for the type.
2539
7
    if (OldAlign == 0 || NewAlign == 0) {
2540
0
      QualType Ty;
2541
0
      if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2542
0
        Ty = VD->getType();
2543
0
      else
2544
0
        Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2545
2546
0
      if (OldAlign == 0)
2547
0
        OldAlign = S.Context.getTypeAlign(Ty);
2548
0
      if (NewAlign == 0)
2549
0
        NewAlign = S.Context.getTypeAlign(Ty);
2550
0
    }
2551
2552
7
    if (OldAlign != NewAlign) {
2553
7
      S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2554
7
        << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2555
7
        << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2556
7
      S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2557
7
    }
2558
7
  }
2559
2560
291k
  if (OldAlignasAttr && 
!NewAlignasAttr19
&&
isAttributeTargetADefinition(New)10
) {
2561
    // C++11 [dcl.align]p6:
2562
    //   if any declaration of an entity has an alignment-specifier,
2563
    //   every defining declaration of that entity shall specify an
2564
    //   equivalent alignment.
2565
    // C11 6.7.5/7:
2566
    //   If the definition of an object does not have an alignment
2567
    //   specifier, any other declaration of that object shall also
2568
    //   have no alignment specifier.
2569
3
    S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2570
3
      << OldAlignasAttr;
2571
3
    S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2572
3
      << OldAlignasAttr;
2573
3
  }
2574
2575
291k
  bool AnyAdded = false;
2576
2577
  // Ensure we have an attribute representing the strictest alignment.
2578
291k
  if (OldAlign > NewAlign) {
2579
52
    AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2580
52
    Clone->setInherited(true);
2581
52
    New->addAttr(Clone);
2582
52
    AnyAdded = true;
2583
52
  }
2584
2585
  // Ensure we have an alignas attribute if the old declaration had one.
2586
291k
  if (OldAlignasAttr && 
!NewAlignasAttr19
&&
2587
291k
      
!(10
AnyAdded10
&&
OldStrictestAlignAttr->isAlignas()10
)) {
2588
0
    AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2589
0
    Clone->setInherited(true);
2590
0
    New->addAttr(Clone);
2591
0
    AnyAdded = true;
2592
0
  }
2593
2594
291k
  return AnyAdded;
2595
291k
}
2596
2597
#define WANT_DECL_MERGE_LOGIC
2598
#include "clang/Sema/AttrParsedAttrImpl.inc"
2599
#undef WANT_DECL_MERGE_LOGIC
2600
2601
static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2602
                               const InheritableAttr *Attr,
2603
524k
                               Sema::AvailabilityMergeKind AMK) {
2604
  // Diagnose any mutual exclusions between the attribute that we want to add
2605
  // and attributes that already exist on the declaration.
2606
524k
  if (!DiagnoseMutualExclusions(S, D, Attr))
2607
8
    return false;
2608
2609
  // This function copies an attribute Attr from a previous declaration to the
2610
  // new declaration D if the new declaration doesn't itself have that attribute
2611
  // yet or if that attribute allows duplicates.
2612
  // If you're adding a new attribute that requires logic different from
2613
  // "use explicit attribute on decl if present, else use attribute from
2614
  // previous decl", for example if the attribute needs to be consistent
2615
  // between redeclarations, you need to call a custom merge function here.
2616
524k
  InheritableAttr *NewAttr = nullptr;
2617
524k
  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2618
170k
    NewAttr = S.mergeAvailabilityAttr(
2619
170k
        D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2620
170k
        AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2621
170k
        AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2622
170k
        AA->getPriority());
2623
353k
  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2624
99.6k
    NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2625
253k
  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2626
19.9k
    NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2627
233k
  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2628
1.47k
    NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2629
232k
  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2630
1.35k
    NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2631
231k
  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2632
895
    NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2633
895
                                FA->getFirstArg());
2634
230k
  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2635
28
    NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2636
230k
  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2637
17
    NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2638
230k
  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2639
33
    NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2640
33
                                       IA->getInheritanceModel());
2641
230k
  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2642
7.18k
    NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2643
7.18k
                                      &S.Context.Idents.get(AA->getSpelling()));
2644
222k
  else if (S.getLangOpts().CUDA && 
isa<FunctionDecl>(D)341
&&
2645
222k
           
(317
isa<CUDAHostAttr>(Attr)317
||
isa<CUDADeviceAttr>(Attr)288
||
2646
317
            
isa<CUDAGlobalAttr>(Attr)3
)) {
2647
    // CUDA target attributes are part of function signature for
2648
    // overloading purposes and must not be merged.
2649
314
    return false;
2650
222k
  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2651
3
    NewAttr = S.mergeMinSizeAttr(D, *MA);
2652
222k
  else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2653
13
    NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2654
222k
  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2655
12
    NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2656
222k
  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2657
7
    NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2658
222k
  else if (isa<AlignedAttr>(Attr))
2659
    // AlignedAttrs are handled separately, because we need to handle all
2660
    // such attributes on a declaration at the same time.
2661
70
    NewAttr = nullptr;
2662
222k
  else if ((isa<DeprecatedAttr>(Attr) || 
isa<UnavailableAttr>(Attr)222k
) &&
2663
222k
           
(235
AMK == Sema::AMK_Override235
||
2664
235
            
AMK == Sema::AMK_ProtocolImplementation156
||
2665
235
            
AMK == Sema::AMK_OptionalProtocolImplementation148
))
2666
95
    NewAttr = nullptr;
2667
222k
  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2668
37
    NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2669
222k
  else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2670
7
    NewAttr = S.mergeImportModuleAttr(D, *IMA);
2671
222k
  else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2672
7
    NewAttr = S.mergeImportNameAttr(D, *INA);
2673
222k
  else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2674
12
    NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2675
222k
  else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2676
3
    NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2677
222k
  else if (const auto *BTFA = dyn_cast<BTFTagAttr>(Attr))
2678
12
    NewAttr = S.mergeBTFTagAttr(D, *BTFA);
2679
222k
  else if (Attr->shouldInheritEvenIfAlreadyPresent() || 
!DeclHasAttr(D, Attr)217k
)
2680
201k
    NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2681
2682
523k
  if (NewAttr) {
2683
322k
    NewAttr->setInherited(true);
2684
322k
    D->addAttr(NewAttr);
2685
322k
    if (isa<MSInheritanceAttr>(NewAttr))
2686
30
      S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2687
322k
    return true;
2688
322k
  }
2689
2690
201k
  return false;
2691
523k
}
2692
2693
132k
static const NamedDecl *getDefinition(const Decl *D) {
2694
132k
  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2695
27.6k
    return TD->getDefinition();
2696
104k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2697
1.07k
    const VarDecl *Def = VD->getDefinition();
2698
1.07k
    if (Def)
2699
43
      return Def;
2700
1.02k
    return VD->getActingDefinition();
2701
1.07k
  }
2702
103k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2703
37.2k
    const FunctionDecl *Def = nullptr;
2704
37.2k
    if (FD->isDefined(Def, true))
2705
298
      return Def;
2706
37.2k
  }
2707
103k
  return nullptr;
2708
103k
}
2709
2710
2.06k
static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2711
2.06k
  for (const auto *Attribute : D->attrs())
2712
2.40k
    if (Attribute->getKind() == Kind)
2713
2.02k
      return true;
2714
41
  return false;
2715
2.06k
}
2716
2717
/// checkNewAttributesAfterDef - If we already have a definition, check that
2718
/// there are no new attributes in this declaration.
2719
314k
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2720
314k
  if (!New->hasAttrs())
2721
181k
    return;
2722
2723
132k
  const NamedDecl *Def = getDefinition(Old);
2724
132k
  if (!Def || 
Def == New12.7k
)
2725
130k
    return;
2726
2727
2.02k
  AttrVec &NewAttributes = New->getAttrs();
2728
4.11k
  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2729
2.08k
    const Attr *NewAttribute = NewAttributes[I];
2730
2731
2.08k
    if (isa<AliasAttr>(NewAttribute) || 
isa<IFuncAttr>(NewAttribute)2.08k
) {
2732
5
      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2733
4
        Sema::SkipBodyInfo SkipBody;
2734
4
        S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2735
2736
        // If we're skipping this definition, drop the "alias" attribute.
2737
4
        if (SkipBody.ShouldSkip) {
2738
0
          NewAttributes.erase(NewAttributes.begin() + I);
2739
0
          --E;
2740
0
          continue;
2741
0
        }
2742
4
      } else {
2743
1
        VarDecl *VD = cast<VarDecl>(New);
2744
1
        unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2745
1
                                VarDecl::TentativeDefinition
2746
1
                            ? diag::err_alias_after_tentative
2747
1
                            : 
diag::err_redefinition0
;
2748
1
        S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2749
1
        if (Diag == diag::err_redefinition)
2750
0
          S.notePreviousDefinition(Def, VD->getLocation());
2751
1
        else
2752
1
          S.Diag(Def->getLocation(), diag::note_previous_definition);
2753
1
        VD->setInvalidDecl();
2754
1
      }
2755
5
      ++I;
2756
5
      continue;
2757
5
    }
2758
2759
2.08k
    if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2760
      // Tentative definitions are only interesting for the alias check above.
2761
67
      if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2762
21
        ++I;
2763
21
        continue;
2764
21
      }
2765
67
    }
2766
2767
2.06k
    if (hasAttribute(Def, NewAttribute->getKind())) {
2768
2.02k
      ++I;
2769
2.02k
      continue; // regular attr merging will take care of validating this.
2770
2.02k
    }
2771
2772
41
    if (isa<C11NoReturnAttr>(NewAttribute)) {
2773
      // C's _Noreturn is allowed to be added to a function after it is defined.
2774
1
      ++I;
2775
1
      continue;
2776
40
    } else if (isa<UuidAttr>(NewAttribute)) {
2777
      // msvc will allow a subsequent definition to add an uuid to a class
2778
2
      ++I;
2779
2
      continue;
2780
38
    } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2781
4
      if (AA->isAlignas()) {
2782
        // C++11 [dcl.align]p6:
2783
        //   if any declaration of an entity has an alignment-specifier,
2784
        //   every defining declaration of that entity shall specify an
2785
        //   equivalent alignment.
2786
        // C11 6.7.5/7:
2787
        //   If the definition of an object does not have an alignment
2788
        //   specifier, any other declaration of that object shall also
2789
        //   have no alignment specifier.
2790
4
        S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2791
4
          << AA;
2792
4
        S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2793
4
          << AA;
2794
4
        NewAttributes.erase(NewAttributes.begin() + I);
2795
4
        --E;
2796
4
        continue;
2797
4
      }
2798
34
    } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2799
      // If there is a C definition followed by a redeclaration with this
2800
      // attribute then there are two different definitions. In C++, prefer the
2801
      // standard diagnostics.
2802
2
      if (!S.getLangOpts().CPlusPlus) {
2803
1
        S.Diag(NewAttribute->getLocation(),
2804
1
               diag::err_loader_uninitialized_redeclaration);
2805
1
        S.Diag(Def->getLocation(), diag::note_previous_definition);
2806
1
        NewAttributes.erase(NewAttributes.begin() + I);
2807
1
        --E;
2808
1
        continue;
2809
1
      }
2810
32
    } else if (isa<SelectAnyAttr>(NewAttribute) &&
2811
32
               
cast<VarDecl>(New)->isInline()8
&&
2812
32
               
!cast<VarDecl>(New)->isInlineSpecified()2
) {
2813
      // Don't warn about applying selectany to implicitly inline variables.
2814
      // Older compilers and language modes would require the use of selectany
2815
      // to make such variables inline, and it would have no effect if we
2816
      // honored it.
2817
2
      ++I;
2818
2
      continue;
2819
30
    } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2820
      // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2821
      // declarations after defintions.
2822
0
      ++I;
2823
0
      continue;
2824
0
    }
2825
2826
31
    S.Diag(NewAttribute->getLocation(),
2827
31
           diag::warn_attribute_precede_definition);
2828
31
    S.Diag(Def->getLocation(), diag::note_previous_definition);
2829
31
    NewAttributes.erase(NewAttributes.begin() + I);
2830
31
    --E;
2831
31
  }
2832
2.02k
}
2833
2834
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2835
                                     const ConstInitAttr *CIAttr,
2836
26
                                     bool AttrBeforeInit) {
2837
26
  SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2838
2839
  // Figure out a good way to write this specifier on the old declaration.
2840
  // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2841
  // enough of the attribute list spelling information to extract that without
2842
  // heroics.
2843
26
  std::string SuitableSpelling;
2844
26
  if (S.getLangOpts().CPlusPlus20)
2845
20
    SuitableSpelling = std::string(
2846
20
        S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2847
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus1124
)
2848
22
    SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2849
22
        InsertLoc, {tok::l_square, tok::l_square,
2850
22
                    S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2851
22
                    S.PP.getIdentifierInfo("require_constant_initialization"),
2852
22
                    tok::r_square, tok::r_square}));
2853
26
  if (SuitableSpelling.empty())
2854
20
    SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2855
20
        InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2856
20
                    S.PP.getIdentifierInfo("require_constant_initialization"),
2857
20
                    tok::r_paren, tok::r_paren}));
2858
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus2020
)
2859
14
    SuitableSpelling = "constinit";
2860
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus116
)
2861
4
    SuitableSpelling = "[[clang::require_constant_initialization]]";
2862
26
  if (SuitableSpelling.empty())
2863
2
    SuitableSpelling = "__attribute__((require_constant_initialization))";
2864
26
  SuitableSpelling += " ";
2865
2866
26
  if (AttrBeforeInit) {
2867
    // extern constinit int a;
2868
    // int a = 0; // error (missing 'constinit'), accepted as extension
2869
14
    assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2870
0
    S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2871
14
        << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2872
14
    S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2873
14
  } else {
2874
    // int a = 0;
2875
    // constinit extern int a; // error (missing 'constinit')
2876
12
    S.Diag(CIAttr->getLocation(),
2877
12
           CIAttr->isConstinit() ? 
diag::err_constinit_added_too_late6
2878
12
                                 : 
diag::warn_require_const_init_added_too_late6
)
2879
12
        << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2880
12
    S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2881
12
        << CIAttr->isConstinit()
2882
12
        << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2883
12
  }
2884
26
}
2885
2886
/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2887
void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2888
699k
                               AvailabilityMergeKind AMK) {
2889
699k
  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2890
944
    UsedAttr *NewAttr = OldAttr->clone(Context);
2891
944
    NewAttr->setInherited(true);
2892
944
    New->addAttr(NewAttr);
2893
944
  }
2894
699k
  if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2895
3
    RetainAttr *NewAttr = OldAttr->clone(Context);
2896
3
    NewAttr->setInherited(true);
2897
3
    New->addAttr(NewAttr);
2898
3
  }
2899
2900
699k
  if (!Old->hasAttrs() && 
!New->hasAttrs()408k
)
2901
385k
    return;
2902
2903
  // [dcl.constinit]p1:
2904
  //   If the [constinit] specifier is applied to any declaration of a
2905
  //   variable, it shall be applied to the initializing declaration.
2906
314k
  const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2907
314k
  const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2908
314k
  if (bool(OldConstInit) != bool(NewConstInit)) {
2909
51
    const auto *OldVD = cast<VarDecl>(Old);
2910
51
    auto *NewVD = cast<VarDecl>(New);
2911
2912
    // Find the initializing declaration. Note that we might not have linked
2913
    // the new declaration into the redeclaration chain yet.
2914
51
    const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2915
51
    if (!InitDecl &&
2916
51
        
(37
NewVD->hasInit()37
||
NewVD->isThisDeclarationADefinition()37
))
2917
37
      InitDecl = NewVD;
2918
2919
51
    if (InitDecl == NewVD) {
2920
      // This is the initializing declaration. If it would inherit 'constinit',
2921
      // that's ill-formed. (Note that we do not apply this to the attribute
2922
      // form).
2923
37
      if (OldConstInit && 
OldConstInit->isConstinit()36
)
2924
14
        diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2925
14
                                 /*AttrBeforeInit=*/true);
2926
37
    } else 
if (14
NewConstInit14
) {
2927
      // This is the first time we've been told that this declaration should
2928
      // have a constant initializer. If we already saw the initializing
2929
      // declaration, this is too late.
2930
12
      if (InitDecl && InitDecl != NewVD) {
2931
12
        diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2932
12
                                 /*AttrBeforeInit=*/false);
2933
12
        NewVD->dropAttr<ConstInitAttr>();
2934
12
      }
2935
12
    }
2936
51
  }
2937
2938
  // Attributes declared post-definition are currently ignored.
2939
314k
  checkNewAttributesAfterDef(*this, New, Old);
2940
2941
314k
  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2942
685
    if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2943
585
      if (!OldA->isEquivalent(NewA)) {
2944
        // This redeclaration changes __asm__ label.
2945
2
        Diag(New->getLocation(), diag::err_different_asm_label);
2946
2
        Diag(OldA->getLocation(), diag::note_previous_declaration);
2947
2
      }
2948
585
    } else 
if (100
Old->isUsed()100
) {
2949
      // This redeclaration adds an __asm__ label to a declaration that has
2950
      // already been ODR-used.
2951
2
      Diag(New->getLocation(), diag::err_late_asm_label_name)
2952
2
        << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2953
2
    }
2954
685
  }
2955
2956
  // Re-declaration cannot add abi_tag's.
2957
314k
  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2958
3
    if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2959
4
      for (const auto &NewTag : NewAbiTagAttr->tags()) {
2960
4
        if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2961
4
                      NewTag) == OldAbiTagAttr->tags_end()) {
2962
1
          Diag(NewAbiTagAttr->getLocation(),
2963
1
               diag::err_new_abi_tag_on_redeclaration)
2964
1
              << NewTag;
2965
1
          Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2966
1
        }
2967
4
      }
2968
2
    } else {
2969
1
      Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2970
1
      Diag(Old->getLocation(), diag::note_previous_declaration);
2971
1
    }
2972
3
  }
2973
2974
  // This redeclaration adds a section attribute.
2975
314k
  if (New->hasAttr<SectionAttr>() && 
!Old->hasAttr<SectionAttr>()24
) {
2976
16
    if (auto *VD = dyn_cast<VarDecl>(New)) {
2977
6
      if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2978
2
        Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2979
2
        Diag(Old->getLocation(), diag::note_previous_declaration);
2980
2
      }
2981
6
    }
2982
16
  }
2983
2984
  // Redeclaration adds code-seg attribute.
2985
314k
  const auto *NewCSA = New->getAttr<CodeSegAttr>();
2986
314k
  if (NewCSA && 
!Old->hasAttr<CodeSegAttr>()16
&&
2987
314k
      
!NewCSA->isImplicit()1
&&
isa<CXXMethodDecl>(New)1
) {
2988
1
    Diag(New->getLocation(), diag::warn_mismatched_section)
2989
1
         << 0 /*codeseg*/;
2990
1
    Diag(Old->getLocation(), diag::note_previous_declaration);
2991
1
  }
2992
2993
314k
  if (!Old->hasAttrs())
2994
23.0k
    return;
2995
2996
291k
  bool foundAny = New->hasAttrs();
2997
2998
  // Ensure that any moving of objects within the allocated map is done before
2999
  // we process them.
3000
291k
  if (!foundAny) 
New->setAttrs(AttrVec())181k
;
3001
3002
525k
  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3003
    // Ignore deprecated/unavailable/availability attributes if requested.
3004
525k
    AvailabilityMergeKind LocalAMK = AMK_None;
3005
525k
    if (isa<DeprecatedAttr>(I) ||
3006
525k
        
isa<UnavailableAttr>(I)524k
||
3007
525k
        
isa<AvailabilityAttr>(I)524k
) {
3008
170k
      switch (AMK) {
3009
0
      case AMK_None:
3010
0
        continue;
3011
3012
35.1k
      case AMK_Redeclaration:
3013
169k
      case AMK_Override:
3014
169k
      case AMK_ProtocolImplementation:
3015
170k
      case AMK_OptionalProtocolImplementation:
3016
170k
        LocalAMK = AMK;
3017
170k
        break;
3018
170k
      }
3019
170k
    }
3020
3021
    // Already handled.
3022
525k
    if (isa<UsedAttr>(I) || 
isa<RetainAttr>(I)524k
)
3023
944
      continue;
3024
3025
524k
    if (mergeDeclAttribute(*this, New, I, LocalAMK))
3026
322k
      foundAny = true;
3027
524k
  }
3028
3029
291k
  if (mergeAlignedAttrs(*this, New, Old))
3030
52
    foundAny = true;
3031
3032
291k
  if (!foundAny) 
New->dropAttrs()4.50k
;
3033
291k
}
3034
3035
/// mergeParamDeclAttributes - Copy attributes from the old parameter
3036
/// to the new one.
3037
static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3038
                                     const ParmVarDecl *oldDecl,
3039
472k
                                     Sema &S) {
3040
  // C++11 [dcl.attr.depend]p2:
3041
  //   The first declaration of a function shall specify the
3042
  //   carries_dependency attribute for its declarator-id if any declaration
3043
  //   of the function specifies the carries_dependency attribute.
3044
472k
  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3045
472k
  if (CDA && 
!oldDecl->hasAttr<CarriesDependencyAttr>()2
) {
3046
1
    S.Diag(CDA->getLocation(),
3047
1
           diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3048
    // Find the first declaration of the parameter.
3049
    // FIXME: Should we build redeclaration chains for function parameters?
3050
1
    const FunctionDecl *FirstFD =
3051
1
      cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3052
1
    const ParmVarDecl *FirstVD =
3053
1
      FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3054
1
    S.Diag(FirstVD->getLocation(),
3055
1
           diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3056
1
  }
3057
3058
472k
  if (!oldDecl->hasAttrs())
3059
467k
    return;
3060
3061
5.33k
  bool foundAny = newDecl->hasAttrs();
3062
3063
  // Ensure that any moving of objects within the allocated map is
3064
  // done before we process them.
3065
5.33k
  if (!foundAny) 
newDecl->setAttrs(AttrVec())19
;
3066
3067
5.33k
  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3068
257
    if (!DeclHasAttr(newDecl, I)) {
3069
15
      InheritableAttr *newAttr =
3070
15
        cast<InheritableParamAttr>(I->clone(S.Context));
3071
15
      newAttr->setInherited(true);
3072
15
      newDecl->addAttr(newAttr);
3073
15
      foundAny = true;
3074
15
    }
3075
257
  }
3076
3077
5.33k
  if (!foundAny) 
newDecl->dropAttrs()6
;
3078
5.33k
}
3079
3080
static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3081
                                const ParmVarDecl *OldParam,
3082
382k
                                Sema &S) {
3083
382k
  if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3084
1.86k
    if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3085
1.39k
      if (*Oldnullability != *Newnullability) {
3086
2
        S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3087
2
          << DiagNullabilityKind(
3088
2
               *Newnullability,
3089
2
               ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3090
2
                != 0))
3091
2
          << DiagNullabilityKind(
3092
2
               *Oldnullability,
3093
2
               ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3094
2
                != 0));
3095
2
        S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3096
2
      }
3097
1.39k
    } else {
3098
476
      QualType NewT = NewParam->getType();
3099
476
      NewT = S.Context.getAttributedType(
3100
476
                         AttributedType::getNullabilityAttrKind(*Oldnullability),
3101
476
                         NewT, NewT);
3102
476
      NewParam->setType(NewT);
3103
476
    }
3104
1.86k
  }
3105
382k
}
3106
3107
namespace {
3108
3109
/// Used in MergeFunctionDecl to keep track of function parameters in
3110
/// C.
3111
struct GNUCompatibleParamWarning {
3112
  ParmVarDecl *OldParm;
3113
  ParmVarDecl *NewParm;
3114
  QualType PromotedType;
3115
};
3116
3117
} // end anonymous namespace
3118
3119
// Determine whether the previous declaration was a definition, implicit
3120
// declaration, or a declaration.
3121
template <typename T>
3122
static std::pair<diag::kind, SourceLocation>
3123
305k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3124
305k
  diag::kind PrevDiag;
3125
305k
  SourceLocation OldLocation = Old->getLocation();
3126
305k
  if (Old->isThisDeclarationADefinition())
3127
9.31k
    PrevDiag = diag::note_previous_definition;
3128
296k
  else if (Old->isImplicit()) {
3129
13.6k
    PrevDiag = diag::note_previous_implicit_declaration;
3130
13.6k
    if (OldLocation.isInvalid())
3131
2.55k
      OldLocation = New->getLocation();
3132
13.6k
  } else
3133
282k
    PrevDiag = diag::note_previous_declaration;
3134
305k
  return std::make_pair(PrevDiag, OldLocation);
3135
305k
}
SemaDecl.cpp:std::__1::pair<unsigned int, clang::SourceLocation> getNoteDiagForInvalidRedeclaration<clang::FunctionDecl>(clang::FunctionDecl const*, clang::FunctionDecl const*)
Line
Count
Source
3123
245k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3124
245k
  diag::kind PrevDiag;
3125
245k
  SourceLocation OldLocation = Old->getLocation();
3126
245k
  if (Old->isThisDeclarationADefinition())
3127
7.77k
    PrevDiag = diag::note_previous_definition;
3128
237k
  else if (Old->isImplicit()) {
3129
13.6k
    PrevDiag = diag::note_previous_implicit_declaration;
3130
13.6k
    if (OldLocation.isInvalid())
3131
2.55k
      OldLocation = New->getLocation();
3132
13.6k
  } else
3133
223k
    PrevDiag = diag::note_previous_declaration;
3134
245k
  return std::make_pair(PrevDiag, OldLocation);
3135
245k
}
SemaDecl.cpp:std::__1::pair<unsigned int, clang::SourceLocation> getNoteDiagForInvalidRedeclaration<clang::VarDecl>(clang::VarDecl const*, clang::VarDecl const*)
Line
Count
Source
3123
60.1k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3124
60.1k
  diag::kind PrevDiag;
3125
60.1k
  SourceLocation OldLocation = Old->getLocation();
3126
60.1k
  if (Old->isThisDeclarationADefinition())
3127
1.54k
    PrevDiag = diag::note_previous_definition;
3128
58.5k
  else if (Old->isImplicit()) {
3129
0
    PrevDiag = diag::note_previous_implicit_declaration;
3130
0
    if (OldLocation.isInvalid())
3131
0
      OldLocation = New->getLocation();
3132
0
  } else
3133
58.5k
    PrevDiag = diag::note_previous_declaration;
3134
60.1k
  return std::make_pair(PrevDiag, OldLocation);
3135
60.1k
}
3136
3137
/// canRedefineFunction - checks if a function can be redefined. Currently,
3138
/// only extern inline functions can be redefined, and even then only in
3139
/// GNU89 mode.
3140
static bool canRedefineFunction(const FunctionDecl *FD,
3141
541
                                const LangOptions& LangOpts) {
3142
541
  return ((FD->hasAttr<GNUInlineAttr>() || 
LangOpts.GNUInline537
) &&
3143
541
          
!LangOpts.CPlusPlus17
&&
3144
541
          
FD->isInlineSpecified()17
&&
3145
541
          
FD->getStorageClass() == SC_Extern15
);
3146
541
}
3147
3148
1.16k
const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3149
1.16k
  const AttributedType *AT = T->getAs<AttributedType>();
3150
1.16k
  while (AT && 
!AT->isCallingConv()154
)
3151
0
    AT = AT->getModifiedType()->getAs<AttributedType>();
3152
1.16k
  return AT;
3153
1.16k
}
3154
3155
template <typename T>
3156
283k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3157
283k
  const DeclContext *DC = Old->getDeclContext();
3158
283k
  if (DC->isRecord())
3159
220k
    return false;
3160
3161
63.8k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3162
63.8k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()48.5k
)
3163
24
    return true;
3164
63.7k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()13.7k
)
3165
17
    return true;
3166
63.7k
  return false;
3167
63.7k
}
SemaDecl.cpp:bool haveIncompatibleLanguageLinkages<clang::FunctionDecl>(clang::FunctionDecl const*, clang::FunctionDecl const*)
Line
Count
Source
3156
224k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3157
224k
  const DeclContext *DC = Old->getDeclContext();
3158
224k
  if (DC->isRecord())
3159
163k
    return false;
3160
3161
60.8k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3162
60.8k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()47.1k
)
3163
21
    return true;
3164
60.8k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()12.3k
)
3165
17
    return true;
3166
60.8k
  return false;
3167
60.8k
}
SemaDecl.cpp:bool haveIncompatibleLanguageLinkages<clang::VarDecl>(clang::VarDecl const*, clang::VarDecl const*)
Line
Count
Source
3156
59.7k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3157
59.7k
  const DeclContext *DC = Old->getDeclContext();
3158
59.7k
  if (DC->isRecord())
3159
56.8k
    return false;
3160
3161
2.91k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3162
2.91k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()1.40k
)
3163
3
    return true;
3164
2.91k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()1.38k
)
3165
0
    return true;
3166
2.91k
  return false;
3167
2.91k
}
3168
3169
24
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
SemaDecl.cpp:bool isExternC<clang::FunctionDecl>(clang::FunctionDecl*)
Line
Count
Source
3169
17
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
SemaDecl.cpp:bool isExternC<clang::VarDecl>(clang::VarDecl*)
Line
Count
Source
3169
7
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3170
2
static bool isExternC(VarTemplateDecl *) { return false; }
3171
6
static bool isExternC(FunctionTemplateDecl *) { return false; }
3172
3173
/// Check whether a redeclaration of an entity introduced by a
3174
/// using-declaration is valid, given that we know it's not an overload
3175
/// (nor a hidden tag declaration).
3176
template<typename ExpectedDecl>
3177
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3178
41
                                   ExpectedDecl *New) {
3179
  // C++11 [basic.scope.declarative]p4:
3180
  //   Given a set of declarations in a single declarative region, each of
3181
  //   which specifies the same unqualified name,
3182
  //   -- they shall all refer to the same entity, or all refer to functions
3183
  //      and function templates; or
3184
  //   -- exactly one declaration shall declare a class name or enumeration
3185
  //      name that is not a typedef name and the other declarations shall all
3186
  //      refer to the same variable or enumerator, or all refer to functions
3187
  //      and function templates; in this case the class name or enumeration
3188
  //      name is hidden (3.3.10).
3189
3190
  // C++11 [namespace.udecl]p14:
3191
  //   If a function declaration in namespace scope or block scope has the
3192
  //   same name and the same parameter-type-list as a function introduced
3193
  //   by a using-declaration, and the declarations do not declare the same
3194
  //   function, the program is ill-formed.
3195
3196
41
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3197
41
  if (Old &&
3198
41
      !Old->getDeclContext()->getRedeclContext()->Equals(
3199
40
          New->getDeclContext()->getRedeclContext()) &&
3200
41
      
!(28
isExternC(Old)28
&&
isExternC(New)4
))
3201
24
    Old = nullptr;
3202
3203
41
  if (!Old) {
3204
25
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3205
25
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3206
25
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3207
25
    return true;
3208
25
  }
3209
16
  return false;
3210
41
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::FunctionTemplateDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::FunctionTemplateDecl*)
Line
Count
Source
3178
8
                                   ExpectedDecl *New) {
3179
  // C++11 [basic.scope.declarative]p4:
3180
  //   Given a set of declarations in a single declarative region, each of
3181
  //   which specifies the same unqualified name,
3182
  //   -- they shall all refer to the same entity, or all refer to functions
3183
  //      and function templates; or
3184
  //   -- exactly one declaration shall declare a class name or enumeration
3185
  //      name that is not a typedef name and the other declarations shall all
3186
  //      refer to the same variable or enumerator, or all refer to functions
3187
  //      and function templates; in this case the class name or enumeration
3188
  //      name is hidden (3.3.10).
3189
3190
  // C++11 [namespace.udecl]p14:
3191
  //   If a function declaration in namespace scope or block scope has the
3192
  //   same name and the same parameter-type-list as a function introduced
3193
  //   by a using-declaration, and the declarations do not declare the same
3194
  //   function, the program is ill-formed.
3195
3196
8
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3197
8
  if (Old &&
3198
8
      !Old->getDeclContext()->getRedeclContext()->Equals(
3199
8
          New->getDeclContext()->getRedeclContext()) &&
3200
8
      
!(6
isExternC(Old)6
&&
isExternC(New)0
))
3201
6
    Old = nullptr;
3202
3203
8
  if (!Old) {
3204
6
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3205
6
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3206
6
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3207
6
    return true;
3208
6
  }
3209
2
  return false;
3210
8
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::FunctionDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::FunctionDecl*)
Line
Count
Source
3178
21
                                   ExpectedDecl *New) {
3179
  // C++11 [basic.scope.declarative]p4:
3180
  //   Given a set of declarations in a single declarative region, each of
3181
  //   which specifies the same unqualified name,
3182
  //   -- they shall all refer to the same entity, or all refer to functions
3183
  //      and function templates; or
3184
  //   -- exactly one declaration shall declare a class name or enumeration
3185
  //      name that is not a typedef name and the other declarations shall all
3186
  //      refer to the same variable or enumerator, or all refer to functions
3187
  //      and function templates; in this case the class name or enumeration
3188
  //      name is hidden (3.3.10).
3189
3190
  // C++11 [namespace.udecl]p14:
3191
  //   If a function declaration in namespace scope or block scope has the
3192
  //   same name and the same parameter-type-list as a function introduced
3193
  //   by a using-declaration, and the declarations do not declare the same
3194
  //   function, the program is ill-formed.
3195
3196
21
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3197
21
  if (Old &&
3198
21
      !Old->getDeclContext()->getRedeclContext()->Equals(
3199
21
          New->getDeclContext()->getRedeclContext()) &&
3200
21
      
!(13
isExternC(Old)13
&&
isExternC(New)4
))
3201
9
    Old = nullptr;
3202
3203
21
  if (!Old) {
3204
9
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3205
9
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3206
9
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3207
9
    return true;
3208
9
  }
3209
12
  return false;
3210
21
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::VarTemplateDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::VarTemplateDecl*)
Line
Count
Source
3178
3
                                   ExpectedDecl *New) {
3179
  // C++11 [basic.scope.declarative]p4:
3180
  //   Given a set of declarations in a single declarative region, each of
3181
  //   which specifies the same unqualified name,
3182
  //   -- they shall all refer to the same entity, or all refer to functions
3183
  //      and function templates; or
3184
  //   -- exactly one declaration shall declare a class name or enumeration
3185
  //      name that is not a typedef name and the other declarations shall all
3186
  //      refer to the same variable or enumerator, or all refer to functions
3187
  //      and function templates; in this case the class name or enumeration
3188
  //      name is hidden (3.3.10).
3189
3190
  // C++11 [namespace.udecl]p14:
3191
  //   If a function declaration in namespace scope or block scope has the
3192
  //   same name and the same parameter-type-list as a function introduced
3193
  //   by a using-declaration, and the declarations do not declare the same
3194
  //   function, the program is ill-formed.
3195
3196
3
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3197
3
  if (Old &&
3198
3
      !Old->getDeclContext()->getRedeclContext()->Equals(
3199
3
          New->getDeclContext()->getRedeclContext()) &&
3200
3
      
!(2
isExternC(Old)2
&&
isExternC(New)0
))
3201
2
    Old = nullptr;
3202
3203
3
  if (!Old) {
3204
2
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3205
2
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3206
2
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3207
2
    return true;
3208
2
  }
3209
1
  return false;
3210
3
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::VarDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::VarDecl*)
Line
Count
Source
3178
9
                                   ExpectedDecl *New) {
3179
  // C++11 [basic.scope.declarative]p4:
3180
  //   Given a set of declarations in a single declarative region, each of
3181
  //   which specifies the same unqualified name,
3182
  //   -- they shall all refer to the same entity, or all refer to functions
3183
  //      and function templates; or
3184
  //   -- exactly one declaration shall declare a class name or enumeration
3185
  //      name that is not a typedef name and the other declarations shall all
3186
  //      refer to the same variable or enumerator, or all refer to functions
3187
  //      and function templates; in this case the class name or enumeration
3188
  //      name is hidden (3.3.10).
3189
3190
  // C++11 [namespace.udecl]p14:
3191
  //   If a function declaration in namespace scope or block scope has the
3192
  //   same name and the same parameter-type-list as a function introduced
3193
  //   by a using-declaration, and the declarations do not declare the same
3194
  //   function, the program is ill-formed.
3195
3196
9
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3197
9
  if (Old &&
3198
9
      !Old->getDeclContext()->getRedeclContext()->Equals(
3199
8
          New->getDeclContext()->getRedeclContext()) &&
3200
9
      
!(7
isExternC(Old)7
&&
isExternC(New)0
))
3201
7
    Old = nullptr;
3202
3203
9
  if (!Old) {
3204
8
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3205
8
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3206
8
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3207
8
    return true;
3208
8
  }
3209
1
  return false;
3210
9
}
3211
3212
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3213
199k
                                            const FunctionDecl *B) {
3214
199k
  assert(A->getNumParams() == B->getNumParams());
3215
3216
382k
  auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3217
382k
    const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3218
382k
    const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3219
382k
    if (AttrA == AttrB)
3220
382k
      return true;
3221
7
    return AttrA && AttrB && 
AttrA->getType() == AttrB->getType()6
&&
3222
7
           
AttrA->isDynamic() == AttrB->isDynamic()2
;
3223
382k
  };
3224
3225
199k
  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3226
199k
}
3227
3228
/// If necessary, adjust the semantic declaration context for a qualified
3229
/// declaration to name the correct inline namespace within the qualifier.
3230
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3231
305k
                                               DeclaratorDecl *OldD) {
3232
  // The only case where we need to update the DeclContext is when
3233
  // redeclaration lookup for a qualified name finds a declaration
3234
  // in an inline namespace within the context named by the qualifier:
3235
  //
3236
  //   inline namespace N { int f(); }
3237
  //   int ::f(); // Sema DC needs adjusting from :: to N::.
3238
  //
3239
  // For unqualified declarations, the semantic context *can* change
3240
  // along the redeclaration chain (for local extern declarations,
3241
  // extern "C" declarations, and friend declarations in particular).
3242
305k
  if (!NewD->getQualifier())
3243
84.6k
    return;
3244
3245
  // NewD is probably already in the right context.
3246
220k
  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3247
220k
  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3248
220k
  if (NamedDC->Equals(SemaDC))
3249
220k
    return;
3250
3251
21
  assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3252
21
          NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3253
21
         "unexpected context for redeclaration");
3254
3255
0
  auto *LexDC = NewD->getLexicalDeclContext();
3256
42
  auto FixSemaDC = [=](NamedDecl *D) {
3257
42
    if (!D)
3258
21
      return;
3259
21
    D->setDeclContext(SemaDC);
3260
21
    D->setLexicalDeclContext(LexDC);
3261
21
  };
3262
3263
21
  FixSemaDC(NewD);
3264
21
  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3265
15
    FixSemaDC(FD->getDescribedFunctionTemplate());
3266
6
  else if (auto *VD = dyn_cast<VarDecl>(NewD))
3267
6
    FixSemaDC(VD->getDescribedVarTemplate());
3268
21
}
3269
3270
/// MergeFunctionDecl - We just parsed a function 'New' from
3271
/// declarator D which has the same name and scope as a previous
3272
/// declaration 'Old'.  Figure out how to resolve this situation,
3273
/// merging decls or emitting diagnostics as appropriate.
3274
///
3275
/// In C++, New and Old must be declarations that are not
3276
/// overloaded. Use IsOverload to determine whether New and Old are
3277
/// overloaded, and to select the Old declaration that New should be
3278
/// merged with.
3279
///
3280
/// Returns true if there was an error, false otherwise.
3281
bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3282
245k
                             Scope *S, bool MergeTypeWithOld) {
3283
  // Verify the old decl was also a function.
3284
245k
  FunctionDecl *Old = OldD->getAsFunction();
3285
245k
  if (!Old) {
3286
78
    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3287
40
      if (New->getFriendObjectKind()) {
3288
11
        Diag(New->getLocation(), diag::err_using_decl_friend);
3289
11
        Diag(Shadow->getTargetDecl()->getLocation(),
3290
11
             diag::note_using_decl_target);
3291
11
        Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3292
11
            << 0;
3293
11
        return true;
3294
11
      }
3295
3296
      // Check whether the two declarations might declare the same function or
3297
      // function template.
3298
29
      if (FunctionTemplateDecl *NewTemplate =
3299
29
              New->getDescribedFunctionTemplate()) {
3300
8
        if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3301
8
                                                         NewTemplate))
3302
6
          return true;
3303
2
        OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3304
2
                         ->getAsFunction();
3305
21
      } else {
3306
21
        if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3307
9
          return true;
3308
12
        OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3309
12
      }
3310
38
    } else {
3311
38
      Diag(New->getLocation(), diag::err_redefinition_different_kind)
3312
38
        << New->getDeclName();
3313
38
      notePreviousDefinition(OldD, New->getLocation());
3314
38
      return true;
3315
38
    }
3316
78
  }
3317
3318
  // If the old declaration was found in an inline namespace and the new
3319
  // declaration was qualified, update the DeclContext to match.
3320
245k
  adjustDeclContextForDeclaratorDecl(New, Old);
3321
3322
  // If the old declaration is invalid, just give up here.
3323
245k
  if (Old->isInvalidDecl())
3324
35
    return true;
3325
3326
  // Disallow redeclaration of some builtins.
3327
245k
  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3328
11
    Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3329
11
    Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3330
11
        << Old << Old->getType();
3331
11
    return true;
3332
11
  }
3333
3334
245k
  diag::kind PrevDiag;
3335
245k
  SourceLocation OldLocation;
3336
245k
  std::tie(PrevDiag, OldLocation) =
3337
245k
      getNoteDiagForInvalidRedeclaration(Old, New);
3338
3339
  // Don't complain about this if we're in GNU89 mode and the old function
3340
  // is an extern inline function.
3341
  // Don't complain about specializations. They are not supposed to have
3342
  // storage classes.
3343
245k
  if (!isa<CXXMethodDecl>(New) && 
!isa<CXXMethodDecl>(Old)81.7k
&&
3344
245k
      
New->getStorageClass() == SC_Static81.7k
&&
3345
245k
      
Old->hasExternalFormalLinkage()4.10k
&&
3346
245k
      
!New->getTemplateSpecializationInfo()193
&&
3347
245k
      
!canRedefineFunction(Old, getLangOpts())192
) {
3348
188
    if (getLangOpts().MicrosoftExt) {
3349
182
      Diag(New->getLocation(), diag::ext_static_non_static) << New;
3350
182
      Diag(OldLocation, PrevDiag);
3351
182
    } else {
3352
6
      Diag(New->getLocation(), diag::err_static_non_static) << New;
3353
6
      Diag(OldLocation, PrevDiag);
3354
6
      return true;
3355
6
    }
3356
188
  }
3357
3358
245k
  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3359
1
    if (!Old->hasAttr<InternalLinkageAttr>()) {
3360
1
      Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3361
1
          << ILA;
3362
1
      Diag(Old->getLocation(), diag::note_previous_declaration);
3363
1
      New->dropAttr<InternalLinkageAttr>();
3364
1
    }
3365
3366
245k
  if (CheckRedeclarationModuleOwnership(New, Old))
3367
14
    return true;
3368
3369
245k
  if (!getLangOpts().CPlusPlus) {
3370
20.7k
    bool OldOvl = Old->hasAttr<OverloadableAttr>();
3371
20.7k
    if (OldOvl != New->hasAttr<OverloadableAttr>() && 
!Old->isImplicit()17
) {
3372
14
      Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3373
14
        << New << OldOvl;
3374
3375
      // Try our best to find a decl that actually has the overloadable
3376
      // attribute for the note. In most cases (e.g. programs with only one
3377
      // broken declaration/definition), this won't matter.
3378
      //
3379
      // FIXME: We could do this if we juggled some extra state in
3380
      // OverloadableAttr, rather than just removing it.
3381
14
      const Decl *DiagOld = Old;
3382
14
      if (OldOvl) {
3383
14
        auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3384
14
          const auto *A = D->getAttr<OverloadableAttr>();
3385
14
          return A && !A->isImplicit();
3386
14
        });
3387
        // If we've implicitly added *all* of the overloadable attrs to this
3388
        // chain, emitting a "previous redecl" note is pointless.
3389
11
        DiagOld = OldIter == Old->redecls_end() ? 
nullptr2
:
*OldIter9
;
3390
11
      }
3391
3392
14
      if (DiagOld)
3393
12
        Diag(DiagOld->getLocation(),
3394
12
             diag::note_attribute_overloadable_prev_overload)
3395
12
          << OldOvl;
3396
3397
14
      if (OldOvl)
3398
11
        New->addAttr(OverloadableAttr::CreateImplicit(Context));
3399
3
      else
3400
3
        New->dropAttr<OverloadableAttr>();
3401
14
    }
3402
20.7k
  }
3403
3404
  // If a function is first declared with a calling convention, but is later
3405
  // declared or defined without one, all following decls assume the calling
3406
  // convention of the first.
3407
  //
3408
  // It's OK if a function is first declared without a calling convention,
3409
  // but is later declared or defined with the default calling convention.
3410
  //
3411
  // To test if either decl has an explicit calling convention, we look for
3412
  // AttributedType sugar nodes on the type as written.  If they are missing or
3413
  // were canonicalized away, we assume the calling convention was implicit.
3414
  //
3415
  // Note also that we DO NOT return at this point, because we still have
3416
  // other tests to run.
3417
245k
  QualType OldQType = Context.getCanonicalType(Old->getType());
3418
245k
  QualType NewQType = Context.getCanonicalType(New->getType());
3419
245k
  const FunctionType *OldType = cast<FunctionType>(OldQType);
3420
245k
  const FunctionType *NewType = cast<FunctionType>(NewQType);
3421
245k
  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3422
245k
  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3423
245k
  bool RequiresAdjustment = false;
3424
3425
245k
  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3426
897
    FunctionDecl *First = Old->getFirstDecl();
3427
897
    const FunctionType *FT =
3428
897
        First->getType().getCanonicalType()->castAs<FunctionType>();
3429
897
    FunctionType::ExtInfo FI = FT->getExtInfo();
3430
897
    bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3431
897
    if (!NewCCExplicit) {
3432
      // Inherit the CC from the previous declaration if it was specified
3433
      // there but not here.
3434
812
      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3435
812
      RequiresAdjustment = true;
3436
812
    } else 
if (85
Old->getBuiltinID()85
) {
3437
      // Builtin attribute isn't propagated to the new one yet at this point,
3438
      // so we check if the old one is a builtin.
3439
3440
      // Calling Conventions on a Builtin aren't really useful and setting a
3441
      // default calling convention and cdecl'ing some builtin redeclarations is
3442
      // common, so warn and ignore the calling convention on the redeclaration.
3443
2
      Diag(New->getLocation(), diag::warn_cconv_unsupported)
3444
2
          << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3445
2
          << (int)CallingConventionIgnoredReason::BuiltinFunction;
3446
2
      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3447
2
      RequiresAdjustment = true;
3448
83
    } else {
3449
      // Calling conventions aren't compatible, so complain.
3450
83
      bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3451
83
      Diag(New->getLocation(), diag::err_cconv_change)
3452
83
        << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3453
83
        << !FirstCCExplicit
3454
83
        << (!FirstCCExplicit ? 
""39
:
3455
83
            
FunctionType::getNameForCallConv(FI.getCC())44
);
3456
3457
      // Put the note on the first decl, since it is the one that matters.
3458
83
      Diag(First->getLocation(), diag::note_previous_declaration);
3459
83
      return true;
3460
83
    }
3461
897
  }
3462
3463
  // FIXME: diagnose the other way around?
3464
245k
  if (OldTypeInfo.getNoReturn() && 
!NewTypeInfo.getNoReturn()665
) {
3465
103
    NewTypeInfo = NewTypeInfo.withNoReturn(true);
3466
103
    RequiresAdjustment = true;
3467
103
  }
3468
3469
  // Merge regparm attribute.
3470
245k
  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3471
245k
      
OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()245k
) {
3472
21
    if (NewTypeInfo.getHasRegParm()) {
3473
5
      Diag(New->getLocation(), diag::err_regparm_mismatch)
3474
5
        << NewType->getRegParmType()
3475
5
        << OldType->getRegParmType();
3476
5
      Diag(OldLocation, diag::note_previous_declaration);
3477
5
      return true;
3478
5
    }
3479
3480
16
    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3481
16
    RequiresAdjustment = true;
3482
16
  }
3483
3484
  // Merge ns_returns_retained attribute.
3485
245k
  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3486
2
    if (NewTypeInfo.getProducesResult()) {
3487
1
      Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3488
1
          << "'ns_returns_retained'";
3489
1
      Diag(OldLocation, diag::note_previous_declaration);
3490
1
      return true;
3491
1
    }
3492
3493
1
    NewTypeInfo = NewTypeInfo.withProducesResult(true);
3494
1
    RequiresAdjustment = true;
3495
1
  }
3496
3497
245k
  if (OldTypeInfo.getNoCallerSavedRegs() !=
3498
245k
      NewTypeInfo.getNoCallerSavedRegs()) {
3499
1
    if (NewTypeInfo.getNoCallerSavedRegs()) {
3500
1
      AnyX86NoCallerSavedRegistersAttr *Attr =
3501
1
        New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3502
1
      Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3503
1
      Diag(OldLocation, diag::note_previous_declaration);
3504
1
      return true;
3505
1
    }
3506
3507
0
    NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3508
0
    RequiresAdjustment = true;
3509
0
  }
3510
3511
245k
  if (RequiresAdjustment) {
3512
925
    const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3513
925
    AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3514
925
    New->setType(QualType(AdjustedType, 0));
3515
925
    NewQType = Context.getCanonicalType(New->getType());
3516
925
  }
3517
3518
  // If this redeclaration makes the function inline, we may need to add it to
3519
  // UndefinedButUsed.
3520
245k
  if (!Old->isInlined() && 
New->isInlined()203k
&&
3521
245k
      
!New->hasAttr<GNUInlineAttr>()68.4k
&&
3522
245k
      
!getLangOpts().GNUInline68.3k
&&
3523
245k
      
Old->isUsed(false)68.3k
&&
3524
245k
      
!Old->isDefined()23
&&
!New->isThisDeclarationADefinition()17
)
3525
17
    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3526
17
                                           SourceLocation()));
3527
3528
  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3529
  // about it.
3530
245k
  if (New->hasAttr<GNUInlineAttr>() &&
3531
245k
      
Old->isInlined()38
&&
!Old->hasAttr<GNUInlineAttr>()17
) {
3532
1
    UndefinedButUsed.erase(Old->getCanonicalDecl());
3533
1
  }
3534
3535
  // If pass_object_size params don't match up perfectly, this isn't a valid
3536
  // redeclaration.
3537
245k
  if (Old->getNumParams() > 0 && 
Old->getNumParams() == New->getNumParams()199k
&&
3538
245k
      
!hasIdenticalPassObjectSizeAttrs(Old, New)199k
) {
3539
6
    Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3540
6
        << New->getDeclName();
3541
6
    Diag(OldLocation, PrevDiag) << Old << Old->getType();
3542
6
    return true;
3543
6
  }
3544
3545
245k
  if (getLangOpts().CPlusPlus) {
3546
    // C++1z [over.load]p2
3547
    //   Certain function declarations cannot be overloaded:
3548
    //     -- Function declarations that differ only in the return type,
3549
    //        the exception specification, or both cannot be overloaded.
3550
3551
    // Check the exception specifications match. This may recompute the type of
3552
    // both Old and New if it resolved exception specifications, so grab the
3553
    // types again after this. Because this updates the type, we do this before
3554
    // any of the other checks below, which may update the "de facto" NewQType
3555
    // but do not necessarily update the type of New.
3556
224k
    if (CheckEquivalentExceptionSpec(Old, New))
3557
48
      return true;
3558
224k
    OldQType = Context.getCanonicalType(Old->getType());
3559
224k
    NewQType = Context.getCanonicalType(New->getType());
3560
3561
    // Go back to the type source info to compare the declared return types,
3562
    // per C++1y [dcl.type.auto]p13:
3563
    //   Redeclarations or specializations of a function or function template
3564
    //   with a declared return type that uses a placeholder type shall also
3565
    //   use that placeholder, not a deduced type.
3566
224k
    QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3567
224k
    QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3568
224k
    if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3569
224k
        canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3570
100
                                       OldDeclaredReturnType)) {
3571
96
      QualType ResQT;
3572
96
      if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3573
96
          
OldDeclaredReturnType->isObjCObjectPointerType()9
)
3574
        // FIXME: This does the wrong thing for a deduced return type.
3575
9
        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3576
96
      if (ResQT.isNull()) {
3577
88
        if (New->isCXXClassMember() && 
New->isOutOfLine()26
)
3578
23
          Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3579
23
              << New << New->getReturnTypeSourceRange();
3580
65
        else
3581
65
          Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3582
65
              << New->getReturnTypeSourceRange();
3583
88
        Diag(OldLocation, PrevDiag) << Old << Old->getType()
3584
88
                                    << Old->getReturnTypeSourceRange();
3585
88
        return true;
3586
88
      }
3587
8
      else
3588
8
        NewQType = ResQT;
3589
96
    }
3590
3591
224k
    QualType OldReturnType = OldType->getReturnType();
3592
224k
    QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3593
224k
    if (OldReturnType != NewReturnType) {
3594
      // If this function has a deduced return type and has already been
3595
      // defined, copy the deduced value from the old declaration.
3596
77
      AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3597
77
      if (OldAT && 
OldAT->isDeduced()73
) {
3598
49
        New->setType(
3599
49
            SubstAutoType(New->getType(),
3600
49
                          OldAT->isDependentType() ? 
Context.DependentTy24
3601
49
                                                   : 
OldAT->getDeducedType()25
));
3602
49
        NewQType = Context.getCanonicalType(
3603
49
            SubstAutoType(NewQType,
3604
49
                          OldAT->isDependentType() ? 
Context.DependentTy24
3605
49
                                                   : 
OldAT->getDeducedType()25
));
3606
49
      }
3607
77
    }
3608
3609
224k
    const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3610
224k
    CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3611
224k
    if (OldMethod && 
NewMethod163k
) {
3612
      // Preserve triviality.
3613
163k
      NewMethod->setTrivial(OldMethod->isTrivial());
3614
3615
      // MSVC allows explicit template specialization at class scope:
3616
      // 2 CXXMethodDecls referring to the same function will be injected.
3617
      // We don't want a redeclaration error.
3618
163k
      bool IsClassScopeExplicitSpecialization =
3619
163k
                              OldMethod->isFunctionTemplateSpecialization() &&
3620
163k
                              
NewMethod->isFunctionTemplateSpecialization()740
;
3621
163k
      bool isFriend = NewMethod->getFriendObjectKind();
3622
3623
163k
      if (!isFriend && 
NewMethod->getLexicalDeclContext()->isRecord()163k
&&
3624
163k
          
!IsClassScopeExplicitSpecialization302
) {
3625
        //    -- Member function declarations with the same name and the
3626
        //       same parameter types cannot be overloaded if any of them
3627
        //       is a static member function declaration.
3628
129
        if (OldMethod->isStatic() != NewMethod->isStatic()) {
3629
1
          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3630
1
          Diag(OldLocation, PrevDiag) << Old << Old->getType();
3631
1
          return true;
3632
1
        }
3633
3634
        // C++ [class.mem]p1:
3635
        //   [...] A member shall not be declared twice in the
3636
        //   member-specification, except that a nested class or member
3637
        //   class template can be declared and then later defined.
3638
128
        if (!inTemplateInstantiation()) {
3639
126
          unsigned NewDiag;
3640
126
          if (isa<CXXConstructorDecl>(OldMethod))
3641
10
            NewDiag = diag::err_constructor_redeclared;
3642
116
          else if (isa<CXXDestructorDecl>(NewMethod))
3643
18
            NewDiag = diag::err_destructor_redeclared;
3644
98
          else if (isa<CXXConversionDecl>(NewMethod))
3645
14
            NewDiag = diag::err_conv_function_redeclared;
3646
84
          else
3647
84
            NewDiag = diag::err_member_redeclared;
3648
3649
126
          Diag(New->getLocation(), NewDiag);
3650
126
        } else {
3651
2
          Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3652
2
            << New << New->getType();
3653
2
        }
3654
128
        Diag(OldLocation, PrevDiag) << Old << Old->getType();
3655
128
        return true;
3656
3657
      // Complain if this is an explicit declaration of a special
3658
      // member that was initially declared implicitly.
3659
      //
3660
      // As an exception, it's okay to befriend such methods in order
3661
      // to permit the implicit constructor/destructor/operator calls.
3662
163k
      } else if (OldMethod->isImplicit()) {
3663
117
        if (isFriend) {
3664
113
          NewMethod->setImplicit();
3665
113
        } else {
3666
4
          Diag(NewMethod->getLocation(),
3667
4
               diag::err_definition_of_implicitly_declared_member)
3668
4
            << New << getSpecialMember(OldMethod);
3669
4
          return true;
3670
4
        }
3671
163k
      } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && 
!isFriend36
) {
3672
10
        Diag(NewMethod->getLocation(),
3673
10
             diag::err_definition_of_explicitly_defaulted_member)
3674
10
          << getSpecialMember(OldMethod);
3675
10
        return true;
3676
10
      }
3677
163k
    }
3678
3679
    // C++11 [dcl.attr.noreturn]p1:
3680
    //   The first declaration of a function shall specify the noreturn
3681
    //   attribute if any declaration of that function specifies the noreturn
3682
    //   attribute.
3683
224k
    if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3684
2
      if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3685
1
        Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3686
1
            << NRA;
3687
1
        Diag(Old->getLocation(), diag::note_previous_declaration);
3688
1
      }
3689
3690
    // C++11 [dcl.attr.depend]p2:
3691
    //   The first declaration of a function shall specify the
3692
    //   carries_dependency attribute for its declarator-id if any declaration
3693
    //   of the function specifies the carries_dependency attribute.
3694
224k
    const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3695
224k
    if (CDA && 
!Old->hasAttr<CarriesDependencyAttr>()3
) {
3696
2
      Diag(CDA->getLocation(),
3697
2
           diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3698
2
      Diag(Old->getFirstDecl()->getLocation(),
3699
2
           diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3700
2
    }
3701
3702
    // (C++98 8.3.5p3):
3703
    //   All declarations for a function shall agree exactly in both the
3704
    //   return type and the parameter-type-list.
3705
    // We also want to respect all the extended bits except noreturn.
3706
3707
    // noreturn should now match unless the old type info didn't have it.
3708
224k
    QualType OldQTypeForComparison = OldQType;
3709
224k
    if (!OldTypeInfo.getNoReturn() && 
NewTypeInfo.getNoReturn()223k
) {
3710
0
      auto *OldType = OldQType->castAs<FunctionProtoType>();
3711
0
      const FunctionType *OldTypeForComparison
3712
0
        = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3713
0
      OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3714
0
      assert(OldQTypeForComparison.isCanonical());
3715
0
    }
3716
3717
224k
    if (haveIncompatibleLanguageLinkages(Old, New)) {
3718
      // As a special case, retain the language linkage from previous
3719
      // declarations of a friend function as an extension.
3720
      //
3721
      // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3722
      // and is useful because there's otherwise no way to specify language
3723
      // linkage within class scope.
3724
      //
3725
      // Check cautiously as the friend object kind isn't yet complete.
3726
38
      if (New->getFriendObjectKind() != Decl::FOK_None) {
3727
2
        Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3728
2
        Diag(OldLocation, PrevDiag);
3729
36
      } else {
3730
36
        Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3731
36
        Diag(OldLocation, PrevDiag);
3732
36
        return true;
3733
36
      }
3734
38
    }
3735
3736
    // If the function types are compatible, merge the declarations. Ignore the
3737
    // exception specifier because it was already checked above in
3738
    // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3739
    // about incompatible types under -fms-compatibility.
3740
224k
    if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3741
224k
                                                         NewQType))
3742
224k
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3743
3744
    // If the types are imprecise (due to dependent constructs in friends or
3745
    // local extern declarations), it's OK if they differ. We'll check again
3746
    // during instantiation.
3747
45
    if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3748
28
      return false;
3749
3750
    // Fall through for conflicting redeclarations and redefinitions.
3751
45
  }
3752
3753
  // C: Function types need to be compatible, not identical. This handles
3754
  // duplicate function decls like "void f(int); void f(enum X);" properly.
3755
20.7k
  if (!getLangOpts().CPlusPlus &&
3756
20.7k
      
Context.typesAreCompatible(OldQType, NewQType)20.7k
) {
3757
20.5k
    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3758
20.5k
    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3759
20.5k
    const FunctionProtoType *OldProto = nullptr;
3760
20.5k
    if (MergeTypeWithOld && 
isa<FunctionNoProtoType>(NewFuncType)20.5k
&&
3761
20.5k
        
(OldProto = dyn_cast<FunctionProtoType>(OldFuncType))531
) {
3762
      // The old declaration provided a function prototype, but the
3763
      // new declaration does not. Merge in the prototype.
3764
63
      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3765
0
      SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3766
63
      NewQType =
3767
63
          Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3768
63
                                  OldProto->getExtProtoInfo());
3769
63
      New->setType(NewQType);
3770
63
      New->setHasInheritedPrototype();
3771
3772
      // Synthesize parameters with the same types.
3773
63
      SmallVector<ParmVarDecl*, 16> Params;
3774
63
      for (const auto &ParamType : OldProto->param_types()) {
3775
29
        ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3776
29
                                                 SourceLocation(), nullptr,
3777
29
                                                 ParamType, /*TInfo=*/nullptr,
3778
29
                                                 SC_None, nullptr);
3779
29
        Param->setScopeInfo(0, Params.size());
3780
29
        Param->setImplicit();
3781
29
        Params.push_back(Param);
3782
29
      }
3783
3784
63
      New->setParams(Params);
3785
63
    }
3786
3787
0
    return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3788
20.5k
  }
3789
3790
  // Check if the function types are compatible when pointer size address
3791
  // spaces are ignored.
3792
165
  if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3793
3
    return false;
3794
3795
  // GNU C permits a K&R definition to follow a prototype declaration
3796
  // if the declared types of the parameters in the K&R definition
3797
  // match the types in the prototype declaration, even when the
3798
  // promoted types of the parameters from the K&R definition differ
3799
  // from the types in the prototype. GCC then keeps the types from
3800
  // the prototype.
3801
  //
3802
  // If a variadic prototype is followed by a non-variadic K&R definition,
3803
  // the K&R definition becomes variadic.  This is sort of an edge case, but
3804
  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3805
  // C99 6.9.1p8.
3806
162
  if (!getLangOpts().CPlusPlus &&
3807
162
      
Old->hasPrototype()145
&&
!New->hasPrototype()116
&&
3808
162
      
New->getType()->getAs<FunctionProtoType>()32
&&
3809
162
      
Old->getNumParams() == New->getNumParams()9
) {
3810
8
    SmallVector<QualType, 16> ArgTypes;
3811
8
    SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3812
8
    const FunctionProtoType *OldProto
3813
8
      = Old->getType()->getAs<FunctionProtoType>();
3814
8
    const FunctionProtoType *NewProto
3815
8
      = New->getType()->getAs<FunctionProtoType>();
3816
3817
    // Determine whether this is the GNU C extension.
3818
8
    QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3819
8
                                               NewProto->getReturnType());
3820
8
    bool LooseCompatible = !MergedReturn.isNull();
3821
8
    for (unsigned Idx = 0, End = Old->getNumParams();
3822
18
         LooseCompatible && 
Idx != End15
;
++Idx10
) {
3823
10
      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3824
10
      ParmVarDecl *NewParm = New->getParamDecl(Idx);
3825
10
      if (Context.typesAreCompatible(OldParm->getType(),
3826
10
                                     NewProto->getParamType(Idx))) {
3827
3
        ArgTypes.push_back(NewParm->getType());
3828
7
      } else if (Context.typesAreCompatible(OldParm->getType(),
3829
7
                                            NewParm->getType(),
3830
7
                                            /*CompareUnqualified=*/true)) {
3831
4
        GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3832
4
                                           NewProto->getParamType(Idx) };
3833
4
        Warnings.push_back(Warn);
3834
4
        ArgTypes.push_back(NewParm->getType());
3835
4
      } else
3836
3
        LooseCompatible = false;
3837
10
    }
3838
3839
8
    if (LooseCompatible) {
3840
9
      for (unsigned Warn = 0; Warn < Warnings.size(); 
++Warn4
) {
3841
4
        Diag(Warnings[Warn].NewParm->getLocation(),
3842
4
             diag::ext_param_promoted_not_compatible_with_prototype)
3843
4
          << Warnings[Warn].PromotedType
3844
4
          << Warnings[Warn].OldParm->getType();
3845
4
        if (Warnings[Warn].OldParm->getLocation().isValid())
3846
3
          Diag(Warnings[Warn].OldParm->getLocation(),
3847
3
               diag::note_previous_declaration);
3848
4
      }
3849
3850
5
      if (MergeTypeWithOld)
3851
5
        New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3852
5
                                             OldProto->getExtProtoInfo()));
3853
5
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3854
5
    }
3855
3856
    // Fall through to diagnose conflicting types.
3857
8
  }
3858
3859
  // A function that has already been declared has been redeclared or
3860
  // defined with a different type; show an appropriate diagnostic.
3861
3862
  // If the previous declaration was an implicitly-generated builtin
3863
  // declaration, then at the very least we should use a specialized note.
3864
157
  unsigned BuiltinID;
3865
157
  if (Old->isImplicit() && 
(BuiltinID = Old->getBuiltinID())71
) {
3866
    // If it's actually a library-defined builtin function like 'malloc'
3867
    // or 'printf', just warn about the incompatible redeclaration.
3868
68
    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3869
65
      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3870
65
      Diag(OldLocation, diag::note_previous_builtin_declaration)
3871
65
        << Old << Old->getType();
3872
65
      return false;
3873
65
    }
3874
3875
3
    PrevDiag = diag::note_previous_builtin_declaration;
3876
3
  }
3877
3878
92
  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3879
92
  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3880
92
  return true;
3881
157
}
3882
3883
/// Completes the merge of two function declarations that are
3884
/// known to be compatible.
3885
///
3886
/// This routine handles the merging of attributes and other
3887
/// properties of function declarations from the old declaration to
3888
/// the new declaration, once we know that New is in fact a
3889
/// redeclaration of Old.
3890
///
3891
/// \returns false
3892
bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3893
244k
                                        Scope *S, bool MergeTypeWithOld) {
3894
  // Merge the attributes
3895
244k
  mergeDeclAttributes(New, Old);
3896
3897
  // Merge "pure" flag.
3898
244k
  if (Old->isPure())
3899
18
    New->setPure();
3900
3901
  // Merge "used" flag.
3902
244k
  if (Old->getMostRecentDecl()->isUsed(false))
3903
4.18k
    New->setIsUsed();
3904
3905
  // Merge attributes from the parameters.  These can mismatch with K&R
3906
  // declarations.
3907
244k
  if (New->getNumParams() == Old->getNumParams())
3908
627k
      
for (unsigned i = 0, e = New->getNumParams(); 244k
i != e;
++i382k
) {
3909
382k
        ParmVarDecl *NewParam = New->getParamDecl(i);
3910
382k
        ParmVarDecl *OldParam = Old->getParamDecl(i);
3911
382k
        mergeParamDeclAttributes(NewParam, OldParam, *this);
3912
382k
        mergeParamDeclTypes(NewParam, OldParam, *this);
3913
382k
      }
3914
3915
244k
  if (getLangOpts().CPlusPlus)
3916
224k
    return MergeCXXFunctionDecl(New, Old, S);
3917
3918
  // Merge the function types so the we get the composite types for the return
3919
  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3920
  // was visible.
3921
20.5k
  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3922
20.5k
  if (!Merged.isNull() && 
MergeTypeWithOld20.5k
)
3923
20.5k
    New->setType(Merged);
3924
3925
20.5k
  return false;
3926
244k
}
3927
3928
void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3929
144k
                                ObjCMethodDecl *oldMethod) {
3930
  // Merge the attributes, including deprecated/unavailable
3931
144k
  AvailabilityMergeKind MergeKind =
3932
144k
      isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3933
144k
          ? 
(11.2k
oldMethod->isOptional()11.2k
?
AMK_OptionalProtocolImplementation606
3934
11.2k
                                     : 
AMK_ProtocolImplementation10.6k
)
3935
144k
          : 
isa<ObjCImplDecl>(newMethod->getDeclContext())133k
?
AMK_Redeclaration4.73k
3936
133k
                                                           : 
AMK_Override128k
;
3937
3938
144k
  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3939
3940
  // Merge attributes from the parameters.
3941
144k
  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3942
144k
                                       oe = oldMethod->param_end();
3943
144k
  for (ObjCMethodDecl::param_iterator
3944
144k
         ni = newMethod->param_begin(), ne = newMethod->param_end();
3945
235k
       ni != ne && 
oi != oe90.3k
;
++ni, ++oi90.3k
)
3946
90.3k
    mergeParamDeclAttributes(*ni, *oi, *this);
3947
3948
144k
  CheckObjCMethodOverride(newMethod, oldMethod);
3949
144k
}
3950
3951
186
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3952
186
  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3953
3954
186
  S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3955
186
         ? 
diag::err_redefinition_different_type95
3956
186
         : 
diag::err_redeclaration_different_type91
)
3957
186
    << New->getDeclName() << New->getType() << Old->getType();
3958
3959
186
  diag::kind PrevDiag;
3960
186
  SourceLocation OldLocation;
3961
186
  std::tie(PrevDiag, OldLocation)
3962
186
    = getNoteDiagForInvalidRedeclaration(Old, New);
3963
186
  S.Diag(OldLocation, PrevDiag);
3964
186
  New->setInvalidDecl();
3965
186
}
3966
3967
/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3968
/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3969
/// emitting diagnostics as appropriate.
3970
///
3971
/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3972
/// to here in AddInitializerToDecl. We can't check them before the initializer
3973
/// is attached.
3974
void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3975
60.2k
                             bool MergeTypeWithOld) {
3976
60.2k
  if (New->isInvalidDecl() || 
Old->isInvalidDecl()60.2k
)
3977
49
    return;
3978
3979
60.1k
  QualType MergedT;
3980
60.1k
  if (getLangOpts().CPlusPlus) {
3981
59.1k
    if (New->getType()->isUndeducedType()) {
3982
      // We don't know what the new type is until the initializer is attached.
3983
22
      return;
3984
59.1k
    } else if (Context.hasSameType(New->getType(), Old->getType())) {
3985
      // These could still be something that needs exception specs checked.
3986
58.8k
      return MergeVarDeclExceptionSpecs(New, Old);
3987
58.8k
    }
3988
    // C++ [basic.link]p10:
3989
    //   [...] the types specified by all declarations referring to a given
3990
    //   object or function shall be identical, except that declarations for an
3991
    //   array object can specify array types that differ by the presence or
3992
    //   absence of a major array bound (8.3.4).
3993
262
    else if (Old->getType()->isArrayType() && 
New->getType()->isArrayType()150
) {
3994
131
      const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3995
131
      const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3996
3997
      // We are merging a variable declaration New into Old. If it has an array
3998
      // bound, and that bound differs from Old's bound, we should diagnose the
3999
      // mismatch.
4000
131
      if (!NewArray->isIncompleteArrayType() && 
!NewArray->isDependentType()62
) {
4001
122
        for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4002
75
             
PrevVD = PrevVD->getPreviousDecl()73
) {
4003
75
          QualType PrevVDTy = PrevVD->getType();
4004
75
          if (PrevVDTy->isIncompleteArrayType() || 
PrevVDTy->isDependentType()27
)
4005
52
            continue;
4006
4007
23
          if (!Context.hasSameType(New->getType(), PrevVDTy))
4008
2
            return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4009
23
        }
4010
49
      }
4011
4012
129
      if (OldArray->isIncompleteArrayType() && 
NewArray->isArrayType()56
) {
4013
56
        if (Context.hasSameType(OldArray->getElementType(),
4014
56
                                NewArray->getElementType()))
4015
56
          MergedT = New->getType();
4016
56
      }
4017
      // FIXME: Check visibility. New is hidden but has a complete type. If New
4018
      // has no array bound, it should not inherit one from Old, if Old is not
4019
      // visible.
4020
73
      else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4021
69
        if (Context.hasSameType(OldArray->getElementType(),
4022
69
                                NewArray->getElementType()))
4023
68
          MergedT = Old->getType();
4024
69
      }
4025
129
    }
4026
131
    else if (New->getType()->isObjCObjectPointerType() &&
4027
131
               
Old->getType()->isObjCObjectPointerType()4
) {
4028
4
      MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4029
4
                                              Old->getType());
4030
4
    }
4031
59.1k
  } else {
4032
    // C 6.2.7p2:
4033
    //   All declarations that refer to the same object or function shall have
4034
    //   compatible type.
4035
1.07k
    MergedT = Context.mergeTypes(New->getType(), Old->getType());
4036
1.07k
  }
4037
1.33k
  if (MergedT.isNull()) {
4038
    // It's OK if we couldn't merge types if either type is dependent, for a
4039
    // block-scope variable. In other cases (static data members of class
4040
    // templates, variable templates, ...), we require the types to be
4041
    // equivalent.
4042
    // FIXME: The C++ standard doesn't say anything about this.
4043
214
    if ((New->getType()->isDependentType() ||
4044
214
         
Old->getType()->isDependentType()174
) &&
New->isLocalVarDecl()56
) {
4045
      // If the old type was dependent, we can't merge with it, so the new type
4046
      // becomes dependent for now. We'll reproduce the original type when we
4047
      // instantiate the TypeSourceInfo for the variable.
4048
30
      if (!New->getType()->isDependentType() && 
MergeTypeWithOld7
)
4049
1
        New->setType(Context.DependentTy);
4050
30
      return;
4051
30
    }
4052
184
    return diagnoseVarDeclTypeMismatch(*this, New, Old);
4053
214
  }
4054
4055
  // Don't actually update the type on the new declaration if the old
4056
  // declaration was an extern declaration in a different scope.
4057
1.12k
  if (MergeTypeWithOld)
4058
1.06k
    New->setType(MergedT);
4059
1.12k
}
4060
4061
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4062
60.2k
                                  LookupResult &Previous) {
4063
  // C11 6.2.7p4:
4064
  //   For an identifier with internal or external linkage declared
4065
  //   in a scope in which a prior declaration of that identifier is
4066
  //   visible, if the prior declaration specifies internal or
4067
  //   external linkage, the type of the identifier at the later
4068
  //   declaration becomes the composite type.
4069
  //
4070
  // If the variable isn't visible, we do not merge with its type.
4071
60.2k
  if (Previous.isShadowed())
4072
38
    return false;
4073
4074
60.2k
  if (S.getLangOpts().CPlusPlus) {
4075
    // C++11 [dcl.array]p3:
4076
    //   If there is a preceding declaration of the entity in the same
4077
    //   scope in which the bound was specified, an omitted array bound
4078
    //   is taken to be the same as in that earlier declaration.
4079
59.1k
    return NewVD->isPreviousDeclInSameBlockScope() ||
4080
59.1k
           
(59.1k
!OldVD->getLexicalDeclContext()->isFunctionOrMethod()59.1k
&&
4081
59.1k
            
!NewVD->getLexicalDeclContext()->isFunctionOrMethod()58.8k
);
4082
59.1k
  } else {
4083
    // If the old declaration was function-local, don't merge with its
4084
    // type unless we're in the same function.
4085
1.06k
    return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4086
1.06k
           
OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext()31
;
4087
1.06k
  }
4088
60.2k
}
4089
4090
/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4091
/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4092
/// situation, merging decls or emitting diagnostics as appropriate.
4093
///
4094
/// Tentative definition rules (C99 6.9.2p2) are checked by
4095
/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4096
/// definitions here, since the initializer hasn't been attached.
4097
///
4098
60.2k
void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4099
  // If the new decl is already invalid, don't do any other checking.
4100
60.2k
  if (New->isInvalidDecl())
4101
0
    return;
4102
4103
60.2k
  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4104
4
    return;
4105
4106
60.2k
  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4107
4108
  // Verify the old decl was also a variable or variable template.
4109
60.2k
  VarDecl *Old = nullptr;
4110
60.2k
  VarTemplateDecl *OldTemplate = nullptr;
4111
60.2k
  if (Previous.isSingleResult()) {
4112
60.2k
    if (NewTemplate) {
4113
417
      OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4114
417
      Old = OldTemplate ? 
OldTemplate->getTemplatedDecl()413
:
nullptr4
;
4115
4116
417
      if (auto *Shadow =
4117
417
              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4118
3
        if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4119
2
          return New->setInvalidDecl();
4120
59.7k
    } else {
4121
59.7k
      Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4122
4123
59.7k
      if (auto *Shadow =
4124
59.7k
              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4125
9
        if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4126
8
          return New->setInvalidDecl();
4127
59.7k
    }
4128
60.2k
  }
4129
60.2k
  if (!Old) {
4130
51
    Diag(New->getLocation(), diag::err_redefinition_different_kind)
4131
51
        << New->getDeclName();
4132
51
    notePreviousDefinition(Previous.getRepresentativeDecl(),
4133
51
                           New->getLocation());
4134
51
    return New->setInvalidDecl();
4135
51
  }
4136
4137
  // If the old declaration was found in an inline namespace and the new
4138
  // declaration was qualified, update the DeclContext to match.
4139
60.1k
  adjustDeclContextForDeclaratorDecl(New, Old);
4140
4141
  // Ensure the template parameters are compatible.
4142
60.1k
  if (NewTemplate &&
4143
60.1k
      !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4144
411
                                      OldTemplate->getTemplateParameters(),
4145
411
                                      /*Complain=*/true, TPL_TemplateMatch))
4146
10
    return New->setInvalidDecl();
4147
4148
  // C++ [class.mem]p1:
4149
  //   A member shall not be declared twice in the member-specification [...]
4150
  //
4151
  // Here, we need only consider static data members.
4152
60.1k
  if (Old->isStaticDataMember() && 
!New->isOutOfLine()56.9k
) {
4153
11
    Diag(New->getLocation(), diag::err_duplicate_member)
4154
11
      << New->getIdentifier();
4155
11
    Diag(Old->getLocation(), diag::note_previous_declaration);
4156
11
    New->setInvalidDecl();
4157
11
  }
4158
4159
60.1k
  mergeDeclAttributes(New, Old);
4160
  // Warn if an already-declared variable is made a weak_import in a subsequent
4161
  // declaration
4162
60.1k
  if (New->hasAttr<WeakImportAttr>() &&
4163
60.1k
      
Old->getStorageClass() == SC_None15
&&
4164
60.1k
      
!Old->hasAttr<WeakImportAttr>()3
) {
4165
2
    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4166
2
    Diag(Old->getLocation(), diag::note_previous_declaration);
4167
    // Remove weak_import attribute on new declaration.
4168
2
    New->dropAttr<WeakImportAttr>();
4169
2
  }
4170
4171
60.1k
  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4172
5
    if (!Old->hasAttr<InternalLinkageAttr>()) {
4173
2
      Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4174
2
          << ILA;
4175
2
      Diag(Old->getLocation(), diag::note_previous_declaration);
4176
2
      New->dropAttr<InternalLinkageAttr>();
4177
2
    }
4178
4179
  // Merge the types.
4180
60.1k
  VarDecl *MostRecent = Old->getMostRecentDecl();
4181
60.1k
  if (MostRecent != Old) {
4182
101
    MergeVarDeclTypes(New, MostRecent,
4183
101
                      mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4184
101
    if (New->isInvalidDecl())
4185
6
      return;
4186
101
  }
4187
4188
60.1k
  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4189
60.1k
  if (New->isInvalidDecl())
4190
197
    return;
4191
4192
59.9k
  diag::kind PrevDiag;
4193
59.9k
  SourceLocation OldLocation;
4194
59.9k
  std::tie(PrevDiag, OldLocation) =
4195
59.9k
      getNoteDiagForInvalidRedeclaration(Old, New);
4196
4197
  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4198
59.9k
  if (New->getStorageClass() == SC_Static &&
4199
59.9k
      
!New->isStaticDataMember()71
&&
4200
59.9k
      
Old->hasExternalFormalLinkage()68
) {
4201
16
    if (getLangOpts().MicrosoftExt) {
4202
3
      Diag(New->getLocation(), diag::ext_static_non_static)
4203
3
          << New->getDeclName();
4204
3
      Diag(OldLocation, PrevDiag);
4205
13
    } else {
4206
13
      Diag(New->getLocation(), diag::err_static_non_static)
4207
13
          << New->getDeclName();
4208
13
      Diag(OldLocation, PrevDiag);
4209
13
      return New->setInvalidDecl();
4210
13
    }
4211
16
  }
4212
  // C99 6.2.2p4:
4213
  //   For an identifier declared with the storage-class specifier
4214
  //   extern in a scope in which a prior declaration of that
4215
  //   identifier is visible,23) if the prior declaration specifies
4216
  //   internal or external linkage, the linkage of the identifier at
4217
  //   the later declaration is the same as the linkage specified at
4218
  //   the prior declaration. If no prior declaration is visible, or
4219
  //   if the prior declaration specifies no linkage, then the
4220
  //   identifier has external linkage.
4221
59.9k
  if (New->hasExternalStorage() && 
Old->hasLinkage()1.84k
)
4222
1.83k
    /* Okay */;
4223
58.0k
  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4224
58.0k
           
!New->isStaticDataMember()58.0k
&&
4225
58.0k
           
Old->getCanonicalDecl()->getStorageClass() == SC_Static1.15k
) {
4226
4
    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4227
4
    Diag(OldLocation, PrevDiag);
4228
4
    return New->setInvalidDecl();
4229
4
  }
4230
4231
  // Check if extern is followed by non-extern and vice-versa.
4232
59.9k
  if (New->hasExternalStorage() &&
4233
59.9k
      
!Old->hasLinkage()1.84k
&&
Old->isLocalVarDeclOrParm()5
) {
4234
5
    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4235
5
    Diag(OldLocation, PrevDiag);
4236
5
    return New->setInvalidDecl();
4237
5
  }
4238
59.9k
  if (Old->hasLinkage() && 
New->isLocalVarDeclOrParm()59.8k
&&
4239
59.9k
      
!New->hasExternalStorage()212
) {
4240
4
    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4241
4
    Diag(OldLocation, PrevDiag);
4242
4
    return New->setInvalidDecl();
4243
4
  }
4244
4245
59.9k
  if (CheckRedeclarationModuleOwnership(New, Old))
4246
19
    return;
4247
4248
  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4249
4250
  // FIXME: The test for external storage here seems wrong? We still
4251
  // need to check for mismatches.
4252
59.8k
  if (!New->hasExternalStorage() && 
!New->isFileVarDecl()58.0k
&&
4253
      // Don't complain about out-of-line definitions of static members.
4254
59.8k
      
!(72
Old->getLexicalDeclContext()->isRecord()72
&&
4255
72
        
!New->getLexicalDeclContext()->isRecord()0
)) {
4256
72
    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4257
72
    Diag(OldLocation, PrevDiag);
4258
72
    return New->setInvalidDecl();
4259
72
  }
4260
4261
59.8k
  if (New->isInline() && 
!Old->getMostRecentDecl()->isInline()981
) {
4262
295
    if (VarDecl *Def = Old->getDefinition()) {
4263
      // C++1z [dcl.fcn.spec]p4:
4264
      //   If the definition of a variable appears in a translation unit before
4265
      //   its first declaration as inline, the program is ill-formed.
4266
0
      Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4267
0
      Diag(Def->getLocation(), diag::note_previous_definition);
4268
0
    }
4269
295
  }
4270
4271
  // If this redeclaration makes the variable inline, we may need to add it to
4272
  // UndefinedButUsed.
4273
59.8k
  if (!Old->isInline() && 
New->isInline()59.1k
&&
Old->isUsed(false)295
&&
4274
59.8k
      
!Old->getDefinition()0
&&
!New->isThisDeclarationADefinition()0
)
4275
0
    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4276
0
                                           SourceLocation()));
4277
4278
59.8k
  if (New->getTLSKind() != Old->getTLSKind()) {
4279
25
    if (!Old->getTLSKind()) {
4280
11
      Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4281
11
      Diag(OldLocation, PrevDiag);
4282
14
    } else if (!New->getTLSKind()) {
4283
10
      Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4284
10
      Diag(OldLocation, PrevDiag);
4285
10
    } else {
4286
      // Do not allow redeclaration to change the variable between requiring
4287
      // static and dynamic initialization.
4288
      // FIXME: GCC allows this, but uses the TLS keyword on the first
4289
      // declaration to determine the kind. Do we need to be compatible here?
4290
4
      Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4291
4
        << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4292
4
      Diag(OldLocation, PrevDiag);
4293
4
    }
4294
25
  }
4295
4296
  // C++ doesn't have tentative definitions, so go right ahead and check here.
4297
59.8k
  if (getLangOpts().CPlusPlus &&
4298
59.8k
      
New->isThisDeclarationADefinition() == VarDecl::Definition58.8k
) {
4299
56.3k
    if (Old->isStaticDataMember() && 
Old->getCanonicalDecl()->isInline()55.7k
&&
4300
56.3k
        
Old->getCanonicalDecl()->isConstexpr()12
) {
4301
      // This definition won't be a definition any more once it's been merged.
4302
8
      Diag(New->getLocation(),
4303
8
           diag::warn_deprecated_redundant_constexpr_static_def);
4304
56.3k
    } else if (VarDecl *Def = Old->getDefinition()) {
4305
42
      if (checkVarDeclRedefinition(Def, New))
4306
33
        return;
4307
42
    }
4308
56.3k
  }
4309
4310
59.7k
  if (haveIncompatibleLanguageLinkages(Old, New)) {
4311
3
    Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4312
3
    Diag(OldLocation, PrevDiag);
4313
3
    New->setInvalidDecl();
4314
3
    return;
4315
3
  }
4316
4317
  // Merge "used" flag.
4318
59.7k
  if (Old->getMostRecentDecl()->isUsed(false))
4319
584
    New->setIsUsed();
4320
4321
  // Keep a chain of previous declarations.
4322
59.7k
  New->setPreviousDecl(Old);
4323
59.7k
  if (NewTemplate)
4324
377
    NewTemplate->setPreviousDecl(OldTemplate);
4325
4326
  // Inherit access appropriately.
4327
59.7k
  New->setAccess(Old->getAccess());
4328
59.7k
  if (NewTemplate)
4329
377
    NewTemplate->setAccess(New->getAccess());
4330
4331
59.7k
  if (Old->isInline())
4332
694
    New->setImplicitlyInline();
4333
59.7k
}
4334
4335
328
void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4336
328
  SourceManager &SrcMgr = getSourceManager();
4337
328
  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4338
328
  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4339
328
  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4340
328
  auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4341
328
  auto &HSI = PP.getHeaderSearchInfo();
4342
328
  StringRef HdrFilename =
4343
328
      SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4344
4345
328
  auto noteFromModuleOrInclude = [&](Module *Mod,
4346
328
                                     SourceLocation IncLoc) -> bool {
4347
    // Redefinition errors with modules are common with non modular mapped
4348
    // headers, example: a non-modular header H in module A that also gets
4349
    // included directly in a TU. Pointing twice to the same header/definition
4350
    // is confusing, try to get better diagnostics when modules is on.
4351
16
    if (IncLoc.isValid()) {
4352
8
      if (Mod) {
4353
3
        Diag(IncLoc, diag::note_redefinition_modules_same_file)
4354
3
            << HdrFilename.str() << Mod->getFullModuleName();
4355
3
        if (!Mod->DefinitionLoc.isInvalid())
4356
1
          Diag(Mod->DefinitionLoc, diag::note_defined_here)
4357
1
              << Mod->getFullModuleName();
4358
5
      } else {
4359
5
        Diag(IncLoc, diag::note_redefinition_include_same_file)
4360
5
            << HdrFilename.str();
4361
5
      }
4362
8
      return true;
4363
8
    }
4364
4365
8
    return false;
4366
16
  };
4367
4368
  // Is it the same file and same offset? Provide more information on why
4369
  // this leads to a redefinition error.
4370
328
  if (FNew == FOld && 
FNewDecLoc.second == FOldDecLoc.second310
) {
4371
8
    SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4372
8
    SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4373
8
    bool EmittedDiag =
4374
8
        noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4375
8
    EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4376
4377
    // If the header has no guards, emit a note suggesting one.
4378
8
    if (FOld && 
!HSI.isFileMultipleIncludeGuarded(FOld)5
)
4379
4
      Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4380
4381
8
    if (EmittedDiag)
4382
5
      return;
4383
8
  }
4384
4385
  // Redefinition coming from different files or couldn't do better above.
4386
323
  if (Old->getLocation().isValid())
4387
314
    Diag(Old->getLocation(), diag::note_previous_definition);
4388
323
}
4389
4390
/// We've just determined that \p Old and \p New both appear to be definitions
4391
/// of the same variable. Either diagnose or fix the problem.
4392
61
bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4393
61
  if (!hasVisibleDefinition(Old) &&
4394
61
      
(10
New->getFormalLinkage() == InternalLinkage10
||
4395
10
       New->isInline() ||
4396
10
       New->getDescribedVarTemplate() ||
4397
10
       
New->getNumTemplateParameterLists()8
||
4398
10
       
New->getDeclContext()->isDependentContext()1
)) {
4399
    // The previous definition is hidden, and multiple definitions are
4400
    // permitted (in separate TUs). Demote this to a declaration.
4401
9
    New->demoteThisDefinitionToDeclaration();
4402
4403
    // Make the canonical definition visible.
4404
9
    if (auto *OldTD = Old->getDescribedVarTemplate())
4405
2
      makeMergedDefinitionVisible(OldTD);
4406
9
    makeMergedDefinitionVisible(Old);
4407
9
    return false;
4408
52
  } else {
4409
52
    Diag(New->getLocation(), diag::err_redefinition) << New;
4410
52
    notePreviousDefinition(Old, New->getLocation());
4411
52
    New->setInvalidDecl();
4412
52
    return true;
4413
52
  }
4414
61
}
4415
4416
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4417
/// no declarator (e.g. "struct foo;") is parsed.
4418
Decl *
4419
Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4420
832k
                                 RecordDecl *&AnonRecord) {
4421
832k
  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4422
832k
                                    AnonRecord);
4423
832k
}
4424
4425
// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4426
// disambiguate entities defined in different scopes.
4427
// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4428
// compatibility.
4429
// We will pick our mangling number depending on which version of MSVC is being
4430
// targeted.
4431
34.7k
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4432
34.7k
  return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4433
34.7k
             ? 
S->getMSCurManglingNumber()148
4434
34.7k
             : 
S->getMSLastManglingNumber()34.6k
;
4435
34.7k
}
4436
4437
2.13M
void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4438
2.13M
  if (!Context.getLangOpts().CPlusPlus)
4439
1.05M
    return;
4440
4441
1.08M
  if (isa<CXXRecordDecl>(Tag->getParent())) {
4442
    // If this tag is the direct child of a class, number it if
4443
    // it is anonymous.
4444
60.1k
    if (!Tag->getName().empty() || 
Tag->getTypedefNameForAnonDecl()16.8k
)
4445
43.2k
      return;
4446
16.8k
    MangleNumberingContext &MCtx =
4447
16.8k
        Context.getManglingNumberContext(Tag->getParent());
4448
16.8k
    Context.setManglingNumber(
4449
16.8k
        Tag, MCtx.getManglingNumber(
4450
16.8k
                 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4451
16.8k
    return;
4452
60.1k
  }
4453
4454
  // If this tag isn't a direct child of a class, number it if it is local.
4455
1.02M
  MangleNumberingContext *MCtx;
4456
1.02M
  Decl *ManglingContextDecl;
4457
1.02M
  std::tie(MCtx, ManglingContextDecl) =
4458
1.02M
      getCurrentMangleNumberContext(Tag->getDeclContext());
4459
1.02M
  if (MCtx) {
4460
13.5k
    Context.setManglingNumber(
4461
13.5k
        Tag, MCtx->getManglingNumber(
4462
13.5k
                 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4463
13.5k
  }
4464
1.02M
}
4465
4466
namespace {
4467
struct NonCLikeKind {
4468
  enum {
4469
    None,
4470
    BaseClass,
4471
    DefaultMemberInit,
4472
    Lambda,
4473
    Friend,
4474
    OtherMember,
4475
    Invalid,
4476
  } Kind = None;
4477
  SourceRange Range;
4478
4479
159k
  explicit operator bool() { return Kind != None; }
4480
};
4481
}
4482
4483
/// Determine whether a class is C-like, according to the rules of C++
4484
/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4485
29.7k
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4486
29.7k
  if (RD->isInvalidDecl())
4487
0
    return {NonCLikeKind::Invalid, {}};
4488
4489
  // C++ [dcl.typedef]p9: [P1766R1]
4490
  //   An unnamed class with a typedef name for linkage purposes shall not
4491
  //
4492
  //    -- have any base classes
4493
29.7k
  if (RD->getNumBases())
4494
4
    return {NonCLikeKind::BaseClass,
4495
4
            SourceRange(RD->bases_begin()->getBeginLoc(),
4496
4
                        RD->bases_end()[-1].getEndLoc())};
4497
29.7k
  bool Invalid = false;
4498
116k
  for (Decl *D : RD->decls()) {
4499
    // Don't complain about things we already diagnosed.
4500
116k
    if (D->isInvalidDecl()) {
4501
12
      Invalid = true;
4502
12
      continue;
4503
12
    }
4504
4505
    //  -- have any [...] default member initializers
4506
116k
    if (auto *FD = dyn_cast<FieldDecl>(D)) {
4507
115k
      if (FD->hasInClassInitializer()) {
4508
4
        auto *Init = FD->getInClassInitializer();
4509
4
        return {NonCLikeKind::DefaultMemberInit,
4510
4
                Init ? Init->getSourceRange() : 
D->getSourceRange()0
};
4511
4
      }
4512
115k
      continue;
4513
115k
    }
4514
4515
    // FIXME: We don't allow friend declarations. This violates the wording of
4516
    // P1766, but not the intent.
4517
592
    if (isa<FriendDecl>(D))
4518
8
      return {NonCLikeKind::Friend, D->getSourceRange()};
4519
4520
    //  -- declare any members other than non-static data members, member
4521
    //     enumerations, or member classes,
4522
584
    if (isa<StaticAssertDecl>(D) || 
isa<IndirectFieldDecl>(D)572
||
4523
584
        
isa<EnumDecl>(D)540
)
4524
56
      continue;
4525
528
    auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4526
528
    if (!MemberRD) {
4527
110
      if (D->isImplicit())
4528
58
        continue;
4529
52
      return {NonCLikeKind::OtherMember, D->getSourceRange()};
4530
110
    }
4531
4532
    //  -- contain a lambda-expression,
4533
418
    if (MemberRD->isLambda())
4534
0
      return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4535
4536
    //  and all member classes shall also satisfy these requirements
4537
    //  (recursively).
4538
418
    if (MemberRD->isThisDeclarationADefinition()) {
4539
387
      if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4540
4
        return Kind;
4541
387
    }
4542
418
  }
4543
4544
29.6k
  return {Invalid ? 
NonCLikeKind::Invalid12
:
NonCLikeKind::None29.6k
, {}};
4545
29.7k
}
4546
4547
void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4548
595k
                                        TypedefNameDecl *NewTD) {
4549
595k
  if (TagFromDeclSpec->isInvalidDecl())
4550
9
    return;
4551
4552
  // Do nothing if the tag already has a name for linkage purposes.
4553
595k
  if (TagFromDeclSpec->hasNameForLinkage())
4554
435k
    return;
4555
4556
  // A well-formed anonymous tag must always be a TUK_Definition.
4557
160k
  assert(TagFromDeclSpec->isThisDeclarationADefinition());
4558
4559
  // The type must match the tag exactly;  no qualifiers allowed.
4560
160k
  if (!Context.hasSameType(NewTD->getUnderlyingType(),
4561
160k
                           Context.getTagDeclType(TagFromDeclSpec))) {
4562
558
    if (getLangOpts().CPlusPlus)
4563
157
      Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4564
558
    return;
4565
558
  }
4566
4567
  // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4568
  //   An unnamed class with a typedef name for linkage purposes shall [be
4569
  //   C-like].
4570
  //
4571
  // FIXME: Also diagnose if we've already computed the linkage. That ideally
4572
  // shouldn't happen, but there are constructs that the language rule doesn't
4573
  // disallow for which we can't reasonably avoid computing linkage early.
4574
159k
  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4575
159k
  NonCLikeKind NonCLike = RD ? 
getNonCLikeKindForAnonymousStruct(RD)29.3k
4576
159k
                             : 
NonCLikeKind()130k
;
4577
159k
  bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4578
159k
  if (NonCLike || 
ChangesLinkage159k
) {
4579
87
    if (NonCLike.Kind == NonCLikeKind::Invalid)
4580
12
      return;
4581
4582
75
    unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4583
75
    if (ChangesLinkage) {
4584
      // If the linkage changes, we can't accept this as an extension.
4585
12
      if (NonCLike.Kind == NonCLikeKind::None)
4586
7
        DiagID = diag::err_typedef_changes_linkage;
4587
5
      else
4588
5
        DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4589
12
    }
4590
4591
75
    SourceLocation FixitLoc =
4592
75
        getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4593
75
    llvm::SmallString<40> TextToInsert;
4594
75
    TextToInsert += ' ';
4595
75
    TextToInsert += NewTD->getIdentifier()->getName();
4596
4597
75
    Diag(FixitLoc, DiagID)
4598
75
      << isa<TypeAliasDecl>(NewTD)
4599
75
      << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4600
75
    if (NonCLike.Kind != NonCLikeKind::None) {
4601
68
      Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4602
68
        << NonCLike.Kind - 1 << NonCLike.Range;
4603
68
    }
4604
75
    Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4605
75
      << NewTD << isa<TypeAliasDecl>(NewTD);
4606
4607
75
    if (ChangesLinkage)
4608
12
      return;
4609
75
  }
4610
4611
  // Otherwise, set this as the anon-decl typedef for the tag.
4612
159k
  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4613
159k
}
4614
4615
98
static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4616
98
  switch (T) {
4617
18
  case DeclSpec::TST_class:
4618
18
    return 0;
4619
38
  case DeclSpec::TST_struct:
4620
38
    return 1;
4621
0
  case DeclSpec::TST_interface:
4622
0
    return 2;
4623
22
  case DeclSpec::TST_union:
4624
22
    return 3;
4625
20
  case DeclSpec::TST_enum:
4626
20
    return 4;
4627
0
  default:
4628
0
    llvm_unreachable("unexpected type specifier");
4629
98
  }
4630
98
}
4631
4632
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4633
/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4634
/// parameters to cope with template friend declarations.
4635
Decl *
4636
Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4637
                                 MultiTemplateParamsArg TemplateParams,
4638
                                 bool IsExplicitInstantiation,
4639
1.35M
                                 RecordDecl *&AnonRecord) {
4640
1.35M
  Decl *TagD = nullptr;
4641
1.35M
  TagDecl *Tag = nullptr;
4642
1.35M
  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4643
1.35M
      
DS.getTypeSpecType() == DeclSpec::TST_struct1.20M
||
4644
1.35M
      
DS.getTypeSpecType() == DeclSpec::TST_interface480k
||
4645
1.35M
      
DS.getTypeSpecType() == DeclSpec::TST_union480k
||
4646
1.35M
      
DS.getTypeSpecType() == DeclSpec::TST_enum462k
) {
4647
1.35M
    TagD = DS.getRepAsDecl();
4648
4649
1.35M
    if (!TagD) // We probably had an error
4650
169
      return nullptr;
4651
4652
    // Note that the above type specs guarantee that the
4653
    // type rep is a Decl, whereas in many of the others
4654
    // it's a Type.
4655
1.35M
    if (isa<TagDecl>(TagD))
4656
1.09M
      Tag = cast<TagDecl>(TagD);
4657
258k
    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4658
258k
      Tag = CTD->getTemplatedDecl();
4659
1.35M
  }
4660
4661
1.35M
  if (Tag) {
4662
1.35M
    handleTagNumbering(Tag, S);
4663
1.35M
    Tag->setFreeStanding();
4664
1.35M
    if (Tag->isInvalidDecl())
4665
699
      return Tag;
4666
1.35M
  }
4667
4668
1.35M
  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4669
    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4670
    // or incomplete types shall not be restrict-qualified."
4671
17
    if (TypeQuals & DeclSpec::TQ_restrict)
4672
2
      Diag(DS.getRestrictSpecLoc(),
4673
2
           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4674
2
           << DS.getSourceRange();
4675
17
  }
4676
4677
1.35M
  if (DS.isInlineSpecified())
4678
2
    Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4679
2
        << getLangOpts().CPlusPlus17;
4680
4681
1.35M
  if (DS.hasConstexprSpecifier()) {
4682
    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4683
    // and definitions of functions and variables.
4684
    // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4685
    // the declaration of a function or function template
4686
68
    if (Tag)
4687
61
      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4688
61
          << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4689
61
          << static_cast<int>(DS.getConstexprSpecifier());
4690
7
    else
4691
7
      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4692
7
          << static_cast<int>(DS.getConstexprSpecifier());
4693
    // Don't emit warnings after this error.
4694
68
    return TagD;
4695
68
  }
4696
4697
1.35M
  DiagnoseFunctionSpecifiers(DS);
4698
4699
1.35M
  if (DS.isFriendSpecified()) {
4700
    // If we're dealing with a decl but not a TagDecl, assume that
4701
    // whatever routines created it handled the friendship aspect.
4702
19.7k
    if (TagD && 
!Tag14.1k
)
4703
11
      return nullptr;
4704
19.6k
    return ActOnFriendTypeDecl(S, DS, TemplateParams);
4705
19.7k
  }
4706
4707
1.33M
  const CXXScopeSpec &SS = DS.getTypeSpecScope();
4708
1.33M
  bool IsExplicitSpecialization =
4709
1.33M
    !TemplateParams.empty() && 
TemplateParams.back()->size() == 0459k
;
4710
1.33M
  if (Tag && 
SS.isNotEmpty()1.33M
&&
!Tag->isCompleteDefinition()1.51k
&&
4711
1.33M
      
!IsExplicitInstantiation133
&&
!IsExplicitSpecialization123
&&
4712
1.33M
      
!isa<ClassTemplatePartialSpecializationDecl>(Tag)27
) {
4713
    // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4714
    // nested-name-specifier unless it is an explicit instantiation
4715
    // or an explicit specialization.
4716
    //
4717
    // FIXME: We allow class template partial specializations here too, per the
4718
    // obvious intent of DR1819.
4719
    //
4720
    // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4721
15
    Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4722
15
        << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4723
15
    return nullptr;
4724
15
  }
4725
4726
  // Track whether this decl-specifier declares anything.
4727
1.33M
  bool DeclaresAnything = true;
4728
4729
  // Handle anonymous struct definitions.
4730
1.33M
  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4731
879k
    if (!Record->getDeclName() && 
Record->isCompleteDefinition()1.73k
&&
4732
879k
        
DS.getStorageClassSpec() != DeclSpec::SCS_typedef1.73k
) {
4733
1.73k
      if (getLangOpts().CPlusPlus ||
4734
1.73k
          
Record->getDeclContext()->isRecord()296
) {
4735
        // If CurContext is a DeclContext that can contain statements,
4736
        // RecursiveASTVisitor won't visit the decls that
4737
        // BuildAnonymousStructOrUnion() will put into CurContext.
4738
        // Also store them here so that they can be part of the
4739
        // DeclStmt that gets created in this case.
4740
        // FIXME: Also return the IndirectFieldDecls created by
4741
        // BuildAnonymousStructOr union, for the same reason?
4742
1.72k
        if (CurContext->isFunctionOrMethod())
4743
36
          AnonRecord = Record;
4744
1.72k
        return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4745
1.72k
                                           Context.getPrintingPolicy());
4746
1.72k
      }
4747
4748
8
      DeclaresAnything = false;
4749
8
    }
4750
879k
  }
4751
4752
  // C11 6.7.2.1p2:
4753
  //   A struct-declaration that does not declare an anonymous structure or
4754
  //   anonymous union shall contain a struct-declarator-list.
4755
  //
4756
  // This rule also existed in C89 and C99; the grammar for struct-declaration
4757
  // did not permit a struct-declaration without a struct-declarator-list.
4758
1.33M
  if (!getLangOpts().CPlusPlus && 
CurContext->isRecord()568k
&&
4759
1.33M
      
DS.getStorageClassSpec() == DeclSpec::SCS_unspecified21
) {
4760
    // Check for Microsoft C extension: anonymous struct/union member.
4761
    // Handle 2 kinds of anonymous struct/union:
4762
    //   struct STRUCT;
4763
    //   union UNION;
4764
    // and
4765
    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4766
    //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4767
21
    if ((Tag && 
Tag->getDeclName()17
) ||
4768
21
        
DS.getTypeSpecType() == DeclSpec::TST_typename7
) {
4769
18
      RecordDecl *Record = nullptr;
4770
18
      if (Tag)
4771
14
        Record = dyn_cast<RecordDecl>(Tag);
4772
4
      else if (const RecordType *RT =
4773
4
                   DS.getRepAsType().get()->getAsStructureType())
4774
3
        Record = RT->getDecl();
4775
1
      else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4776
1
        Record = UT->getDecl();
4777
4778
18
      if (Record && getLangOpts().MicrosoftExt) {
4779
9
        Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4780
9
            << Record->isUnion() << DS.getSourceRange();
4781
9
        return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4782
9
      }
4783
4784
9
      DeclaresAnything = false;
4785
9
    }
4786
21
  }
4787
4788
  // Skip all the checks below if we have a type error.
4789
1.33M
  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4790
1.33M
      
(1.33M
TagD1.33M
&&
TagD->isInvalidDecl()1.33M
))
4791
189
    return TagD;
4792
4793
1.33M
  if (getLangOpts().CPlusPlus &&
4794
1.33M
      
DS.getStorageClassSpec() != DeclSpec::SCS_typedef766k
)
4795
766k
    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4796
74.6k
      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4797
74.6k
          
!Enum->getIdentifier()1.49k
&&
!Enum->isInvalidDecl()12
)
4798
12
        DeclaresAnything = false;
4799
4800
1.33M
  if (!DS.isMissingDeclaratorOk()) {
4801
    // Customize diagnostic for a typedef missing a name.
4802
176
    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4803
53
      Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4804
53
          << DS.getSourceRange();
4805
123
    else
4806
123
      DeclaresAnything = false;
4807
176
  }
4808
4809
1.33M
  if (DS.isModulePrivateSpecified() &&
4810
1.33M
      
Tag18
&&
Tag->getDeclContext()->isFunctionOrMethod()18
)
4811
1
    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4812
1
      << Tag->getTagKind()
4813
1
      << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4814
4815
1.33M
  ActOnDocumentableDecl(TagD);
4816
4817
  // C 6.7/2:
4818
  //   A declaration [...] shall declare at least a declarator [...], a tag,
4819
  //   or the members of an enumeration.
4820
  // C++ [dcl.dcl]p3:
4821
  //   [If there are no declarators], and except for the declaration of an
4822
  //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4823
  //   names into the program, or shall redeclare a name introduced by a
4824
  //   previous declaration.
4825
1.33M
  if (!DeclaresAnything) {
4826
    // In C, we allow this as a (popular) extension / bug. Don't bother
4827
    // producing further diagnostics for redundant qualifiers after this.
4828
152
    Diag(DS.getBeginLoc(), (IsExplicitInstantiation || 
!TemplateParams.empty()146
)
4829
152
                               ? 
diag::err_no_declarators43
4830
152
                               : 
diag::ext_no_declarators109
)
4831
152
        << DS.getSourceRange();
4832
152
    return TagD;
4833
152
  }
4834
4835
  // C++ [dcl.stc]p1:
4836
  //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4837
  //   init-declarator-list of the declaration shall not be empty.
4838
  // C++ [dcl.fct.spec]p1:
4839
  //   If a cv-qualifier appears in a decl-specifier-seq, the
4840
  //   init-declarator-list of the declaration shall not be empty.
4841
  //
4842
  // Spurious qualifiers here appear to be valid in C.
4843
1.33M
  unsigned DiagID = diag::warn_standalone_specifier;
4844
1.33M
  if (getLangOpts().CPlusPlus)
4845
766k
    DiagID = diag::ext_standalone_specifier;
4846
4847
  // Note that a linkage-specification sets a storage class, but
4848
  // 'extern "C" struct foo;' is actually valid and not theoretically
4849
  // useless.
4850
1.33M
  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4851
62
    if (SCS == DeclSpec::SCS_mutable)
4852
      // Since mutable is not a viable storage class specifier in C, there is