Coverage Report

Created: 2022-07-16 07:03

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