Coverage Report

Created: 2020-10-24 06:27

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