Coverage Report

Created: 2019-07-24 05:18

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