Coverage Report

Created: 2023-11-11 10:31

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaDecl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements semantic analysis for declarations.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TypeLocBuilder.h"
14
#include "clang/AST/ASTConsumer.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/ASTLambda.h"
17
#include "clang/AST/CXXInheritance.h"
18
#include "clang/AST/CharUnits.h"
19
#include "clang/AST/CommentDiagnostic.h"
20
#include "clang/AST/DeclCXX.h"
21
#include "clang/AST/DeclObjC.h"
22
#include "clang/AST/DeclTemplate.h"
23
#include "clang/AST/EvaluatedExprVisitor.h"
24
#include "clang/AST/Expr.h"
25
#include "clang/AST/ExprCXX.h"
26
#include "clang/AST/NonTrivialTypeVisitor.h"
27
#include "clang/AST/Randstruct.h"
28
#include "clang/AST/StmtCXX.h"
29
#include "clang/Basic/Builtins.h"
30
#include "clang/Basic/HLSLRuntime.h"
31
#include "clang/Basic/PartialDiagnostic.h"
32
#include "clang/Basic/SourceManager.h"
33
#include "clang/Basic/TargetInfo.h"
34
#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35
#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36
#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37
#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
38
#include "clang/Sema/CXXFieldCollector.h"
39
#include "clang/Sema/DeclSpec.h"
40
#include "clang/Sema/DelayedDiagnostic.h"
41
#include "clang/Sema/Initialization.h"
42
#include "clang/Sema/Lookup.h"
43
#include "clang/Sema/ParsedTemplate.h"
44
#include "clang/Sema/Scope.h"
45
#include "clang/Sema/ScopeInfo.h"
46
#include "clang/Sema/SemaInternal.h"
47
#include "clang/Sema/Template.h"
48
#include "llvm/ADT/SmallString.h"
49
#include "llvm/ADT/StringExtras.h"
50
#include "llvm/TargetParser/Triple.h"
51
#include <algorithm>
52
#include <cstring>
53
#include <functional>
54
#include <optional>
55
#include <unordered_map>
56
57
using namespace clang;
58
using namespace sema;
59
60
7.75M
Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
61
7.75M
  if (OwnedType) {
62
1.93k
    Decl *Group[2] = { OwnedType, Ptr };
63
1.93k
    return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
64
1.93k
  }
65
66
7.75M
  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
67
7.75M
}
68
69
namespace {
70
71
class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
72
 public:
73
   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
74
                        bool AllowTemplates = false,
75
                        bool AllowNonTemplates = true)
76
1.35k
       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
77
1.35k
         AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
78
1.35k
     WantExpressionKeywords = false;
79
1.35k
     WantCXXNamedCasts = false;
80
1.35k
     WantRemainingKeywords = false;
81
1.35k
  }
82
83
710
  bool ValidateCandidate(const TypoCorrection &candidate) override {
84
710
    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
85
668
      if (!AllowInvalidDecl && 
ND->isInvalidDecl()658
)
86
17
        return false;
87
88
651
      if (getAsTypeTemplateDecl(ND))
89
96
        return AllowTemplates;
90
91
555
      bool IsType = isa<TypeDecl>(ND) || 
isa<ObjCInterfaceDecl>(ND)180
;
92
555
      if (!IsType)
93
177
        return false;
94
95
378
      if (AllowNonTemplates)
96
378
        return true;
97
98
      // An injected-class-name of a class template (specialization) is valid
99
      // as a template or as a non-template.
100
0
      if (AllowTemplates) {
101
0
        auto *RD = dyn_cast<CXXRecordDecl>(ND);
102
0
        if (!RD || !RD->isInjectedClassName())
103
0
          return false;
104
0
        RD = cast<CXXRecordDecl>(RD->getDeclContext());
105
0
        return RD->getDescribedClassTemplate() ||
106
0
               isa<ClassTemplateSpecializationDecl>(RD);
107
0
      }
108
109
0
      return false;
110
0
    }
111
112
42
    return !WantClassName && 
candidate.isKeyword()40
;
113
710
  }
114
115
988
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
116
988
    return std::make_unique<TypeNameValidatorCCC>(*this);
117
988
  }
118
119
 private:
120
  bool AllowInvalidDecl;
121
  bool WantClassName;
122
  bool AllowTemplates;
123
  bool AllowNonTemplates;
124
};
125
126
} // end anonymous namespace
127
128
/// Determine whether the token kind starts a simple-type-specifier.
129
23.4k
bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
130
23.4k
  switch (Kind) {
131
  // FIXME: Take into account the current language when deciding whether a
132
  // token kind is a valid type specifier
133
0
  case tok::kw_short:
134
0
  case tok::kw_long:
135
0
  case tok::kw___int64:
136
0
  case tok::kw___int128:
137
0
  case tok::kw_signed:
138
0
  case tok::kw_unsigned:
139
0
  case tok::kw_void:
140
0
  case tok::kw_char:
141
1
  case tok::kw_int:
142
1
  case tok::kw_half:
143
1
  case tok::kw_float:
144
1
  case tok::kw_double:
145
1
  case tok::kw___bf16:
146
1
  case tok::kw__Float16:
147
1
  case tok::kw___float128:
148
1
  case tok::kw___ibm128:
149
1
  case tok::kw_wchar_t:
150
1
  case tok::kw_bool:
151
16
#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
152
16
#include 
"clang/Basic/TransformTypeTraits.def"1
153
16
  case tok::kw___auto_type:
154
1
    return true;
155
156
21.6k
  case tok::annot_typename:
157
21.6k
  case tok::kw_char16_t:
158
21.6k
  case tok::kw_char32_t:
159
21.6k
  case tok::kw_typeof:
160
21.6k
  case tok::annot_decltype:
161
21.6k
  case tok::kw_decltype:
162
21.6k
    return getLangOpts().CPlusPlus;
163
164
0
  case tok::kw_char8_t:
165
0
    return getLangOpts().Char8;
166
167
1.80k
  default:
168
1.80k
    break;
169
23.4k
  }
170
171
1.80k
  return false;
172
23.4k
}
173
174
namespace {
175
enum class UnqualifiedTypeNameLookupResult {
176
  NotFound,
177
  FoundNonType,
178
  FoundType
179
};
180
} // end anonymous namespace
181
182
/// Tries to perform unqualified lookup of the type decls in bases for
183
/// dependent class.
184
/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
185
/// type decl, \a FoundType if only type decls are found.
186
static UnqualifiedTypeNameLookupResult
187
lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
188
                                SourceLocation NameLoc,
189
128
                                const CXXRecordDecl *RD) {
190
128
  if (!RD->hasDefinition())
191
2
    return UnqualifiedTypeNameLookupResult::NotFound;
192
  // Look for type decls in base classes.
193
126
  UnqualifiedTypeNameLookupResult FoundTypeDecl =
194
126
      UnqualifiedTypeNameLookupResult::NotFound;
195
126
  for (const auto &Base : RD->bases()) {
196
124
    const CXXRecordDecl *BaseRD = nullptr;
197
124
    if (auto *BaseTT = Base.getType()->getAs<TagType>())
198
10
      BaseRD = BaseTT->getAsCXXRecordDecl();
199
114
    else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
200
      // Look for type decls in dependent base classes that have known primary
201
      // templates.
202
88
      if (!TST || !TST->isDependentType())
203
0
        continue;
204
88
      auto *TD = TST->getTemplateName().getAsTemplateDecl();
205
88
      if (!TD)
206
0
        continue;
207
88
      if (auto *BasePrimaryTemplate =
208
88
          dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
209
84
        if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
210
82
          BaseRD = BasePrimaryTemplate;
211
2
        else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
212
2
          if (const ClassTemplatePartialSpecializationDecl *PS =
213
2
                  CTD->findPartialSpecialization(Base.getType()))
214
2
            if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
215
2
              BaseRD = PS;
216
2
        }
217
84
      }
218
88
    }
219
124
    if (BaseRD) {
220
94
      for (NamedDecl *ND : BaseRD->lookup(&II)) {
221
76
        if (!isa<TypeDecl>(ND))
222
24
          return UnqualifiedTypeNameLookupResult::FoundNonType;
223
52
        FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
224
52
      }
225
70
      if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
226
18
        switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
227
0
        case UnqualifiedTypeNameLookupResult::FoundNonType:
228
0
          return UnqualifiedTypeNameLookupResult::FoundNonType;
229
10
        case UnqualifiedTypeNameLookupResult::FoundType:
230
10
          FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
231
10
          break;
232
8
        case UnqualifiedTypeNameLookupResult::NotFound:
233
8
          break;
234
18
        }
235
18
      }
236
70
    }
237
124
  }
238
239
102
  return FoundTypeDecl;
240
126
}
241
242
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
243
                                                      const IdentifierInfo &II,
244
189
                                                      SourceLocation NameLoc) {
245
  // Lookup in the parent class template context, if any.
246
189
  const CXXRecordDecl *RD = nullptr;
247
189
  UnqualifiedTypeNameLookupResult FoundTypeDecl =
248
189
      UnqualifiedTypeNameLookupResult::NotFound;
249
189
  for (DeclContext *DC = S.CurContext;
250
593
       DC && 
FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound472
;
251
404
       DC = DC->getParent()) {
252
    // Look for type decls in dependent base classes that have known primary
253
    // templates.
254
404
    RD = dyn_cast<CXXRecordDecl>(DC);
255
404
    if (RD && 
RD->getDescribedClassTemplate()127
)
256
110
      FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
257
404
  }
258
189
  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
259
145
    return nullptr;
260
261
  // We found some types in dependent base classes.  Recover as if the user
262
  // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
263
  // lookup during template instantiation.
264
44
  S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
265
266
44
  ASTContext &Context = S.Context;
267
44
  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
268
44
                                          cast<Type>(Context.getRecordType(RD)));
269
44
  QualType T =
270
44
      Context.getDependentNameType(ElaboratedTypeKeyword::Typename, NNS, &II);
271
272
44
  CXXScopeSpec SS;
273
44
  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
274
275
44
  TypeLocBuilder Builder;
276
44
  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
277
44
  DepTL.setNameLoc(NameLoc);
278
44
  DepTL.setElaboratedKeywordLoc(SourceLocation());
279
44
  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
280
44
  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
281
189
}
282
283
/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
284
static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
285
                                 SourceLocation NameLoc,
286
139M
                                 bool WantNontrivialTypeSourceInfo = true) {
287
139M
  switch (T->getTypeClass()) {
288
3.82k
  case Type::DeducedTemplateSpecialization:
289
128k
  case Type::Enum:
290
564k
  case Type::InjectedClassName:
291
1.36M
  case Type::Record:
292
131M
  case Type::Typedef:
293
131M
  case Type::UnresolvedUsing:
294
132M
  case Type::Using:
295
132M
    break;
296
  // These can never be qualified so an ElaboratedType node
297
  // would carry no additional meaning.
298
1.15M
  case Type::ObjCInterface:
299
1.19M
  case Type::ObjCTypeParam:
300
7.14M
  case Type::TemplateTypeParm:
301
7.14M
    return ParsedType::make(T);
302
0
  default:
303
0
    llvm_unreachable("Unexpected Type Class");
304
139M
  }
305
306
132M
  if (!SS || 
SS->isEmpty()40.2M
)
307
132M
    return ParsedType::make(S.Context.getElaboratedType(
308
132M
        ElaboratedTypeKeyword::None, nullptr, T, nullptr));
309
310
187k
  QualType ElTy = S.getElaboratedType(ElaboratedTypeKeyword::None, *SS, T);
311
187k
  if (!WantNontrivialTypeSourceInfo)
312
67
    return ParsedType::make(ElTy);
313
314
187k
  TypeLocBuilder Builder;
315
187k
  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
316
187k
  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
317
187k
  ElabTL.setElaboratedKeywordLoc(SourceLocation());
318
187k
  ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
319
187k
  return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
320
187k
}
321
322
/// If the identifier refers to a type name within this scope,
323
/// return the declaration of that type.
324
///
325
/// This routine performs ordinary name lookup of the identifier II
326
/// within the given scope, with optional C++ scope specifier SS, to
327
/// determine whether the name refers to a type. If so, returns an
328
/// opaque pointer (actually a QualType) corresponding to that
329
/// type. Otherwise, returns NULL.
330
ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
331
                             Scope *S, CXXScopeSpec *SS, bool isClassName,
332
                             bool HasTrailingDot, ParsedType ObjectTypePtr,
333
                             bool IsCtorOrDtorName,
334
                             bool WantNontrivialTypeSourceInfo,
335
                             bool IsClassTemplateDeductionContext,
336
                             ImplicitTypenameContext AllowImplicitTypename,
337
128M
                             IdentifierInfo **CorrectedII) {
338
  // FIXME: Consider allowing this outside C++1z mode as an extension.
339
128M
  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
340
128M
                              
getLangOpts().CPlusPlus17128M
&&
!IsCtorOrDtorName35.1M
&&
341
128M
                              
!isClassName35.1M
&&
!HasTrailingDot35.1M
;
342
343
  // Determine where we will perform name lookup.
344
128M
  DeclContext *LookupCtx = nullptr;
345
128M
  if (ObjectTypePtr) {
346
6.33k
    QualType ObjectType = ObjectTypePtr.get();
347
6.33k
    if (ObjectType->isRecordType())
348
472
      LookupCtx = computeDeclContext(ObjectType);
349
128M
  } else if (SS && 
SS->isNotEmpty()33.8M
) {
350
4.52M
    LookupCtx = computeDeclContext(*SS, false);
351
352
4.52M
    if (!LookupCtx) {
353
2.48M
      if (isDependentScopeSpecifier(*SS)) {
354
        // C++ [temp.res]p3:
355
        //   A qualified-id that refers to a type and in which the
356
        //   nested-name-specifier depends on a template-parameter (14.6.2)
357
        //   shall be prefixed by the keyword typename to indicate that the
358
        //   qualified-id denotes a type, forming an
359
        //   elaborated-type-specifier (7.1.5.3).
360
        //
361
        // We therefore do not perform any name lookup if the result would
362
        // refer to a member of an unknown specialization.
363
        // In C++2a, in several contexts a 'typename' is not required. Also
364
        // allow this as an extension.
365
2.48M
        if (AllowImplicitTypename == ImplicitTypenameContext::No &&
366
2.48M
            
!isClassName2.48M
&&
!IsCtorOrDtorName2.48M
)
367
2.48M
          return nullptr;
368
2.23k
        bool IsImplicitTypename = !isClassName && 
!IsCtorOrDtorName173
;
369
2.23k
        if (IsImplicitTypename) {
370
173
          SourceLocation QualifiedLoc = SS->getRange().getBegin();
371
173
          if (getLangOpts().CPlusPlus20)
372
51
            Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
373
122
          else
374
122
            Diag(QualifiedLoc, diag::ext_implicit_typename)
375
122
                << SS->getScopeRep() << II.getName()
376
122
                << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
377
173
        }
378
379
        // We know from the grammar that this name refers to a type,
380
        // so build a dependent node to describe the type.
381
2.23k
        if (WantNontrivialTypeSourceInfo)
382
2.20k
          return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
383
2.20k
                                   (ImplicitTypenameContext)IsImplicitTypename)
384
2.20k
              .get();
385
386
26
        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
387
26
        QualType T = CheckTypenameType(
388
26
            IsImplicitTypename ? 
ElaboratedTypeKeyword::Typename0
389
26
                               : ElaboratedTypeKeyword::None,
390
26
            SourceLocation(), QualifierLoc, II, NameLoc);
391
26
        return ParsedType::make(T);
392
2.23k
      }
393
394
325
      return nullptr;
395
2.48M
    }
396
397
2.03M
    if (!LookupCtx->isDependentContext() &&
398
2.03M
        
RequireCompleteDeclContext(*SS, LookupCtx)2.03M
)
399
129
      return nullptr;
400
2.03M
  }
401
402
  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
403
  // lookup for class-names.
404
125M
  LookupNameKind Kind = isClassName ? 
LookupNestedNameSpecifierName155k
:
405
125M
                                      
LookupOrdinaryName125M
;
406
125M
  LookupResult Result(*this, &II, NameLoc, Kind);
407
125M
  if (LookupCtx) {
408
    // Perform "qualified" name lookup into the declaration context we
409
    // computed, which is either the type of the base of a member access
410
    // expression or the declaration context associated with a prior
411
    // nested-name-specifier.
412
2.03M
    LookupQualifiedName(Result, LookupCtx);
413
414
2.03M
    if (ObjectTypePtr && 
Result.empty()0
) {
415
      // C++ [basic.lookup.classref]p3:
416
      //   If the unqualified-id is ~type-name, the type-name is looked up
417
      //   in the context of the entire postfix-expression. If the type T of
418
      //   the object expression is of a class type C, the type-name is also
419
      //   looked up in the scope of class C. At least one of the lookups shall
420
      //   find a name that refers to (possibly cv-qualified) T.
421
0
      LookupName(Result, S);
422
0
    }
423
123M
  } else {
424
    // Perform unqualified name lookup.
425
123M
    LookupName(Result, S);
426
427
    // For unqualified lookup in a class template in MSVC mode, look into
428
    // dependent base classes where the primary class template is known.
429
123M
    if (Result.empty() && 
getLangOpts().MSVCCompat125k
&&
(112
!SS112
||
SS->isEmpty()34
)) {
430
112
      if (ParsedType TypeInBase =
431
112
              recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
432
30
        return TypeInBase;
433
112
    }
434
123M
  }
435
436
125M
  NamedDecl *IIDecl = nullptr;
437
125M
  UsingShadowDecl *FoundUsingShadow = nullptr;
438
125M
  switch (Result.getResultKind()) {
439
126k
  case LookupResult::NotFound:
440
126k
  case LookupResult::NotFoundInCurrentInstantiation:
441
126k
    if (CorrectedII) {
442
11
      TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
443
11
                               AllowDeducedTemplate);
444
11
      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
445
11
                                              S, SS, CCC, CTK_ErrorRecovery);
446
11
      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
447
11
      TemplateTy Template;
448
11
      bool MemberOfUnknownSpecialization;
449
11
      UnqualifiedId TemplateName;
450
11
      TemplateName.setIdentifier(NewII, NameLoc);
451
11
      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
452
11
      CXXScopeSpec NewSS, *NewSSPtr = SS;
453
11
      if (SS && NNS) {
454
0
        NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
455
0
        NewSSPtr = &NewSS;
456
0
      }
457
11
      if (Correction && 
(2
NNS2
||
NewII != &II2
) &&
458
          // Ignore a correction to a template type as the to-be-corrected
459
          // identifier is not a template (typo correction for template names
460
          // is handled elsewhere).
461
11
          
!(2
getLangOpts().CPlusPlus2
&&
NewSSPtr2
&&
462
2
            isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
463
2
                           Template, MemberOfUnknownSpecialization))) {
464
2
        ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
465
2
                                    isClassName, HasTrailingDot, ObjectTypePtr,
466
2
                                    IsCtorOrDtorName,
467
2
                                    WantNontrivialTypeSourceInfo,
468
2
                                    IsClassTemplateDeductionContext);
469
2
        if (Ty) {
470
2
          diagnoseTypo(Correction,
471
2
                       PDiag(diag::err_unknown_type_or_class_name_suggest)
472
2
                         << Result.getLookupName() << isClassName);
473
2
          if (SS && NNS)
474
0
            SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
475
2
          *CorrectedII = NewII;
476
2
          return Ty;
477
2
        }
478
2
      }
479
11
    }
480
    // If typo correction failed or was not performed, fall through
481
126k
    
[[fallthrough]];126k
482
1.74M
  case LookupResult::FoundOverloaded:
483
1.74M
  case LookupResult::FoundUnresolvedValue:
484
1.74M
    Result.suppressDiagnostics();
485
1.74M
    return nullptr;
486
487
90
  case LookupResult::Ambiguous:
488
    // Recover from type-hiding ambiguities by hiding the type.  We'll
489
    // do the lookup again when looking for an object, and we can
490
    // diagnose the error then.  If we don't do this, then the error
491
    // about hiding the type will be immediately followed by an error
492
    // that only makes sense if the identifier was treated like a type.
493
90
    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
494
2
      Result.suppressDiagnostics();
495
2
      return nullptr;
496
2
    }
497
498
    // Look to see if we have a type anywhere in the list of results.
499
88
    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
500
240
         Res != ResEnd; 
++Res152
) {
501
152
      NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
502
152
      if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
503
152
              RealRes) ||
504
152
          
(85
AllowDeducedTemplate85
&&
getAsTypeTemplateDecl(RealRes)51
)) {
505
67
        if (!IIDecl ||
506
            // Make the selection of the recovery decl deterministic.
507
67
            
RealRes->getLocation() < IIDecl->getLocation()33
) {
508
45
          IIDecl = RealRes;
509
45
          FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
510
45
        }
511
67
      }
512
152
    }
513
514
88
    if (!IIDecl) {
515
      // None of the entities we found is a type, so there is no way
516
      // to even assume that the result is a type. In this case, don't
517
      // complain about the ambiguity. The parser will either try to
518
      // perform this lookup again (e.g., as an object name), which
519
      // will produce the ambiguity, or will complain that it expected
520
      // a type name.
521
54
      Result.suppressDiagnostics();
522
54
      return nullptr;
523
54
    }
524
525
    // We found a type within the ambiguous lookup; diagnose the
526
    // ambiguity and then return that type. This might be the right
527
    // answer, or it might not be, but it suppresses any attempt to
528
    // perform the name lookup again.
529
34
    break;
530
531
124M
  case LookupResult::Found:
532
124M
    IIDecl = Result.getFoundDecl();
533
124M
    FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
534
124M
    break;
535
125M
  }
536
537
124M
  assert(IIDecl && "Didn't find decl");
538
539
124M
  QualType T;
540
124M
  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
541
    // C++ [class.qual]p2: A lookup that would find the injected-class-name
542
    // instead names the constructors of the class, except when naming a class.
543
    // This is ill-formed when we're not actually forming a ctor or dtor name.
544
120M
    auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
545
120M
    auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
546
120M
    if (!isClassName && 
!IsCtorOrDtorName120M
&&
LookupRD120M
&&
FoundRD104k
&&
547
120M
        
FoundRD->isInjectedClassName()16.3k
&&
548
120M
        
declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))81
)
549
55
      Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
550
55
          << &II << /*Type*/1;
551
552
120M
    DiagnoseUseOfDecl(IIDecl, NameLoc);
553
554
120M
    T = Context.getTypeDeclType(TD);
555
120M
    MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
556
120M
  } else 
if (ObjCInterfaceDecl *3.87M
IDecl3.87M
= dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
557
1.15M
    (void)DiagnoseUseOfDecl(IDecl, NameLoc);
558
1.15M
    if (!HasTrailingDot)
559
1.15M
      T = Context.getObjCInterfaceType(IDecl);
560
1.15M
    FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
561
2.72M
  } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
562
7
    (void)DiagnoseUseOfDecl(UD, NameLoc);
563
    // Recover with 'int'
564
7
    return ParsedType::make(Context.IntTy);
565
2.72M
  } else if (AllowDeducedTemplate) {
566
984k
    if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
567
3.82k
      assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
568
3.82k
      TemplateName Template =
569
3.82k
          FoundUsingShadow ? 
TemplateName(FoundUsingShadow)14
:
TemplateName(TD)3.81k
;
570
3.82k
      T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
571
3.82k
                                                       false);
572
      // Don't wrap in a further UsingType.
573
3.82k
      FoundUsingShadow = nullptr;
574
3.82k
    }
575
984k
  }
576
577
124M
  if (T.isNull()) {
578
    // If it's not plausibly a type, suppress diagnostics.
579
2.71M
    Result.suppressDiagnostics();
580
2.71M
    return nullptr;
581
2.71M
  }
582
583
121M
  if (FoundUsingShadow)
584
401k
    T = Context.getUsingType(FoundUsingShadow, T);
585
586
121M
  return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
587
124M
}
588
589
// Builds a fake NNS for the given decl context.
590
static NestedNameSpecifier *
591
3
synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
592
3
  for (;; 
DC = DC->getLookupParent()0
) {
593
3
    DC = DC->getPrimaryContext();
594
3
    auto *ND = dyn_cast<NamespaceDecl>(DC);
595
3
    if (ND && 
!ND->isInline()2
&&
!ND->isAnonymousNamespace()2
)
596
2
      return NestedNameSpecifier::Create(Context, nullptr, ND);
597
1
    else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
598
1
      return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
599
1
                                         RD->getTypeForDecl());
600
0
    else if (isa<TranslationUnitDecl>(DC))
601
0
      return NestedNameSpecifier::GlobalSpecifier(Context);
602
3
  }
603
0
  llvm_unreachable("something isn't in TU scope?");
604
0
}
605
606
/// Find the parent class with dependent bases of the innermost enclosing method
607
/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
608
/// up allowing unqualified dependent type names at class-level, which MSVC
609
/// correctly rejects.
610
static const CXXRecordDecl *
611
38
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
612
52
  for (; DC && DC->isDependentContext(); 
DC = DC->getLookupParent()14
) {
613
26
    DC = DC->getPrimaryContext();
614
26
    if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
615
12
      if (MD->getParent()->hasAnyDependentBases())
616
12
        return MD->getParent();
617
26
  }
618
26
  return nullptr;
619
38
}
620
621
ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
622
                                          SourceLocation NameLoc,
623
41
                                          bool IsTemplateTypeArg) {
624
41
  assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
625
626
41
  NestedNameSpecifier *NNS = nullptr;
627
41
  if (IsTemplateTypeArg && 
getCurScope()->isTemplateParamScope()3
) {
628
    // If we weren't able to parse a default template argument, delay lookup
629
    // until instantiation time by making a non-dependent DependentTypeName. We
630
    // pretend we saw a NestedNameSpecifier referring to the current scope, and
631
    // lookup is retried.
632
    // FIXME: This hurts our diagnostic quality, since we get errors like "no
633
    // type named 'Foo' in 'current_namespace'" when the user didn't write any
634
    // name specifiers.
635
3
    NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
636
3
    Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
637
38
  } else if (const CXXRecordDecl *RD =
638
38
                 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
639
    // Build a DependentNameType that will perform lookup into RD at
640
    // instantiation time.
641
12
    NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
642
12
                                      RD->getTypeForDecl());
643
644
    // Diagnose that this identifier was undeclared, and retry the lookup during
645
    // template instantiation.
646
12
    Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
647
12
                                                                      << RD;
648
26
  } else {
649
    // This is not a situation that we should recover from.
650
26
    return ParsedType();
651
26
  }
652
653
15
  QualType T =
654
15
      Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
655
656
  // Build type location information.  We synthesized the qualifier, so we have
657
  // to build a fake NestedNameSpecifierLoc.
658
15
  NestedNameSpecifierLocBuilder NNSLocBuilder;
659
15
  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
660
15
  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
661
662
15
  TypeLocBuilder Builder;
663
15
  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
664
15
  DepTL.setNameLoc(NameLoc);
665
15
  DepTL.setElaboratedKeywordLoc(SourceLocation());
666
15
  DepTL.setQualifierLoc(QualifierLoc);
667
15
  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
668
41
}
669
670
/// isTagName() - This method is called *for error recovery purposes only*
671
/// to determine if the specified name is a valid tag name ("struct foo").  If
672
/// so, this returns the TST for the tag corresponding to it (TST_enum,
673
/// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
674
/// cases in C where the user forgot to specify the tag.
675
1.17k
DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
676
  // Do a tag name lookup in this scope.
677
1.17k
  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
678
1.17k
  LookupName(R, S, false);
679
1.17k
  R.suppressDiagnostics();
680
1.17k
  if (R.getResultKind() == LookupResult::Found)
681
74
    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
682
38
      switch (TD->getTagKind()) {
683
18
      case TagTypeKind::Struct:
684
18
        return DeclSpec::TST_struct;
685
0
      case TagTypeKind::Interface:
686
0
        return DeclSpec::TST_interface;
687
0
      case TagTypeKind::Union:
688
0
        return DeclSpec::TST_union;
689
9
      case TagTypeKind::Class:
690
9
        return DeclSpec::TST_class;
691
11
      case TagTypeKind::Enum:
692
11
        return DeclSpec::TST_enum;
693
38
      }
694
38
    }
695
696
1.13k
  return DeclSpec::TST_unspecified;
697
1.17k
}
698
699
/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
700
/// if a CXXScopeSpec's type is equal to the type of one of the base classes
701
/// then downgrade the missing typename error to a warning.
702
/// This is needed for MSVC compatibility; Example:
703
/// @code
704
/// template<class T> class A {
705
/// public:
706
///   typedef int TYPE;
707
/// };
708
/// template<class T> class B : public A<T> {
709
/// public:
710
///   A<T>::TYPE a; // no typename required because A<T> is a base class.
711
/// };
712
/// @endcode
713
12
bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
714
12
  if (CurContext->isRecord()) {
715
0
    if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
716
0
      return true;
717
718
0
    const Type *Ty = SS->getScopeRep()->getAsType();
719
720
0
    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
721
0
    for (const auto &Base : RD->bases())
722
0
      if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
723
0
        return true;
724
0
    return S->isFunctionPrototypeScope();
725
0
  }
726
12
  return CurContext->isFunctionOrMethod() || 
S->isFunctionPrototypeScope()5
;
727
12
}
728
729
void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
730
                                   SourceLocation IILoc,
731
                                   Scope *S,
732
                                   CXXScopeSpec *SS,
733
                                   ParsedType &SuggestedType,
734
1.35k
                                   bool IsTemplateName) {
735
  // Don't report typename errors for editor placeholders.
736
1.35k
  if (II->isEditorPlaceholder())
737
7
    return;
738
  // We don't have anything to suggest (yet).
739
1.34k
  SuggestedType = nullptr;
740
741
  // There may have been a typo in the name of the type. Look up typo
742
  // results, in case we have something that we can suggest.
743
1.34k
  TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
744
1.34k
                           /*AllowTemplates=*/IsTemplateName,
745
1.34k
                           /*AllowNonTemplates=*/!IsTemplateName);
746
1.34k
  if (TypoCorrection Corrected =
747
1.34k
          CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
748
1.34k
                      CCC, CTK_ErrorRecovery)) {
749
    // FIXME: Support error recovery for the template-name case.
750
193
    bool CanRecover = !IsTemplateName;
751
193
    if (Corrected.isKeyword()) {
752
      // We corrected to a keyword.
753
13
      diagnoseTypo(Corrected,
754
13
                   PDiag(IsTemplateName ? 
diag::err_no_template_suggest0
755
13
                                        : diag::err_unknown_typename_suggest)
756
13
                       << II);
757
13
      II = Corrected.getCorrectionAsIdentifierInfo();
758
180
    } else {
759
      // We found a similarly-named type or interface; suggest that.
760
180
      if (!SS || 
!SS->isSet()71
) {
761
109
        diagnoseTypo(Corrected,
762
109
                     PDiag(IsTemplateName ? 
diag::err_no_template_suggest2
763
109
                                          : 
diag::err_unknown_typename_suggest107
)
764
109
                         << II, CanRecover);
765
109
      } else 
if (DeclContext *71
DC71
= computeDeclContext(*SS, false)) {
766
71
        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
767
71
        bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
768
71
                                
II->getName().equals(CorrectedStr)43
;
769
71
        diagnoseTypo(Corrected,
770
71
                     PDiag(IsTemplateName
771
71
                               ? 
diag::err_no_member_template_suggest0
772
71
                               : diag::err_unknown_nested_typename_suggest)
773
71
                         << II << DC << DroppedSpecifier << SS->getRange(),
774
71
                     CanRecover);
775
71
      } else {
776
0
        llvm_unreachable("could not have corrected a typo here");
777
0
      }
778
779
180
      if (!CanRecover)
780
2
        return;
781
782
178
      CXXScopeSpec tmpSS;
783
178
      if (Corrected.getCorrectionSpecifier())
784
41
        tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
785
41
                          SourceRange(IILoc));
786
      // FIXME: Support class template argument deduction here.
787
178
      SuggestedType =
788
178
          getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
789
178
                      tmpSS.isSet() ? 
&tmpSS41
:
SS137
, false, false, nullptr,
790
178
                      /*IsCtorOrDtorName=*/false,
791
178
                      /*WantNontrivialTypeSourceInfo=*/true);
792
178
    }
793
191
    return;
794
193
  }
795
796
1.15k
  if (getLangOpts().CPlusPlus && 
!IsTemplateName750
) {
797
    // See if II is a class template that the user forgot to pass arguments to.
798
728
    UnqualifiedId Name;
799
728
    Name.setIdentifier(II, IILoc);
800
728
    CXXScopeSpec EmptySS;
801
728
    TemplateTy TemplateResult;
802
728
    bool MemberOfUnknownSpecialization;
803
728
    if (isTemplateName(S, SS ? 
*SS275
:
EmptySS453
, /*hasTemplateKeyword=*/false,
804
728
                       Name, nullptr, true, TemplateResult,
805
728
                       MemberOfUnknownSpecialization) == TNK_Type_template) {
806
39
      diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
807
39
      return;
808
39
    }
809
728
  }
810
811
  // FIXME: Should we move the logic that tries to recover from a missing tag
812
  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
813
814
1.11k
  if (!SS || 
(280
!SS->isSet()280
&&
!SS->isInvalid()151
))
815
831
    Diag(IILoc, IsTemplateName ? 
diag::err_no_template0
816
831
                               : diag::err_unknown_typename)
817
831
        << II;
818
280
  else if (DeclContext *DC = computeDeclContext(*SS, false))
819
63
    Diag(IILoc, IsTemplateName ? 
diag::err_no_member_template22
820
63
                               : 
diag::err_typename_nested_not_found41
)
821
63
        << II << DC << SS->getRange();
822
217
  else if (SS->isValid() && 
SS->getScopeRep()->containsErrors()66
) {
823
1
    SuggestedType =
824
1
        ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
825
216
  } else if (isDependentScopeSpecifier(*SS)) {
826
65
    unsigned DiagID = diag::err_typename_missing;
827
65
    if (getLangOpts().MSVCCompat && 
isMicrosoftMissingTypename(SS, S)12
)
828
12
      DiagID = diag::ext_typename_missing;
829
830
65
    Diag(SS->getRange().getBegin(), DiagID)
831
65
      << SS->getScopeRep() << II->getName()
832
65
      << SourceRange(SS->getRange().getBegin(), IILoc)
833
65
      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
834
65
    SuggestedType = ActOnTypenameType(S, SourceLocation(),
835
65
                                      *SS, *II, IILoc).get();
836
151
  } else {
837
151
    assert(SS && SS->isInvalid() &&
838
151
           "Invalid scope specifier has already been diagnosed");
839
151
  }
840
1.11k
}
841
842
/// Determine whether the given result set contains either a type name
843
/// or
844
4.65k
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
845
4.65k
  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
846
4.65k
                       
NextToken.is(tok::less)1.09k
;
847
848
7.38k
  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; 
++I2.73k
) {
849
3.85k
    if (isa<TypeDecl>(*I) || 
isa<ObjCInterfaceDecl>(*I)3.29k
)
850
1.11k
      return true;
851
852
2.73k
    if (CheckTemplate && 
isa<TemplateDecl>(*I)0
)
853
0
      return true;
854
2.73k
  }
855
856
3.53k
  return false;
857
4.65k
}
858
859
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
860
                                    Scope *S, CXXScopeSpec &SS,
861
                                    IdentifierInfo *&Name,
862
922
                                    SourceLocation NameLoc) {
863
922
  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
864
922
  SemaRef.LookupParsedName(R, S, &SS);
865
922
  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
866
37
    StringRef FixItTagName;
867
37
    switch (Tag->getTagKind()) {
868
13
    case TagTypeKind::Class:
869
13
      FixItTagName = "class ";
870
13
      break;
871
872
10
    case TagTypeKind::Enum:
873
10
      FixItTagName = "enum ";
874
10
      break;
875
876
14
    case TagTypeKind::Struct:
877
14
      FixItTagName = "struct ";
878
14
      break;
879
880
0
    case TagTypeKind::Interface:
881
0
      FixItTagName = "__interface ";
882
0
      break;
883
884
0
    case TagTypeKind::Union:
885
0
      FixItTagName = "union ";
886
0
      break;
887
37
    }
888
889
37
    StringRef TagName = FixItTagName.drop_back();
890
37
    SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
891
37
      << Name << TagName << SemaRef.getLangOpts().CPlusPlus
892
37
      << FixItHint::CreateInsertion(NameLoc, FixItTagName);
893
894
37
    for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
895
70
         I != IEnd; 
++I33
)
896
33
      SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
897
33
        << Name << TagName;
898
899
    // Replace lookup results with just the tag decl.
900
37
    Result.clear(Sema::LookupTagName);
901
37
    SemaRef.LookupParsedName(Result, S, &SS);
902
37
    return true;
903
37
  }
904
905
885
  return false;
906
922
}
907
908
Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
909
                                            IdentifierInfo *&Name,
910
                                            SourceLocation NameLoc,
911
                                            const Token &NextToken,
912
21.9M
                                            CorrectionCandidateCallback *CCC) {
913
21.9M
  DeclarationNameInfo NameInfo(Name, NameLoc);
914
21.9M
  ObjCMethodDecl *CurMethod = getCurMethodDecl();
915
916
21.9M
  assert(NextToken.isNot(tok::coloncolon) &&
917
21.9M
         "parse nested name specifiers before calling ClassifyName");
918
21.9M
  if (getLangOpts().CPlusPlus && 
SS.isSet()20.7M
&&
919
21.9M
      
isCurrentClassName(*Name, S, &SS)149k
) {
920
    // Per [class.qual]p2, this names the constructors of SS, not the
921
    // injected-class-name. We don't have a classification for that.
922
    // There's not much point caching this result, since the parser
923
    // will reject it later.
924
8
    return NameClassification::Unknown();
925
8
  }
926
927
21.9M
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
928
21.9M
  LookupParsedName(Result, S, &SS, !CurMethod);
929
930
21.9M
  if (SS.isInvalid())
931
8
    return NameClassification::Error();
932
933
  // For unqualified lookup in a class template in MSVC mode, look into
934
  // dependent base classes where the primary class template is known.
935
21.9M
  if (Result.empty() && 
SS.isEmpty()20.0k
&&
getLangOpts().MSVCCompat3.89k
) {
936
77
    if (ParsedType TypeInBase =
937
77
            recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
938
14
      return TypeInBase;
939
77
  }
940
941
  // Perform lookup for Objective-C instance variables (including automatically
942
  // synthesized instance variables), if we're in an Objective-C method.
943
  // FIXME: This lookup really, really needs to be folded in to the normal
944
  // unqualified lookup mechanism.
945
21.9M
  if (SS.isEmpty() && 
CurMethod21.7M
&&
!isResultTypeOrTemplate(Result, NextToken)4.65k
) {
946
3.53k
    DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
947
3.53k
    if (Ivar.isInvalid())
948
5
      return NameClassification::Error();
949
3.53k
    if (Ivar.isUsable())
950
797
      return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
951
952
    // We defer builtin creation until after ivar lookup inside ObjC methods.
953
2.73k
    if (Result.empty())
954
154
      LookupBuiltin(Result);
955
2.73k
  }
956
957
21.9M
  bool SecondTry = false;
958
21.9M
  bool IsFilteredTemplateName = false;
959
960
21.9M
Corrected:
961
21.9M
  switch (Result.getResultKind()) {
962
3.39k
  case LookupResult::NotFound:
963
    // If an unqualified-id is followed by a '(', then we have a function
964
    // call.
965
3.39k
    if (SS.isEmpty() && 
NextToken.is(tok::l_paren)3.23k
) {
966
      // In C++, this is an ADL-only call.
967
      // FIXME: Reference?
968
946
      if (getLangOpts().CPlusPlus)
969
679
        return NameClassification::UndeclaredNonType();
970
971
      // C90 6.3.2.2:
972
      //   If the expression that precedes the parenthesized argument list in a
973
      //   function call consists solely of an identifier, and if no
974
      //   declaration is visible for this identifier, the identifier is
975
      //   implicitly declared exactly as if, in the innermost block containing
976
      //   the function call, the declaration
977
      //
978
      //     extern int identifier ();
979
      //
980
      //   appeared.
981
      //
982
      // We also allow this in C99 as an extension. However, this is not
983
      // allowed in all language modes as functions without prototypes may not
984
      // be supported.
985
267
      if (getLangOpts().implicitFunctionsAllowed()) {
986
185
        if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
987
185
          return NameClassification::NonType(D);
988
185
      }
989
267
    }
990
991
2.52k
    if (getLangOpts().CPlusPlus20 && 
SS.isEmpty()171
&&
NextToken.is(tok::less)158
) {
992
      // In C++20 onwards, this could be an ADL-only call to a function
993
      // template, and we're required to assume that this is a template name.
994
      //
995
      // FIXME: Find a way to still do typo correction in this case.
996
2
      TemplateName Template =
997
2
          Context.getAssumedTemplateName(NameInfo.getName());
998
2
      return NameClassification::UndeclaredTemplate(Template);
999
2
    }
1000
1001
    // In C, we first see whether there is a tag type by the same name, in
1002
    // which case it's likely that the user just forgot to write "enum",
1003
    // "struct", or "union".
1004
2.52k
    if (!getLangOpts().CPlusPlus && 
!SecondTry696
&&
1005
2.52k
        
isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)696
) {
1006
4
      break;
1007
4
    }
1008
1009
    // Perform typo correction to determine if there is another name that is
1010
    // close to this name.
1011
2.52k
    if (!SecondTry && CCC) {
1012
2.36k
      SecondTry = true;
1013
2.36k
      if (TypoCorrection Corrected =
1014
2.36k
              CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1015
2.36k
                          &SS, *CCC, CTK_ErrorRecovery)) {
1016
105
        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1017
105
        unsigned QualifiedDiag = diag::err_no_member_suggest;
1018
1019
105
        NamedDecl *FirstDecl = Corrected.getFoundDecl();
1020
105
        NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1021
105
        if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)81
&&
1022
105
            
UnderlyingFirstDecl0
&&
isa<TemplateDecl>(UnderlyingFirstDecl)0
) {
1023
0
          UnqualifiedDiag = diag::err_no_template_suggest;
1024
0
          QualifiedDiag = diag::err_no_member_template_suggest;
1025
105
        } else if (UnderlyingFirstDecl &&
1026
105
                   
(85
isa<TypeDecl>(UnderlyingFirstDecl)85
||
1027
85
                    
isa<ObjCInterfaceDecl>(UnderlyingFirstDecl)56
||
1028
85
                    
isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl)54
)) {
1029
31
          UnqualifiedDiag = diag::err_unknown_typename_suggest;
1030
31
          QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1031
31
        }
1032
1033
105
        if (SS.isEmpty()) {
1034
105
          diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1035
105
        } else {// FIXME: is this even reachable? Test it.
1036
0
          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1037
0
          bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1038
0
                                  Name->getName().equals(CorrectedStr);
1039
0
          diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1040
0
                                    << Name << computeDeclContext(SS, false)
1041
0
                                    << DroppedSpecifier << SS.getRange());
1042
0
        }
1043
1044
        // Update the name, so that the caller has the new name.
1045
105
        Name = Corrected.getCorrectionAsIdentifierInfo();
1046
1047
        // Typo correction corrected to a keyword.
1048
105
        if (Corrected.isKeyword())
1049
20
          return Name;
1050
1051
        // Also update the LookupResult...
1052
        // FIXME: This should probably go away at some point
1053
85
        Result.clear();
1054
85
        Result.setLookupName(Corrected.getCorrection());
1055
85
        if (FirstDecl)
1056
85
          Result.addDecl(FirstDecl);
1057
1058
        // If we found an Objective-C instance variable, let
1059
        // LookupInObjCMethod build the appropriate expression to
1060
        // reference the ivar.
1061
        // FIXME: This is a gross hack.
1062
85
        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1063
5
          DeclResult R =
1064
5
              LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1065
5
          if (R.isInvalid())
1066
0
            return NameClassification::Error();
1067
5
          if (R.isUsable())
1068
5
            return NameClassification::NonType(Ivar);
1069
5
        }
1070
1071
80
        goto Corrected;
1072
85
      }
1073
2.36k
    }
1074
1075
    // We failed to correct; just fall through and let the parser deal with it.
1076
2.41k
    Result.suppressDiagnostics();
1077
2.41k
    return NameClassification::Unknown();
1078
1079
15.9k
  case LookupResult::NotFoundInCurrentInstantiation: {
1080
    // We performed name lookup into the current instantiation, and there were
1081
    // dependent bases, so we treat this result the same way as any other
1082
    // dependent nested-name-specifier.
1083
1084
    // C++ [temp.res]p2:
1085
    //   A name used in a template declaration or definition and that is
1086
    //   dependent on a template-parameter is assumed not to name a type
1087
    //   unless the applicable name lookup finds a type name or the name is
1088
    //   qualified by the keyword typename.
1089
    //
1090
    // FIXME: If the next token is '<', we might want to ask the parser to
1091
    // perform some heroics to see if we actually have a
1092
    // template-argument-list, which would indicate a missing 'template'
1093
    // keyword here.
1094
15.9k
    return NameClassification::DependentNonType();
1095
2.52k
  }
1096
1097
21.6M
  case LookupResult::Found:
1098
21.9M
  case LookupResult::FoundOverloaded:
1099
21.9M
  case LookupResult::FoundUnresolvedValue:
1100
21.9M
    break;
1101
1102
51
  case LookupResult::Ambiguous:
1103
51
    if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)48
&&
1104
51
        hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1105
0
                                      /*AllowDependent=*/false)) {
1106
      // C++ [temp.local]p3:
1107
      //   A lookup that finds an injected-class-name (10.2) can result in an
1108
      //   ambiguity in certain cases (for example, if it is found in more than
1109
      //   one base class). If all of the injected-class-names that are found
1110
      //   refer to specializations of the same class template, and if the name
1111
      //   is followed by a template-argument-list, the reference refers to the
1112
      //   class template itself and not a specialization thereof, and is not
1113
      //   ambiguous.
1114
      //
1115
      // This filtering can make an ambiguous result into an unambiguous one,
1116
      // so try again after filtering out template names.
1117
0
      FilterAcceptableTemplateNames(Result);
1118
0
      if (!Result.isAmbiguous()) {
1119
0
        IsFilteredTemplateName = true;
1120
0
        break;
1121
0
      }
1122
0
    }
1123
1124
    // Diagnose the ambiguity and return an error.
1125
51
    return NameClassification::Error();
1126
21.9M
  }
1127
1128
21.9M
  if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)20.7M
&&
1129
21.9M
      
(146
IsFilteredTemplateName146
||
1130
146
       hasAnyAcceptableTemplateNames(
1131
146
           Result, /*AllowFunctionTemplates=*/true,
1132
146
           /*AllowDependent=*/false,
1133
146
           /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1134
146
               
getLangOpts().CPlusPlus20125
))) {
1135
    // C++ [temp.names]p3:
1136
    //   After name lookup (3.4) finds that a name is a template-name or that
1137
    //   an operator-function-id or a literal- operator-id refers to a set of
1138
    //   overloaded functions any member of which is a function template if
1139
    //   this is followed by a <, the < is always taken as the delimiter of a
1140
    //   template-argument-list and never as the less-than operator.
1141
    // C++2a [temp.names]p2:
1142
    //   A name is also considered to refer to a template if it is an
1143
    //   unqualified-id followed by a < and name lookup finds either one
1144
    //   or more functions or finds nothing.
1145
1
    if (!IsFilteredTemplateName)
1146
1
      FilterAcceptableTemplateNames(Result);
1147
1148
1
    bool IsFunctionTemplate;
1149
1
    bool IsVarTemplate;
1150
1
    TemplateName Template;
1151
1
    if (Result.end() - Result.begin() > 1) {
1152
0
      IsFunctionTemplate = true;
1153
0
      Template = Context.getOverloadedTemplateName(Result.begin(),
1154
0
                                                   Result.end());
1155
1
    } else if (!Result.empty()) {
1156
1
      auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1157
1
          *Result.begin(), /*AllowFunctionTemplates=*/true,
1158
1
          /*AllowDependent=*/false));
1159
1
      IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1160
1
      IsVarTemplate = isa<VarTemplateDecl>(TD);
1161
1162
1
      UsingShadowDecl *FoundUsingShadow =
1163
1
          dyn_cast<UsingShadowDecl>(*Result.begin());
1164
1
      assert(!FoundUsingShadow ||
1165
1
             TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1166
1
      Template =
1167
1
          FoundUsingShadow ? 
TemplateName(FoundUsingShadow)0
: TemplateName(TD);
1168
1
      if (SS.isNotEmpty())
1169
0
        Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1170
0
                                                    /*TemplateKeyword=*/false,
1171
0
                                                    Template);
1172
1
    } else {
1173
      // All results were non-template functions. This is a function template
1174
      // name.
1175
0
      IsFunctionTemplate = true;
1176
0
      Template = Context.getAssumedTemplateName(NameInfo.getName());
1177
0
    }
1178
1179
1
    if (IsFunctionTemplate) {
1180
      // Function templates always go through overload resolution, at which
1181
      // point we'll perform the various checks (e.g., accessibility) we need
1182
      // to based on which function we selected.
1183
0
      Result.suppressDiagnostics();
1184
1185
0
      return NameClassification::FunctionTemplate(Template);
1186
0
    }
1187
1188
1
    return IsVarTemplate ? NameClassification::VarTemplate(Template)
1189
1
                         : 
NameClassification::TypeTemplate(Template)0
;
1190
1
  }
1191
1192
21.9M
  auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1193
18.1M
    QualType T = Context.getTypeDeclType(Type);
1194
18.1M
    if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1195
99.0k
      T = Context.getUsingType(USD, T);
1196
18.1M
    return buildNamedType(*this, &SS, T, NameLoc);
1197
18.1M
  };
1198
1199
21.9M
  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1200
21.9M
  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1201
18.1M
    DiagnoseUseOfDecl(Type, NameLoc);
1202
18.1M
    MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1203
18.1M
    return BuildTypeFor(Type, *Result.begin());
1204
18.1M
  }
1205
1206
3.70M
  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1207
3.70M
  if (!Class) {
1208
    // FIXME: It's unfortunate that we don't have a Type node for handling this.
1209
3.69M
    if (ObjCCompatibleAliasDecl *Alias =
1210
3.69M
            dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1211
0
      Class = Alias->getClassInterface();
1212
3.69M
  }
1213
1214
3.70M
  if (Class) {
1215
8.57k
    DiagnoseUseOfDecl(Class, NameLoc);
1216
1217
8.57k
    if (NextToken.is(tok::period)) {
1218
      // Interface. <something> is parsed as a property reference expression.
1219
      // Just return "unknown" as a fall-through for now.
1220
62
      Result.suppressDiagnostics();
1221
62
      return NameClassification::Unknown();
1222
62
    }
1223
1224
8.51k
    QualType T = Context.getObjCInterfaceType(Class);
1225
8.51k
    return ParsedType::make(T);
1226
8.57k
  }
1227
1228
3.69M
  if (isa<ConceptDecl>(FirstDecl))
1229
72
    return NameClassification::Concept(
1230
72
        TemplateName(cast<TemplateDecl>(FirstDecl)));
1231
1232
3.69M
  if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1233
2
    (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1234
2
    return NameClassification::Error();
1235
2
  }
1236
1237
  // We can have a type template here if we're classifying a template argument.
1238
3.69M
  if (isa<TemplateDecl>(FirstDecl) && 
!isa<FunctionTemplateDecl>(FirstDecl)170k
&&
1239
3.69M
      
!isa<VarTemplateDecl>(FirstDecl)13.8k
)
1240
13.8k
    return NameClassification::TypeTemplate(
1241
13.8k
        TemplateName(cast<TemplateDecl>(FirstDecl)));
1242
1243
  // Check for a tag type hidden by a non-type decl in a few cases where it
1244
  // seems likely a type is wanted instead of the non-type that was found.
1245
3.68M
  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1246
3.68M
  if ((NextToken.is(tok::identifier) ||
1247
3.68M
       
(3.68M
NextIsOp3.68M
&&
1248
3.68M
        
FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate()27.4k
)) &&
1249
3.68M
      
isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)226
) {
1250
33
    TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1251
33
    DiagnoseUseOfDecl(Type, NameLoc);
1252
33
    return BuildTypeFor(Type, *Result.begin());
1253
33
  }
1254
1255
  // If we already know which single declaration is referenced, just annotate
1256
  // that declaration directly. Defer resolving even non-overloaded class
1257
  // member accesses, as we need to defer certain access checks until we know
1258
  // the context.
1259
3.68M
  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1260
3.68M
  if (Result.isSingleResult() && 
!ADL3.43M
&&
1261
3.68M
      
(3.14M
!FirstDecl->isCXXClassMember()3.14M
||
isa<EnumConstantDecl>(FirstDecl)520k
))
1262
2.62M
    return NameClassification::NonType(Result.getRepresentativeDecl());
1263
1264
  // Otherwise, this is an overload set that we will need to resolve later.
1265
1.05M
  Result.suppressDiagnostics();
1266
1.05M
  return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1267
1.05M
      Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1268
1.05M
      Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1269
1.05M
      Result.begin(), Result.end()));
1270
3.68M
}
1271
1272
ExprResult
1273
Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1274
679
                                             SourceLocation NameLoc) {
1275
679
  assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1276
679
  CXXScopeSpec SS;
1277
679
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1278
679
  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1279
679
}
1280
1281
ExprResult
1282
Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1283
                                            IdentifierInfo *Name,
1284
                                            SourceLocation NameLoc,
1285
15.9k
                                            bool IsAddressOfOperand) {
1286
15.9k
  DeclarationNameInfo NameInfo(Name, NameLoc);
1287
15.9k
  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1288
15.9k
                                    NameInfo, IsAddressOfOperand,
1289
15.9k
                                    /*TemplateArgs=*/nullptr);
1290
15.9k
}
1291
1292
ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1293
                                              NamedDecl *Found,
1294
                                              SourceLocation NameLoc,
1295
2.62M
                                              const Token &NextToken) {
1296
2.62M
  if (getCurMethodDecl() && 
SS.isEmpty()3.22k
)
1297
3.22k
    if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1298
802
      return BuildIvarRefExpr(S, NameLoc, Ivar);
1299
1300
  // Reconstruct the lookup result.
1301
2.62M
  LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1302
2.62M
  Result.addDecl(Found);
1303
2.62M
  Result.resolveKind();
1304
1305
2.62M
  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1306
2.62M
  return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1307
2.62M
}
1308
1309
1.05M
ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1310
  // For an implicit class member access, transform the result into a member
1311
  // access expression if necessary.
1312
1.05M
  auto *ULE = cast<UnresolvedLookupExpr>(E);
1313
1.05M
  if ((*ULE->decls_begin())->isCXXClassMember()) {
1314
625k
    CXXScopeSpec SS;
1315
625k
    SS.Adopt(ULE->getQualifierLoc());
1316
1317
    // Reconstruct the lookup result.
1318
625k
    LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1319
625k
                        LookupOrdinaryName);
1320
625k
    Result.setNamingClass(ULE->getNamingClass());
1321
1.45M
    for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; 
++I833k
)
1322
833k
      Result.addDecl(*I, I.getAccess());
1323
625k
    Result.resolveKind();
1324
625k
    return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1325
625k
                                           nullptr, S);
1326
625k
  }
1327
1328
  // Otherwise, this is already in the form we needed, and no further checks
1329
  // are necessary.
1330
432k
  return ULE;
1331
1.05M
}
1332
1333
Sema::TemplateNameKindForDiagnostics
1334
1.92k
Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1335
1.92k
  auto *TD = Name.getAsTemplateDecl();
1336
1.92k
  if (!TD)
1337
160
    return TemplateNameKindForDiagnostics::DependentTemplate;
1338
1.76k
  if (isa<ClassTemplateDecl>(TD))
1339
284
    return TemplateNameKindForDiagnostics::ClassTemplate;
1340
1.48k
  if (isa<FunctionTemplateDecl>(TD))
1341
1.40k
    return TemplateNameKindForDiagnostics::FunctionTemplate;
1342
77
  if (isa<VarTemplateDecl>(TD))
1343
27
    return TemplateNameKindForDiagnostics::VarTemplate;
1344
50
  if (isa<TypeAliasTemplateDecl>(TD))
1345
31
    return TemplateNameKindForDiagnostics::AliasTemplate;
1346
19
  if (isa<TemplateTemplateParmDecl>(TD))
1347
15
    return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1348
4
  if (isa<ConceptDecl>(TD))
1349
4
    return TemplateNameKindForDiagnostics::Concept;
1350
0
  return TemplateNameKindForDiagnostics::DependentTemplate;
1351
4
}
1352
1353
8.83M
void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1354
8.83M
  assert(DC->getLexicalParent() == CurContext &&
1355
8.83M
      "The next DeclContext should be lexically contained in the current one.");
1356
8.83M
  CurContext = DC;
1357
8.83M
  S->setEntity(DC);
1358
8.83M
}
1359
1360
10.8M
void Sema::PopDeclContext() {
1361
10.8M
  assert(CurContext && "DeclContext imbalance!");
1362
1363
10.8M
  CurContext = CurContext->getLexicalParent();
1364
10.8M
  assert(CurContext && "Popped translation unit!");
1365
10.8M
}
1366
1367
Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1368
47
                                                                    Decl *D) {
1369
  // Unlike PushDeclContext, the context to which we return is not necessarily
1370
  // the containing DC of TD, because the new context will be some pre-existing
1371
  // TagDecl definition instead of a fresh one.
1372
47
  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1373
47
  CurContext = cast<TagDecl>(D)->getDefinition();
1374
47
  assert(CurContext && "skipping definition of undefined tag");
1375
  // Start lookups from the parent of the current context; we don't want to look
1376
  // into the pre-existing complete definition.
1377
47
  S->setEntity(CurContext->getLookupParent());
1378
47
  return Result;
1379
47
}
1380
1381
47
void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1382
47
  CurContext = static_cast<decltype(CurContext)>(Context);
1383
47
}
1384
1385
/// EnterDeclaratorContext - Used when we must lookup names in the context
1386
/// of a declarator's nested name specifier.
1387
///
1388
423k
void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1389
  // C++0x [basic.lookup.unqual]p13:
1390
  //   A name used in the definition of a static data member of class
1391
  //   X (after the qualified-id of the static member) is looked up as
1392
  //   if the name was used in a member function of X.
1393
  // C++0x [basic.lookup.unqual]p14:
1394
  //   If a variable member of a namespace is defined outside of the
1395
  //   scope of its namespace then any name used in the definition of
1396
  //   the variable member (after the declarator-id) is looked up as
1397
  //   if the definition of the variable member occurred in its
1398
  //   namespace.
1399
  // Both of these imply that we should push a scope whose context
1400
  // is the semantic context of the declaration.  We can't use
1401
  // PushDeclContext here because that context is not necessarily
1402
  // lexically contained in the current context.  Fortunately,
1403
  // the containing scope should have the appropriate information.
1404
1405
423k
  assert(!S->getEntity() && "scope already has entity");
1406
1407
423k
#ifndef NDEBUG
1408
423k
  Scope *Ancestor = S->getParent();
1409
813k
  while (!Ancestor->getEntity()) 
Ancestor = Ancestor->getParent()389k
;
1410
423k
  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1411
423k
#endif
1412
1413
423k
  CurContext = DC;
1414
423k
  S->setEntity(DC);
1415
1416
423k
  if (S->getParent()->isTemplateParamScope()) {
1417
    // Also set the corresponding entities for all immediately-enclosing
1418
    // template parameter scopes.
1419
333k
    EnterTemplatedContext(S->getParent(), DC);
1420
333k
  }
1421
423k
}
1422
1423
423k
void Sema::ExitDeclaratorContext(Scope *S) {
1424
423k
  assert(S->getEntity() == CurContext && "Context imbalance!");
1425
1426
  // Switch back to the lexical context.  The safety of this is
1427
  // enforced by an assert in EnterDeclaratorContext.
1428
423k
  Scope *Ancestor = S->getParent();
1429
813k
  while (!Ancestor->getEntity()) 
Ancestor = Ancestor->getParent()389k
;
1430
423k
  CurContext = Ancestor->getEntity();
1431
1432
  // We don't need to do anything with the scope, which is going to
1433
  // disappear.
1434
423k
}
1435
1436
529k
void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1437
529k
  assert(S->isTemplateParamScope() &&
1438
529k
         "expected to be initializing a template parameter scope");
1439
1440
  // C++20 [temp.local]p7:
1441
  //   In the definition of a member of a class template that appears outside
1442
  //   of the class template definition, the name of a member of the class
1443
  //   template hides the name of a template-parameter of any enclosing class
1444
  //   templates (but not a template-parameter of the member if the member is a
1445
  //   class or function template).
1446
  // C++20 [temp.local]p9:
1447
  //   In the definition of a class template or in the definition of a member
1448
  //   of such a template that appears outside of the template definition, for
1449
  //   each non-dependent base class (13.8.2.1), if the name of the base class
1450
  //   or the name of a member of the base class is the same as the name of a
1451
  //   template-parameter, the base class name or member name hides the
1452
  //   template-parameter name (6.4.10).
1453
  //
1454
  // This means that a template parameter scope should be searched immediately
1455
  // after searching the DeclContext for which it is a template parameter
1456
  // scope. For example, for
1457
  //   template<typename T> template<typename U> template<typename V>
1458
  //     void N::A<T>::B<U>::f(...)
1459
  // we search V then B<U> (and base classes) then U then A<T> (and base
1460
  // classes) then T then N then ::.
1461
529k
  unsigned ScopeDepth = getTemplateDepth(S);
1462
1.11M
  for (; S && S->isTemplateParamScope(); 
S = S->getParent(), --ScopeDepth585k
) {
1463
585k
    DeclContext *SearchDCAfterScope = DC;
1464
613k
    for (; DC; 
DC = DC->getLookupParent()27.4k
) {
1465
606k
      if (const TemplateParameterList *TPL =
1466
606k
              cast<Decl>(DC)->getDescribedTemplateParams()) {
1467
579k
        unsigned DCDepth = TPL->getDepth() + 1;
1468
579k
        if (DCDepth > ScopeDepth)
1469
0
          continue;
1470
579k
        if (ScopeDepth == DCDepth)
1471
523k
          SearchDCAfterScope = DC = DC->getLookupParent();
1472
579k
        break;
1473
579k
      }
1474
606k
    }
1475
585k
    S->setLookupEntity(SearchDCAfterScope);
1476
585k
  }
1477
529k
}
1478
1479
9.02k
void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1480
  // We assume that the caller has already called
1481
  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1482
9.02k
  FunctionDecl *FD = D->getAsFunction();
1483
9.02k
  if (!FD)
1484
0
    return;
1485
1486
  // Same implementation as PushDeclContext, but enters the context
1487
  // from the lexical parent, rather than the top-level class.
1488
9.02k
  assert(CurContext == FD->getLexicalParent() &&
1489
9.02k
    "The next DeclContext should be lexically contained in the current one.");
1490
9.02k
  CurContext = FD;
1491
9.02k
  S->setEntity(CurContext);
1492
1493
22.2k
  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; 
++P13.2k
) {
1494
13.2k
    ParmVarDecl *Param = FD->getParamDecl(P);
1495
    // If the parameter has an identifier, then add it to the scope
1496
13.2k
    if (Param->getIdentifier()) {
1497
13.1k
      S->AddDecl(Param);
1498
13.1k
      IdResolver.AddDecl(Param);
1499
13.1k
    }
1500
13.2k
  }
1501
9.02k
}
1502
1503
9.02k
void Sema::ActOnExitFunctionContext() {
1504
  // Same implementation as PopDeclContext, but returns to the lexical parent,
1505
  // rather than the top-level class.
1506
9.02k
  assert(CurContext && "DeclContext imbalance!");
1507
9.02k
  CurContext = CurContext->getLexicalParent();
1508
9.02k
  assert(CurContext && "Popped translation unit!");
1509
9.02k
}
1510
1511
/// Determine whether overloading is allowed for a new function
1512
/// declaration considering prior declarations of the same name.
1513
///
1514
/// This routine determines whether overloading is possible, not
1515
/// whether a new declaration actually overloads a previous one.
1516
/// It will return true in C++ (where overloads are alway permitted)
1517
/// or, as a C extension, when either the new declaration or a
1518
/// previous one is declared with the 'overloadable' attribute.
1519
static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1520
                                       ASTContext &Context,
1521
15.2M
                                       const FunctionDecl *New) {
1522
15.2M
  if (Context.getLangOpts().CPlusPlus || 
New->hasAttr<OverloadableAttr>()7.59M
)
1523
15.1M
    return true;
1524
1525
  // Multiversion function declarations are not overloads in the
1526
  // usual sense of that term, but lookup will report that an
1527
  // overload set was found if more than one multiversion function
1528
  // declaration is present for the same name. It is therefore
1529
  // inadequate to assume that some prior declaration(s) had
1530
  // the overloadable attribute; checking is required. Since one
1531
  // declaration is permitted to omit the attribute, it is necessary
1532
  // to check at least two; hence the 'any_of' check below. Note that
1533
  // the overloadable attribute is implicitly added to declarations
1534
  // that were required to have it but did not.
1535
82.3k
  if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1536
4.25k
    return llvm::any_of(Previous, [](const NamedDecl *ND) {
1537
4.25k
      return ND->hasAttr<OverloadableAttr>();
1538
4.25k
    });
1539
81.9k
  } else if (Previous.getResultKind() == LookupResult::Found)
1540
81.9k
    return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1541
1542
2
  return false;
1543
82.3k
}
1544
1545
/// Add this decl to the scope shadowed decl chains.
1546
64.7M
void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1547
  // Move up the scope chain until we find the nearest enclosing
1548
  // non-transparent context. The declaration will be introduced into this
1549
  // scope.
1550
78.2M
  while (S->getEntity() && 
S->getEntity()->isTransparentContext()77.7M
)
1551
13.5M
    S = S->getParent();
1552
1553
  // Add scoped declarations into their context, so that they can be
1554
  // found later. Declarations without a context won't be inserted
1555
  // into any context.
1556
64.7M
  if (AddToContext)
1557
64.3M
    CurContext->addDecl(D);
1558
1559
  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1560
  // are function-local declarations.
1561
64.7M
  if (getLangOpts().CPlusPlus && 
D->isOutOfLine()29.0M
&&
!S->getFnParent()357k
)
1562
356k
    return;
1563
1564
  // Template instantiations should also not be pushed into scope.
1565
64.3M
  if (isa<FunctionDecl>(D) &&
1566
64.3M
      
cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()37.6M
)
1567
2.70k
    return;
1568
1569
  // If this replaces anything in the current scope,
1570
64.3M
  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1571
64.3M
                               IEnd = IdResolver.end();
1572
183M
  for (; I != IEnd; 
++I118M
) {
1573
119M
    if (S->isDeclScope(*I) && 
D->declarationReplaces(*I)116M
) {
1574
653k
      S->RemoveDecl(*I);
1575
653k
      IdResolver.RemoveDecl(*I);
1576
1577
      // Should only need to replace one decl.
1578
653k
      break;
1579
653k
    }
1580
119M
  }
1581
1582
64.3M
  S->AddDecl(D);
1583
1584
64.3M
  if (isa<LabelDecl>(D) && 
!cast<LabelDecl>(D)->isGnuLocal()3.76k
) {
1585
    // Implicitly-generated labels may end up getting generated in an order that
1586
    // isn't strictly lexical, which breaks name lookup. Be careful to insert
1587
    // the label at the appropriate place in the identifier chain.
1588
3.76k
    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; 
++I17
) {
1589
366
      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1590
366
      if (IDC == CurContext) {
1591
17
        if (!S->isDeclScope(*I))
1592
3
          continue;
1593
349
      } else if (IDC->Encloses(CurContext))
1594
349
        break;
1595
366
    }
1596
1597
3.75k
    IdResolver.InsertDeclAfter(I, D);
1598
64.3M
  } else {
1599
64.3M
    IdResolver.AddDecl(D);
1600
64.3M
  }
1601
64.3M
  warnOnReservedIdentifier(D);
1602
64.3M
}
1603
1604
bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1605
118M
                         bool AllowInlineNamespace) const {
1606
118M
  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1607
118M
}
1608
1609
51.3k
Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1610
51.3k
  DeclContext *TargetDC = DC->getPrimaryContext();
1611
153k
  do {
1612
153k
    if (DeclContext *ScopeDC = S->getEntity())
1613
105k
      if (ScopeDC->getPrimaryContext() == TargetDC)
1614
50.5k
        return S;
1615
153k
  } while (
(S = S->getParent())102k
);
1616
1617
847
  return nullptr;
1618
51.3k
}
1619
1620
static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1621
                                            DeclContext*,
1622
                                            ASTContext&);
1623
1624
/// Filters out lookup results that don't fall within the given scope
1625
/// as determined by isDeclInScope.
1626
void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1627
                                bool ConsiderLinkage,
1628
42.1M
                                bool AllowInlineNamespace) {
1629
42.1M
  LookupResult::Filter F = R.makeFilter();
1630
160M
  while (F.hasNext()) {
1631
118M
    NamedDecl *D = F.next();
1632
1633
118M
    if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1634
117M
      continue;
1635
1636
639k
    if (ConsiderLinkage && 
isOutOfScopePreviousDeclaration(D, Ctx, Context)1.69k
)
1637
586
      continue;
1638
1639
638k
    F.erase();
1640
638k
  }
1641
1642
42.1M
  F.done();
1643
42.1M
}
1644
1645
/// We've determined that \p New is a redeclaration of \p Old. Check that they
1646
/// have compatible owning modules.
1647
646k
bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1648
  // [module.interface]p7:
1649
  // A declaration is attached to a module as follows:
1650
  // - If the declaration is a non-dependent friend declaration that nominates a
1651
  // function with a declarator-id that is a qualified-id or template-id or that
1652
  // nominates a class other than with an elaborated-type-specifier with neither
1653
  // a nested-name-specifier nor a simple-template-id, it is attached to the
1654
  // module to which the friend is attached ([basic.link]).
1655
646k
  if (New->getFriendObjectKind() &&
1656
646k
      
Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()34.0k
) {
1657
0
    New->setLocalOwningModule(Old->getOwningModule());
1658
0
    makeMergedDefinitionVisible(New);
1659
0
    return false;
1660
0
  }
1661
1662
646k
  Module *NewM = New->getOwningModule();
1663
646k
  Module *OldM = Old->getOwningModule();
1664
1665
646k
  if (NewM && 
NewM->isPrivateModule()13.9k
)
1666
14
    NewM = NewM->Parent;
1667
646k
  if (OldM && 
OldM->isPrivateModule()14.3k
)
1668
0
    OldM = OldM->Parent;
1669
1670
646k
  if (NewM == OldM)
1671
642k
    return false;
1672
1673
3.99k
  if (NewM && 
OldM3.57k
) {
1674
    // A module implementation unit has visibility of the decls in its
1675
    // implicitly imported interface.
1676
3.56k
    if (NewM->isModuleImplementation() && 
OldM == ThePrimaryInterface32
)
1677
9
      return false;
1678
1679
    // Partitions are part of the module, but a partition could import another
1680
    // module, so verify that the PMIs agree.
1681
3.55k
    if ((NewM->isModulePartition() || 
OldM->isModulePartition()3.54k
) &&
1682
3.55k
        NewM->getPrimaryModuleInterfaceName() ==
1683
10
            OldM->getPrimaryModuleInterfaceName())
1684
6
      return false;
1685
3.55k
  }
1686
1687
3.97k
  bool NewIsModuleInterface = NewM && 
NewM->isNamedModule()3.55k
;
1688
3.97k
  bool OldIsModuleInterface = OldM && 
OldM->isNamedModule()3.97k
;
1689
3.97k
  if (NewIsModuleInterface || 
OldIsModuleInterface3.91k
) {
1690
    // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1691
    //   if a declaration of D [...] appears in the purview of a module, all
1692
    //   other such declarations shall appear in the purview of the same module
1693
76
    Diag(New->getLocation(), diag::err_mismatched_owning_module)
1694
76
      << New
1695
76
      << NewIsModuleInterface
1696
76
      << (NewIsModuleInterface ? 
NewM->getFullModuleName()62
:
""14
)
1697
76
      << OldIsModuleInterface
1698
76
      << (OldIsModuleInterface ? 
OldM->getFullModuleName()42
:
""34
);
1699
76
    Diag(Old->getLocation(), diag::note_previous_declaration);
1700
76
    New->setInvalidDecl();
1701
76
    return true;
1702
76
  }
1703
1704
3.90k
  return false;
1705
3.97k
}
1706
1707
// [module.interface]p6:
1708
// A redeclaration of an entity X is implicitly exported if X was introduced by
1709
// an exported declaration; otherwise it shall not be exported.
1710
646k
bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1711
  // [module.interface]p1:
1712
  // An export-declaration shall inhabit a namespace scope.
1713
  //
1714
  // So it is meaningless to talk about redeclaration which is not at namespace
1715
  // scope.
1716
646k
  if (!New->getLexicalDeclContext()
1717
646k
           ->getNonTransparentContext()
1718
646k
           ->isFileContext() ||
1719
646k
      !Old->getLexicalDeclContext()
1720
610k
           ->getNonTransparentContext()
1721
610k
           ->isFileContext())
1722
381k
    return false;
1723
1724
265k
  bool IsNewExported = New->isInExportDeclContext();
1725
265k
  bool IsOldExported = Old->isInExportDeclContext();
1726
1727
  // It should be irrevelant if both of them are not exported.
1728
265k
  if (!IsNewExported && 
!IsOldExported265k
)
1729
265k
    return false;
1730
1731
41
  if (IsOldExported)
1732
22
    return false;
1733
1734
19
  assert(IsNewExported);
1735
1736
19
  auto Lk = Old->getFormalLinkage();
1737
19
  int S = 0;
1738
19
  if (Lk == Linkage::Internal)
1739
2
    S = 1;
1740
17
  else if (Lk == Linkage::Module)
1741
17
    S = 2;
1742
19
  Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1743
19
  Diag(Old->getLocation(), diag::note_previous_declaration);
1744
19
  return true;
1745
19
}
1746
1747
// A wrapper function for checking the semantic restrictions of
1748
// a redeclaration within a module.
1749
646k
bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1750
646k
  if (CheckRedeclarationModuleOwnership(New, Old))
1751
76
    return true;
1752
1753
646k
  if (CheckRedeclarationExported(New, Old))
1754
19
    return true;
1755
1756
646k
  return false;
1757
646k
}
1758
1759
// Check the redefinition in C++20 Modules.
1760
//
1761
// [basic.def.odr]p14:
1762
// For any definable item D with definitions in multiple translation units,
1763
// - if D is a non-inline non-templated function or variable, or
1764
// - if the definitions in different translation units do not satisfy the
1765
// following requirements,
1766
//   the program is ill-formed; a diagnostic is required only if the definable
1767
//   item is attached to a named module and a prior definition is reachable at
1768
//   the point where a later definition occurs.
1769
// - Each such definition shall not be attached to a named module
1770
// ([module.unit]).
1771
// - Each such definition shall consist of the same sequence of tokens, ...
1772
// ...
1773
//
1774
// Return true if the redefinition is not allowed. Return false otherwise.
1775
bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1776
8
                                     const NamedDecl *Old) const {
1777
8
  assert(getASTContext().isSameEntity(New, Old) &&
1778
8
         "New and Old are not the same definition, we should diagnostic it "
1779
8
         "immediately instead of checking it.");
1780
8
  assert(const_cast<Sema *>(this)->isReachable(New) &&
1781
8
         const_cast<Sema *>(this)->isReachable(Old) &&
1782
8
         "We shouldn't see unreachable definitions here.");
1783
1784
8
  Module *NewM = New->getOwningModule();
1785
8
  Module *OldM = Old->getOwningModule();
1786
1787
  // We only checks for named modules here. The header like modules is skipped.
1788
  // FIXME: This is not right if we import the header like modules in the module
1789
  // purview.
1790
  //
1791
  // For example, assuming "header.h" provides definition for `D`.
1792
  // ```C++
1793
  // //--- M.cppm
1794
  // export module M;
1795
  // import "header.h"; // or #include "header.h" but import it by clang modules
1796
  // actually.
1797
  //
1798
  // //--- Use.cpp
1799
  // import M;
1800
  // import "header.h"; // or uses clang modules.
1801
  // ```
1802
  //
1803
  // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1804
  // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1805
  // reject it. But the current implementation couldn't detect the case since we
1806
  // don't record the information about the importee modules.
1807
  //
1808
  // But this might not be painful in practice. Since the design of C++20 Named
1809
  // Modules suggests us to use headers in global module fragment instead of
1810
  // module purview.
1811
8
  if (NewM && 
NewM->isHeaderLikeModule()4
)
1812
1
    NewM = nullptr;
1813
8
  if (OldM && 
OldM->isHeaderLikeModule()6
)
1814
1
    OldM = nullptr;
1815
1816
8
  if (!NewM && 
!OldM5
)
1817
3
    return true;
1818
1819
  // [basic.def.odr]p14.3
1820
  // Each such definition shall not be attached to a named module
1821
  // ([module.unit]).
1822
5
  if ((NewM && 
NewM->isNamedModule()3
) ||
(3
OldM3
&&
OldM->isNamedModule()3
))
1823
2
    return true;
1824
1825
  // Then New and Old lives in the same TU if their share one same module unit.
1826
3
  if (NewM)
1827
1
    NewM = NewM->getTopLevelModule();
1828
3
  if (OldM)
1829
3
    OldM = OldM->getTopLevelModule();
1830
3
  return OldM == NewM;
1831
5
}
1832
1833
1.18M
static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1834
1.18M
  if (D->getDeclContext()->isFileContext())
1835
470
    return false;
1836
1837
1.18M
  return isa<UsingShadowDecl>(D) ||
1838
1.18M
         
isa<UnresolvedUsingTypenameDecl>(D)1.18M
||
1839
1.18M
         
isa<UnresolvedUsingValueDecl>(D)1.18M
;
1840
1.18M
}
1841
1842
/// Removes using shadow declarations not at class scope from the lookup
1843
/// results.
1844
331k
static void RemoveUsingDecls(LookupResult &R) {
1845
331k
  LookupResult::Filter F = R.makeFilter();
1846
1.52M
  while (F.hasNext())
1847
1.18M
    if (isUsingDeclNotAtClassScope(F.next()))
1848
8
      F.erase();
1849
1850
331k
  F.done();
1851
331k
}
1852
1853
/// Check for this common pattern:
1854
/// @code
1855
/// class S {
1856
///   S(const S&); // DO NOT IMPLEMENT
1857
///   void operator=(const S&); // DO NOT IMPLEMENT
1858
/// };
1859
/// @endcode
1860
489k
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1861
  // FIXME: Should check for private access too but access is set after we get
1862
  // the decl here.
1863
489k
  if (D->doesThisDeclarationHaveABody())
1864
2.73k
    return false;
1865
1866
486k
  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1867
133k
    return CD->isCopyConstructor();
1868
353k
  return D->isCopyAssignmentOperator();
1869
486k
}
1870
1871
// We need this to handle
1872
//
1873
// typedef struct {
1874
//   void *foo() { return 0; }
1875
// } A;
1876
//
1877
// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1878
// for example. If 'A', foo will have external linkage. If we have '*A',
1879
// foo will have no linkage. Since we can't know until we get to the end
1880
// of the typedef, this function finds out if D might have non-external linkage.
1881
// Callers should verify at the end of the TU if it D has external linkage or
1882
// not.
1883
5.88M
bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1884
5.88M
  const DeclContext *DC = D->getDeclContext();
1885
9.82M
  while (!DC->isTranslationUnit()) {
1886
3.94M
    if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1887
624k
      if (!RD->hasNameForLinkage())
1888
807
        return true;
1889
624k
    }
1890
3.94M
    DC = DC->getParent();
1891
3.94M
  }
1892
1893
5.88M
  return !D->isExternallyVisible();
1894
5.88M
}
1895
1896
// FIXME: This needs to be refactored; some other isInMainFile users want
1897
// these semantics.
1898
32.9M
static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1899
32.9M
  if (S.TUKind != TU_Complete || 
S.getLangOpts().IsHeaderFile32.8M
)
1900
80.7k
    return false;
1901
32.8M
  return S.SourceMgr.isInMainFile(Loc);
1902
32.9M
}
1903
1904
38.4M
bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1905
38.4M
  assert(D);
1906
1907
38.4M
  if (D->isInvalidDecl() || 
D->isUsed()38.4M
||
D->hasAttr<UnusedAttr>()38.4M
)
1908
12.9k
    return false;
1909
1910
  // Ignore all entities declared within templates, and out-of-line definitions
1911
  // of members of class templates.
1912
38.4M
  if (D->getDeclContext()->isDependentContext() ||
1913
38.4M
      
D->getLexicalDeclContext()->isDependentContext()36.5M
)
1914
1.91M
    return false;
1915
1916
36.5M
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1917
35.3M
    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1918
11.8k
      return false;
1919
    // A non-out-of-line declaration of a member specialization was implicitly
1920
    // instantiated; it's the out-of-line declaration that we're interested in.
1921
35.3M
    if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1922
35.3M
        
FD->getMemberSpecializationInfo()21.6k
&&
!FD->isOutOfLine()11.7k
)
1923
43
      return false;
1924
1925
35.3M
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1926
568k
      if (MD->isVirtual() || 
IsDisallowedCopyOrAssign(MD)489k
)
1927
130k
        return false;
1928
34.7M
    } else {
1929
      // 'static inline' functions are defined in headers; don't warn.
1930
34.7M
      if (FD->isInlined() && 
!isMainFileLoc(*this, FD->getLocation())31.7M
)
1931
31.7M
        return false;
1932
34.7M
    }
1933
1934
3.46M
    if (FD->doesThisDeclarationHaveABody() &&
1935
3.46M
        
Context.DeclMustBeEmitted(FD)17.4k
)
1936
234
      return false;
1937
3.46M
  } else 
if (const VarDecl *1.16M
VD1.16M
= dyn_cast<VarDecl>(D)) {
1938
    // Constants and utility variables are defined in headers with internal
1939
    // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1940
    // like "inline".)
1941
1.16M
    if (!isMainFileLoc(*this, VD->getLocation()))
1942
1.04M
      return false;
1943
1944
115k
    if (Context.DeclMustBeEmitted(VD))
1945
70.1k
      return false;
1946
1947
45.1k
    if (VD->isStaticDataMember() &&
1948
45.1k
        
VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation8.68k
)
1949
0
      return false;
1950
45.1k
    if (VD->isStaticDataMember() &&
1951
45.1k
        
VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization8.68k
&&
1952
45.1k
        
VD->getMemberSpecializationInfo()289
&&
!VD->isOutOfLine()209
)
1953
148
      return false;
1954
1955
44.9k
    if (VD->isInline() && 
!isMainFileLoc(*this, VD->getLocation())447
)
1956
0
      return false;
1957
44.9k
  } else {
1958
0
    return false;
1959
0
  }
1960
1961
  // Only warn for unused decls internal to the translation unit.
1962
  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1963
  // for inline functions defined in the main source file, for instance.
1964
3.50M
  return mightHaveNonExternalLinkage(D);
1965
36.5M
}
1966
1967
37.9M
void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1968
37.9M
  if (!D)
1969
0
    return;
1970
1971
37.9M
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1972
36.5M
    const FunctionDecl *First = FD->getFirstDecl();
1973
36.5M
    if (FD != First && 
ShouldWarnIfUnusedFileScopedDecl(First)422k
)
1974
641
      return; // First should already be in the vector.
1975
36.5M
  }
1976
1977
37.9M
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1978
1.35M
    const VarDecl *First = VD->getFirstDecl();
1979
1.35M
    if (VD != First && 
ShouldWarnIfUnusedFileScopedDecl(First)61.3k
)
1980
116
      return; // First should already be in the vector.
1981
1.35M
  }
1982
1983
37.9M
  if (ShouldWarnIfUnusedFileScopedDecl(D))
1984
29.1k
    UnusedFileScopedDecls.push_back(D);
1985
37.9M
}
1986
1987
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1988
119M
                                     const NamedDecl *D) {
1989
119M
  if (D->isInvalidDecl())
1990
248
    return false;
1991
1992
119M
  if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1993
    // For a decomposition declaration, warn if none of the bindings are
1994
    // referenced, instead of if the variable itself is referenced (which
1995
    // it is, by the bindings' expressions).
1996
455
    bool IsAllPlaceholders = true;
1997
623
    for (auto *BD : DD->bindings()) {
1998
623
      if (BD->isReferenced())
1999
307
        return false;
2000
316
      IsAllPlaceholders = IsAllPlaceholders && 
BD->isPlaceholderVar(LangOpts)165
;
2001
316
    }
2002
148
    if (IsAllPlaceholders)
2003
4
      return false;
2004
119M
  } else if (!D->getDeclName()) {
2005
80.8M
    return false;
2006
80.8M
  } else 
if (38.5M
D->isReferenced()38.5M
||
D->isUsed()23.4M
) {
2007
15.0M
    return false;
2008
15.0M
  }
2009
2010
23.4M
  if (D->isPlaceholderVar(LangOpts))
2011
139
    return false;
2012
2013
23.4M
  if (D->hasAttr<UnusedAttr>() || 
D->hasAttr<ObjCPreciseLifetimeAttr>()23.4M
||
2014
23.4M
      
D->hasAttr<CleanupAttr>()23.4M
)
2015
743
    return false;
2016
2017
23.4M
  if (isa<LabelDecl>(D))
2018
291
    return true;
2019
2020
  // Except for labels, we only care about unused decls that are local to
2021
  // functions.
2022
23.4M
  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2023
23.4M
  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2024
    // For dependent types, the diagnostic is deferred.
2025
4.04M
    WithinFunction =
2026
4.04M
        WithinFunction || (R->isLocalClass() && 
!R->isDependentType()43.4k
);
2027
23.4M
  if (!WithinFunction)
2028
21.9M
    return false;
2029
2030
1.50M
  if (isa<TypedefNameDecl>(D))
2031
670
    return true;
2032
2033
  // White-list anything that isn't a local variable.
2034
1.50M
  if (!isa<VarDecl>(D) || 
isa<ParmVarDecl>(D)1.31M
||
isa<ImplicitParamDecl>(D)58.6k
)
2035
1.46M
    return false;
2036
2037
  // Types of valid local variables should be complete, so this should succeed.
2038
47.6k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2039
2040
47.6k
    const Expr *Init = VD->getInit();
2041
47.6k
    if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
2042
3.39k
      Init = Cleanups->getSubExpr();
2043
2044
47.6k
    const auto *Ty = VD->getType().getTypePtr();
2045
2046
    // Only look at the outermost level of typedef.
2047
47.6k
    if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2048
      // Allow anything marked with __attribute__((unused)).
2049
3.84k
      if (TT->getDecl()->hasAttr<UnusedAttr>())
2050
5
        return false;
2051
3.84k
    }
2052
2053
    // Warn for reference variables whose initializtion performs lifetime
2054
    // extension.
2055
47.6k
    if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
2056
536
      if (MTE->getExtendingDecl()) {
2057
536
        Ty = VD->getType().getNonReferenceType().getTypePtr();
2058
536
        Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2059
536
      }
2060
536
    }
2061
2062
    // If we failed to complete the type for some reason, or if the type is
2063
    // dependent, don't diagnose the variable.
2064
47.6k
    if (Ty->isIncompleteType() || 
Ty->isDependentType()47.4k
)
2065
6.67k
      return false;
2066
2067
    // Look at the element type to ensure that the warning behaviour is
2068
    // consistent for both scalars and arrays.
2069
40.9k
    Ty = Ty->getBaseElementTypeUnsafe();
2070
2071
40.9k
    if (const TagType *TT = Ty->getAs<TagType>()) {
2072
12.4k
      const TagDecl *Tag = TT->getDecl();
2073
12.4k
      if (Tag->hasAttr<UnusedAttr>())
2074
4
        return false;
2075
2076
12.4k
      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2077
11.3k
        if (!RD->hasTrivialDestructor() && 
!RD->hasAttr<WarnUnusedAttr>()3.78k
)
2078
3.78k
          return false;
2079
2080
7.56k
        if (Init) {
2081
7.54k
          const CXXConstructExpr *Construct =
2082
7.54k
            dyn_cast<CXXConstructExpr>(Init);
2083
7.54k
          if (Construct && 
!Construct->isElidable()5.98k
) {
2084
4.62k
            CXXConstructorDecl *CD = Construct->getConstructor();
2085
4.62k
            if (!CD->isTrivial() && 
!RD->hasAttr<WarnUnusedAttr>()2.49k
&&
2086
4.62k
                
(2.48k
VD->getInit()->isValueDependent()2.48k
||
!VD->evaluateValue()2.48k
))
2087
2.25k
              return false;
2088
4.62k
          }
2089
2090
          // Suppress the warning if we don't know how this is constructed, and
2091
          // it could possibly be non-trivial constructor.
2092
5.29k
          if (Init->isTypeDependent()) {
2093
89
            for (const CXXConstructorDecl *Ctor : RD->ctors())
2094
66
              if (!Ctor->isTrivial())
2095
42
                return false;
2096
89
          }
2097
2098
          // Suppress the warning if the constructor is unresolved because
2099
          // its arguments are dependent.
2100
5.24k
          if (isa<CXXUnresolvedConstructExpr>(Init))
2101
2
            return false;
2102
5.24k
        }
2103
7.56k
      }
2104
12.4k
    }
2105
2106
    // TODO: __attribute__((unused)) templates?
2107
40.9k
  }
2108
2109
34.8k
  return true;
2110
47.6k
}
2111
2112
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2113
35.1k
                                     FixItHint &Hint) {
2114
35.1k
  if (isa<LabelDecl>(D)) {
2115
291
    SourceLocation AfterColon = Lexer::findLocationAfterToken(
2116
291
        D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2117
291
        /*SkipTrailingWhitespaceAndNewline=*/false);
2118
291
    if (AfterColon.isInvalid())
2119
10
      return;
2120
281
    Hint = FixItHint::CreateRemoval(
2121
281
        CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2122
281
  }
2123
35.1k
}
2124
2125
592k
void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2126
592k
  DiagnoseUnusedNestedTypedefs(
2127
592k
      D, [this](SourceLocation Loc, PartialDiagnostic PD) 
{ Diag(Loc, PD); }0
);
2128
592k
}
2129
2130
void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2131
1.65M
                                        DiagReceiverTy DiagReceiver) {
2132
1.65M
  if (D->getTypeForDecl()->isDependentType())
2133
511k
    return;
2134
2135
1.14M
  for (auto *TmpD : D->decls()) {
2136
670k
    if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2137
18.6k
      DiagnoseUnusedDecl(T, DiagReceiver);
2138
651k
    else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2139
100k
      DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2140
670k
  }
2141
1.14M
}
2142
2143
76.8k
void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2144
76.8k
  DiagnoseUnusedDecl(
2145
76.8k
      D, [this](SourceLocation Loc, PartialDiagnostic PD) 
{ Diag(Loc, PD); }2.54k
);
2146
76.8k
}
2147
2148
/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2149
/// unless they are marked attr(unused).
2150
119M
void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2151
119M
  if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D))
2152
119M
    return;
2153
2154
35.8k
  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2155
    // typedefs can be referenced later on, so the diagnostics are emitted
2156
    // at end-of-translation-unit.
2157
670
    UnusedLocalTypedefNameCandidates.insert(TD);
2158
670
    return;
2159
670
  }
2160
2161
35.1k
  FixItHint Hint;
2162
35.1k
  GenerateFixForUnusedDecl(D, Context, Hint);
2163
2164
35.1k
  unsigned DiagID;
2165
35.1k
  if (isa<VarDecl>(D) && 
cast<VarDecl>(D)->isExceptionVariable()34.8k
)
2166
362
    DiagID = diag::warn_unused_exception_param;
2167
34.8k
  else if (isa<LabelDecl>(D))
2168
291
    DiagID = diag::warn_unused_label;
2169
34.5k
  else
2170
34.5k
    DiagID = diag::warn_unused_variable;
2171
2172
35.1k
  SourceLocation DiagLoc = D->getLocation();
2173
35.1k
  DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2174
35.1k
}
2175
2176
void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2177
107M
                                    DiagReceiverTy DiagReceiver) {
2178
  // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2179
  // it's not really unused.
2180
107M
  if (!VD->isReferenced() || 
!VD->getDeclName()10.9M
||
VD->hasAttr<CleanupAttr>()10.9M
)
2181
96.2M
    return;
2182
2183
  //  In C++, `_` variables behave as if they were maybe_unused
2184
10.9M
  if (VD->hasAttr<UnusedAttr>() || 
VD->isPlaceholderVar(getLangOpts())10.9M
)
2185
26
    return;
2186
2187
10.9M
  const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2188
2189
10.9M
  if (Ty->isReferenceType() || 
Ty->isDependentType()9.97M
)
2190
2.73M
    return;
2191
2192
8.19M
  if (const TagType *TT = Ty->getAs<TagType>()) {
2193
200k
    const TagDecl *Tag = TT->getDecl();
2194
200k
    if (Tag->hasAttr<UnusedAttr>())
2195
0
      return;
2196
    // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2197
    // mimic gcc's behavior.
2198
200k
    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2199
84.8k
      if (!RD->hasAttr<WarnUnusedAttr>())
2200
84.8k
        return;
2201
84.8k
    }
2202
200k
  }
2203
2204
  // Don't warn about __block Objective-C pointer variables, as they might
2205
  // be assigned in the block but not used elsewhere for the purpose of lifetime
2206
  // extension.
2207
8.10M
  if (VD->hasAttr<BlocksAttr>() && 
Ty->isObjCObjectPointerType()355
)
2208
80
    return;
2209
2210
  // Don't warn about Objective-C pointer variables with precise lifetime
2211
  // semantics; they can be used to ensure ARC releases the object at a known
2212
  // time, which may mean assignment but no other references.
2213
8.10M
  if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && 
Ty->isObjCObjectPointerType()8
)
2214
8
    return;
2215
2216
8.10M
  auto iter = RefsMinusAssignments.find(VD);
2217
8.10M
  if (iter == RefsMinusAssignments.end())
2218
51.4k
    return;
2219
2220
8.05M
  assert(iter->getSecond() >= 0 &&
2221
8.05M
         "Found a negative number of references to a VarDecl");
2222
8.05M
  if (iter->getSecond() != 0)
2223
8.05M
    return;
2224
4.58k
  unsigned DiagID = isa<ParmVarDecl>(VD) ? 
diag::warn_unused_but_set_parameter960
2225
4.58k
                                         : 
diag::warn_unused_but_set_variable3.62k
;
2226
4.58k
  DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2227
4.58k
}
2228
2229
static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2230
3.76k
                             Sema::DiagReceiverTy DiagReceiver) {
2231
  // Verify that we have no forward references left.  If so, there was a goto
2232
  // or address of a label taken, but no definition of it.  Label fwd
2233
  // definitions are indicated with a null substmt which is also not a resolved
2234
  // MS inline assembly label name.
2235
3.76k
  bool Diagnose = false;
2236
3.76k
  if (L->isMSAsmLabel())
2237
27
    Diagnose = !L->isResolvedMSAsmLabel();
2238
3.74k
  else
2239
3.74k
    Diagnose = L->getStmt() == nullptr;
2240
3.76k
  if (Diagnose)
2241
425
    DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2242
425
                                       << L);
2243
3.76k
}
2244
2245
51.8M
void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2246
51.8M
  S->applyNRVO();
2247
2248
51.8M
  if (S->decl_empty()) 
return5.78M
;
2249
46.0M
  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2250
46.0M
         "Scope shouldn't contain decls!");
2251
2252
  /// We visit the decls in non-deterministic order, but we want diagnostics
2253
  /// emitted in deterministic order. Collect any diagnostic that may be emitted
2254
  /// and sort the diagnostics before emitting them, after we visited all decls.
2255
46.0M
  struct LocAndDiag {
2256
46.0M
    SourceLocation Loc;
2257
46.0M
    std::optional<SourceLocation> PreviousDeclLoc;
2258
46.0M
    PartialDiagnostic PD;
2259
46.0M
  };
2260
46.0M
  SmallVector<LocAndDiag, 16> DeclDiags;
2261
46.0M
  auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2262
37.6k
    DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2263
37.6k
  };
2264
46.0M
  auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2265
46.0M
                                      SourceLocation PreviousDeclLoc,
2266
46.0M
                                      PartialDiagnostic PD) {
2267
4
    DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2268
4
  };
2269
2270
119M
  for (auto *TmpD : S->decls()) {
2271
119M
    assert(TmpD && "This decl didn't get pushed??");
2272
2273
119M
    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2274
119M
    NamedDecl *D = cast<NamedDecl>(TmpD);
2275
2276
    // Diagnose unused variables in this scope.
2277
119M
    if (!S->hasUnrecoverableErrorOccurred()) {
2278
119M
      DiagnoseUnusedDecl(D, addDiag);
2279
119M
      if (const auto *RD = dyn_cast<RecordDecl>(D))
2280
963k
        DiagnoseUnusedNestedTypedefs(RD, addDiag);
2281
119M
      if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2282
107M
        DiagnoseUnusedButSetDecl(VD, addDiag);
2283
107M
        RefsMinusAssignments.erase(VD);
2284
107M
      }
2285
119M
    }
2286
2287
119M
    if (!D->getDeclName()) 
continue80.8M
;
2288
2289
    // If this was a forward reference to a label, verify it was defined.
2290
38.6M
    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2291
3.76k
      CheckPoppedLabel(LD, *this, addDiag);
2292
2293
    // Remove this name from our lexical scope, and warn on it if we haven't
2294
    // already.
2295
38.6M
    IdResolver.RemoveDecl(D);
2296
38.6M
    auto ShadowI = ShadowingDecls.find(D);
2297
38.6M
    if (ShadowI != ShadowingDecls.end()) {
2298
4
      if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2299
4
        addDiagWithPrev(D->getLocation(), FD->getLocation(),
2300
4
                        PDiag(diag::warn_ctor_parm_shadows_field)
2301
4
                            << D << FD << FD->getParent());
2302
4
      }
2303
4
      ShadowingDecls.erase(ShadowI);
2304
4
    }
2305
38.6M
  }
2306
2307
46.0M
  llvm::sort(DeclDiags,
2308
46.0M
             [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2309
               // The particular order for diagnostics is not important, as long
2310
               // as the order is deterministic. Using the raw location is going
2311
               // to generally be in source order unless there are macro
2312
               // expansions involved.
2313
38.9k
               return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2314
38.9k
             });
2315
46.0M
  for (const LocAndDiag &D : DeclDiags) {
2316
37.6k
    Diag(D.Loc, D.PD);
2317
37.6k
    if (D.PreviousDeclLoc)
2318
4
      Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2319
37.6k
  }
2320
46.0M
}
2321
2322
/// Look for an Objective-C class in the translation unit.
2323
///
2324
/// \param Id The name of the Objective-C class we're looking for. If
2325
/// typo-correction fixes this name, the Id will be updated
2326
/// to the fixed name.
2327
///
2328
/// \param IdLoc The location of the name in the translation unit.
2329
///
2330
/// \param DoTypoCorrection If true, this routine will attempt typo correction
2331
/// if there is no class with the given name.
2332
///
2333
/// \returns The declaration of the named Objective-C class, or NULL if the
2334
/// class could not be found.
2335
ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2336
                                              SourceLocation IdLoc,
2337
41.8k
                                              bool DoTypoCorrection) {
2338
  // The third "scope" argument is 0 since we aren't enabling lazy built-in
2339
  // creation from this context.
2340
41.8k
  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2341
2342
41.8k
  if (!IDecl && 
DoTypoCorrection115
) {
2343
    // Perform typo correction at the given location, but only if we
2344
    // find an Objective-C class name.
2345
38
    DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2346
38
    if (TypoCorrection C =
2347
38
            CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2348
38
                        TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2349
1
      diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2350
1
      IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2351
1
      Id = IDecl->getIdentifier();
2352
1
    }
2353
38
  }
2354
41.8k
  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2355
  // This routine must always return a class definition, if any.
2356
41.8k
  if (Def && 
Def->getDefinition()41.7k
)
2357
41.7k
      Def = Def->getDefinition();
2358
41.8k
  return Def;
2359
41.8k
}
2360
2361
/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2362
/// from S, where a non-field would be declared. This routine copes
2363
/// with the difference between C and C++ scoping rules in structs and
2364
/// unions. For example, the following code is well-formed in C but
2365
/// ill-formed in C++:
2366
/// @code
2367
/// struct S6 {
2368
///   enum { BAR } e;
2369
/// };
2370
///
2371
/// void test_S6() {
2372
///   struct S6 a;
2373
///   a.e = BAR;
2374
/// }
2375
/// @endcode
2376
/// For the declaration of BAR, this routine will return a different
2377
/// scope. The scope S will be the scope of the unnamed enumeration
2378
/// within S6. In C++, this routine will return the scope associated
2379
/// with S6, because the enumeration's scope is a transparent
2380
/// context but structures can contain non-field names. In C, this
2381
/// routine will return the translation unit scope, since the
2382
/// enumeration's scope is a transparent context and structures cannot
2383
/// contain non-field names.
2384
5.82M
Scope *Sema::getNonFieldDeclScope(Scope *S) {
2385
10.1M
  while (((S->getFlags() & Scope::DeclScope) == 0) ||
2386
10.1M
         
(10.1M
S->getEntity()10.1M
&&
S->getEntity()->isTransparentContext()10.1M
) ||
2387
10.1M
         
(5.82M
S->isClassScope()5.82M
&&
!getLangOpts().CPlusPlus107k
))
2388
4.37M
    S = S->getParent();
2389
5.82M
  return S;
2390
5.82M
}
2391
2392
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2393
5
                               ASTContext::GetBuiltinTypeError Error) {
2394
5
  switch (Error) {
2395
0
  case ASTContext::GE_None:
2396
0
    return "";
2397
0
  case ASTContext::GE_Missing_type:
2398
0
    return BuiltinInfo.getHeaderName(ID);
2399
5
  case ASTContext::GE_Missing_stdio:
2400
5
    return "stdio.h";
2401
0
  case ASTContext::GE_Missing_setjmp:
2402
0
    return "setjmp.h";
2403
0
  case ASTContext::GE_Missing_ucontext:
2404
0
    return "ucontext.h";
2405
5
  }
2406
0
  llvm_unreachable("unhandled error kind");
2407
0
}
2408
2409
FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2410
2.08M
                                  unsigned ID, SourceLocation Loc) {
2411
2.08M
  DeclContext *Parent = Context.getTranslationUnitDecl();
2412
2413
2.08M
  if (getLangOpts().CPlusPlus) {
2414
731k
    LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2415
731k
        Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2416
731k
    CLinkageDecl->setImplicit();
2417
731k
    Parent->addDecl(CLinkageDecl);
2418
731k
    Parent = CLinkageDecl;
2419
731k
  }
2420
2421
2.08M
  FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2422
2.08M
                                           /*TInfo=*/nullptr, SC_Extern,
2423
2.08M
                                           getCurFPFeatures().isFPConstrained(),
2424
2.08M
                                           false, Type->isFunctionProtoType());
2425
2.08M
  New->setImplicit();
2426
2.08M
  New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2427
2428
  // Create Decl objects for each parameter, adding them to the
2429
  // FunctionDecl.
2430
2.08M
  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2431
2.08M
    SmallVector<ParmVarDecl *, 16> Params;
2432
5.14M
    for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i3.06M
) {
2433
3.06M
      ParmVarDecl *parm = ParmVarDecl::Create(
2434
3.06M
          Context, New, SourceLocation(), SourceLocation(), nullptr,
2435
3.06M
          FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2436
3.06M
      parm->setScopeInfo(0, i);
2437
3.06M
      Params.push_back(parm);
2438
3.06M
    }
2439
2.08M
    New->setParams(Params);
2440
2.08M
  }
2441
2442
2.08M
  AddKnownFunctionAttributes(New);
2443
2.08M
  return New;
2444
2.08M
}
2445
2446
/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2447
/// file scope.  lazily create a decl for it. ForRedeclaration is true
2448
/// if we're creating this built-in in anticipation of redeclaring the
2449
/// built-in.
2450
NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2451
                                     Scope *S, bool ForRedeclaration,
2452
2.08M
                                     SourceLocation Loc) {
2453
2.08M
  LookupNecessaryTypesForBuiltin(S, ID);
2454
2455
2.08M
  ASTContext::GetBuiltinTypeError Error;
2456
2.08M
  QualType R = Context.GetBuiltinType(ID, Error);
2457
2.08M
  if (Error) {
2458
45
    if (!ForRedeclaration)
2459
4
      return nullptr;
2460
2461
    // If we have a builtin without an associated type we should not emit a
2462
    // warning when we were not able to find a type for it.
2463
41
    if (Error == ASTContext::GE_Missing_type ||
2464
41
        
Context.BuiltinInfo.allowTypeMismatch(ID)15
)
2465
36
      return nullptr;
2466
2467
    // If we could not find a type for setjmp it is because the jmp_buf type was
2468
    // not defined prior to the setjmp declaration.
2469
5
    if (Error == ASTContext::GE_Missing_setjmp) {
2470
0
      Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2471
0
          << Context.BuiltinInfo.getName(ID);
2472
0
      return nullptr;
2473
0
    }
2474
2475
    // Generally, we emit a warning that the declaration requires the
2476
    // appropriate header.
2477
5
    Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2478
5
        << getHeaderName(Context.BuiltinInfo, ID, Error)
2479
5
        << Context.BuiltinInfo.getName(ID);
2480
5
    return nullptr;
2481
5
  }
2482
2483
2.08M
  if (!ForRedeclaration &&
2484
2.08M
      
(2.01M
Context.BuiltinInfo.isPredefinedLibFunction(ID)2.01M
||
2485
2.01M
       
Context.BuiltinInfo.isHeaderDependentFunction(ID)2.01M
)) {
2486
1.85k
    Diag(Loc, LangOpts.C99 ? 
diag::ext_implicit_lib_function_decl_c991.72k
2487
1.85k
                           : 
diag::ext_implicit_lib_function_decl133
)
2488
1.85k
        << Context.BuiltinInfo.getName(ID) << R;
2489
1.85k
    if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2490
1.85k
      Diag(Loc, diag::note_include_header_or_declare)
2491
1.85k
          << Header << Context.BuiltinInfo.getName(ID);
2492
1.85k
  }
2493
2494
2.08M
  if (R.isNull())
2495
6
    return nullptr;
2496
2497
2.08M
  FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2498
2.08M
  RegisterLocallyScopedExternCDecl(New, S);
2499
2500
  // TUScope is the translation-unit scope to insert this function into.
2501
  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2502
  // relate Scopes to DeclContexts, and probably eliminate CurContext
2503
  // entirely, but we're not there yet.
2504
2.08M
  DeclContext *SavedContext = CurContext;
2505
2.08M
  CurContext = New->getDeclContext();
2506
2.08M
  PushOnScopeChains(New, TUScope);
2507
2.08M
  CurContext = SavedContext;
2508
2.08M
  return New;
2509
2.08M
}
2510
2511
/// Typedef declarations don't have linkage, but they still denote the same
2512
/// entity if their types are the same.
2513
/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2514
/// isSameEntity.
2515
static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2516
                                                     TypedefNameDecl *Decl,
2517
2.32M
                                                     LookupResult &Previous) {
2518
  // This is only interesting when modules are enabled.
2519
2.32M
  if (!S.getLangOpts().Modules && 
!S.getLangOpts().ModulesLocalVisibility2.25M
)
2520
2.25M
    return;
2521
2522
  // Empty sets are uninteresting.
2523
69.3k
  if (Previous.empty())
2524
64.4k
    return;
2525
2526
4.91k
  LookupResult::Filter Filter = Previous.makeFilter();
2527
9.82k
  while (Filter.hasNext()) {
2528
4.91k
    NamedDecl *Old = Filter.next();
2529
2530
    // Non-hidden declarations are never ignored.
2531
4.91k
    if (S.isVisible(Old))
2532
4.89k
      continue;
2533
2534
    // Declarations of the same entity are not ignored, even if they have
2535
    // different linkages.
2536
17
    if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2537
16
      if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2538
16
                                Decl->getUnderlyingType()))
2539
5
        continue;
2540
2541
      // If both declarations give a tag declaration a typedef name for linkage
2542
      // purposes, then they declare the same entity.
2543
11
      if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2544
11
          Decl->getAnonDeclWithTypedefName())
2545
11
        continue;
2546
11
    }
2547
2548
1
    Filter.erase();
2549
1
  }
2550
2551
4.91k
  Filter.done();
2552
4.91k
}
2553
2554
31.1k
bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2555
31.1k
  QualType OldType;
2556
31.1k
  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2557
5.40k
    OldType = OldTypedef->getUnderlyingType();
2558
25.7k
  else
2559
25.7k
    OldType = Context.getTypeDeclType(Old);
2560
31.1k
  QualType NewType = New->getUnderlyingType();
2561
2562
31.1k
  if (NewType->isVariablyModifiedType()) {
2563
    // Must not redefine a typedef with a variably-modified type.
2564
2
    int Kind = isa<TypeAliasDecl>(Old) ? 
10
: 0;
2565
2
    Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2566
2
      << Kind << NewType;
2567
2
    if (Old->getLocation().isValid())
2568
2
      notePreviousDefinition(Old, New->getLocation());
2569
2
    New->setInvalidDecl();
2570
2
    return true;
2571
2
  }
2572
2573
31.1k
  if (OldType != NewType &&
2574
31.1k
      
!OldType->isDependentType()29.8k
&&
2575
31.1k
      
!NewType->isDependentType()29.7k
&&
2576
31.1k
      
!Context.hasSameType(OldType, NewType)29.7k
) {
2577
101
    int Kind = isa<TypeAliasDecl>(Old) ? 
145
:
056
;
2578
101
    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2579
101
      << Kind << NewType << OldType;
2580
101
    if (Old->getLocation().isValid())
2581
96
      notePreviousDefinition(Old, New->getLocation());
2582
101
    New->setInvalidDecl();
2583
101
    return true;
2584
101
  }
2585
31.0k
  return false;
2586
31.1k
}
2587
2588
/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2589
/// same name and scope as a previous declaration 'Old'.  Figure out
2590
/// how to resolve this situation, merging decls or emitting
2591
/// diagnostics as appropriate. If there was an error, set New to be invalid.
2592
///
2593
void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2594
31.7k
                                LookupResult &OldDecls) {
2595
  // If the new decl is known invalid already, don't bother doing any
2596
  // merging checks.
2597
31.7k
  if (New->isInvalidDecl()) 
return11
;
2598
2599
  // Allow multiple definitions for ObjC built-in typedefs.
2600
  // FIXME: Verify the underlying types are equivalent!
2601
31.7k
  if (getLangOpts().ObjC) {
2602
22.4k
    const IdentifierInfo *TypeID = New->getIdentifier();
2603
22.4k
    switch (TypeID->getLength()) {
2604
21.2k
    default: break;
2605
21.2k
    case 2:
2606
355
      {
2607
355
        if (!TypeID->isStr("id"))
2608
4
          break;
2609
351
        QualType T = New->getUnderlyingType();
2610
351
        if (!T->isPointerType())
2611
3
          break;
2612
348
        if (!T->isVoidPointerType()) {
2613
343
          QualType PT = T->castAs<PointerType>()->getPointeeType();
2614
343
          if (!PT->isStructureType())
2615
2
            break;
2616
343
        }
2617
346
        Context.setObjCIdRedefinitionType(T);
2618
        // Install the built-in type for 'id', ignoring the current definition.
2619
346
        New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2620
346
        return;
2621
348
      }
2622
477
    case 5:
2623
477
      if (!TypeID->isStr("Class"))
2624
142
        break;
2625
335
      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2626
      // Install the built-in type for 'Class', ignoring the current definition.
2627
335
      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2628
335
      return;
2629
334
    case 3:
2630
334
      if (!TypeID->isStr("SEL"))
2631
3
        break;
2632
331
      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2633
      // Install the built-in type for 'SEL', ignoring the current definition.
2634
331
      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2635
331
      return;
2636
22.4k
    }
2637
    // Fall through - the typedef name was not a builtin type.
2638
22.4k
  }
2639
2640
  // Verify the old decl was also a type.
2641
30.6k
  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2642
30.6k
  if (!Old) {
2643
15
    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2644
15
      << New->getDeclName();
2645
2646
15
    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2647
15
    if (OldD->getLocation().isValid())
2648
15
      notePreviousDefinition(OldD, New->getLocation());
2649
2650
15
    return New->setInvalidDecl();
2651
15
  }
2652
2653
  // If the old declaration is invalid, just give up here.
2654
30.6k
  if (Old->isInvalidDecl())
2655
15
    return New->setInvalidDecl();
2656
2657
30.6k
  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2658
4.91k
    auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2659
4.91k
    auto *NewTag = New->getAnonDeclWithTypedefName();
2660
4.91k
    NamedDecl *Hidden = nullptr;
2661
4.91k
    if (OldTag && 
NewTag18
&&
2662
4.91k
        
OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl()12
&&
2663
4.91k
        
!hasVisibleDefinition(OldTag, &Hidden)12
) {
2664
      // There is a definition of this tag, but it is not visible. Use it
2665
      // instead of our tag.
2666
11
      New->setTypeForDecl(OldTD->getTypeForDecl());
2667
11
      if (OldTD->isModed())
2668
0
        New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2669
0
                                    OldTD->getUnderlyingType());
2670
11
      else
2671
11
        New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2672
2673
      // Make the old tag definition visible.
2674
11
      makeMergedDefinitionVisible(Hidden);
2675
2676
      // If this was an unscoped enumeration, yank all of its enumerators
2677
      // out of the scope.
2678
11
      if (isa<EnumDecl>(NewTag)) {
2679
5
        Scope *EnumScope = getNonFieldDeclScope(S);
2680
5
        for (auto *D : NewTag->decls()) {
2681
0
          auto *ED = cast<EnumConstantDecl>(D);
2682
0
          assert(EnumScope->isDeclScope(ED));
2683
0
          EnumScope->RemoveDecl(ED);
2684
0
          IdResolver.RemoveDecl(ED);
2685
0
          ED->getLexicalDeclContext()->removeDecl(ED);
2686
0
        }
2687
5
      }
2688
11
    }
2689
4.91k
  }
2690
2691
  // If the typedef types are not identical, reject them in all languages and
2692
  // with any extensions enabled.
2693
30.6k
  if (isIncompatibleTypedef(Old, New))
2694
62
    return;
2695
2696
  // The types match.  Link up the redeclaration chain and merge attributes if
2697
  // the old declaration was a typedef.
2698
30.6k
  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2699
4.85k
    New->setPreviousDecl(Typedef);
2700
4.85k
    mergeDeclAttributes(New, Old);
2701
4.85k
  }
2702
2703
30.6k
  if (getLangOpts().MicrosoftExt)
2704
37
    return;
2705
2706
30.5k
  if (getLangOpts().CPlusPlus) {
2707
    // C++ [dcl.typedef]p2:
2708
    //   In a given non-class scope, a typedef specifier can be used to
2709
    //   redefine the name of any type declared in that scope to refer
2710
    //   to the type to which it already refers.
2711
28.1k
    if (!isa<CXXRecordDecl>(CurContext))
2712
28.0k
      return;
2713
2714
    // C++0x [dcl.typedef]p4:
2715
    //   In a given class scope, a typedef specifier can be used to redefine
2716
    //   any class-name declared in that scope that is not also a typedef-name
2717
    //   to refer to the type to which it already refers.
2718
    //
2719
    // This wording came in via DR424, which was a correction to the
2720
    // wording in DR56, which accidentally banned code like:
2721
    //
2722
    //   struct S {
2723
    //     typedef struct A { } A;
2724
    //   };
2725
    //
2726
    // in the C++03 standard. We implement the C++0x semantics, which
2727
    // allow the above but disallow
2728
    //
2729
    //   struct S {
2730
    //     typedef int I;
2731
    //     typedef int I;
2732
    //   };
2733
    //
2734
    // since that was the intent of DR56.
2735
48
    if (!isa<TypedefNameDecl>(Old))
2736
16
      return;
2737
2738
32
    Diag(New->getLocation(), diag::err_redefinition)
2739
32
      << New->getDeclName();
2740
32
    notePreviousDefinition(Old, New->getLocation());
2741
32
    return New->setInvalidDecl();
2742
48
  }
2743
2744
  // Modules always permit redefinition of typedefs, as does C11.
2745
2.46k
  if (getLangOpts().Modules || 
getLangOpts().C11408
)
2746
2.42k
    return;
2747
2748
  // If we have a redefinition of a typedef in C, emit a warning.  This warning
2749
  // is normally mapped to an error, but can be controlled with
2750
  // -Wtypedef-redefinition.  If either the original or the redefinition is
2751
  // in a system header, don't emit this for compatibility with GCC.
2752
39
  if (getDiagnostics().getSuppressSystemWarnings() &&
2753
      // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2754
39
      (Old->isImplicit() ||
2755
39
       
Context.getSourceManager().isInSystemHeader(Old->getLocation())38
||
2756
39
       
Context.getSourceManager().isInSystemHeader(New->getLocation())15
))
2757
24
    return;
2758
2759
15
  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2760
15
    << New->getDeclName();
2761
15
  notePreviousDefinition(Old, New->getLocation());
2762
15
}
2763
2764
/// DeclhasAttr - returns true if decl Declaration already has the target
2765
/// attribute.
2766
495k
static bool DeclHasAttr(const Decl *D, const Attr *A) {
2767
495k
  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2768
495k
  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2769
495k
  for (const auto *i : D->attrs())
2770
480k
    if (i->getKind() == A->getKind()) {
2771
67.0k
      if (Ann) {
2772
65
        if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2773
32
          return true;
2774
33
        continue;
2775
65
      }
2776
      // FIXME: Don't hardcode this check
2777
66.9k
      if (OA && 
isa<OwnershipAttr>(i)0
)
2778
0
        return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2779
66.9k
      return true;
2780
66.9k
    }
2781
2782
428k
  return false;
2783
495k
}
2784
2785
8
static bool isAttributeTargetADefinition(Decl *D) {
2786
8
  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2787
5
    return VD->isThisDeclarationADefinition();
2788
3
  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2789
3
    return TD->isCompleteDefinition() || TD->isBeingDefined();
2790
0
  return true;
2791
3
}
2792
2793
/// Merge alignment attributes from \p Old to \p New, taking into account the
2794
/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2795
///
2796
/// \return \c true if any attributes were added to \p New.
2797
497k
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2798
  // Look for alignas attributes on Old, and pick out whichever attribute
2799
  // specifies the strictest alignment requirement.
2800
497k
  AlignedAttr *OldAlignasAttr = nullptr;
2801
497k
  AlignedAttr *OldStrictestAlignAttr = nullptr;
2802
497k
  unsigned OldAlign = 0;
2803
497k
  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2804
    // FIXME: We have no way of representing inherited dependent alignments
2805
    // in a case like:
2806
    //   template<int A, int B> struct alignas(A) X;
2807
    //   template<int A, int B> struct alignas(B) X {};
2808
    // For now, we just ignore any alignas attributes which are not on the
2809
    // definition in such a case.
2810
71
    if (I->isAlignmentDependent())
2811
2
      return false;
2812
2813
69
    if (I->isAlignas())
2814
18
      OldAlignasAttr = I;
2815
2816
69
    unsigned Align = I->getAlignment(S.Context);
2817
69
    if (Align > OldAlign) {
2818
67
      OldAlign = Align;
2819
67
      OldStrictestAlignAttr = I;
2820
67
    }
2821
69
  }
2822
2823
  // Look for alignas attributes on New.
2824
497k
  AlignedAttr *NewAlignasAttr = nullptr;
2825
497k
  unsigned NewAlign = 0;
2826
497k
  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2827
56
    if (I->isAlignmentDependent())
2828
0
      return false;
2829
2830
56
    if (I->isAlignas())
2831
10
      NewAlignasAttr = I;
2832
2833
56
    unsigned Align = I->getAlignment(S.Context);
2834
56
    if (Align > NewAlign)
2835
54
      NewAlign = Align;
2836
56
  }
2837
2838
497k
  if (OldAlignasAttr && 
NewAlignasAttr16
&&
OldAlign != NewAlign8
) {
2839
    // Both declarations have 'alignas' attributes. We require them to match.
2840
    // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2841
    // fall short. (If two declarations both have alignas, they must both match
2842
    // every definition, and so must match each other if there is a definition.)
2843
2844
    // If either declaration only contains 'alignas(0)' specifiers, then it
2845
    // specifies the natural alignment for the type.
2846
6
    if (OldAlign == 0 || NewAlign == 0) {
2847
0
      QualType Ty;
2848
0
      if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2849
0
        Ty = VD->getType();
2850
0
      else
2851
0
        Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2852
2853
0
      if (OldAlign == 0)
2854
0
        OldAlign = S.Context.getTypeAlign(Ty);
2855
0
      if (NewAlign == 0)
2856
0
        NewAlign = S.Context.getTypeAlign(Ty);
2857
0
    }
2858
2859
6
    if (OldAlign != NewAlign) {
2860
6
      S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2861
6
        << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2862
6
        << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2863
6
      S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2864
6
    }
2865
6
  }
2866
2867
497k
  if (OldAlignasAttr && 
!NewAlignasAttr16
&&
isAttributeTargetADefinition(New)8
) {
2868
    // C++11 [dcl.align]p6:
2869
    //   if any declaration of an entity has an alignment-specifier,
2870
    //   every defining declaration of that entity shall specify an
2871
    //   equivalent alignment.
2872
    // C11 6.7.5/7:
2873
    //   If the definition of an object does not have an alignment
2874
    //   specifier, any other declaration of that object shall also
2875
    //   have no alignment specifier.
2876
2
    S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2877
2
      << OldAlignasAttr;
2878
2
    S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2879
2
      << OldAlignasAttr;
2880
2
  }
2881
2882
497k
  bool AnyAdded = false;
2883
2884
  // Ensure we have an attribute representing the strictest alignment.
2885
497k
  if (OldAlign > NewAlign) {
2886
49
    AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2887
49
    Clone->setInherited(true);
2888
49
    New->addAttr(Clone);
2889
49
    AnyAdded = true;
2890
49
  }
2891
2892
  // Ensure we have an alignas attribute if the old declaration had one.
2893
497k
  if (OldAlignasAttr && 
!NewAlignasAttr16
&&
2894
497k
      
!(8
AnyAdded8
&&
OldStrictestAlignAttr->isAlignas()8
)) {
2895
0
    AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2896
0
    Clone->setInherited(true);
2897
0
    New->addAttr(Clone);
2898
0
    AnyAdded = true;
2899
0
  }
2900
2901
497k
  return AnyAdded;
2902
497k
}
2903
2904
#define WANT_DECL_MERGE_LOGIC
2905
#include "clang/Sema/AttrParsedAttrImpl.inc"
2906
#undef WANT_DECL_MERGE_LOGIC
2907
2908
static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2909
                               const InheritableAttr *Attr,
2910
962k
                               Sema::AvailabilityMergeKind AMK) {
2911
  // Diagnose any mutual exclusions between the attribute that we want to add
2912
  // and attributes that already exist on the declaration.
2913
962k
  if (!DiagnoseMutualExclusions(S, D, Attr))
2914
8
    return false;
2915
2916
  // This function copies an attribute Attr from a previous declaration to the
2917
  // new declaration D if the new declaration doesn't itself have that attribute
2918
  // yet or if that attribute allows duplicates.
2919
  // If you're adding a new attribute that requires logic different from
2920
  // "use explicit attribute on decl if present, else use attribute from
2921
  // previous decl", for example if the attribute needs to be consistent
2922
  // between redeclarations, you need to call a custom merge function here.
2923
962k
  InheritableAttr *NewAttr = nullptr;
2924
962k
  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2925
190k
    NewAttr = S.mergeAvailabilityAttr(
2926
190k
        D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2927
190k
        AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2928
190k
        AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2929
190k
        AA->getPriority());
2930
771k
  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2931
234k
    NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2932
537k
  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2933
336
    NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2934
537k
  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2935
1.69k
    NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2936
535k
  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2937
1.53k
    NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2938
533k
  else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2939
5
    NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2940
533k
  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2941
9.81k
    NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2942
9.81k
                                FA->getFirstArg());
2943
524k
  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2944
23
    NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2945
524k
  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2946
17
    NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2947
524k
  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2948
39
    NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2949
39
                                       IA->getInheritanceModel());
2950
523k
  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2951
14.3k
    NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2952
14.3k
                                      &S.Context.Idents.get(AA->getSpelling()));
2953
509k
  else if (S.getLangOpts().CUDA && 
isa<FunctionDecl>(D)419
&&
2954
509k
           
(373
isa<CUDAHostAttr>(Attr)373
||
isa<CUDADeviceAttr>(Attr)350
||
2955
373
            
isa<CUDAGlobalAttr>(Attr)22
)) {
2956
    // CUDA target attributes are part of function signature for
2957
    // overloading purposes and must not be merged.
2958
352
    return false;
2959
509k
  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2960
3
    NewAttr = S.mergeMinSizeAttr(D, *MA);
2961
509k
  else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2962
17
    NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2963
509k
  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2964
12
    NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2965
509k
  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2966
1.98k
    NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2967
507k
  else if (isa<AlignedAttr>(Attr))
2968
    // AlignedAttrs are handled separately, because we need to handle all
2969
    // such attributes on a declaration at the same time.
2970
72
    NewAttr = nullptr;
2971
507k
  else if ((isa<DeprecatedAttr>(Attr) || 
isa<UnavailableAttr>(Attr)506k
) &&
2972
507k
           
(659
AMK == Sema::AMK_Override659
||
2973
659
            
AMK == Sema::AMK_ProtocolImplementation587
||
2974
659
            
AMK == Sema::AMK_OptionalProtocolImplementation578
))
2975
89
    NewAttr = nullptr;
2976
507k
  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2977
37
    NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2978
507k
  else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2979
7
    NewAttr = S.mergeImportModuleAttr(D, *IMA);
2980
507k
  else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2981
7
    NewAttr = S.mergeImportNameAttr(D, *INA);
2982
507k
  else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2983
15
    NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2984
507k
  else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2985
5
    NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2986
507k
  else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2987
21
    NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2988
506k
  else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2989
47
    NewAttr =
2990
47
        S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2991
506k
  else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2992
23
    NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2993
506k
  else if (Attr->shouldInheritEvenIfAlreadyPresent() || 
!DeclHasAttr(D, Attr)495k
)
2994
440k
    NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2995
2996
961k
  if (NewAttr) {
2997
662k
    NewAttr->setInherited(true);
2998
662k
    D->addAttr(NewAttr);
2999
662k
    if (isa<MSInheritanceAttr>(NewAttr))
3000
36
      S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
3001
662k
    return true;
3002
662k
  }
3003
3004
299k
  return false;
3005
961k
}
3006
3007
204k
static const NamedDecl *getDefinition(const Decl *D) {
3008
204k
  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
3009
20.3k
    return TD->getDefinition();
3010
184k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3011
1.32k
    const VarDecl *Def = VD->getDefinition();
3012
1.32k
    if (Def)
3013
46
      return Def;
3014
1.27k
    return VD->getActingDefinition();
3015
1.32k
  }
3016
183k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3017
113k
    const FunctionDecl *Def = nullptr;
3018
113k
    if (FD->isDefined(Def, true))
3019
859
      return Def;
3020
113k
  }
3021
182k
  return nullptr;
3022
183k
}
3023
3024
1.78k
static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3025
1.78k
  for (const auto *Attribute : D->attrs())
3026
3.97k
    if (Attribute->getKind() == Kind)
3027
1.73k
      return true;
3028
49
  return false;
3029
1.78k
}
3030
3031
/// checkNewAttributesAfterDef - If we already have a definition, check that
3032
/// there are no new attributes in this declaration.
3033
538k
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3034
538k
  if (!New->hasAttrs())
3035
333k
    return;
3036
3037
204k
  const NamedDecl *Def = getDefinition(Old);
3038
204k
  if (!Def || 
Def == New7.29k
)
3039
203k
    return;
3040
3041
1.00k
  AttrVec &NewAttributes = New->getAttrs();
3042
2.82k
  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3043
1.82k
    const Attr *NewAttribute = NewAttributes[I];
3044
3045
1.82k
    if (isa<AliasAttr>(NewAttribute) || 
isa<IFuncAttr>(NewAttribute)1.81k
) {
3046
5
      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3047
4
        Sema::SkipBodyInfo SkipBody;
3048
4
        S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3049
3050
        // If we're skipping this definition, drop the "alias" attribute.
3051
4
        if (SkipBody.ShouldSkip) {
3052
0
          NewAttributes.erase(NewAttributes.begin() + I);
3053
0
          --E;
3054
0
          continue;
3055
0
        }
3056
4
      } else {
3057
1
        VarDecl *VD = cast<VarDecl>(New);
3058
1
        unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3059
1
                                VarDecl::TentativeDefinition
3060
1
                            ? diag::err_alias_after_tentative
3061
1
                            : 
diag::err_redefinition0
;
3062
1
        S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3063
1
        if (Diag == diag::err_redefinition)
3064
0
          S.notePreviousDefinition(Def, VD->getLocation());
3065
1
        else
3066
1
          S.Diag(Def->getLocation(), diag::note_previous_definition);
3067
1
        VD->setInvalidDecl();
3068
1
      }
3069
5
      ++I;
3070
5
      continue;
3071
5
    }
3072
3073
1.81k
    if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3074
      // Tentative definitions are only interesting for the alias check above.
3075
77
      if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3076
28
        ++I;
3077
28
        continue;
3078
28
      }
3079
77
    }
3080
3081
1.78k
    if (hasAttribute(Def, NewAttribute->getKind())) {
3082
1.73k
      ++I;
3083
1.73k
      continue; // regular attr merging will take care of validating this.
3084
1.73k
    }
3085
3086
49
    if (isa<C11NoReturnAttr>(NewAttribute)) {
3087
      // C's _Noreturn is allowed to be added to a function after it is defined.
3088
1
      ++I;
3089
1
      continue;
3090
48
    } else if (isa<UuidAttr>(NewAttribute)) {
3091
      // msvc will allow a subsequent definition to add an uuid to a class
3092
2
      ++I;
3093
2
      continue;
3094
46
    } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3095
3
      if (AA->isAlignas()) {
3096
        // C++11 [dcl.align]p6:
3097
        //   if any declaration of an entity has an alignment-specifier,
3098
        //   every defining declaration of that entity shall specify an
3099
        //   equivalent alignment.
3100
        // C11 6.7.5/7:
3101
        //   If the definition of an object does not have an alignment
3102
        //   specifier, any other declaration of that object shall also
3103
        //   have no alignment specifier.
3104
3
        S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3105
3
          << AA;
3106
3
        S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3107
3
          << AA;
3108
3
        NewAttributes.erase(NewAttributes.begin() + I);
3109
3
        --E;
3110
3
        continue;
3111
3
      }
3112
43
    } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3113
      // If there is a C definition followed by a redeclaration with this
3114
      // attribute then there are two different definitions. In C++, prefer the
3115
      // standard diagnostics.
3116
2
      if (!S.getLangOpts().CPlusPlus) {
3117
1
        S.Diag(NewAttribute->getLocation(),
3118
1
               diag::err_loader_uninitialized_redeclaration);
3119
1
        S.Diag(Def->getLocation(), diag::note_previous_definition);
3120
1
        NewAttributes.erase(NewAttributes.begin() + I);
3121
1
        --E;
3122
1
        continue;
3123
1
      }
3124
41
    } else if (isa<SelectAnyAttr>(NewAttribute) &&
3125
41
               
cast<VarDecl>(New)->isInline()8
&&
3126
41
               
!cast<VarDecl>(New)->isInlineSpecified()2
) {
3127
      // Don't warn about applying selectany to implicitly inline variables.
3128
      // Older compilers and language modes would require the use of selectany
3129
      // to make such variables inline, and it would have no effect if we
3130
      // honored it.
3131
2
      ++I;
3132
2
      continue;
3133
39
    } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3134
      // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3135
      // declarations after definitions.
3136
0
      ++I;
3137
0
      continue;
3138
0
    }
3139
3140
40
    S.Diag(NewAttribute->getLocation(),
3141
40
           diag::warn_attribute_precede_definition);
3142
40
    S.Diag(Def->getLocation(), diag::note_previous_definition);
3143
40
    NewAttributes.erase(NewAttributes.begin() + I);
3144
40
    --E;
3145
40
  }
3146
1.00k
}
3147
3148
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3149
                                     const ConstInitAttr *CIAttr,
3150
26
                                     bool AttrBeforeInit) {
3151
26
  SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3152
3153
  // Figure out a good way to write this specifier on the old declaration.
3154
  // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3155
  // enough of the attribute list spelling information to extract that without
3156
  // heroics.
3157
26
  std::string SuitableSpelling;
3158
26
  if (S.getLangOpts().CPlusPlus20)
3159
20
    SuitableSpelling = std::string(
3160
20
        S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3161
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus1124
)
3162
22
    SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3163
22
        InsertLoc, {tok::l_square, tok::l_square,
3164
22
                    S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3165
22
                    S.PP.getIdentifierInfo("require_constant_initialization"),
3166
22
                    tok::r_square, tok::r_square}));
3167
26
  if (SuitableSpelling.empty())
3168
20
    SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3169
20
        InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3170
20
                    S.PP.getIdentifierInfo("require_constant_initialization"),
3171
20
                    tok::r_paren, tok::r_paren}));
3172
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus2020
)
3173
14
    SuitableSpelling = "constinit";
3174
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus116
)
3175
4
    SuitableSpelling = "[[clang::require_constant_initialization]]";
3176
26
  if (SuitableSpelling.empty())
3177
2
    SuitableSpelling = "__attribute__((require_constant_initialization))";
3178
26
  SuitableSpelling += " ";
3179
3180
26
  if (AttrBeforeInit) {
3181
    // extern constinit int a;
3182
    // int a = 0; // error (missing 'constinit'), accepted as extension
3183
14
    assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3184
14
    S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3185
14
        << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3186
14
    S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3187
14
  } else {
3188
    // int a = 0;
3189
    // constinit extern int a; // error (missing 'constinit')
3190
12
    S.Diag(CIAttr->getLocation(),
3191
12
           CIAttr->isConstinit() ? 
diag::err_constinit_added_too_late6
3192
12
                                 : 
diag::warn_require_const_init_added_too_late6
)
3193
12
        << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3194
12
    S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3195
12
        << CIAttr->isConstinit()
3196
12
        << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3197
12
  }
3198
26
}
3199
3200
/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3201
void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3202
928k
                               AvailabilityMergeKind AMK) {
3203
928k
  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3204
191
    UsedAttr *NewAttr = OldAttr->clone(Context);
3205
191
    NewAttr->setInherited(true);
3206
191
    New->addAttr(NewAttr);
3207
191
  }
3208
928k
  if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3209
3
    RetainAttr *NewAttr = OldAttr->clone(Context);
3210
3
    NewAttr->setInherited(true);
3211
3
    New->addAttr(NewAttr);
3212
3
  }
3213
3214
928k
  if (!Old->hasAttrs() && 
!New->hasAttrs()431k
)
3215
389k
    return;
3216
3217
  // [dcl.constinit]p1:
3218
  //   If the [constinit] specifier is applied to any declaration of a
3219
  //   variable, it shall be applied to the initializing declaration.
3220
538k
  const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3221
538k
  const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3222
538k
  if (bool(OldConstInit) != bool(NewConstInit)) {
3223
51
    const auto *OldVD = cast<VarDecl>(Old);
3224
51
    auto *NewVD = cast<VarDecl>(New);
3225
3226
    // Find the initializing declaration. Note that we might not have linked
3227
    // the new declaration into the redeclaration chain yet.
3228
51
    const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3229
51
    if (!InitDecl &&
3230
51
        
(37
NewVD->hasInit()37
||
NewVD->isThisDeclarationADefinition()37
))
3231
37
      InitDecl = NewVD;
3232
3233
51
    if (InitDecl == NewVD) {
3234
      // This is the initializing declaration. If it would inherit 'constinit',
3235
      // that's ill-formed. (Note that we do not apply this to the attribute
3236
      // form).
3237
37
      if (OldConstInit && 
OldConstInit->isConstinit()36
)
3238
14
        diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3239
14
                                 /*AttrBeforeInit=*/true);
3240
37
    } else 
if (14
NewConstInit14
) {
3241
      // This is the first time we've been told that this declaration should
3242
      // have a constant initializer. If we already saw the initializing
3243
      // declaration, this is too late.
3244
12
      if (InitDecl && InitDecl != NewVD) {
3245
12
        diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3246
12
                                 /*AttrBeforeInit=*/false);
3247
12
        NewVD->dropAttr<ConstInitAttr>();
3248
12
      }
3249
12
    }
3250
51
  }
3251
3252
  // Attributes declared post-definition are currently ignored.
3253
538k
  checkNewAttributesAfterDef(*this, New, Old);
3254
3255
538k
  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3256
2.56k
    if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3257
550
      if (!OldA->isEquivalent(NewA)) {
3258
        // This redeclaration changes __asm__ label.
3259
2
        Diag(New->getLocation(), diag::err_different_asm_label);
3260
2
        Diag(OldA->getLocation(), diag::note_previous_declaration);
3261
2
      }
3262
2.01k
    } else if (Old->isUsed()) {
3263
      // This redeclaration adds an __asm__ label to a declaration that has
3264
      // already been ODR-used.
3265
2
      Diag(New->getLocation(), diag::err_late_asm_label_name)
3266
2
        << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3267
2
    }
3268
2.56k
  }
3269
3270
  // Re-declaration cannot add abi_tag's.
3271
538k
  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3272
60.1k
    if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3273
60.1k
      for (const auto &NewTag : NewAbiTagAttr->tags()) {
3274
60.1k
        if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3275
1
          Diag(NewAbiTagAttr->getLocation(),
3276
1
               diag::err_new_abi_tag_on_redeclaration)
3277
1
              << NewTag;
3278
1
          Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3279
1
        }
3280
60.1k
      }
3281
60.1k
    } else {
3282
1
      Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3283
1
      Diag(Old->getLocation(), diag::note_previous_declaration);
3284
1
    }
3285
60.1k
  }
3286
3287
  // This redeclaration adds a section attribute.
3288
538k
  if (New->hasAttr<SectionAttr>() && 
!Old->hasAttr<SectionAttr>()26
) {
3289
21
    if (auto *VD = dyn_cast<VarDecl>(New)) {
3290
11
      if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3291
2
        Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3292
2
        Diag(Old->getLocation(), diag::note_previous_declaration);
3293
2
      }
3294
11
    }
3295
21
  }
3296
3297
  // Redeclaration adds code-seg attribute.
3298
538k
  const auto *NewCSA = New->getAttr<CodeSegAttr>();
3299
538k
  if (NewCSA && 
!Old->hasAttr<CodeSegAttr>()16
&&
3300
538k
      
!NewCSA->isImplicit()1
&&
isa<CXXMethodDecl>(New)1
) {
3301
1
    Diag(New->getLocation(), diag::warn_mismatched_section)
3302
1
         << 0 /*codeseg*/;
3303
1
    Diag(Old->getLocation(), diag::note_previous_declaration);
3304
1
  }
3305
3306
538k
  if (!Old->hasAttrs())
3307
41.6k
    return;
3308
3309
497k
  bool foundAny = New->hasAttrs();
3310
3311
  // Ensure that any moving of objects within the allocated map is done before
3312
  // we process them.
3313
497k
  if (!foundAny) 
New->setAttrs(AttrVec())333k
;
3314
3315
962k
  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3316
    // Ignore deprecated/unavailable/availability attributes if requested.
3317
962k
    AvailabilityMergeKind LocalAMK = AMK_None;
3318
962k
    if (isa<DeprecatedAttr>(I) ||
3319
962k
        
isa<UnavailableAttr>(I)961k
||
3320
962k
        
isa<AvailabilityAttr>(I)961k
) {
3321
190k
      switch (AMK) {
3322
0
      case AMK_None:
3323
0
        continue;
3324
3325
53.1k
      case AMK_Redeclaration:
3326
189k
      case AMK_Override:
3327
189k
      case AMK_ProtocolImplementation:
3328
190k
      case AMK_OptionalProtocolImplementation:
3329
190k
        LocalAMK = AMK;
3330
190k
        break;
3331
190k
      }
3332
190k
    }
3333
3334
    // Already handled.
3335
962k
    if (isa<UsedAttr>(I) || 
isa<RetainAttr>(I)962k
)
3336
191
      continue;
3337
3338
962k
    if (mergeDeclAttribute(*this, New, I, LocalAMK))
3339
662k
      foundAny = true;
3340
962k
  }
3341
3342
497k
  if (mergeAlignedAttrs(*this, New, Old))
3343
49
    foundAny = true;
3344
3345
497k
  if (!foundAny) 
New->dropAttrs()4.48k
;
3346
497k
}
3347
3348
/// mergeParamDeclAttributes - Copy attributes from the old parameter
3349
/// to the new one.
3350
static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3351
                                     const ParmVarDecl *oldDecl,
3352
831k
                                     Sema &S) {
3353
  // C++11 [dcl.attr.depend]p2:
3354
  //   The first declaration of a function shall specify the
3355
  //   carries_dependency attribute for its declarator-id if any declaration
3356
  //   of the function specifies the carries_dependency attribute.
3357
831k
  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3358
831k
  if (CDA && 
!oldDecl->hasAttr<CarriesDependencyAttr>()2
) {
3359
1
    S.Diag(CDA->getLocation(),
3360
1
           diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3361
    // Find the first declaration of the parameter.
3362
    // FIXME: Should we build redeclaration chains for function parameters?
3363
1
    const FunctionDecl *FirstFD =
3364
1
      cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3365
1
    const ParmVarDecl *FirstVD =
3366
1
      FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3367
1
    S.Diag(FirstVD->getLocation(),
3368
1
           diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3369
1
  }
3370
3371
831k
  if (!oldDecl->hasAttrs())
3372
826k
    return;
3373
3374
5.07k
  bool foundAny = newDecl->hasAttrs();
3375
3376
  // Ensure that any moving of objects within the allocated map is
3377
  // done before we process them.
3378
5.07k
  if (!foundAny) 
newDecl->setAttrs(AttrVec())30
;
3379
3380
5.07k
  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3381
270
    if (!DeclHasAttr(newDecl, I)) {
3382
25
      InheritableAttr *newAttr =
3383
25
        cast<InheritableParamAttr>(I->clone(S.Context));
3384
25
      newAttr->setInherited(true);
3385
25
      newDecl->addAttr(newAttr);
3386
25
      foundAny = true;
3387
25
    }
3388
270
  }
3389
3390
5.07k
  if (!foundAny) 
newDecl->dropAttrs()7
;
3391
5.07k
}
3392
3393
static bool EquivalentArrayTypes(QualType Old, QualType New,
3394
68
                                 const ASTContext &Ctx) {
3395
3396
88
  auto NoSizeInfo = [&Ctx](QualType Ty) {
3397
88
    if (Ty->isIncompleteArrayType() || 
Ty->isPointerType()55
)
3398
33
      return true;
3399
55
    if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3400
5
      return VAT->getSizeModifier() == ArraySizeModifier::Star;
3401
50
    return false;
3402
55
  };
3403
3404
  // `type[]` is equivalent to `type *` and `type[*]`.
3405
68
  if (NoSizeInfo(Old) && 
NoSizeInfo(New)20
)
3406
17
    return true;
3407
3408
  // Don't try to compare VLA sizes, unless one of them has the star modifier.
3409
51
  if (Old->isVariableArrayType() && 
New->isVariableArrayType()1
) {
3410
1
    const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3411
1
    const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3412
1
    if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3413
1
        (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3414
1
      return false;
3415
0
    return true;
3416
1
  }
3417
3418
  // Only compare size, ignore Size modifiers and CVR.
3419
50
  if (Old->isConstantArrayType() && 
New->isConstantArrayType()40
) {
3420
32
    return Ctx.getAsConstantArrayType(Old)->getSize() ==
3421
32
           Ctx.getAsConstantArrayType(New)->getSize();
3422
32
  }
3423
3424
  // Don't try to compare dependent sized array
3425
18
  if (Old->isDependentSizedArrayType() && 
New->isDependentSizedArrayType()1
) {
3426
1
    return true;
3427
1
  }
3428
3429
17
  return Old == New;
3430
18
}
3431
3432
static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3433
                                const ParmVarDecl *OldParam,
3434
741k
                                Sema &S) {
3435
741k
  if (auto Oldnullability = OldParam->getType()->getNullability()) {
3436
1.73k
    if (auto Newnullability = NewParam->getType()->getNullability()) {
3437
1.28k
      if (*Oldnullability != *Newnullability) {
3438
2
        S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3439
2
          << DiagNullabilityKind(
3440
2
               *Newnullability,
3441
2
               ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3442
2
                != 0))
3443
2
          << DiagNullabilityKind(
3444
2
               *Oldnullability,
3445
2
               ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3446
2
                != 0));
3447
2
        S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3448
2
      }
3449
1.28k
    } else {
3450
452
      QualType NewT = NewParam->getType();
3451
452
      NewT = S.Context.getAttributedType(
3452
452
                         AttributedType::getNullabilityAttrKind(*Oldnullability),
3453
452
                         NewT, NewT);
3454
452
      NewParam->setType(NewT);
3455
452
    }
3456
1.73k
  }
3457
741k
  const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3458
741k
  const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3459
741k
  if (OldParamDT && 
NewParamDT79
&&
3460
741k
      
OldParamDT->getPointeeType() == NewParamDT->getPointeeType()68
) {
3461
68
    QualType OldParamOT = OldParamDT->getOriginalType();
3462
68
    QualType NewParamOT = NewParamDT->getOriginalType();
3463
68
    if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3464
19
      S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3465
19
          << NewParam << NewParamOT;
3466
19
      S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3467
19
          << OldParamOT;
3468
19
    }
3469
68
  }
3470
741k
}
3471
3472
namespace {
3473
3474
/// Used in MergeFunctionDecl to keep track of function parameters in
3475
/// C.
3476
struct GNUCompatibleParamWarning {
3477
  ParmVarDecl *OldParm;
3478
  ParmVarDecl *NewParm;
3479
  QualType PromotedType;
3480
};
3481
3482
} // end anonymous namespace
3483
3484
// Determine whether the previous declaration was a definition, implicit
3485
// declaration, or a declaration.
3486
template <typename T>
3487
static std::pair<diag::kind, SourceLocation>
3488
510k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3489
510k
  diag::kind PrevDiag;
3490
510k
  SourceLocation OldLocation = Old->getLocation();
3491
510k
  if (Old->isThisDeclarationADefinition())
3492
15.1k
    PrevDiag = diag::note_previous_definition;
3493
495k
  else if (Old->isImplicit()) {
3494
76.8k
    PrevDiag = diag::note_previous_implicit_declaration;
3495
76.8k
    if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3496
76.8k
      if (FD->getBuiltinID())
3497
73.2k
        PrevDiag = diag::note_previous_builtin_declaration;
3498
76.8k
    }
3499
76.8k
    if (OldLocation.isInvalid())
3500
3.07k
      OldLocation = New->getLocation();
3501
76.8k
  } else
3502
418k
    PrevDiag = diag::note_previous_declaration;
3503
510k
  return std::make_pair(PrevDiag, OldLocation);
3504
510k
}
SemaDecl.cpp:std::__1::pair<unsigned int, clang::SourceLocation> getNoteDiagForInvalidRedeclaration<clang::FunctionDecl>(clang::FunctionDecl const*, clang::FunctionDecl const*)
Line
Count
Source
3488
439k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3489
439k
  diag::kind PrevDiag;
3490
439k
  SourceLocation OldLocation = Old->getLocation();
3491
439k
  if (Old->isThisDeclarationADefinition())
3492
11.5k
    PrevDiag = diag::note_previous_definition;
3493
427k
  else if (Old->isImplicit()) {
3494
76.8k
    PrevDiag = diag::note_previous_implicit_declaration;
3495
76.8k
    if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3496
76.8k
      if (FD->getBuiltinID())
3497
73.2k
        PrevDiag = diag::note_previous_builtin_declaration;
3498
76.8k
    }
3499
76.8k
    if (OldLocation.isInvalid())
3500
3.07k
      OldLocation = New->getLocation();
3501
76.8k
  } else
3502
351k
    PrevDiag = diag::note_previous_declaration;
3503
439k
  return std::make_pair(PrevDiag, OldLocation);
3504
439k
}
SemaDecl.cpp:std::__1::pair<unsigned int, clang::SourceLocation> getNoteDiagForInvalidRedeclaration<clang::VarDecl>(clang::VarDecl const*, clang::VarDecl const*)
Line
Count
Source
3488
71.1k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3489
71.1k
  diag::kind PrevDiag;
3490
71.1k
  SourceLocation OldLocation = Old->getLocation();
3491
71.1k
  if (Old->isThisDeclarationADefinition())
3492
3.60k
    PrevDiag = diag::note_previous_definition;
3493
67.5k
  else if (Old->isImplicit()) {
3494
0
    PrevDiag = diag::note_previous_implicit_declaration;
3495
0
    if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3496
0
      if (FD->getBuiltinID())
3497
0
        PrevDiag = diag::note_previous_builtin_declaration;
3498
0
    }
3499
0
    if (OldLocation.isInvalid())
3500
0
      OldLocation = New->getLocation();
3501
0
  } else
3502
67.5k
    PrevDiag = diag::note_previous_declaration;
3503
71.1k
  return std::make_pair(PrevDiag, OldLocation);
3504
71.1k
}
3505
3506
/// canRedefineFunction - checks if a function can be redefined. Currently,
3507
/// only extern inline functions can be redefined, and even then only in
3508
/// GNU89 mode.
3509
static bool canRedefineFunction(const FunctionDecl *FD,
3510
562
                                const LangOptions& LangOpts) {
3511
562
  return ((FD->hasAttr<GNUInlineAttr>() || 
LangOpts.GNUInline555
) &&
3512
562
          
!LangOpts.CPlusPlus22
&&
3513
562
          
FD->isInlineSpecified()22
&&
3514
562
          
FD->getStorageClass() == SC_Extern18
);
3515
562
}
3516
3517
1.18k
const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3518
1.18k
  const AttributedType *AT = T->getAs<AttributedType>();
3519
1.18k
  while (AT && 
!AT->isCallingConv()160
)
3520
0
    AT = AT->getModifiedType()->getAs<AttributedType>();
3521
1.18k
  return AT;
3522
1.18k
}
3523
3524
template <typename T>
3525
427k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3526
427k
  const DeclContext *DC = Old->getDeclContext();
3527
427k
  if (DC->isRecord())
3528
340k
    return false;
3529
3530
87.8k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3531
87.8k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()64.6k
)
3532
33
    return true;
3533
87.8k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()21.1k
)
3534
23
    return true;
3535
87.8k
  return false;
3536
87.8k
}
SemaDecl.cpp:bool haveIncompatibleLanguageLinkages<clang::FunctionDecl>(clang::FunctionDecl const*, clang::FunctionDecl const*)
Line
Count
Source
3525
357k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3526
357k
  const DeclContext *DC = Old->getDeclContext();
3527
357k
  if (DC->isRecord())
3528
272k
    return false;
3529
3530
84.6k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3531
84.6k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()63.0k
)
3532
30
    return true;
3533
84.6k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()19.7k
)
3534
23
    return true;
3535
84.6k
  return false;
3536
84.6k
}
SemaDecl.cpp:bool haveIncompatibleLanguageLinkages<clang::VarDecl>(clang::VarDecl const*, clang::VarDecl const*)
Line
Count
Source
3525
70.7k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3526
70.7k
  const DeclContext *DC = Old->getDeclContext();
3527
70.7k
  if (DC->isRecord())
3528
67.5k
    return false;
3529
3530
3.18k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3531
3.18k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()1.61k
)
3532
3
    return true;
3533
3.18k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()1.44k
)
3534
0
    return true;
3535
3.18k
  return false;
3536
3.18k
}
3537
3538
28
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
SemaDecl.cpp:bool isExternC<clang::FunctionDecl>(clang::FunctionDecl*)
Line
Count
Source
3538
22
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
SemaDecl.cpp:bool isExternC<clang::VarDecl>(clang::VarDecl*)
Line
Count
Source
3538
6
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3539
2
static bool isExternC(VarTemplateDecl *) { return false; }
3540
8
static bool isExternC(FunctionTemplateDecl *) { return false; }
3541
3542
/// Check whether a redeclaration of an entity introduced by a
3543
/// using-declaration is valid, given that we know it's not an overload
3544
/// (nor a hidden tag declaration).
3545
template<typename ExpectedDecl>
3546
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3547
47
                                   ExpectedDecl *New) {
3548
  // C++11 [basic.scope.declarative]p4:
3549
  //   Given a set of declarations in a single declarative region, each of
3550
  //   which specifies the same unqualified name,
3551
  //   -- they shall all refer to the same entity, or all refer to functions
3552
  //      and function templates; or
3553
  //   -- exactly one declaration shall declare a class name or enumeration
3554
  //      name that is not a typedef name and the other declarations shall all
3555
  //      refer to the same variable or enumerator, or all refer to functions
3556
  //      and function templates; in this case the class name or enumeration
3557
  //      name is hidden (3.3.10).
3558
3559
  // C++11 [namespace.udecl]p14:
3560
  //   If a function declaration in namespace scope or block scope has the
3561
  //   same name and the same parameter-type-list as a function introduced
3562
  //   by a using-declaration, and the declarations do not declare the same
3563
  //   function, the program is ill-formed.
3564
3565
47
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3566
47
  if (Old &&
3567
47
      !Old->getDeclContext()->getRedeclContext()->Equals(
3568
46
          New->getDeclContext()->getRedeclContext()) &&
3569
47
      
!(32
isExternC(Old)32
&&
isExternC(New)6
))
3570
26
    Old = nullptr;
3571
3572
47
  if (!Old) {
3573
27
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3574
27
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3575
27
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3576
27
    return true;
3577
27
  }
3578
20
  return false;
3579
47
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::FunctionTemplateDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::FunctionTemplateDecl*)
Line
Count
Source
3547
10
                                   ExpectedDecl *New) {
3548
  // C++11 [basic.scope.declarative]p4:
3549
  //   Given a set of declarations in a single declarative region, each of
3550
  //   which specifies the same unqualified name,
3551
  //   -- they shall all refer to the same entity, or all refer to functions
3552
  //      and function templates; or
3553
  //   -- exactly one declaration shall declare a class name or enumeration
3554
  //      name that is not a typedef name and the other declarations shall all
3555
  //      refer to the same variable or enumerator, or all refer to functions
3556
  //      and function templates; in this case the class name or enumeration
3557
  //      name is hidden (3.3.10).
3558
3559
  // C++11 [namespace.udecl]p14:
3560
  //   If a function declaration in namespace scope or block scope has the
3561
  //   same name and the same parameter-type-list as a function introduced
3562
  //   by a using-declaration, and the declarations do not declare the same
3563
  //   function, the program is ill-formed.
3564
3565
10
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3566
10
  if (Old &&
3567
10
      !Old->getDeclContext()->getRedeclContext()->Equals(
3568
10
          New->getDeclContext()->getRedeclContext()) &&
3569
10
      
!(8
isExternC(Old)8
&&
isExternC(New)0
))
3570
8
    Old = nullptr;
3571
3572
10
  if (!Old) {
3573
8
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3574
8
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3575
8
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3576
8
    return true;
3577
8
  }
3578
2
  return false;
3579
10
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::FunctionDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::FunctionDecl*)
Line
Count
Source
3547
26
                                   ExpectedDecl *New) {
3548
  // C++11 [basic.scope.declarative]p4:
3549
  //   Given a set of declarations in a single declarative region, each of
3550
  //   which specifies the same unqualified name,
3551
  //   -- they shall all refer to the same entity, or all refer to functions
3552
  //      and function templates; or
3553
  //   -- exactly one declaration shall declare a class name or enumeration
3554
  //      name that is not a typedef name and the other declarations shall all
3555
  //      refer to the same variable or enumerator, or all refer to functions
3556
  //      and function templates; in this case the class name or enumeration
3557
  //      name is hidden (3.3.10).
3558
3559
  // C++11 [namespace.udecl]p14:
3560
  //   If a function declaration in namespace scope or block scope has the
3561
  //   same name and the same parameter-type-list as a function introduced
3562
  //   by a using-declaration, and the declarations do not declare the same
3563
  //   function, the program is ill-formed.
3564
3565
26
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3566
26
  if (Old &&
3567
26
      !Old->getDeclContext()->getRedeclContext()->Equals(
3568
26
          New->getDeclContext()->getRedeclContext()) &&
3569
26
      
!(16
isExternC(Old)16
&&
isExternC(New)6
))
3570
10
    Old = nullptr;
3571
3572
26
  if (!Old) {
3573
10
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3574
10
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3575
10
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3576
10
    return true;
3577
10
  }
3578
16
  return false;
3579
26
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::VarTemplateDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::VarTemplateDecl*)
Line
Count
Source
3547
3
                                   ExpectedDecl *New) {
3548
  // C++11 [basic.scope.declarative]p4:
3549
  //   Given a set of declarations in a single declarative region, each of
3550
  //   which specifies the same unqualified name,
3551
  //   -- they shall all refer to the same entity, or all refer to functions
3552
  //      and function templates; or
3553
  //   -- exactly one declaration shall declare a class name or enumeration
3554
  //      name that is not a typedef name and the other declarations shall all
3555
  //      refer to the same variable or enumerator, or all refer to functions
3556
  //      and function templates; in this case the class name or enumeration
3557
  //      name is hidden (3.3.10).
3558
3559
  // C++11 [namespace.udecl]p14:
3560
  //   If a function declaration in namespace scope or block scope has the
3561
  //   same name and the same parameter-type-list as a function introduced
3562
  //   by a using-declaration, and the declarations do not declare the same
3563
  //   function, the program is ill-formed.
3564
3565
3
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3566
3
  if (Old &&
3567
3
      !Old->getDeclContext()->getRedeclContext()->Equals(
3568
3
          New->getDeclContext()->getRedeclContext()) &&
3569
3
      
!(2
isExternC(Old)2
&&
isExternC(New)0
))
3570
2
    Old = nullptr;
3571
3572
3
  if (!Old) {
3573
2
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3574
2
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3575
2
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3576
2
    return true;
3577
2
  }
3578
1
  return false;
3579
3
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::VarDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::VarDecl*)
Line
Count
Source
3547
8
                                   ExpectedDecl *New) {
3548
  // C++11 [basic.scope.declarative]p4:
3549
  //   Given a set of declarations in a single declarative region, each of
3550
  //   which specifies the same unqualified name,
3551
  //   -- they shall all refer to the same entity, or all refer to functions
3552
  //      and function templates; or
3553
  //   -- exactly one declaration shall declare a class name or enumeration
3554
  //      name that is not a typedef name and the other declarations shall all
3555
  //      refer to the same variable or enumerator, or all refer to functions
3556
  //      and function templates; in this case the class name or enumeration
3557
  //      name is hidden (3.3.10).
3558
3559
  // C++11 [namespace.udecl]p14:
3560
  //   If a function declaration in namespace scope or block scope has the
3561
  //   same name and the same parameter-type-list as a function introduced
3562
  //   by a using-declaration, and the declarations do not declare the same
3563
  //   function, the program is ill-formed.
3564
3565
8
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3566
8
  if (Old &&
3567
8
      !Old->getDeclContext()->getRedeclContext()->Equals(
3568
7
          New->getDeclContext()->getRedeclContext()) &&
3569
8
      
!(6
isExternC(Old)6
&&
isExternC(New)0
))
3570
6
    Old = nullptr;
3571
3572
8
  if (!Old) {
3573
7
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3574
7
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3575
7
    S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3576
7
    return true;
3577
7
  }
3578
1
  return false;
3579
8
}
3580
3581
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3582
370k
                                            const FunctionDecl *B) {
3583
370k
  assert(A->getNumParams() == B->getNumParams());
3584
3585
741k
  
auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) 370k
{
3586
741k
    const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3587
741k
    const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3588
741k
    if (AttrA == AttrB)
3589
741k
      return true;
3590
7
    return AttrA && AttrB && 
AttrA->getType() == AttrB->getType()6
&&
3591
7
           
AttrA->isDynamic() == AttrB->isDynamic()2
;
3592
741k
  };
3593
3594
370k
  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3595
370k
}
3596
3597
/// If necessary, adjust the semantic declaration context for a qualified
3598
/// declaration to name the correct inline namespace within the qualifier.
3599
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3600
510k
                                               DeclaratorDecl *OldD) {
3601
  // The only case where we need to update the DeclContext is when
3602
  // redeclaration lookup for a qualified name finds a declaration
3603
  // in an inline namespace within the context named by the qualifier:
3604
  //
3605
  //   inline namespace N { int f(); }
3606
  //   int ::f(); // Sema DC needs adjusting from :: to N::.
3607
  //
3608
  // For unqualified declarations, the semantic context *can* change
3609
  // along the redeclaration chain (for local extern declarations,
3610
  // extern "C" declarations, and friend declarations in particular).
3611
510k
  if (!NewD->getQualifier())
3612
169k
    return;
3613
3614
  // NewD is probably already in the right context.
3615
340k
  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3616
340k
  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3617
340k
  if (NamedDC->Equals(SemaDC))
3618
340k
    return;
3619
3620
28
  assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3621
28
          NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3622
28
         "unexpected context for redeclaration");
3623
3624
28
  auto *LexDC = NewD->getLexicalDeclContext();
3625
56
  auto FixSemaDC = [=](NamedDecl *D) {
3626
56
    if (!D)
3627
28
      return;
3628
28
    D->setDeclContext(SemaDC);
3629
28
    D->setLexicalDeclContext(LexDC);
3630
28
  };
3631
3632
28
  FixSemaDC(NewD);
3633
28
  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3634
20
    FixSemaDC(FD->getDescribedFunctionTemplate());
3635
8
  else if (auto *VD = dyn_cast<VarDecl>(NewD))
3636
8
    FixSemaDC(VD->getDescribedVarTemplate());
3637
28
}
3638
3639
/// MergeFunctionDecl - We just parsed a function 'New' from
3640
/// declarator D which has the same name and scope as a previous
3641
/// declaration 'Old'.  Figure out how to resolve this situation,
3642
/// merging decls or emitting diagnostics as appropriate.
3643
///
3644
/// In C++, New and Old must be declarations that are not
3645
/// overloaded. Use IsOverload to determine whether New and Old are
3646
/// overloaded, and to select the Old declaration that New should be
3647
/// merged with.
3648
///
3649
/// Returns true if there was an error, false otherwise.
3650
bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3651
439k
                             bool MergeTypeWithOld, bool NewDeclIsDefn) {
3652
  // Verify the old decl was also a function.
3653
439k
  FunctionDecl *Old = OldD->getAsFunction();
3654
439k
  if (!Old) {
3655
92
    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3656
47
      if (New->getFriendObjectKind()) {
3657
11
        Diag(New->getLocation(), diag::err_using_decl_friend);
3658
11
        Diag(Shadow->getTargetDecl()->getLocation(),
3659
11
             diag::note_using_decl_target);
3660
11
        Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3661
11
            << 0;
3662
11
        return true;
3663
11
      }
3664
3665
      // Check whether the two declarations might declare the same function or
3666
      // function template.
3667
36
      if (FunctionTemplateDecl *NewTemplate =
3668
36
              New->getDescribedFunctionTemplate()) {
3669
10
        if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3670
10
                                                         NewTemplate))
3671
8
          return true;
3672
2
        OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3673
2
                         ->getAsFunction();
3674
26
      } else {
3675
26
        if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3676
10
          return true;
3677
16
        OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3678
16
      }
3679
45
    } else {
3680
45
      Diag(New->getLocation(), diag::err_redefinition_different_kind)
3681
45
        << New->getDeclName();
3682
45
      notePreviousDefinition(OldD, New->getLocation());
3683
45
      return true;
3684
45
    }
3685
92
  }
3686
3687
  // If the old declaration was found in an inline namespace and the new
3688
  // declaration was qualified, update the DeclContext to match.
3689
439k
  adjustDeclContextForDeclaratorDecl(New, Old);
3690
3691
  // If the old declaration is invalid, just give up here.
3692
439k
  if (Old->isInvalidDecl())
3693
29
    return true;
3694
3695
  // Disallow redeclaration of some builtins.
3696
439k
  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3697
11
    Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3698
11
    Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3699
11
        << Old << Old->getType();
3700
11
    return true;
3701
11
  }
3702
3703
439k
  diag::kind PrevDiag;
3704
439k
  SourceLocation OldLocation;
3705
439k
  std::tie(PrevDiag, OldLocation) =
3706
439k
      getNoteDiagForInvalidRedeclaration(Old, New);
3707
3708
  // Don't complain about this if we're in GNU89 mode and the old function
3709
  // is an extern inline function.
3710
  // Don't complain about specializations. They are not supposed to have
3711
  // storage classes.
3712
439k
  if (!isa<CXXMethodDecl>(New) && 
!isa<CXXMethodDecl>(Old)166k
&&
3713
439k
      
New->getStorageClass() == SC_Static166k
&&
3714
439k
      
Old->hasExternalFormalLinkage()2.54k
&&
3715
439k
      
!New->getTemplateSpecializationInfo()216
&&
3716
439k
      
!canRedefineFunction(Old, getLangOpts())215
) {
3717
211
    if (getLangOpts().MicrosoftExt) {
3718
202
      Diag(New->getLocation(), diag::ext_static_non_static) << New;
3719
202
      Diag(OldLocation, PrevDiag) << Old << Old->getType();
3720
202
    } else {
3721
9
      Diag(New->getLocation(), diag::err_static_non_static) << New;
3722
9
      Diag(OldLocation, PrevDiag) << Old << Old->getType();
3723
9
      return true;
3724
9
    }
3725
211
  }
3726
3727
439k
  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3728
342
    if (!Old->hasAttr<InternalLinkageAttr>()) {
3729
1
      Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3730
1
          << ILA;
3731
1
      Diag(Old->getLocation(), diag::note_previous_declaration);
3732
1
      New->dropAttr<InternalLinkageAttr>();
3733
1
    }
3734
3735
439k
  if (auto *EA = New->getAttr<ErrorAttr>()) {
3736
7
    if (!Old->hasAttr<ErrorAttr>()) {
3737
2
      Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3738
2
      Diag(Old->getLocation(), diag::note_previous_declaration);
3739
2
      New->dropAttr<ErrorAttr>();
3740
2
    }
3741
7
  }
3742
3743
439k
  if (CheckRedeclarationInModule(New, Old))
3744
29
    return true;
3745
3746
439k
  if (!getLangOpts().CPlusPlus) {
3747
81.9k
    bool OldOvl = Old->hasAttr<OverloadableAttr>();
3748
81.9k
    if (OldOvl != New->hasAttr<OverloadableAttr>() && 
!Old->isImplicit()18
) {
3749
15
      Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3750
15
        << New << OldOvl;
3751
3752
      // Try our best to find a decl that actually has the overloadable
3753
      // attribute for the note. In most cases (e.g. programs with only one
3754
      // broken declaration/definition), this won't matter.
3755
      //
3756
      // FIXME: We could do this if we juggled some extra state in
3757
      // OverloadableAttr, rather than just removing it.
3758
15
      const Decl *DiagOld = Old;
3759
15
      if (OldOvl) {
3760
14
        auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3761
14
          const auto *A = D->getAttr<OverloadableAttr>();
3762
14
          return A && !A->isImplicit();
3763
14
        });
3764
        // If we've implicitly added *all* of the overloadable attrs to this
3765
        // chain, emitting a "previous redecl" note is pointless.
3766
11
        DiagOld = OldIter == Old->redecls_end() ? 
nullptr2
:
*OldIter9
;
3767
11
      }
3768
3769
15
      if (DiagOld)
3770
13
        Diag(DiagOld->getLocation(),
3771
13
             diag::note_attribute_overloadable_prev_overload)
3772
13
          << OldOvl;
3773
3774
15
      if (OldOvl)
3775
11
        New->addAttr(OverloadableAttr::CreateImplicit(Context));
3776
4
      else
3777
4
        New->dropAttr<OverloadableAttr>();
3778
15
    }
3779
81.9k
  }
3780
3781
  // It is not permitted to redeclare an SME function with different SME
3782
  // attributes.
3783
439k
  if (IsInvalidSMECallConversion(Old->getType(), New->getType(),
3784
439k
                                 AArch64SMECallConversionKind::MatchExactly)) {
3785
6
    Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3786
6
        << New->getType() << Old->getType();
3787
6
    Diag(OldLocation, diag::note_previous_declaration);
3788
6
    return true;
3789
6
  }
3790
3791
  // If a function is first declared with a calling convention, but is later
3792
  // declared or defined without one, all following decls assume the calling
3793
  // convention of the first.
3794
  //
3795
  // It's OK if a function is first declared without a calling convention,
3796
  // but is later declared or defined with the default calling convention.
3797
  //
3798
  // To test if either decl has an explicit calling convention, we look for
3799
  // AttributedType sugar nodes on the type as written.  If they are missing or
3800
  // were canonicalized away, we assume the calling convention was implicit.
3801
  //
3802
  // Note also that we DO NOT return at this point, because we still have
3803
  // other tests to run.
3804
439k
  QualType OldQType = Context.getCanonicalType(Old->getType());
3805
439k
  QualType NewQType = Context.getCanonicalType(New->getType());
3806
439k
  const FunctionType *OldType = cast<FunctionType>(OldQType);
3807
439k
  const FunctionType *NewType = cast<FunctionType>(NewQType);
3808
439k
  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3809
439k
  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3810
439k
  bool RequiresAdjustment = false;
3811
3812
439k
  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3813
914
    FunctionDecl *First = Old->getFirstDecl();
3814
914
    const FunctionType *FT =
3815
914
        First->getType().getCanonicalType()->castAs<FunctionType>();
3816
914
    FunctionType::ExtInfo FI = FT->getExtInfo();
3817
914
    bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3818
914
    if (!NewCCExplicit) {
3819
      // Inherit the CC from the previous declaration if it was specified
3820
      // there but not here.
3821
825
      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3822
825
      RequiresAdjustment = true;
3823
825
    } else 
if (89
Old->getBuiltinID()89
) {
3824
      // Builtin attribute isn't propagated to the new one yet at this point,
3825
      // so we check if the old one is a builtin.
3826
3827
      // Calling Conventions on a Builtin aren't really useful and setting a
3828
      // default calling convention and cdecl'ing some builtin redeclarations is
3829
      // common, so warn and ignore the calling convention on the redeclaration.
3830
2
      Diag(New->getLocation(), diag::warn_cconv_unsupported)
3831
2
          << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3832
2
          << (int)CallingConventionIgnoredReason::BuiltinFunction;
3833
2
      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3834
2
      RequiresAdjustment = true;
3835
87
    } else {
3836
      // Calling conventions aren't compatible, so complain.
3837
87
      bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3838
87
      Diag(New->getLocation(), diag::err_cconv_change)
3839
87
        << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3840
87
        << !FirstCCExplicit
3841
87
        << (!FirstCCExplicit ? 
""42
:
3842
87
            
FunctionType::getNameForCallConv(FI.getCC())45
);
3843
3844
      // Put the note on the first decl, since it is the one that matters.
3845
87
      Diag(First->getLocation(), diag::note_previous_declaration);
3846
87
      return true;
3847
87
    }
3848
914
  }
3849
3850
  // FIXME: diagnose the other way around?
3851
439k
  if (OldTypeInfo.getNoReturn() && 
!NewTypeInfo.getNoReturn()2.32k
) {
3852
98
    NewTypeInfo = NewTypeInfo.withNoReturn(true);
3853
98
    RequiresAdjustment = true;
3854
98
  }
3855
3856
  // Merge regparm attribute.
3857
439k
  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3858
439k
      
OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()439k
) {
3859
21
    if (NewTypeInfo.getHasRegParm()) {
3860
6
      Diag(New->getLocation(), diag::err_regparm_mismatch)
3861
6
        << NewType->getRegParmType()
3862
6
        << OldType->getRegParmType();
3863
6
      Diag(OldLocation, diag::note_previous_declaration);
3864
6
      return true;
3865
6
    }
3866
3867
15
    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3868
15
    RequiresAdjustment = true;
3869
15
  }
3870
3871
  // Merge ns_returns_retained attribute.
3872
439k
  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3873
2
    if (NewTypeInfo.getProducesResult()) {
3874
1
      Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3875
1
          << "'ns_returns_retained'";
3876
1
      Diag(OldLocation, diag::note_previous_declaration);
3877
1
      return true;
3878
1
    }
3879
3880
1
    NewTypeInfo = NewTypeInfo.withProducesResult(true);
3881
1
    RequiresAdjustment = true;
3882
1
  }
3883
3884
439k
  if (OldTypeInfo.getNoCallerSavedRegs() !=
3885
439k
      NewTypeInfo.getNoCallerSavedRegs()) {
3886
1
    if (NewTypeInfo.getNoCallerSavedRegs()) {
3887
1
      AnyX86NoCallerSavedRegistersAttr *Attr =
3888
1
        New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3889
1
      Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3890
1
      Diag(OldLocation, diag::note_previous_declaration);
3891
1
      return true;
3892
1
    }
3893
3894
0
    NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3895
0
    RequiresAdjustment = true;
3896
0
  }
3897
3898
439k
  if (RequiresAdjustment) {
3899
932
    const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3900
932
    AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3901
932
    New->setType(QualType(AdjustedType, 0));
3902
932
    NewQType = Context.getCanonicalType(New->getType());
3903
932
  }
3904
3905
  // If this redeclaration makes the function inline, we may need to add it to
3906
  // UndefinedButUsed.
3907
439k
  if (!Old->isInlined() && 
New->isInlined()375k
&&
3908
439k
      
!New->hasAttr<GNUInlineAttr>()86.1k
&&
3909
439k
      
!getLangOpts().GNUInline86.1k
&&
3910
439k
      
Old->isUsed(false)86.1k
&&
3911
439k
      
!Old->isDefined()22
&&
!New->isThisDeclarationADefinition()16
)
3912
16
    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3913
16
                                           SourceLocation()));
3914
3915
  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3916
  // about it.
3917
439k
  if (New->hasAttr<GNUInlineAttr>() &&
3918
439k
      
Old->isInlined()40
&&
!Old->hasAttr<GNUInlineAttr>()9
) {
3919
1
    UndefinedButUsed.erase(Old->getCanonicalDecl());
3920
1
  }
3921
3922
  // If pass_object_size params don't match up perfectly, this isn't a valid
3923
  // redeclaration.
3924
439k
  if (Old->getNumParams() > 0 && 
Old->getNumParams() == New->getNumParams()370k
&&
3925
439k
      
!hasIdenticalPassObjectSizeAttrs(Old, New)370k
) {
3926
6
    Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3927
6
        << New->getDeclName();
3928
6
    Diag(OldLocation, PrevDiag) << Old << Old->getType();
3929
6
    return true;
3930
6
  }
3931
3932
439k
  if (getLangOpts().CPlusPlus) {
3933
357k
    OldQType = Context.getCanonicalType(Old->getType());
3934
357k
    NewQType = Context.getCanonicalType(New->getType());
3935
3936
    // Go back to the type source info to compare the declared return types,
3937
    // per C++1y [dcl.type.auto]p13:
3938
    //   Redeclarations or specializations of a function or function template
3939
    //   with a declared return type that uses a placeholder type shall also
3940
    //   use that placeholder, not a deduced type.
3941
357k
    QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3942
357k
    QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3943
357k
    if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3944
357k
        canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3945
104
                                       OldDeclaredReturnType)) {
3946
100
      QualType ResQT;
3947
100
      if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3948
100
          
OldDeclaredReturnType->isObjCObjectPointerType()9
)
3949
        // FIXME: This does the wrong thing for a deduced return type.
3950
9
        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3951
100
      if (ResQT.isNull()) {
3952
92
        if (New->isCXXClassMember() && 
New->isOutOfLine()28
)
3953
25
          Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3954
25
              << New << New->getReturnTypeSourceRange();
3955
67
        else
3956
67
          Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3957
67
              << New->getReturnTypeSourceRange();
3958
92
        Diag(OldLocation, PrevDiag) << Old << Old->getType()
3959
92
                                    << Old->getReturnTypeSourceRange();
3960
92
        return true;
3961
92
      }
3962
8
      else
3963
8
        NewQType = ResQT;
3964
100
    }
3965
3966
357k
    QualType OldReturnType = OldType->getReturnType();
3967
357k
    QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3968
357k
    if (OldReturnType != NewReturnType) {
3969
      // If this function has a deduced return type and has already been
3970
      // defined, copy the deduced value from the old declaration.
3971
79
      AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3972
79
      if (OldAT && 
OldAT->isDeduced()75
) {
3973
51
        QualType DT = OldAT->getDeducedType();
3974
51
        if (DT.isNull()) {
3975
24
          New->setType(SubstAutoTypeDependent(New->getType()));
3976
24
          NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3977
27
        } else {
3978
27
          New->setType(SubstAutoType(New->getType(), DT));
3979
27
          NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3980
27
        }
3981
51
      }
3982
79
    }
3983
3984
357k
    const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3985
357k
    CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3986
357k
    if (OldMethod && 
NewMethod272k
) {
3987
      // Preserve triviality.
3988
272k
      NewMethod->setTrivial(OldMethod->isTrivial());
3989
3990
      // MSVC allows explicit template specialization at class scope:
3991
      // 2 CXXMethodDecls referring to the same function will be injected.
3992
      // We don't want a redeclaration error.
3993
272k
      bool IsClassScopeExplicitSpecialization =
3994
272k
                              OldMethod->isFunctionTemplateSpecialization() &&
3995
272k
                              
NewMethod->isFunctionTemplateSpecialization()825
;
3996
272k
      bool isFriend = NewMethod->getFriendObjectKind();
3997
3998
272k
      if (!isFriend && 
NewMethod->getLexicalDeclContext()->isRecord()272k
&&
3999
272k
          
!IsClassScopeExplicitSpecialization334
) {
4000
        //    -- Member function declarations with the same name and the
4001
        //       same parameter types cannot be overloaded if any of them
4002
        //       is a static member function declaration.
4003
116
        if (OldMethod->isStatic() != NewMethod->isStatic()) {
4004
1
          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4005
1
          Diag(OldLocation, PrevDiag) << Old << Old->getType();
4006
1
          return true;
4007
1
        }
4008
4009
        // C++ [class.mem]p1:
4010
        //   [...] A member shall not be declared twice in the
4011
        //   member-specification, except that a nested class or member
4012
        //   class template can be declared and then later defined.
4013
115
        if (!inTemplateInstantiation()) {
4014
113
          unsigned NewDiag;
4015
113
          if (isa<CXXConstructorDecl>(OldMethod))
4016
4
            NewDiag = diag::err_constructor_redeclared;
4017
109
          else if (isa<CXXDestructorDecl>(NewMethod))
4018
14
            NewDiag = diag::err_destructor_redeclared;
4019
95
          else if (isa<CXXConversionDecl>(NewMethod))
4020
14
            NewDiag = diag::err_conv_function_redeclared;
4021
81
          else
4022
81
            NewDiag = diag::err_member_redeclared;
4023
4024
113
          Diag(New->getLocation(), NewDiag);
4025
113
        } else {
4026
2
          Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4027
2
            << New << New->getType();
4028
2
        }
4029
115
        Diag(OldLocation, PrevDiag) << Old << Old->getType();
4030
115
        return true;
4031
4032
      // Complain if this is an explicit declaration of a special
4033
      // member that was initially declared implicitly.
4034
      //
4035
      // As an exception, it's okay to befriend such methods in order
4036
      // to permit the implicit constructor/destructor/operator calls.
4037
272k
      } else if (OldMethod->isImplicit()) {
4038
126
        if (isFriend) {
4039
121
          NewMethod->setImplicit();
4040
121
        } else {
4041
5
          Diag(NewMethod->getLocation(),
4042
5
               diag::err_definition_of_implicitly_declared_member)
4043
5
            << New << getSpecialMember(OldMethod);
4044
5
          return true;
4045
5
        }
4046
272k
      } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && 
!isFriend37
) {
4047
11
        Diag(NewMethod->getLocation(),
4048
11
             diag::err_definition_of_explicitly_defaulted_member)
4049
11
          << getSpecialMember(OldMethod);
4050
11
        return true;
4051
11
      }
4052
272k
    }
4053
4054
    // C++1z [over.load]p2
4055
    //   Certain function declarations cannot be overloaded:
4056
    //     -- Function declarations that differ only in the return type,
4057
    //        the exception specification, or both cannot be overloaded.
4058
4059
    // Check the exception specifications match. This may recompute the type of
4060
    // both Old and New if it resolved exception specifications, so grab the
4061
    // types again after this. Because this updates the type, we do this before
4062
    // any of the other checks below, which may update the "de facto" NewQType
4063
    // but do not necessarily update the type of New.
4064
357k
    if (CheckEquivalentExceptionSpec(Old, New))
4065
53
      return true;
4066
4067
    // C++11 [dcl.attr.noreturn]p1:
4068
    //   The first declaration of a function shall specify the noreturn
4069
    //   attribute if any declaration of that function specifies the noreturn
4070
    //   attribute.
4071
357k
    if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4072
2
      if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4073
1
        Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4074
1
            << NRA;
4075
1
        Diag(Old->getLocation(), diag::note_previous_declaration);
4076
1
      }
4077
4078
    // C++11 [dcl.attr.depend]p2:
4079
    //   The first declaration of a function shall specify the
4080
    //   carries_dependency attribute for its declarator-id if any declaration
4081
    //   of the function specifies the carries_dependency attribute.
4082
357k
    const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4083
357k
    if (CDA && 
!Old->hasAttr<CarriesDependencyAttr>()3
) {
4084
2
      Diag(CDA->getLocation(),
4085
2
           diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4086
2
      Diag(Old->getFirstDecl()->getLocation(),
4087
2
           diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4088
2
    }
4089
4090
    // (C++98 8.3.5p3):
4091
    //   All declarations for a function shall agree exactly in both the
4092
    //   return type and the parameter-type-list.
4093
    // We also want to respect all the extended bits except noreturn.
4094
4095
    // noreturn should now match unless the old type info didn't have it.
4096
357k
    QualType OldQTypeForComparison = OldQType;
4097
357k
    if (!OldTypeInfo.getNoReturn() && 
NewTypeInfo.getNoReturn()356k
) {
4098
0
      auto *OldType = OldQType->castAs<FunctionProtoType>();
4099
0
      const FunctionType *OldTypeForComparison
4100
0
        = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4101
0
      OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4102
0
      assert(OldQTypeForComparison.isCanonical());
4103
0
    }
4104
4105
357k
    if (haveIncompatibleLanguageLinkages(Old, New)) {
4106
      // As a special case, retain the language linkage from previous
4107
      // declarations of a friend function as an extension.
4108
      //
4109
      // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4110
      // and is useful because there's otherwise no way to specify language
4111
      // linkage within class scope.
4112
      //
4113
      // Check cautiously as the friend object kind isn't yet complete.
4114
53
      if (New->getFriendObjectKind() != Decl::FOK_None) {
4115
2
        Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4116
2
        Diag(OldLocation, PrevDiag);
4117
51
      } else {
4118
51
        Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4119
51
        Diag(OldLocation, PrevDiag);
4120
51
        return true;
4121
51
      }
4122
53
    }
4123
4124
    // If the function types are compatible, merge the declarations. Ignore the
4125
    // exception specifier because it was already checked above in
4126
    // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4127
    // about incompatible types under -fms-compatibility.
4128
357k
    if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4129
357k
                                                         NewQType))
4130
357k
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4131
4132
    // If the types are imprecise (due to dependent constructs in friends or
4133
    // local extern declarations), it's OK if they differ. We'll check again
4134
    // during instantiation.
4135
49
    if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4136
28
      return false;
4137
4138
    // Fall through for conflicting redeclarations and redefinitions.
4139
49
  }
4140
4141
  // C: Function types need to be compatible, not identical. This handles
4142
  // duplicate function decls like "void f(int); void f(enum X);" properly.
4143
81.9k
  if (!getLangOpts().CPlusPlus) {
4144
    // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4145
    // type is specified by a function definition that contains a (possibly
4146
    // empty) identifier list, both shall agree in the number of parameters
4147
    // and the type of each parameter shall be compatible with the type that
4148
    // results from the application of default argument promotions to the
4149
    // type of the corresponding identifier. ...
4150
    // This cannot be handled by ASTContext::typesAreCompatible() because that
4151
    // doesn't know whether the function type is for a definition or not when
4152
    // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4153
    // we need to cover here is that the number of arguments agree as the
4154
    // default argument promotion rules were already checked by
4155
    // ASTContext::typesAreCompatible().
4156
81.8k
    if (Old->hasPrototype() && 
!New->hasWrittenPrototype()81.7k
&&
NewDeclIsDefn81
&&
4157
81.8k
        
Old->getNumParams() != New->getNumParams()47
&&
!Old->isImplicit()9
) {
4158
8
      if (Old->hasInheritedPrototype())
4159
1
        Old = Old->getCanonicalDecl();
4160
8
      Diag(New->getLocation(), diag::err_conflicting_types) << New;
4161
8
      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4162
8
      return true;
4163
8
    }
4164
4165
    // If we are merging two functions where only one of them has a prototype,
4166
    // we may have enough information to decide to issue a diagnostic that the
4167
    // function without a protoype will change behavior in C23. This handles
4168
    // cases like:
4169
    //   void i(); void i(int j);
4170
    //   void i(int j); void i();
4171
    //   void i(); void i(int j) {}
4172
    // See ActOnFinishFunctionBody() for other cases of the behavior change
4173
    // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4174
    // type without a prototype.
4175
81.8k
    if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4176
81.8k
        
!New->isImplicit()116
&&
!Old->isImplicit()116
) {
4177
96
      const FunctionDecl *WithProto, *WithoutProto;
4178
96
      if (New->hasWrittenPrototype()) {
4179
46
        WithProto = New;
4180
46
        WithoutProto = Old;
4181
50
      } else {
4182
50
        WithProto = Old;
4183
50
        WithoutProto = New;
4184
50
      }
4185
4186
96
      if (WithProto->getNumParams() != 0) {
4187
79
        if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4188
          // The one without the prototype will be changing behavior in C23, so
4189
          // warn about that one so long as it's a user-visible declaration.
4190
79
          bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4191
79
          if (WithoutProto == New)
4192
40
            IsWithoutProtoADef = NewDeclIsDefn;
4193
39
          else
4194
39
            IsWithProtoADef = NewDeclIsDefn;
4195
79
          Diag(WithoutProto->getLocation(),
4196
79
               diag::warn_non_prototype_changes_behavior)
4197
79
              << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 
036
:
143
)
4198
79
              << (WithoutProto == Old) << IsWithProtoADef;
4199
4200
          // The reason the one without the prototype will be changing behavior
4201
          // is because of the one with the prototype, so note that so long as
4202
          // it's a user-visible declaration. There is one exception to this:
4203
          // when the new declaration is a definition without a prototype, the
4204
          // old declaration with a prototype is not the cause of the issue,
4205
          // and that does not need to be noted because the one with a
4206
          // prototype will not change behavior in C23.
4207
79
          if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4208
79
              !IsWithoutProtoADef)
4209
52
            Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4210
79
        }
4211
79
      }
4212
96
    }
4213
4214
81.8k
    if (Context.typesAreCompatible(OldQType, NewQType)) {
4215
81.7k
      const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4216
81.7k
      const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4217
81.7k
      const FunctionProtoType *OldProto = nullptr;
4218
81.7k
      if (MergeTypeWithOld && 
isa<FunctionNoProtoType>(NewFuncType)81.6k
&&
4219
81.7k
          
(OldProto = dyn_cast<FunctionProtoType>(OldFuncType))148
) {
4220
        // The old declaration provided a function prototype, but the
4221
        // new declaration does not. Merge in the prototype.
4222
36
        assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4223
36
        NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4224
36
                                           OldProto->getParamTypes(),
4225
36
                                           OldProto->getExtProtoInfo());
4226
36
        New->setType(NewQType);
4227
36
        New->setHasInheritedPrototype();
4228
4229
        // Synthesize parameters with the same types.
4230
36
        SmallVector<ParmVarDecl *, 16> Params;
4231
36
        for (const auto &ParamType : OldProto->param_types()) {
4232
17
          ParmVarDecl *Param = ParmVarDecl::Create(
4233
17
              Context, New, SourceLocation(), SourceLocation(), nullptr,
4234
17
              ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4235
17
          Param->setScopeInfo(0, Params.size());
4236
17
          Param->setImplicit();
4237
17
          Params.push_back(Param);
4238
17
        }
4239
4240
36
        New->setParams(Params);
4241
36
      }
4242
4243
81.7k
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4244
81.7k
    }
4245
81.8k
  }
4246
4247
  // Check if the function types are compatible when pointer size address
4248
  // spaces are ignored.
4249
210
  if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4250
3
    return false;
4251
4252
  // GNU C permits a K&R definition to follow a prototype declaration
4253
  // if the declared types of the parameters in the K&R definition
4254
  // match the types in the prototype declaration, even when the
4255
  // promoted types of the parameters from the K&R definition differ
4256
  // from the types in the prototype. GCC then keeps the types from
4257
  // the prototype.
4258
  //
4259
  // If a variadic prototype is followed by a non-variadic K&R definition,
4260
  // the K&R definition becomes variadic.  This is sort of an edge case, but
4261
  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4262
  // C99 6.9.1p8.
4263
207
  if (!getLangOpts().CPlusPlus &&
4264
207
      
Old->hasPrototype()186
&&
!New->hasPrototype()168
&&
4265
207
      
New->getType()->getAs<FunctionProtoType>()18
&&
4266
207
      
Old->getNumParams() == New->getNumParams()11
) {
4267
11
    SmallVector<QualType, 16> ArgTypes;
4268
11
    SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4269
11
    const FunctionProtoType *OldProto
4270
11
      = Old->getType()->getAs<FunctionProtoType>();
4271
11
    const FunctionProtoType *NewProto
4272
11
      = New->getType()->getAs<FunctionProtoType>();
4273
4274
    // Determine whether this is the GNU C extension.
4275
11
    QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4276
11
                                               NewProto->getReturnType());
4277
11
    bool LooseCompatible = !MergedReturn.isNull();
4278
11
    for (unsigned Idx = 0, End = Old->getNumParams();
4279
24
         LooseCompatible && 
Idx != End20
;
++Idx13
) {
4280
13
      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4281
13
      ParmVarDecl *NewParm = New->getParamDecl(Idx);
4282
13
      if (Context.typesAreCompatible(OldParm->getType(),
4283
13
                                     NewProto->getParamType(Idx))) {
4284
5
        ArgTypes.push_back(NewParm->getType());
4285
8
      } else if (Context.typesAreCompatible(OldParm->getType(),
4286
8
                                            NewParm->getType(),
4287
8
                                            /*CompareUnqualified=*/true)) {
4288
4
        GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4289
4
                                           NewProto->getParamType(Idx) };
4290
4
        Warnings.push_back(Warn);
4291
4
        ArgTypes.push_back(NewParm->getType());
4292
4
      } else
4293
4
        LooseCompatible = false;
4294
13
    }
4295
4296
11
    if (LooseCompatible) {
4297
11
      for (unsigned Warn = 0; Warn < Warnings.size(); 
++Warn4
) {
4298
4
        Diag(Warnings[Warn].NewParm->getLocation(),
4299
4
             diag::ext_param_promoted_not_compatible_with_prototype)
4300
4
          << Warnings[Warn].PromotedType
4301
4
          << Warnings[Warn].OldParm->getType();
4302
4
        if (Warnings[Warn].OldParm->getLocation().isValid())
4303
3
          Diag(Warnings[Warn].OldParm->getLocation(),
4304
3
               diag::note_previous_declaration);
4305
4
      }
4306
4307
7
      if (MergeTypeWithOld)
4308
7
        New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4309
7
                                             OldProto->getExtProtoInfo()));
4310
7
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4311
7
    }
4312
4313
    // Fall through to diagnose conflicting types.
4314
11
  }
4315
4316
  // A function that has already been declared has been redeclared or
4317
  // defined with a different type; show an appropriate diagnostic.
4318
4319
  // If the previous declaration was an implicitly-generated builtin
4320
  // declaration, then at the very least we should use a specialized note.
4321
200
  unsigned BuiltinID;
4322
200
  if (Old->isImplicit() && 
(BuiltinID = Old->getBuiltinID())85
) {
4323
    // If it's actually a library-defined builtin function like 'malloc'
4324
    // or 'printf', just warn about the incompatible redeclaration.
4325
81
    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4326
78
      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4327
78
      Diag(OldLocation, diag::note_previous_builtin_declaration)
4328
78
        << Old << Old->getType();
4329
78
      return false;
4330
78
    }
4331
4332
3
    PrevDiag = diag::note_previous_builtin_declaration;
4333
3
  }
4334
4335
122
  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4336
122
  Diag(OldLocation, PrevDiag) << Old << Old->getType();
4337
122
  return true;
4338
200
}
4339
4340
/// Completes the merge of two function declarations that are
4341
/// known to be compatible.
4342
///
4343
/// This routine handles the merging of attributes and other
4344
/// properties of function declarations from the old declaration to
4345
/// the new declaration, once we know that New is in fact a
4346
/// redeclaration of Old.
4347
///
4348
/// \returns false
4349
bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4350
438k
                                        Scope *S, bool MergeTypeWithOld) {
4351
  // Merge the attributes
4352
438k
  mergeDeclAttributes(New, Old);
4353
4354
  // Merge "pure" flag.
4355
438k
  if (Old->isPure())
4356
19
    New->setPure();
4357
4358
  // Merge "used" flag.
4359
438k
  if (Old->getMostRecentDecl()->isUsed(false))
4360
1.96k
    New->setIsUsed();
4361
4362
  // Merge attributes from the parameters.  These can mismatch with K&R
4363
  // declarations.
4364
438k
  if (New->getNumParams() == Old->getNumParams())
4365
1.18M
      
for (unsigned i = 0, e = New->getNumParams(); 438k
i != e;
++i741k
) {
4366
741k
        ParmVarDecl *NewParam = New->getParamDecl(i);
4367
741k
        ParmVarDecl *OldParam = Old->getParamDecl(i);
4368
741k
        mergeParamDeclAttributes(NewParam, OldParam, *this);
4369
741k
        mergeParamDeclTypes(NewParam, OldParam, *this);
4370
741k
      }
4371
4372
438k
  if (getLangOpts().CPlusPlus)
4373
357k
    return MergeCXXFunctionDecl(New, Old, S);
4374
4375
  // Merge the function types so the we get the composite types for the return
4376
  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4377
  // was visible.
4378
81.7k
  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4379
81.7k
  if (!Merged.isNull() && 
MergeTypeWithOld81.7k
)
4380
81.6k
    New->setType(Merged);
4381
4382
81.7k
  return false;
4383
438k
}
4384
4385
void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4386
146k
                                ObjCMethodDecl *oldMethod) {
4387
  // Merge the attributes, including deprecated/unavailable
4388
146k
  AvailabilityMergeKind MergeKind =
4389
146k
      isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4390
146k
          ? 
(11.2k
oldMethod->isOptional()11.2k
?
AMK_OptionalProtocolImplementation585
4391
11.2k
                                     : 
AMK_ProtocolImplementation10.6k
)
4392
146k
          : 
isa<ObjCImplDecl>(newMethod->getDeclContext())135k
?
AMK_Redeclaration4.51k
4393
135k
                                                           : 
AMK_Override130k
;
4394
4395
146k
  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4396
4397
  // Merge attributes from the parameters.
4398
146k
  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4399
146k
                                       oe = oldMethod->param_end();
4400
146k
  for (ObjCMethodDecl::param_iterator
4401
146k
         ni = newMethod->param_begin(), ne = newMethod->param_end();
4402
236k
       ni != ne && 
oi != oe90.4k
;
++ni, ++oi90.4k
)
4403
90.4k
    mergeParamDeclAttributes(*ni, *oi, *this);
4404
4405
146k
  CheckObjCMethodOverride(newMethod, oldMethod);
4406
146k
}
4407
4408
208
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4409
208
  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4410
4411
208
  S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4412
208
         ? 
diag::err_redefinition_different_type98
4413
208
         : 
diag::err_redeclaration_different_type110
)
4414
208
    << New->getDeclName() << New->getType() << Old->getType();
4415
4416
208
  diag::kind PrevDiag;
4417
208
  SourceLocation OldLocation;
4418
208
  std::tie(PrevDiag, OldLocation)
4419
208
    = getNoteDiagForInvalidRedeclaration(Old, New);
4420
208
  S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4421
208
  New->setInvalidDecl();
4422
208
}
4423
4424
/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4425
/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4426
/// emitting diagnostics as appropriate.
4427
///
4428
/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4429
/// to here in AddInitializerToDecl. We can't check them before the initializer
4430
/// is attached.
4431
void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4432
71.2k
                             bool MergeTypeWithOld) {
4433
71.2k
  if (New->isInvalidDecl() || 
Old->isInvalidDecl()71.2k
||
New->getType()->containsErrors()71.2k
||
Old->getType()->containsErrors()71.2k
)
4434
33
    return;
4435
4436
71.2k
  QualType MergedT;
4437
71.2k
  if (getLangOpts().CPlusPlus) {
4438
70.0k
    if (New->getType()->isUndeducedType()) {
4439
      // We don't know what the new type is until the initializer is attached.
4440
23
      return;
4441
70.0k
    } else if (Context.hasSameType(New->getType(), Old->getType())) {
4442
      // These could still be something that needs exception specs checked.
4443
69.7k
      return MergeVarDeclExceptionSpecs(New, Old);
4444
69.7k
    }
4445
    // C++ [basic.link]p10:
4446
    //   [...] the types specified by all declarations referring to a given
4447
    //   object or function shall be identical, except that declarations for an
4448
    //   array object can specify array types that differ by the presence or
4449
    //   absence of a major array bound (8.3.4).
4450
275
    else if (Old->getType()->isArrayType() && 
New->getType()->isArrayType()159
) {
4451
140
      const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4452
140
      const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4453
4454
      // We are merging a variable declaration New into Old. If it has an array
4455
      // bound, and that bound differs from Old's bound, we should diagnose the
4456
      // mismatch.
4457
140
      if (!NewArray->isIncompleteArrayType() && 
!NewArray->isDependentType()66
) {
4458
130
        for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4459
79
             
PrevVD = PrevVD->getPreviousDecl()77
) {
4460
79
          QualType PrevVDTy = PrevVD->getType();
4461
79
          if (PrevVDTy->isIncompleteArrayType() || 
PrevVDTy->isDependentType()27
)
4462
56
            continue;
4463
4464
23
          if (!Context.hasSameType(New->getType(), PrevVDTy))
4465
2
            return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4466
23
        }
4467
53
      }
4468
4469
138
      if (OldArray->isIncompleteArrayType() && 
NewArray->isArrayType()60
) {
4470
60
        if (Context.hasSameType(OldArray->getElementType(),
4471
60
                                NewArray->getElementType()))
4472
60
          MergedT = New->getType();
4473
60
      }
4474
      // FIXME: Check visibility. New is hidden but has a complete type. If New
4475
      // has no array bound, it should not inherit one from Old, if Old is not
4476
      // visible.
4477
78
      else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4478
74
        if (Context.hasSameType(OldArray->getElementType(),
4479
74
                                NewArray->getElementType()))
4480
73
          MergedT = Old->getType();
4481
74
      }
4482
138
    }
4483
135
    else if (New->getType()->isObjCObjectPointerType() &&
4484
135
               
Old->getType()->isObjCObjectPointerType()4
) {
4485
4
      MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4486
4
                                              Old->getType());
4487
4
    }
4488
70.0k
  } else {
4489
    // C 6.2.7p2:
4490
    //   All declarations that refer to the same object or function shall have
4491
    //   compatible type.
4492
1.18k
    MergedT = Context.mergeTypes(New->getType(), Old->getType());
4493
1.18k
  }
4494
1.46k
  if (MergedT.isNull()) {
4495
    // It's OK if we couldn't merge types if either type is dependent, for a
4496
    // block-scope variable. In other cases (static data members of class
4497
    // templates, variable templates, ...), we require the types to be
4498
    // equivalent.
4499
    // FIXME: The C++ standard doesn't say anything about this.
4500
236
    if ((New->getType()->isDependentType() ||
4501
236
         
Old->getType()->isDependentType()196
) &&
New->isLocalVarDecl()56
) {
4502
      // If the old type was dependent, we can't merge with it, so the new type
4503
      // becomes dependent for now. We'll reproduce the original type when we
4504
      // instantiate the TypeSourceInfo for the variable.
4505
30
      if (!New->getType()->isDependentType() && 
MergeTypeWithOld7
)
4506
1
        New->setType(Context.DependentTy);
4507
30
      return;
4508
30
    }
4509
206
    return diagnoseVarDeclTypeMismatch(*this, New, Old);
4510
236
  }
4511
4512
  // Don't actually update the type on the new declaration if the old
4513
  // declaration was an extern declaration in a different scope.
4514
1.22k
  if (MergeTypeWithOld)
4515
1.16k
    New->setType(MergedT);
4516
1.22k
}
4517
4518
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4519
71.2k
                                  LookupResult &Previous) {
4520
  // C11 6.2.7p4:
4521
  //   For an identifier with internal or external linkage declared
4522
  //   in a scope in which a prior declaration of that identifier is
4523
  //   visible, if the prior declaration specifies internal or
4524
  //   external linkage, the type of the identifier at the later
4525
  //   declaration becomes the composite type.
4526
  //
4527
  // If the variable isn't visible, we do not merge with its type.
4528
71.2k
  if (Previous.isShadowed())
4529
38
    return false;
4530
4531
71.2k
  if (S.getLangOpts().CPlusPlus) {
4532
    // C++11 [dcl.array]p3:
4533
    //   If there is a preceding declaration of the entity in the same
4534
    //   scope in which the bound was specified, an omitted array bound
4535
    //   is taken to be the same as in that earlier declaration.
4536
70.0k
    return NewVD->isPreviousDeclInSameBlockScope() ||
4537
70.0k
           
(70.0k
!OldVD->getLexicalDeclContext()->isFunctionOrMethod()70.0k
&&
4538
70.0k
            
!NewVD->getLexicalDeclContext()->isFunctionOrMethod()69.7k
);
4539
70.0k
  } else {
4540
    // If the old declaration was function-local, don't merge with its
4541
    // type unless we're in the same function.
4542
1.18k
    return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4543
1.18k
           
OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext()56
;
4544
1.18k
  }
4545
71.2k
}
4546
4547
/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4548
/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4549
/// situation, merging decls or emitting diagnostics as appropriate.
4550
///
4551
/// Tentative definition rules (C99 6.9.2p2) are checked by
4552
/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4553
/// definitions here, since the initializer hasn't been attached.
4554
///
4555
71.2k
void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4556
  // If the new decl is already invalid, don't do any other checking.
4557
71.2k
  if (New->isInvalidDecl())
4558
0
    return;
4559
4560
71.2k
  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4561
5
    return;
4562
4563
71.2k
  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4564
4565
  // Verify the old decl was also a variable or variable template.
4566
71.2k
  VarDecl *Old = nullptr;
4567
71.2k
  VarTemplateDecl *OldTemplate = nullptr;
4568
71.2k
  if (Previous.isSingleResult()) {
4569
71.2k
    if (NewTemplate) {
4570
476
      OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4571
476
      Old = OldTemplate ? 
OldTemplate->getTemplatedDecl()472
:
nullptr4
;
4572
4573
476
      if (auto *Shadow =
4574
476
              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4575
3
        if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4576
2
          return New->setInvalidDecl();
4577
70.7k
    } else {
4578
70.7k
      Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4579
4580
70.7k
      if (auto *Shadow =
4581
70.7k
              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4582
8
        if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4583
7
          return New->setInvalidDecl();
4584
70.7k
    }
4585
71.2k
  }
4586
71.2k
  if (!Old) {
4587
60
    Diag(New->getLocation(), diag::err_redefinition_different_kind)
4588
60
        << New->getDeclName();
4589
60
    notePreviousDefinition(Previous.getRepresentativeDecl(),
4590
60
                           New->getLocation());
4591
60
    return New->setInvalidDecl();
4592
60
  }
4593
4594
  // If the old declaration was found in an inline namespace and the new
4595
  // declaration was qualified, update the DeclContext to match.
4596
71.1k
  adjustDeclContextForDeclaratorDecl(New, Old);
4597
4598
  // Ensure the template parameters are compatible.
4599
71.1k
  if (NewTemplate &&
4600
71.1k
      !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4601
470
                                      OldTemplate->getTemplateParameters(),
4602
470
                                      /*Complain=*/true, TPL_TemplateMatch))
4603
10
    return New->setInvalidDecl();
4604
4605
  // C++ [class.mem]p1:
4606
  //   A member shall not be declared twice in the member-specification [...]
4607
  //
4608
  // Here, we need only consider static data members.
4609
71.1k
  if (Old->isStaticDataMember() && 
!New->isOutOfLine()67.6k
) {
4610
11
    Diag(New->getLocation(), diag::err_duplicate_member)
4611
11
      << New->getIdentifier();
4612
11
    Diag(Old->getLocation(), diag::note_previous_declaration);
4613
11
    New->setInvalidDecl();
4614
11
  }
4615
4616
71.1k
  mergeDeclAttributes(New, Old);
4617
  // Warn if an already-declared variable is made a weak_import in a subsequent
4618
  // declaration
4619
71.1k
  if (New->hasAttr<WeakImportAttr>() &&
4620
71.1k
      
Old->getStorageClass() == SC_None12
&&
4621
71.1k
      
!Old->hasAttr<WeakImportAttr>()3
) {
4622
2
    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4623
2
    Diag(Old->getLocation(), diag::note_previous_declaration);
4624
    // Remove weak_import attribute on new declaration.
4625
2
    New->dropAttr<WeakImportAttr>();
4626
2
  }
4627
4628
71.1k
  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4629
5
    if (!Old->hasAttr<InternalLinkageAttr>()) {
4630
2
      Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4631
2
          << ILA;
4632
2
      Diag(Old->getLocation(), diag::note_previous_declaration);
4633
2
      New->dropAttr<InternalLinkageAttr>();
4634
2
    }
4635
4636
  // Merge the types.
4637
71.1k
  VarDecl *MostRecent = Old->getMostRecentDecl();
4638
71.1k
  if (MostRecent != Old) {
4639
112
    MergeVarDeclTypes(New, MostRecent,
4640
112
                      mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4641
112
    if (New->isInvalidDecl())
4642
6
      return;
4643
112
  }
4644
4645
71.1k
  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4646
71.1k
  if (New->isInvalidDecl())
4647
219
    return;
4648
4649
70.9k
  diag::kind PrevDiag;
4650
70.9k
  SourceLocation OldLocation;
4651
70.9k
  std::tie(PrevDiag, OldLocation) =
4652
70.9k
      getNoteDiagForInvalidRedeclaration(Old, New);
4653
4654
  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4655
70.9k
  if (New->getStorageClass() == SC_Static &&
4656
70.9k
      
!New->isStaticDataMember()72
&&
4657
70.9k
      
Old->hasExternalFormalLinkage()69
) {
4658
16
    if (getLangOpts().MicrosoftExt) {
4659
3
      Diag(New->getLocation(), diag::ext_static_non_static)
4660
3
          << New->getDeclName();
4661
3
      Diag(OldLocation, PrevDiag);
4662
13
    } else {
4663
13
      Diag(New->getLocation(), diag::err_static_non_static)
4664
13
          << New->getDeclName();
4665
13
      Diag(OldLocation, PrevDiag);
4666
13
      return New->setInvalidDecl();
4667
13
    }
4668
16
  }
4669
  // C99 6.2.2p4:
4670
  //   For an identifier declared with the storage-class specifier
4671
  //   extern in a scope in which a prior declaration of that
4672
  //   identifier is visible,23) if the prior declaration specifies
4673
  //   internal or external linkage, the linkage of the identifier at
4674
  //   the later declaration is the same as the linkage specified at
4675
  //   the prior declaration. If no prior declaration is visible, or
4676
  //   if the prior declaration specifies no linkage, then the
4677
  //   identifier has external linkage.
4678
70.9k
  if (New->hasExternalStorage() && 
Old->hasLinkage()1.99k
)
4679
1.98k
    /* Okay */;
4680
68.9k
  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4681
68.9k
           
!New->isStaticDataMember()68.8k
&&
4682
68.9k
           
Old->getCanonicalDecl()->getStorageClass() == SC_Static1.30k
) {
4683
5
    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4684
5
    Diag(OldLocation, PrevDiag);
4685
5
    return New->setInvalidDecl();
4686
5
  }
4687
4688
  // Check if extern is followed by non-extern and vice-versa.
4689
70.9k
  if (New->hasExternalStorage() &&
4690
70.9k
      
!Old->hasLinkage()1.99k
&&
Old->isLocalVarDeclOrParm()5
) {
4691
5
    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4692
5
    Diag(OldLocation, PrevDiag);
4693
5
    return New->setInvalidDecl();
4694
5
  }
4695
70.9k
  if (Old->hasLinkage() && 
New->isLocalVarDeclOrParm()70.8k
&&
4696
70.9k
      
!New->hasExternalStorage()243
) {
4697
4
    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4698
4
    Diag(OldLocation, PrevDiag);
4699
4
    return New->setInvalidDecl();
4700
4
  }
4701
4702
70.9k
  if (CheckRedeclarationInModule(New, Old))
4703
31
    return;
4704
4705
  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4706
4707
  // FIXME: The test for external storage here seems wrong? We still
4708
  // need to check for mismatches.
4709
70.8k
  if (!New->hasExternalStorage() && 
!New->isFileVarDecl()68.8k
&&
4710
      // Don't complain about out-of-line definitions of static members.
4711
70.8k
      
!(75
Old->getLexicalDeclContext()->isRecord()75
&&
4712
75
        
!New->getLexicalDeclContext()->isRecord()0
)) {
4713
75
    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4714
75
    Diag(OldLocation, PrevDiag);
4715
75
    return New->setInvalidDecl();
4716
75
  }
4717
4718
70.7k
  if (New->isInline() && 
!Old->getMostRecentDecl()->isInline()3.05k
) {
4719
473
    if (VarDecl *Def = Old->getDefinition()) {
4720
      // C++1z [dcl.fcn.spec]p4:
4721
      //   If the definition of a variable appears in a translation unit before
4722
      //   its first declaration as inline, the program is ill-formed.
4723
0
      Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4724
0
      Diag(Def->getLocation(), diag::note_previous_definition);
4725
0
    }
4726
473
  }
4727
4728
  // If this redeclaration makes the variable inline, we may need to add it to
4729
  // UndefinedButUsed.
4730
70.7k
  if (!Old->isInline() && 
New->isInline()68.1k
&&
Old->isUsed(false)473
&&
4731
70.7k
      
!Old->getDefinition()72
&&
!New->isThisDeclarationADefinition()72
)
4732
72
    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4733
72
                                           SourceLocation()));
4734
4735
70.7k
  if (New->getTLSKind() != Old->getTLSKind()) {
4736
25
    if (!Old->getTLSKind()) {
4737
11
      Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4738
11
      Diag(OldLocation, PrevDiag);
4739
14
    } else if (!New->getTLSKind()) {
4740
10
      Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4741
10
      Diag(OldLocation, PrevDiag);
4742
10
    } else {
4743
      // Do not allow redeclaration to change the variable between requiring
4744
      // static and dynamic initialization.
4745
      // FIXME: GCC allows this, but uses the TLS keyword on the first
4746
      // declaration to determine the kind. Do we need to be compatible here?
4747
4
      Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4748
4
        << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4749
4
      Diag(OldLocation, PrevDiag);
4750
4
    }
4751
25
  }
4752
4753
  // C++ doesn't have tentative definitions, so go right ahead and check here.
4754
70.7k
  if (getLangOpts().CPlusPlus) {
4755
69.7k
    if (Old->isStaticDataMember() && 
Old->getCanonicalDecl()->isInline()67.5k
&&
4756
69.7k
        
Old->getCanonicalDecl()->isConstexpr()2.58k
) {
4757
      // This definition won't be a definition any more once it's been merged.
4758
2.58k
      Diag(New->getLocation(),
4759
2.58k
           diag::warn_deprecated_redundant_constexpr_static_def);
4760
67.1k
    } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4761
65.0k
      VarDecl *Def = Old->getDefinition();
4762
65.0k
      if (Def && 
checkVarDeclRedefinition(Def, New)75
)
4763
40
        return;
4764
65.0k
    }
4765
69.7k
  }
4766
4767
70.7k
  if (haveIncompatibleLanguageLinkages(Old, New)) {
4768
3
    Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4769
3
    Diag(OldLocation, PrevDiag);
4770
3
    New->setInvalidDecl();
4771
3
    return;
4772
3
  }
4773
4774
  // Merge "used" flag.
4775
70.7k
  if (Old->getMostRecentDecl()->isUsed(false))
4776
716
    New->setIsUsed();
4777
4778
  // Keep a chain of previous declarations.
4779
70.7k
  New->setPreviousDecl(Old);
4780
70.7k
  if (NewTemplate)
4781
429
    NewTemplate->setPreviousDecl(OldTemplate);
4782
4783
  // Inherit access appropriately.
4784
70.7k
  New->setAccess(Old->getAccess());
4785
70.7k
  if (NewTemplate)
4786
429
    NewTemplate->setAccess(New->getAccess());
4787
4788
70.7k
  if (Old->isInline())
4789
2.58k
    New->setImplicitlyInline();
4790
70.7k
}
4791
4792
434
void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4793
434
  SourceManager &SrcMgr = getSourceManager();
4794
434
  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4795
434
  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4796
434
  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4797
434
  auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4798
434
  auto &HSI = PP.getHeaderSearchInfo();
4799
434
  StringRef HdrFilename =
4800
434
      SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4801
4802
434
  auto noteFromModuleOrInclude = [&](Module *Mod,
4803
434
                                     SourceLocation IncLoc) -> bool {
4804
    // Redefinition errors with modules are common with non modular mapped
4805
    // headers, example: a non-modular header H in module A that also gets
4806
    // included directly in a TU. Pointing twice to the same header/definition
4807
    // is confusing, try to get better diagnostics when modules is on.
4808
14
    if (IncLoc.isValid()) {
4809
6
      if (Mod) {
4810
1
        Diag(IncLoc, diag::note_redefinition_modules_same_file)
4811
1
            << HdrFilename.str() << Mod->getFullModuleName();
4812
1
        if (!Mod->DefinitionLoc.isInvalid())
4813
1
          Diag(Mod->DefinitionLoc, diag::note_defined_here)
4814
1
              << Mod->getFullModuleName();
4815
5
      } else {
4816
5
        Diag(IncLoc, diag::note_redefinition_include_same_file)
4817
5
            << HdrFilename.str();
4818
5
      }
4819
6
      return true;
4820
6
    }
4821
4822
8
    return false;
4823
14
  };
4824
4825
  // Is it the same file and same offset? Provide more information on why
4826
  // this leads to a redefinition error.
4827
434
  if (FNew == FOld && 
FNewDecLoc.second == FOldDecLoc.second399
) {
4828
7
    SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4829
7
    SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4830
7
    bool EmittedDiag =
4831
7
        noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4832
7
    EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4833
4834
    // If the header has no guards, emit a note suggesting one.
4835
7
    if (FOld && 
!HSI.isFileMultipleIncludeGuarded(*FOld)5
)
4836
4
      Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4837
4838
7
    if (EmittedDiag)
4839
3
      return;
4840
7
  }
4841
4842
  // Redefinition coming from different files or couldn't do better above.
4843
431
  if (Old->getLocation().isValid())
4844
421
    Diag(Old->getLocation(), diag::note_previous_definition);
4845
431
}
4846
4847
/// We've just determined that \p Old and \p New both appear to be definitions
4848
/// of the same variable. Either diagnose or fix the problem.
4849
94
bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4850
94
  if (!hasVisibleDefinition(Old) &&
4851
94
      
(36
New->getFormalLinkage() == Linkage::Internal36
||
New->isInline()36
||
4852
36
       
isa<VarTemplateSpecializationDecl>(New)32
||
4853
36
       
New->getDescribedVarTemplate()30
||
New->getNumTemplateParameterLists()8
||
4854
36
       
New->getDeclContext()->isDependentContext()1
)) {
4855
    // The previous definition is hidden, and multiple definitions are
4856
    // permitted (in separate TUs). Demote this to a declaration.
4857
35
    New->demoteThisDefinitionToDeclaration();
4858
4859
    // Make the canonical definition visible.
4860
35
    if (auto *OldTD = Old->getDescribedVarTemplate())
4861
23
      makeMergedDefinitionVisible(OldTD);
4862
35
    makeMergedDefinitionVisible(Old);
4863
35
    return false;
4864
59
  } else {
4865
59
    Diag(New->getLocation(), diag::err_redefinition) << New;
4866
59
    notePreviousDefinition(Old, New->getLocation());
4867
59
    New->setInvalidDecl();
4868
59
    return true;
4869
59
  }
4870
94
}
4871
4872
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4873
/// no declarator (e.g. "struct foo;") is parsed.
4874
Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4875
                                       DeclSpec &DS,
4876
                                       const ParsedAttributesView &DeclAttrs,
4877
889k
                                       RecordDecl *&AnonRecord) {
4878
889k
  return ParsedFreeStandingDeclSpec(
4879
889k
      S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4880
889k
}
4881
4882
// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4883
// disambiguate entities defined in different scopes.
4884
// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4885
// compatibility.
4886
// We will pick our mangling number depending on which version of MSVC is being
4887
// targeted.
4888
52.3k
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4889
52.3k
  return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4890
52.3k
             ? 
S->getMSCurManglingNumber()159
4891
52.3k
             : 
S->getMSLastManglingNumber()52.1k
;
4892
52.3k
}
4893
4894
2.41M
void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4895
2.41M
  if (!Context.getLangOpts().CPlusPlus)
4896
1.07M
    return;
4897
4898
1.34M
  if (isa<CXXRecordDecl>(Tag->getParent())) {
4899
    // If this tag is the direct child of a class, number it if
4900
    // it is anonymous.
4901
79.0k
    if (!Tag->getName().empty() || 
Tag->getTypedefNameForAnonDecl()21.8k
)
4902
57.1k
      return;
4903
21.8k
    MangleNumberingContext &MCtx =
4904
21.8k
        Context.getManglingNumberContext(Tag->getParent());
4905
21.8k
    Context.setManglingNumber(
4906
21.8k
        Tag, MCtx.getManglingNumber(
4907
21.8k
                 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4908
21.8k
    return;
4909
79.0k
  }
4910
4911
  // If this tag isn't a direct child of a class, number it if it is local.
4912
1.26M
  MangleNumberingContext *MCtx;
4913
1.26M
  Decl *ManglingContextDecl;
4914
1.26M
  std::tie(MCtx, ManglingContextDecl) =
4915
1.26M
      getCurrentMangleNumberContext(Tag->getDeclContext());
4916
1.26M
  if (MCtx) {
4917
27.2k
    Context.setManglingNumber(
4918
27.2k
        Tag, MCtx->getManglingNumber(
4919
27.2k
                 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4920
27.2k
  }
4921
1.26M
}
4922
4923
namespace {
4924
struct NonCLikeKind {
4925
  enum {
4926
    None,
4927
    BaseClass,
4928
    DefaultMemberInit,
4929
    Lambda,
4930
    Friend,
4931
    OtherMember,
4932
    Invalid,
4933
  } Kind = None;
4934
  SourceRange Range;
4935
4936
154k
  explicit operator bool() { return Kind != None; }
4937
};
4938
}
4939
4940
/// Determine whether a class is C-like, according to the rules of C++
4941
/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4942
25.9k
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4943
25.9k
  if (RD->isInvalidDecl())
4944
0
    return {NonCLikeKind::Invalid, {}};
4945
4946
  // C++ [dcl.typedef]p9: [P1766R1]
4947
  //   An unnamed class with a typedef name for linkage purposes shall not
4948
  //
4949
  //    -- have any base classes
4950
25.9k
  if (RD->getNumBases())
4951
4
    return {NonCLikeKind::BaseClass,
4952
4
            SourceRange(RD->bases_begin()->getBeginLoc(),
4953
4
                        RD->bases_end()[-1].getEndLoc())};
4954
25.9k
  bool Invalid = false;
4955
99.9k
  for (Decl *D : RD->decls()) {
4956
    // Don't complain about things we already diagnosed.
4957
99.9k
    if (D->isInvalidDecl()) {
4958
18
      Invalid = true;
4959
18
      continue;
4960
18
    }
4961
4962
    //  -- have any [...] default member initializers
4963
99.8k
    if (auto *FD = dyn_cast<FieldDecl>(D)) {
4964
99.3k
      if (FD->hasInClassInitializer()) {
4965
4
        auto *Init = FD->getInClassInitializer();
4966
4
        return {NonCLikeKind::DefaultMemberInit,
4967
4
                Init ? Init->getSourceRange() : 
D->getSourceRange()0
};
4968
4
      }
4969
99.3k
      continue;
4970
99.3k
    }
4971
4972
    // FIXME: We don't allow friend declarations. This violates the wording of
4973
    // P1766, but not the intent.
4974
562
    if (isa<FriendDecl>(D))
4975
8
      return {NonCLikeKind::Friend, D->getSourceRange()};
4976
4977
    //  -- declare any members other than non-static data members, member
4978
    //     enumerations, or member classes,
4979
554
    if (isa<StaticAssertDecl>(D) || 
isa<IndirectFieldDecl>(D)542
||
4980
554
        
isa<EnumDecl>(D)524
)
4981
42
      continue;
4982
512
    auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4983
512
    if (!MemberRD) {
4984
124
      if (D->isImplicit())
4985
68
        continue;
4986
56
      return {NonCLikeKind::OtherMember, D->getSourceRange()};
4987
124
    }
4988
4989
    //  -- contain a lambda-expression,
4990
388
    if (MemberRD->isLambda())
4991
0
      return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4992
4993
    //  and all member classes shall also satisfy these requirements
4994
    //  (recursively).
4995
388
    if (MemberRD->isThisDeclarationADefinition()) {
4996
364
      if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4997
4
        return Kind;
4998
364
    }
4999
388
  }
5000
5001
25.8k
  return {Invalid ? 
NonCLikeKind::Invalid18
:
NonCLikeKind::None25.8k
, {}};
5002
25.9k
}
5003
5004
void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5005
597k
                                        TypedefNameDecl *NewTD) {
5006
597k
  if (TagFromDeclSpec->isInvalidDecl())
5007
8
    return;
5008
5009
  // Do nothing if the tag already has a name for linkage purposes.
5010
597k
  if (TagFromDeclSpec->hasNameForLinkage())
5011
441k
    return;
5012
5013
  // A well-formed anonymous tag must always be a TUK_Definition.
5014
155k
  assert(TagFromDeclSpec->isThisDeclarationADefinition());
5015
5016
  // The type must match the tag exactly;  no qualifiers allowed.
5017
155k
  if (!Context.hasSameType(NewTD->getUnderlyingType(),
5018
155k
                           Context.getTagDeclType(TagFromDeclSpec))) {
5019
558
    if (getLangOpts().CPlusPlus)
5020
149
      Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5021
558
    return;
5022
558
  }
5023
5024
  // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5025
  //   An unnamed class with a typedef name for linkage purposes shall [be
5026
  //   C-like].
5027
  //
5028
  // FIXME: Also diagnose if we've already computed the linkage. That ideally
5029
  // shouldn't happen, but there are constructs that the language rule doesn't
5030
  // disallow for which we can't reasonably avoid computing linkage early.
5031
154k
  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5032
154k
  NonCLikeKind NonCLike = RD ? 
getNonCLikeKindForAnonymousStruct(RD)25.5k
5033
154k
                             : 
NonCLikeKind()129k
;
5034
154k
  bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5035
154k
  if (NonCLike || 
ChangesLinkage154k
) {
5036
97
    if (NonCLike.Kind == NonCLikeKind::Invalid)
5037
18
      return;
5038
5039
79
    unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5040
79
    if (ChangesLinkage) {
5041
      // If the linkage changes, we can't accept this as an extension.
5042
12
      if (NonCLike.Kind == NonCLikeKind::None)
5043
7
        DiagID = diag::err_typedef_changes_linkage;
5044
5
      else
5045
5
        DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5046
12
    }
5047
5048
79
    SourceLocation FixitLoc =
5049
79
        getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5050
79
    llvm::SmallString<40> TextToInsert;
5051
79
    TextToInsert += ' ';
5052
79
    TextToInsert += NewTD->getIdentifier()->getName();
5053
5054
79
    Diag(FixitLoc, DiagID)
5055
79
      << isa<TypeAliasDecl>(NewTD)
5056
79
      << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5057
79
    if (NonCLike.Kind != NonCLikeKind::None) {
5058
72
      Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5059
72
        << NonCLike.Kind - 1 << NonCLike.Range;
5060
72
    }
5061
79
    Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5062
79
      << NewTD << isa<TypeAliasDecl>(NewTD);
5063
5064
79
    if (ChangesLinkage)
5065
12
      return;
5066
79
  }
5067
5068
  // Otherwise, set this as the anon-decl typedef for the tag.
5069
154k
  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5070
154k
}
5071
5072
144
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5073
144
  DeclSpec::TST T = DS.getTypeSpecType();
5074
144
  switch (T) {
5075
23
  case DeclSpec::TST_class:
5076
23
    return 0;
5077
54
  case DeclSpec::TST_struct:
5078
54
    return 1;
5079
0
  case DeclSpec::TST_interface:
5080
0
    return 2;
5081
28
  case DeclSpec::TST_union:
5082
28
    return 3;
5083
39
  case DeclSpec::TST_enum:
5084
39
    if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5085
39
      if (ED->isScopedUsingClassTag())
5086
10
        return 5;
5087
29
      if (ED->isScoped())
5088
6
        return 6;
5089
29
    }
5090
23
    return 4;
5091
0
  default:
5092
0
    llvm_unreachable("unexpected type specifier");
5093
144
  }
5094
144
}
5095
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5096
/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5097
/// parameters to cope with template friend declarations.
5098
Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5099
                                       DeclSpec &DS,
5100
                                       const ParsedAttributesView &DeclAttrs,
5101
                                       MultiTemplateParamsArg TemplateParams,
5102
                                       bool IsExplicitInstantiation,
5103
1.60M
                                       RecordDecl *&AnonRecord) {
5104
1.60M
  Decl *TagD = nullptr;
5105
1.60M
  TagDecl *Tag = nullptr;
5106
1.60M
  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5107
1.60M
      
DS.getTypeSpecType() == DeclSpec::TST_struct1.37M
||
5108
1.60M
      
DS.getTypeSpecType() == DeclSpec::TST_interface493k
||
5109
1.60M
      
DS.getTypeSpecType() == DeclSpec::TST_union493k
||
5110
1.60M
      
DS.getTypeSpecType() == DeclSpec::TST_enum473k
) {
5111
1.59M
    TagD = DS.getRepAsDecl();
5112
5113
1.59M
    if (!TagD) // We probably had an error
5114
60
      return nullptr;
5115
5116
    // Note that the above type specs guarantee that the
5117
    // type rep is a Decl, whereas in many of the others
5118
    // it's a Type.
5119
1.59M
    if (isa<TagDecl>(TagD))
5120
1.23M
      Tag = cast<TagDecl>(TagD);
5121
364k
    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5122
364k
      Tag = CTD->getTemplatedDecl();
5123
1.59M
  }
5124
5125
1.60M
  if (Tag) {
5126
1.59M
    handleTagNumbering(Tag, S);
5127
1.59M
    Tag->setFreeStanding();
5128
1.59M
    if (Tag->isInvalidDecl())
5129
674
      return Tag;
5130
1.59M
  }
5131
5132
1.60M
  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5133
    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5134
    // or incomplete types shall not be restrict-qualified."
5135
17
    if (TypeQuals & DeclSpec::TQ_restrict)
5136
2
      Diag(DS.getRestrictSpecLoc(),
5137
2
           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5138
2
           << DS.getSourceRange();
5139
17
  }
5140
5141
1.60M
  if (DS.isInlineSpecified())
5142
2
    Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5143
2
        << getLangOpts().CPlusPlus17;
5144
5145
1.60M
  if (DS.hasConstexprSpecifier()) {
5146
    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5147
    // and definitions of functions and variables.
5148
    // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5149
    // the declaration of a function or function template
5150
68
    if (Tag)
5151
61
      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5152
61
          << GetDiagnosticTypeSpecifierID(DS)
5153
61
          << static_cast<int>(DS.getConstexprSpecifier());
5154
7
    else
5155
7
      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5156
7
          << static_cast<int>(DS.getConstexprSpecifier());
5157
    // Don't emit warnings after this error.
5158
68
    return TagD;
5159
68
  }
5160
5161
1.60M
  DiagnoseFunctionSpecifiers(DS);
5162
5163
1.60M
  if (DS.isFriendSpecified()) {
5164
    // If we're dealing with a decl but not a TagDecl, assume that
5165
    // whatever routines created it handled the friendship aspect.
5166
36.7k
    if (TagD && 
!Tag26.1k
)
5167
12
      return nullptr;
5168
36.7k
    return ActOnFriendTypeDecl(S, DS, TemplateParams);
5169
36.7k
  }
5170
5171
1.57M
  const CXXScopeSpec &SS = DS.getTypeSpecScope();
5172
1.57M
  bool IsExplicitSpecialization =
5173
1.57M
    !TemplateParams.empty() && 
TemplateParams.back()->size() == 0611k
;
5174
1.57M
  if (Tag && 
SS.isNotEmpty()1.56M
&&
!Tag->isCompleteDefinition()3.23k
&&
5175
1.57M
      
!IsExplicitInstantiation133
&&
!IsExplicitSpecialization123
&&
5176
1.57M
      
!isa<ClassTemplatePartialSpecializationDecl>(Tag)27
) {
5177
    // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5178
    // nested-name-specifier unless it is an explicit instantiation
5179
    // or an explicit specialization.
5180
    //
5181
    // FIXME: We allow class template partial specializations here too, per the
5182
    // obvious intent of DR1819.
5183
    //
5184
    // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5185
15
    Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5186
15
        << GetDiagnosticTypeSpecifierID(DS) << SS.getRange();
5187
15
    return nullptr;
5188
15
  }
5189
5190
  // Track whether this decl-specifier declares anything.
5191
1.57M
  bool DeclaresAnything = true;
5192
5193
  // Handle anonymous struct definitions.
5194
1.57M
  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5195
1.10M
    if (!Record->getDeclName() && 
Record->isCompleteDefinition()3.90k
&&
5196
1.10M
        
DS.getStorageClassSpec() != DeclSpec::SCS_typedef3.90k
) {
5197
3.90k
      if (getLangOpts().CPlusPlus ||
5198
3.90k
          
Record->getDeclContext()->isRecord()636
) {
5199
        // If CurContext is a DeclContext that can contain statements,
5200
        // RecursiveASTVisitor won't visit the decls that
5201
        // BuildAnonymousStructOrUnion() will put into CurContext.
5202
        // Also store them here so that they can be part of the
5203
        // DeclStmt that gets created in this case.
5204
        // FIXME: Also return the IndirectFieldDecls created by
5205
        // BuildAnonymousStructOr union, for the same reason?
5206
3.88k
        if (CurContext->isFunctionOrMethod())
5207
42
          AnonRecord = Record;
5208
3.88k
        return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5209
3.88k
                                           Context.getPrintingPolicy());
5210
3.88k
      }
5211
5212
18
      DeclaresAnything = false;
5213
18
    }
5214
1.10M
  }
5215
5216
  // C11 6.7.2.1p2:
5217
  //   A struct-declaration that does not declare an anonymous structure or
5218
  //   anonymous union shall contain a struct-declarator-list.
5219
  //
5220
  // This rule also existed in C89 and C99; the grammar for struct-declaration
5221
  // did not permit a struct-declaration without a struct-declarator-list.
5222
1.56M
  if (!getLangOpts().CPlusPlus && 
CurContext->isRecord()581k
&&
5223
1.56M
      
DS.getStorageClassSpec() == DeclSpec::SCS_unspecified29
) {
5224
    // Check for Microsoft C extension: anonymous struct/union member.
5225
    // Handle 2 kinds of anonymous struct/union:
5226
    //   struct STRUCT;
5227
    //   union UNION;
5228
    // and
5229
    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5230
    //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5231
29
    if ((Tag && 
Tag->getDeclName()21
) ||
5232
29
        
DS.getTypeSpecType() == DeclSpec::TST_typename11
) {
5233
22
      RecordDecl *Record = nullptr;
5234
22
      if (Tag)
5235
18
        Record = dyn_cast<RecordDecl>(Tag);
5236
4
      else if (const RecordType *RT =
5237
4
                   DS.getRepAsType().get()->getAsStructureType())
5238
3
        Record = RT->getDecl();
5239
1
      else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5240
1
        Record = UT->getDecl();
5241
5242
22
      if (Record && getLangOpts().MicrosoftExt) {
5243
9
        Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5244
9
            << Record->isUnion() << DS.getSourceRange();
5245
9
        return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5246
9
      }
5247
5248
13
      DeclaresAnything = false;
5249
13
    }
5250
29
  }
5251
5252
  // Skip all the checks below if we have a type error.
5253
1.56M
  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5254
1.56M
      
(1.56M
TagD1.56M
&&
TagD->isInvalidDecl()1.56M
))
5255
452
    return TagD;
5256
5257
1.56M
  if (getLangOpts().CPlusPlus &&
5258
1.56M
      
DS.getStorageClassSpec() != DeclSpec::SCS_typedef984k
)
5259
984k
    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5260
78.2k
      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5261
78.2k
          
!Enum->getIdentifier()2.26k
&&
!Enum->isInvalidDecl()12
)
5262
12
        DeclaresAnything = false;
5263
5264
1.56M
  if (!DS.isMissingDeclaratorOk()) {
5265
    // Customize diagnostic for a typedef missing a name.
5266
181
    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5267
54
      Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5268
54
          << DS.getSourceRange();
5269
127
    else
5270
127
      DeclaresAnything = false;
5271
181
  }
5272
5273
1.56M
  if (DS.isModulePrivateSpecified() &&
5274
1.56M
      
Tag18
&&
Tag->getDeclContext()->isFunctionOrMethod()18
)
5275
1
    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5276
1
        << llvm::to_underlying(Tag->getTagKind())
5277
1
        << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5278
5279
1.56M
  ActOnDocumentableDecl(TagD);
5280
5281
  // C 6.7/2:
5282
  //   A declaration [...] shall declare at least a declarator [...], a tag,
5283
  //   or the members of an enumeration.
5284
  // C++ [dcl.dcl]p3:
5285
  //   [If there are no declarators], and except for the declaration of an
5286
  //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5287
  //   names into the program, or shall redeclare a name introduced by a
5288
  //   previous declaration.
5289
1.56M
  if (!DeclaresAnything) {
5290
    // In C, we allow this as a (popular) extension / bug. Don't bother
5291
    // producing further diagnostics for redundant qualifiers after this.
5292
170
    Diag(DS.getBeginLoc(), (IsExplicitInstantiation || 
!TemplateParams.empty()164
)
5293
170
                               ? 
diag::err_no_declarators43
5294
170
                               : 
diag::ext_no_declarators127
)
5295
170
        << DS.getSourceRange();
5296
170
    return TagD;
5297
170
  }
5298
5299
  // C++ [dcl.stc]p1:
5300
  //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5301
  //   init-declarator-list of the declaration shall not be empty.
5302
  // C++ [dcl.fct.spec]p1:
5303
  //   If a cv-qualifier appears in a decl-specifier-seq, the
5304
  //   init-declarator-list of the declaration shall not be empty.
5305
  //
5306
  // Spurious qualifiers here appear to be valid in C.
5307
1.56M
  unsigned DiagID = diag::warn_standalone_specifier;
5308
1.56M
  if (getLangOpts().CPlusPlus)
5309
984k
    DiagID = diag::ext_standalone_specifier;
5310
5311
  // Note that a linkage-specification sets a storage class, but
5312
  // 'extern "C" struct foo;' is actually valid and not theoretically
5313
  // useless.
5314
1.56M
  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5315
73
    if (SCS == DeclSpec::SCS_mutable)
5316
      // Since mutable is not a viable storage class specifier in C, there is
5317
      // no reason to treat it as an extension. Instead, diagnose as an error.
5318
1
      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5319
72
    else if (!DS.isExternInLinkageSpec() && 
SCS != DeclSpec::SCS_typedef56
)
5320
2
      Diag(DS.getStorageClassSpecLoc(), DiagID)
5321
2
        << DeclSpec::getSpecifierName(SCS);
5322
73
  }
5323
5324
1.56M
  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5325
0
    Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5326
0
      << DeclSpec::getSpecifierName(TSCS);
5327
1.56M
  if (DS.getTypeQualifiers()) {
5328
4
    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5329
1
      Diag(DS.getConstSpecLoc(), DiagID) << "const";
5330
4
    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5331
0
      Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5332
    // Restrict is covered above.
5333
4
    if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5334
2
      Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5335
4
    if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5336
0
      Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5337
4
  }
5338
5339
  // Warn about ignored type attributes, for example:
5340
  // __attribute__((aligned)) struct A;
5341
  // Attributes should be placed after tag to apply to type declaration.
5342
1.56M
  if (!DS.getAttributes().empty() || 
!DeclAttrs.empty()1.56M
) {
5343
44
    DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5344
44
    if (TypeSpecType == DeclSpec::TST_class ||
5345
44
        
TypeSpecType == DeclSpec::TST_struct39
||
5346
44
        
TypeSpecType == DeclSpec::TST_interface19
||
5347
44
        
TypeSpecType == DeclSpec::TST_union19
||
5348
44
        
TypeSpecType == DeclSpec::TST_enum14
) {
5349
5350
68
      auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5351
68
        unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5352
68
        if (AL.isAlignas() && 
!getLangOpts().CPlusPlus8
)
5353
8
          DiagnosticId = diag::warn_attribute_ignored;
5354
60
        else if (AL.isRegularKeywordAttribute())
5355
2
          DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5356
58
        else
5357
58
          DiagnosticId = diag::warn_declspec_attribute_ignored;
5358
68
        Diag(AL.getLoc(), DiagnosticId)
5359
68
            << AL << GetDiagnosticTypeSpecifierID(DS);
5360
68
      };
5361
5362
44
      llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5363
44
      llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5364
44
    }
5365
44
  }
5366
5367
1.56M
  return TagD;
5368
1.56M
}
5369
5370
/// We are trying to inject an anonymous member into the given scope;
5371
/// check if there's an existing declaration that can't be overloaded.
5372
///
5373
/// \return true if this is a forbidden redeclaration
5374
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5375
                                         DeclContext *Owner,
5376
                                         DeclarationName Name,
5377
                                         SourceLocation NameLoc, bool IsUnion,
5378
6.73k
                                         StorageClass SC) {
5379
6.73k
  LookupResult R(SemaRef, Name, NameLoc,
5380
6.73k
                 Owner->isRecord() ? 
Sema::LookupMemberName6.58k
5381
6.73k
                                   : 
Sema::LookupOrdinaryName149
,
5382
6.73k
                 Sema::ForVisibleRedeclaration);
5383
6.73k
  if (!SemaRef.LookupName(R, S)) 
return false6.70k
;
5384
5385
  // Pick a representative declaration.
5386
33
  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5387
33
  assert(PrevDecl && "Expected a non-null Decl");
5388
5389
33
  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5390
15
    return false;
5391
5392
18
  if (SC == StorageClass::SC_None &&
5393
18
      
PrevDecl->isPlaceholderVar(SemaRef.getLangOpts())16
&&
5394
18
      
(7
Owner->isFunctionOrMethod()7
||
Owner->isRecord()4
)) {
5395
7
    if (!Owner->isRecord())
5396
3
      SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5397
7
    return false;
5398
7
  }
5399
5400
11
  SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5401
11
    << IsUnion << Name;
5402
11
  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5403
5404
11
  return true;
5405
18
}
5406
5407
1.87M
void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5408
1.87M
  if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5409
1.01M
    DiagPlaceholderFieldDeclDefinitions(RD);
5410
1.87M
}
5411
5412
/// Emit diagnostic warnings for placeholder members.
5413
/// We can only do that after the class is fully constructed,
5414
/// as anonymous union/structs can insert placeholders
5415
/// in their parent scope (which might be a Record).
5416
1.01M
void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5417
1.01M
  if (!getLangOpts().CPlusPlus)
5418
397k
    return;
5419
5420
  // This function can be parsed before we have validated the
5421
  // structure as an anonymous struct
5422
615k
  if (Record->isAnonymousStructOrUnion())
5423
0
    return;
5424
5425
615k
  const NamedDecl *First = 0;
5426
3.38M
  for (const Decl *D : Record->decls()) {
5427
3.38M
    const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5428
3.38M
    if (!ND || 
!ND->isPlaceholderVar(getLangOpts())3.19M
)
5429
3.38M
      continue;
5430
35
    if (!First)
5431
21
      First = ND;
5432
14
    else
5433
14
      DiagPlaceholderVariableDefinition(ND->getLocation());
5434
35
  }
5435
615k
}
5436
5437
/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5438
/// anonymous struct or union AnonRecord into the owning context Owner
5439
/// and scope S. This routine will be invoked just after we realize
5440
/// that an unnamed union or struct is actually an anonymous union or
5441
/// struct, e.g.,
5442
///
5443
/// @code
5444
/// union {
5445
///   int i;
5446
///   float f;
5447
/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5448
///    // f into the surrounding scope.x
5449
/// @endcode
5450
///
5451
/// This routine is recursive, injecting the names of nested anonymous
5452
/// structs/unions into the owning context and scope as well.
5453
static bool
5454
InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5455
                                    RecordDecl *AnonRecord, AccessSpecifier AS,
5456
                                    StorageClass SC,
5457
3.89k
                                    SmallVectorImpl<NamedDecl *> &Chaining) {
5458
3.89k
  bool Invalid = false;
5459
5460
  // Look every FieldDecl and IndirectFieldDecl with a name.
5461
7.81k
  for (auto *D : AnonRecord->decls()) {
5462
7.81k
    if ((isa<FieldDecl>(D) || 
isa<IndirectFieldDecl>(D)1.17k
) &&
5463
7.81k
        
cast<NamedDecl>(D)->getDeclName()6.95k
) {
5464
6.73k
      ValueDecl *VD = cast<ValueDecl>(D);
5465
6.73k
      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5466
6.73k
                                       VD->getLocation(), AnonRecord->isUnion(),
5467
6.73k
                                       SC)) {
5468
        // C++ [class.union]p2:
5469
        //   The names of the members of an anonymous union shall be
5470
        //   distinct from the names of any other entity in the
5471
        //   scope in which the anonymous union is declared.
5472
11
        Invalid = true;
5473
6.72k
      } else {
5474
        // C++ [class.union]p2:
5475
        //   For the purpose of name lookup, after the anonymous union
5476
        //   definition, the members of the anonymous union are
5477
        //   considered to have been defined in the scope in which the
5478
        //   anonymous union is declared.
5479
6.72k
        unsigned OldChainingSize = Chaining.size();
5480
6.72k
        if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5481
308
          Chaining.append(IF->chain_begin(), IF->chain_end());
5482
6.41k
        else
5483
6.41k
          Chaining.push_back(VD);
5484
5485
6.72k
        assert(Chaining.size() >= 2);
5486
6.72k
        NamedDecl **NamedChain =
5487
6.72k
          new (SemaRef.Context)NamedDecl*[Chaining.size()];
5488
20.5k
        for (unsigned i = 0; i < Chaining.size(); 
i++13.8k
)
5489
13.8k
          NamedChain[i] = Chaining[i];
5490
5491
6.72k
        IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5492
6.72k
            SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5493
6.72k
            VD->getType(), {NamedChain, Chaining.size()});
5494
5495
6.72k
        for (const auto *Attr : VD->attrs())
5496
23
          IndirectField->addAttr(Attr->clone(SemaRef.Context));
5497
5498
6.72k
        IndirectField->setAccess(AS);
5499
6.72k
        IndirectField->setImplicit();
5500
6.72k
        SemaRef.PushOnScopeChains(IndirectField, S);
5501
5502
        // That includes picking up the appropriate access specifier.
5503
6.72k
        if (AS != AS_none) 
IndirectField->setAccess(AS)5.56k
;
5504
5505
6.72k
        Chaining.resize(OldChainingSize);
5506
6.72k
      }
5507
6.73k
    }
5508
7.81k
  }
5509
5510
3.89k
  return Invalid;
5511
3.89k
}
5512
5513
/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5514
/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5515
/// illegal input values are mapped to SC_None.
5516
static StorageClass
5517
3.09M
StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5518
3.09M
  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5519
3.09M
  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5520
3.09M
         "Parser allowed 'typedef' as storage class VarDecl.");
5521
3.09M
  switch (StorageClassSpec) {
5522
1.87M
  case DeclSpec::SCS_unspecified:    return SC_None;
5523
963k
  case DeclSpec::SCS_extern:
5524
963k
    if (DS.isExternInLinkageSpec())
5525
43.5k
      return SC_None;
5526
919k
    return SC_Extern;
5527
255k
  case DeclSpec::SCS_static:         return SC_Static;
5528
53
  case DeclSpec::SCS_auto:           return SC_Auto;
5529
737
  case DeclSpec::SCS_register:       return SC_Register;
5530
50
  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5531
    // Illegal SCSs map to None: error reporting is up to the caller.
5532
5
  case DeclSpec::SCS_mutable:        // Fall through.
5533
5
  case DeclSpec::SCS_typedef:        return SC_None;
5534
3.09M
  }
5535
0
  llvm_unreachable("unknown storage class specifier");
5536
0
}
5537
5538
20
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5539
20
  assert(Record->hasInClassInitializer());
5540
5541
40
  
for (const auto *I : Record->decls())20
{
5542
40
    const auto *FD = dyn_cast<FieldDecl>(I);
5543
40
    if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5544
4
      FD = IFD->getAnonField();
5545
40
    if (FD && 
FD->hasInClassInitializer()25
)
5546
20
      return FD->getLocation();
5547
40
  }
5548
5549
0
  llvm_unreachable("couldn't find in-class initializer");
5550
0
}
5551
5552
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5553
8.15k
                                      SourceLocation DefaultInitLoc) {
5554
8.15k
  if (!Parent->isUnion() || 
!Parent->hasInClassInitializer()172
)
5555
8.13k
    return;
5556
5557
15
  S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5558
15
  S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5559
15
}
5560
5561
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5562
101
                                      CXXRecordDecl *AnonUnion) {
5563
101
  if (!Parent->isUnion() || 
!Parent->hasInClassInitializer()14
)
5564
96
    return;
5565
5566
5
  checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5567
5
}
5568
5569
/// BuildAnonymousStructOrUnion - Handle the declaration of an
5570
/// anonymous structure or union. Anonymous unions are a C++ feature
5571
/// (C++ [class.union]) and a C11 feature; anonymous structures
5572
/// are a C11 feature and GNU C++ extension.
5573
Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5574
                                        AccessSpecifier AS,
5575
                                        RecordDecl *Record,
5576
3.88k
                                        const PrintingPolicy &Policy) {
5577
3.88k
  DeclContext *Owner = Record->getDeclContext();
5578
5579
  // Diagnose whether this anonymous struct/union is an extension.
5580
3.88k
  if (Record->isUnion() && 
!getLangOpts().CPlusPlus2.39k
&&
!getLangOpts().C11326
)
5581
12
    Diag(Record->getLocation(), diag::ext_anonymous_union);
5582
3.87k
  else if (!Record->isUnion() && 
getLangOpts().CPlusPlus1.48k
)
5583
1.19k
    Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5584
2.67k
  else if (!Record->isUnion() && 
!getLangOpts().C11292
)
5585
49
    Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5586
5587
  // C and C++ require different kinds of checks for anonymous
5588
  // structs/unions.
5589
3.88k
  bool Invalid = false;
5590
3.88k
  if (getLangOpts().CPlusPlus) {
5591
3.26k
    const char *PrevSpec = nullptr;
5592
3.26k
    if (Record->isUnion()) {
5593
      // C++ [class.union]p6:
5594
      // C++17 [class.union.anon]p2:
5595
      //   Anonymous unions declared in a named namespace or in the
5596
      //   global namespace shall be declared static.
5597
2.07k
      unsigned DiagID;
5598
2.07k
      DeclContext *OwnerScope = Owner->getRedeclContext();
5599
2.07k
      if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5600
2.07k
          
(2.00k
OwnerScope->isTranslationUnit()2.00k
||
5601
2.00k
           
(1.99k
OwnerScope->isNamespace()1.99k
&&
5602
1.99k
            
!cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()12
))) {
5603
10
        Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5604
10
          << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5605
5606
        // Recover by adding 'static'.
5607
10
        DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5608
10
                               PrevSpec, DiagID, Policy);
5609
10
      }
5610
      // C++ [class.union]p6:
5611
      //   A storage class is not allowed in a declaration of an
5612
      //   anonymous union in a class scope.
5613
2.06k
      else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5614
2.06k
               
isa<RecordDecl>(Owner)69
) {
5615
1
        Diag(DS.getStorageClassSpecLoc(),
5616
1
             diag::err_anonymous_union_with_storage_spec)
5617
1
          << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5618
5619
        // Recover by removing the storage specifier.
5620
1
        DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5621
1
                               SourceLocation(),
5622
1
                               PrevSpec, DiagID, Context.getPrintingPolicy());
5623
1
      }
5624
2.07k
    }
5625
5626
    // Ignore const/volatile/restrict qualifiers.
5627
3.26k
    if (DS.getTypeQualifiers()) {
5628
4
      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5629
1
        Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5630
1
          << Record->isUnion() << "const"
5631
1
          << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5632
4
      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5633
1
        Diag(DS.getVolatileSpecLoc(),
5634
1
             diag::ext_anonymous_struct_union_qualified)
5635
1
          << Record->isUnion() << "volatile"
5636
1
          << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5637
4
      if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5638
0
        Diag(DS.getRestrictSpecLoc(),
5639
0
             diag::ext_anonymous_struct_union_qualified)
5640
0
          << Record->isUnion() << "restrict"
5641
0
          << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5642
4
      if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5643
2
        Diag(DS.getAtomicSpecLoc(),
5644
2
             diag::ext_anonymous_struct_union_qualified)
5645
2
          << Record->isUnion() << "_Atomic"
5646
2
          << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5647
4
      if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5648
0
        Diag(DS.getUnalignedSpecLoc(),
5649
0
             diag::ext_anonymous_struct_union_qualified)
5650
0
          << Record->isUnion() << "__unaligned"
5651
0
          << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5652
5653
4
      DS.ClearTypeQualifiers();
5654
4
    }
5655
5656
    // C++ [class.union]p2:
5657
    //   The member-specification of an anonymous union shall only
5658
    //   define non-static data members. [Note: nested types and
5659
    //   functions cannot be declared within an anonymous union. ]
5660
6.26k
    for (auto *Mem : Record->decls()) {
5661
      // Ignore invalid declarations; we already diagnosed them.
5662
6.26k
      if (Mem->isInvalidDecl())
5663
8
        continue;
5664
5665
6.25k
      if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5666
        // C++ [class.union]p3:
5667
        //   An anonymous union shall not have private or protected
5668
        //   members (clause 11).
5669
5.67k
        assert(FD->getAccess() != AS_none);
5670
5.67k
        if (FD->getAccess() != AS_public) {
5671
6
          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5672
6
            << Record->isUnion() << (FD->getAccess() == AS_protected);
5673
6
          Invalid = true;
5674
6
        }
5675
5676
        // C++ [class.union]p1
5677
        //   An object of a class with a non-trivial constructor, a non-trivial
5678
        //   copy constructor, a non-trivial destructor, or a non-trivial copy
5679
        //   assignment operator cannot be a member of a union, nor can an
5680
        //   array of such objects.
5681
5.67k
        if (CheckNontrivialField(FD))
5682
1
          Invalid = true;
5683
5.67k
      } else 
if (584
Mem->isImplicit()584
) {
5684
        // Any implicit members are fine.
5685
353
      } else 
if (231
isa<TagDecl>(Mem)231
&&
Mem->getDeclContext() != Record213
) {
5686
        // This is a type that showed up in an
5687
        // elaborated-type-specifier inside the anonymous struct or
5688
        // union, but which actually declares a type outside of the
5689
        // anonymous struct or union. It's okay.
5690
229
      } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5691
211
        if (!MemRecord->isAnonymousStructOrUnion() &&
5692
211
            
MemRecord->getDeclName()54
) {
5693
          // Visual C++ allows type definition in anonymous struct or union.
5694
27
          if (getLangOpts().MicrosoftExt)
5695
18
            Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5696
18
              << Record->isUnion();
5697
9
          else {
5698
            // This is a nested type declaration.
5699
9
            Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5700
9
              << Record->isUnion();
5701
9
            Invalid = true;
5702
9
          }
5703
184
        } else {
5704
          // This is an anonymous type definition within another anonymous type.
5705
          // This is a popular extension, provided by Plan9, MSVC and GCC, but
5706
          // not part of standard C++.
5707
184
          Diag(MemRecord->getLocation(),
5708
184
               diag::ext_anonymous_record_with_anonymous_type)
5709
184
            << Record->isUnion();
5710
184
        }
5711
211
      } else 
if (18
isa<AccessSpecDecl>(Mem)18
) {
5712
        // Any access specifier is fine.
5713
15
      } else if (isa<StaticAssertDecl>(Mem)) {
5714
        // In C++1z, static_assert declarations are also fine.
5715
8
      } else {
5716
        // We have something that isn't a non-static data
5717
        // member. Complain about it.
5718
8
        unsigned DK = diag::err_anonymous_record_bad_member;
5719
8
        if (isa<TypeDecl>(Mem))
5720
6
          DK = diag::err_anonymous_record_with_type;
5721
2
        else if (isa<FunctionDecl>(Mem))
5722
2
          DK = diag::err_anonymous_record_with_function;
5723
0
        else if (isa<VarDecl>(Mem))
5724
0
          DK = diag::err_anonymous_record_with_static;
5725
5726
        // Visual C++ allows type definition in anonymous struct or union.
5727
8
        if (getLangOpts().MicrosoftExt &&
5728
8
            
DK == diag::err_anonymous_record_with_type6
)
5729
6
          Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5730
6
            << Record->isUnion();
5731
2
        else {
5732
2
          Diag(Mem->getLocation(), DK) << Record->isUnion();
5733
2
          Invalid = true;
5734
2
        }
5735
8
      }
5736
6.25k
    }
5737
5738
    // C++11 [class.union]p8 (DR1460):
5739
    //   At most one variant member of a union may have a
5740
    //   brace-or-equal-initializer.
5741
3.26k
    if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5742
3.26k
        
Owner->isRecord()110
)
5743
101
      checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5744
101
                                cast<CXXRecordDecl>(Record));
5745
3.26k
  }
5746
5747
3.88k
  if (!Record->isUnion() && 
!Owner->isRecord()1.48k
) {
5748
12
    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5749
12
      << getLangOpts().CPlusPlus;
5750
12
    Invalid = true;
5751
12
  }
5752
5753
  // C++ [dcl.dcl]p3:
5754
  //   [If there are no declarators], and except for the declaration of an
5755
  //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5756
  //   names into the program
5757
  // C++ [class.mem]p2:
5758
  //   each such member-declaration shall either declare at least one member
5759
  //   name of the class or declare at least one unnamed bit-field
5760
  //
5761
  // For C this is an error even for a named struct, and is diagnosed elsewhere.
5762
3.88k
  if (getLangOpts().CPlusPlus && 
Record->field_empty()3.26k
)
5763
89
    Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5764
5765
  // Mock up a declarator.
5766
3.88k
  Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5767
3.88k
  StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5768
3.88k
  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5769
3.88k
  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5770
5771
  // Create a declaration for this anonymous struct/union.
5772
3.88k
  NamedDecl *Anon = nullptr;
5773
3.88k
  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5774
3.75k
    Anon = FieldDecl::Create(
5775
3.75k
        Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5776
3.75k
        /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5777
3.75k
        /*BitWidth=*/nullptr, /*Mutable=*/false,
5778
3.75k
        /*InitStyle=*/ICIS_NoInit);
5779
3.75k
    Anon->setAccess(AS);
5780
3.75k
    ProcessDeclAttributes(S, Anon, Dc);
5781
5782
3.75k
    if (getLangOpts().CPlusPlus)
5783
3.14k
      FieldCollector->Add(cast<FieldDecl>(Anon));
5784
3.75k
  } else {
5785
125
    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5786
125
    if (SCSpec == DeclSpec::SCS_mutable) {
5787
      // mutable can only appear on non-static class members, so it's always
5788
      // an error here
5789
0
      Diag(Record->getLocation(), diag::err_mutable_nonmember);
5790
0
      Invalid = true;
5791
0
      SC = SC_None;
5792
0
    }
5793
5794
125
    Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5795
125
                           Record->getLocation(), /*IdentifierInfo=*/nullptr,
5796
125
                           Context.getTypeDeclType(Record), TInfo, SC);
5797
125
    ProcessDeclAttributes(S, Anon, Dc);
5798
5799
    // Default-initialize the implicit variable. This initialization will be
5800
    // trivial in almost all cases, except if a union member has an in-class
5801
    // initializer:
5802
    //   union { int n = 0; };
5803
125
    ActOnUninitializedDecl(Anon);
5804
125
  }
5805
3.88k
  Anon->setImplicit();
5806
5807
  // Mark this as an anonymous struct/union type.
5808
3.88k
  Record->setAnonymousStructOrUnion(true);
5809
5810
  // Add the anonymous struct/union object to the current
5811
  // context. We'll be referencing this object when we refer to one of
5812
  // its members.
5813
3.88k
  Owner->addDecl(Anon);
5814
5815
  // Inject the members of the anonymous struct/union into the owning
5816
  // context and into the identifier resolver chain for name lookup
5817
  // purposes.
5818
3.88k
  SmallVector<NamedDecl*, 2> Chain;
5819
3.88k
  Chain.push_back(Anon);
5820
5821
3.88k
  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5822
3.88k
                                          Chain))
5823
7
    Invalid = true;
5824
5825
3.88k
  if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5826
125
    if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5827
13
      MangleNumberingContext *MCtx;
5828
13
      Decl *ManglingContextDecl;
5829
13
      std::tie(MCtx, ManglingContextDecl) =
5830
13
          getCurrentMangleNumberContext(NewVD->getDeclContext());
5831
13
      if (MCtx) {
5832
8
        Context.setManglingNumber(
5833
8
            NewVD, MCtx->getManglingNumber(
5834
8
                       NewVD, getMSManglingNumber(getLangOpts(), S)));
5835
8
        Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5836
8
      }
5837
13
    }
5838
125
  }
5839
5840
3.88k
  if (Invalid)
5841
33
    Anon->setInvalidDecl();
5842
5843
3.88k
  return Anon;
5844
3.88k
}
5845
5846
/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5847
/// Microsoft C anonymous structure.
5848
/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5849
/// Example:
5850
///
5851
/// struct A { int a; };
5852
/// struct B { struct A; int b; };
5853
///
5854
/// void foo() {
5855
///   B var;
5856
///   var.a = 3;
5857
/// }
5858
///
5859
Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5860
9
                                           RecordDecl *Record) {
5861
9
  assert(Record && "expected a record!");
5862
5863
  // Mock up a declarator.
5864
9
  Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5865
9
  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5866
9
  assert(TInfo && "couldn't build declarator info for anonymous struct");
5867
5868
9
  auto *ParentDecl = cast<RecordDecl>(CurContext);
5869
9
  QualType RecTy = Context.getTypeDeclType(Record);
5870
5871
  // Create a declaration for this anonymous struct.
5872
9
  NamedDecl *Anon =
5873
9
      FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5874
9
                        /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5875
9
                        /*BitWidth=*/nullptr, /*Mutable=*/false,
5876
9
                        /*InitStyle=*/ICIS_NoInit);
5877
9
  Anon->setImplicit();
5878
5879
  // Add the anonymous struct object to the current context.
5880
9
  CurContext->addDecl(Anon);
5881
5882
  // Inject the members of the anonymous struct into the current
5883
  // context and into the identifier resolver chain for name lookup
5884
  // purposes.
5885
9
  SmallVector<NamedDecl*, 2> Chain;
5886
9
  Chain.push_back(Anon);
5887
5888
9
  RecordDecl *RecordDef = Record->getDefinition();
5889
9
  if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5890
9
                               diag::err_field_incomplete_or_sizeless) ||
5891
9
      InjectAnonymousStructOrUnionMembers(
5892
8
          *this, S, CurContext, RecordDef, AS_none,
5893
8
          StorageClassSpecToVarDeclStorageClass(DS), Chain)) {
5894
1
    Anon->setInvalidDecl();
5895
1
    ParentDecl->setInvalidDecl();
5896
1
  }
5897
5898
9
  return Anon;
5899
9
}
5900
5901
/// GetNameForDeclarator - Determine the full declaration name for the
5902
/// given Declarator.
5903
121M
DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5904
121M
  return GetNameFromUnqualifiedId(D.getName());
5905
121M
}
5906
5907
/// Retrieves the declaration name from a parsed unqualified-id.
5908
DeclarationNameInfo
5909
146M
Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5910
146M
  DeclarationNameInfo NameInfo;
5911
146M
  NameInfo.setLoc(Name.StartLocation);
5912
5913
146M
  switch (Name.getKind()) {
5914
5915
1.95k
  case UnqualifiedIdKind::IK_ImplicitSelfParam:
5916
142M
  case UnqualifiedIdKind::IK_Identifier:
5917
142M
    NameInfo.setName(Name.Identifier);
5918
142M
    return NameInfo;
5919
5920
4.88k
  case UnqualifiedIdKind::IK_DeductionGuideName: {
5921
    // C++ [temp.deduct.guide]p3:
5922
    //   The simple-template-id shall name a class template specialization.
5923
    //   The template-name shall be the same identifier as the template-name
5924
    //   of the simple-template-id.
5925
    // These together intend to imply that the template-name shall name a
5926
    // class template.
5927
    // FIXME: template<typename T> struct X {};
5928
    //        template<typename T> using Y = X<T>;
5929
    //        Y(int) -> Y<int>;
5930
    //   satisfies these rules but does not name a class template.
5931
4.88k
    TemplateName TN = Name.TemplateName.get().get();
5932
4.88k
    auto *Template = TN.getAsTemplateDecl();
5933
4.88k
    if (!Template || !isa<ClassTemplateDecl>(Template)) {
5934
3
      Diag(Name.StartLocation,
5935
3
           diag::err_deduction_guide_name_not_class_template)
5936
3
        << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5937
3
      if (Template)
5938
3
        Diag(Template->getLocation(), diag::note_template_decl_here);
5939
3
      return DeclarationNameInfo();
5940
3
    }
5941
5942
4.87k
    NameInfo.setName(
5943
4.87k
        Context.DeclarationNames.getCXXDeductionGuideName(Template));
5944
4.87k
    return NameInfo;
5945
4.88k
  }
5946
5947
1.83M
  case UnqualifiedIdKind::IK_OperatorFunctionId:
5948
1.83M
    NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5949
1.83M
                                           Name.OperatorFunctionId.Operator));
5950
1.83M
    NameInfo.setCXXOperatorNameRange(SourceRange(
5951
1.83M
        Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5952
1.83M
    return NameInfo;
5953
5954
3.33k
  case UnqualifiedIdKind::IK_LiteralOperatorId:
5955
3.33k
    NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5956
3.33k
                                                           Name.Identifier));
5957
3.33k
    NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5958
3.33k
    return NameInfo;
5959
5960
69.2k
  case UnqualifiedIdKind::IK_ConversionFunctionId: {
5961
69.2k
    TypeSourceInfo *TInfo;
5962
69.2k
    QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5963
69.2k
    if (Ty.isNull())
5964
0
      return DeclarationNameInfo();
5965
69.2k
    NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5966
69.2k
                                               Context.getCanonicalType(Ty)));
5967
69.2k
    NameInfo.setNamedTypeInfo(TInfo);
5968
69.2k
    return NameInfo;
5969
69.2k
  }
5970
5971
1.62M
  case UnqualifiedIdKind::IK_ConstructorName: {
5972
1.62M
    TypeSourceInfo *TInfo;
5973
1.62M
    QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5974
1.62M
    if (Ty.isNull())
5975
0
      return DeclarationNameInfo();
5976
1.62M
    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5977
1.62M
                                              Context.getCanonicalType(Ty)));
5978
1.62M
    NameInfo.setNamedTypeInfo(TInfo);
5979
1.62M
    return NameInfo;
5980
1.62M
  }
5981
5982
123
  case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5983
    // In well-formed code, we can only have a constructor
5984
    // template-id that refers to the current context, so go there
5985
    // to find the actual type being constructed.
5986
123
    CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5987
123
    if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5988
0
      return DeclarationNameInfo();
5989
5990
    // Determine the type of the class being constructed.
5991
123
    QualType CurClassType = Context.getTypeDeclType(CurClass);
5992
5993
    // FIXME: Check two things: that the template-id names the same type as
5994
    // CurClassType, and that the template-id does not occur when the name
5995
    // was qualified.
5996
5997
123
    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5998
123
                                    Context.getCanonicalType(CurClassType)));
5999
    // FIXME: should we retrieve TypeSourceInfo?
6000
123
    NameInfo.setNamedTypeInfo(nullptr);
6001
123
    return NameInfo;
6002
123
  }
6003
6004
268k
  case UnqualifiedIdKind::IK_DestructorName: {
6005
268k
    TypeSourceInfo *TInfo;
6006
268k
    QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6007
268k
    if (Ty.isNull())
6008
0
      return DeclarationNameInfo();
6009
268k
    NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6010
268k
                                              Context.getCanonicalType(Ty)));
6011
268k
    NameInfo.setNamedTypeInfo(TInfo);
6012
268k
    return NameInfo;
6013
268k
  }
6014
6015
28.6k
  case UnqualifiedIdKind::IK_TemplateId: {
6016
28.6k
    TemplateName TName = Name.TemplateId->Template.get();
6017
28.6k
    SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6018
28.6k
    return Context.getNameForTemplate(TName, TNameLoc);
6019
268k
  }
6020
6021
146M
  } // switch (Name.getKind())
6022
6023
0
  llvm_unreachable("Unknown name kind");
6024
0
}
6025
6026
50
static QualType getCoreType(QualType Ty) {
6027
74
  do {
6028
74
    if (Ty->isPointerType() || 
Ty->isReferenceType()61
)
6029
24
      Ty = Ty->getPointeeType();
6030
50
    else if (Ty->isArrayType())
6031
0
      Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6032
50
    else
6033
50
      return Ty.withoutLocalFastQualifiers();
6034
74
  } while (
true24
);
6035
50
}
6036
6037
/// hasSimilarParameters - Determine whether the C++ functions Declaration
6038
/// and Definition have "nearly" matching parameters. This heuristic is
6039
/// used to improve diagnostics in the case where an out-of-line function
6040
/// definition doesn't match any declaration within the class or namespace.
6041
/// Also sets Params to the list of indices to the parameters that differ
6042
/// between the declaration and the definition. If hasSimilarParameters
6043
/// returns true and Params is empty, then all of the parameters match.
6044
static bool hasSimilarParameters(ASTContext &Context,
6045
                                     FunctionDecl *Declaration,
6046
                                     FunctionDecl *Definition,
6047
245
                                     SmallVectorImpl<unsigned> &Params) {
6048
245
  Params.clear();
6049
245
  if (Declaration->param_size() != Definition->param_size())
6050
51
    return false;
6051
233
  
for (unsigned Idx = 0; 194
Idx < Declaration->param_size();
++Idx39
) {
6052
55
    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6053
55
    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6054
6055
    // The parameter types are identical
6056
55
    if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6057
30
      continue;
6058
6059
25
    QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6060
25
    QualType DefParamBaseTy = getCoreType(DefParamTy);
6061
25
    const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6062
25
    const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6063
6064
25
    if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6065
25
        
(21
DeclTyName21
&&
DeclTyName == DefTyName13
))
6066
9
      Params.push_back(Idx);
6067
16
    else  // The two parameters aren't even close
6068
16
      return false;
6069
25
  }
6070
6071
178
  return true;
6072
194
}
6073
6074
/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6075
/// declarator needs to be rebuilt in the current instantiation.
6076
/// Any bits of declarator which appear before the name are valid for
6077
/// consideration here.  That's specifically the type in the decl spec
6078
/// and the base type in any member-pointer chunks.
6079
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6080
293k
                                                    DeclarationName Name) {
6081
  // The types we specifically need to rebuild are:
6082
  //   - typenames, typeofs, and decltypes
6083
  //   - types which will become injected class names
6084
  // Of course, we also need to rebuild any type referencing such a
6085
  // type.  It's safest to just say "dependent", but we call out a
6086
  // few cases here.
6087
6088
293k
  DeclSpec &DS = D.getMutableDeclSpec();
6089
293k
  switch (DS.getTypeSpecType()) {
6090
125k
  case DeclSpec::TST_typename:
6091
125k
  case DeclSpec::TST_typeofType:
6092
125k
  case DeclSpec::TST_typeof_unqualType:
6093
2.01M
#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6094
2.01M
#include 
"clang/Basic/TransformTypeTraits.def"125k
6095
2.01M
  case DeclSpec::TST_atomic: {
6096
    // Grab the type from the parser.
6097
125k
    TypeSourceInfo *TSI = nullptr;
6098
125k
    QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6099
125k
    if (T.isNull() || !T->isInstantiationDependentType()) 
break13.6k
;
6100
6101
    // Make sure there's a type source info.  This isn't really much
6102
    // of a waste; most dependent types should have type source info
6103
    // attached already.
6104
112k
    if (!TSI)
6105
17.4k
      TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
6106
6107
    // Rebuild the type in the current instantiation.
6108
112k
    TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6109
112k
    if (!TSI) 
return true4
;
6110
6111
    // Store the new type back in the decl spec.
6112
112k
    ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6113
112k
    DS.UpdateTypeRep(LocType);
6114
112k
    break;
6115
112k
  }
6116
6117
3
  case DeclSpec::TST_decltype:
6118
3
  case DeclSpec::TST_typeof_unqualExpr:
6119
3
  case DeclSpec::TST_typeofExpr: {
6120
3
    Expr *E = DS.getRepAsExpr();
6121
3
    ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6122
3
    if (Result.isInvalid()) 
return true0
;
6123
3
    DS.UpdateExprRep(Result.get());
6124
3
    break;
6125
3
  }
6126
6127
167k
  default:
6128
    // Nothing to do for these decl specs.
6129
167k
    break;
6130
293k
  }
6131
6132
  // It doesn't matter what order we do this in.
6133
574k
  
for (unsigned I = 0, E = D.getNumTypeObjects(); 293k
I != E;
++I281k
) {
6134
281k
    DeclaratorChunk &Chunk = D.getTypeObject(I);
6135
6136
    // The only type information in the declarator which can come
6137
    // before the declaration name is the base type of a member
6138
    // pointer.
6139
281k
    if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6140
281k
      continue;
6141
6142
    // Rebuild the scope specifier in-place.
6143
3
    CXXScopeSpec &SS = Chunk.Mem.Scope();
6144
3
    if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6145
0
      return true;
6146
3
  }
6147
6148
293k
  return false;
6149
293k
}
6150
6151
/// Returns true if the declaration is declared in a system header or from a
6152
/// system macro.
6153
16.4M
static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6154
16.4M
  return SM.isInSystemHeader(D->getLocation()) ||
6155
16.4M
         
SM.isInSystemMacro(D->getLocation())124k
;
6156
16.4M
}
6157
6158
68.0M
void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6159
  // Avoid warning twice on the same identifier, and don't warn on redeclaration
6160
  // of system decl.
6161
68.0M
  if (D->getPreviousDecl() || 
D->isImplicit()67.0M
)
6162
5.24M
    return;
6163
62.7M
  ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6164
62.7M
  if (Status != ReservedIdentifierStatus::NotReserved &&
6165
62.7M
      
!isFromSystemHeader(Context.getSourceManager(), D)16.4M
) {
6166
111k
    Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6167
111k
        << D << static_cast<int>(Status);
6168
111k
  }
6169
62.7M
}
6170
6171
34.7M
Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6172
34.7M
  D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6173
6174
  // Check if we are in an `omp begin/end declare variant` scope. Handle this
6175
  // declaration only if the `bind_to_declaration` extension is set.
6176
34.7M
  SmallVector<FunctionDecl *, 4> Bases;
6177
34.7M
  if (LangOpts.OpenMP && 
isInOpenMPDeclareVariantScope()297k
)
6178
9.65k
    if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6179
9.65k
              implementation_extension_bind_to_declaration))
6180
1
    ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6181
1
        S, D, MultiTemplateParamsArg(), Bases);
6182
6183
34.7M
  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6184
6185
34.7M
  if (OriginalLexicalContext && 
OriginalLexicalContext->isObjCContainer()43.2k
&&
6186
34.7M
      
Dcl43.2k
&&
Dcl->getDeclContext()->isFileContext()43.2k
)
6187
38.8k
    Dcl->setTopLevelDeclInObjCContainer();
6188
6189
34.7M
  if (!Bases.empty())
6190
1
    ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
6191
6192
34.7M
  return Dcl;
6193
34.7M
}
6194
6195
/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6196
///   If T is the name of a class, then each of the following shall have a
6197
///   name different from T:
6198
///     - every static data member of class T;
6199
///     - every member function of class T
6200
///     - every member of class T that is itself a type;
6201
/// \returns true if the declaration name violates these rules.
6202
bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6203
7.03M
                                   DeclarationNameInfo NameInfo) {
6204
7.03M
  DeclarationName Name = NameInfo.getName();
6205
6206
7.03M
  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6207
7.03M
  while (Record && 
Record->isAnonymousStructOrUnion()849k
)
6208
0
    Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6209
7.03M
  if (Record && 
Record->getIdentifier()849k
&&
Record->getDeclName() == Name849k
) {
6210
47
    Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6211
47
    return true;
6212
47
  }
6213
6214
7.03M
  return false;
6215
7.03M
}
6216
6217
/// Diagnose a declaration whose declarator-id has the given
6218
/// nested-name-specifier.
6219
///
6220
/// \param SS The nested-name-specifier of the declarator-id.
6221
///
6222
/// \param DC The declaration context to which the nested-name-specifier
6223
/// resolves.
6224
///
6225
/// \param Name The name of the entity being declared.
6226
///
6227
/// \param Loc The location of the name of the entity being declared.
6228
///
6229
/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6230
/// we're declaring an explicit / partial specialization / instantiation.
6231
///
6232
/// \returns true if we cannot safely recover from this error, false otherwise.
6233
bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6234
                                        DeclarationName Name,
6235
334k
                                        SourceLocation Loc, bool IsTemplateId) {
6236
334k
  DeclContext *Cur = CurContext;
6237
334k
  while (isa<LinkageSpecDecl>(Cur) || 
isa<CapturedDecl>(Cur)334k
)
6238
15
    Cur = Cur->getParent();
6239
6240
  // If the user provided a superfluous scope specifier that refers back to the
6241
  // class in which the entity is already declared, diagnose and ignore it.
6242
  //
6243
  // class X {
6244
  //   void X::f();
6245
  // };
6246
  //
6247
  // Note, it was once ill-formed to give redundant qualification in all
6248
  // contexts, but that rule was removed by DR482.
6249
334k
  if (Cur->Equals(DC)) {
6250
145
    if (Cur->isRecord()) {
6251
46
      Diag(Loc, LangOpts.MicrosoftExt ? 
diag::warn_member_extra_qualification3
6252
46
                                      : 
diag::err_member_extra_qualification43
)
6253
46
        << Name << FixItHint::CreateRemoval(SS.getRange());
6254
46
      SS.clear();
6255
99
    } else {
6256
99
      Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6257
99
    }
6258
145
    return false;
6259
145
  }
6260
6261
  // Check whether the qualifying scope encloses the scope of the original
6262
  // declaration. For a template-id, we perform the checks in
6263
  // CheckTemplateSpecializationScope.
6264
334k
  if (!Cur->Encloses(DC) && 
!IsTemplateId138
) {
6265
91
    if (Cur->isRecord())
6266
17
      Diag(Loc, diag::err_member_qualification)
6267
17
        << Name << SS.getRange();
6268
74
    else if (isa<TranslationUnitDecl>(DC))
6269
17
      Diag(Loc, diag::err_invalid_declarator_global_scope)
6270
17
        << Name << SS.getRange();
6271
57
    else if (isa<FunctionDecl>(Cur))
6272
7
      Diag(Loc, diag::err_invalid_declarator_in_function)
6273
7
        << Name << SS.getRange();
6274
50
    else if (isa<BlockDecl>(Cur))
6275
1
      Diag(Loc, diag::err_invalid_declarator_in_block)
6276
1
        << Name << SS.getRange();
6277
49
    else if (isa<ExportDecl>(Cur)) {
6278
11
      if (!isa<NamespaceDecl>(DC))
6279
8
        Diag(Loc, diag::err_export_non_namespace_scope_name)
6280
8
            << Name << SS.getRange();
6281
3
      else
6282
        // The cases that DC is not NamespaceDecl should be handled in
6283
        // CheckRedeclarationExported.
6284
3
        return false;
6285
11
    } else
6286
38
      Diag(Loc, diag::err_invalid_declarator_scope)
6287
38
      << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6288
6289
88
    return true;
6290
91
  }
6291
6292
333k
  if (Cur->isRecord()) {
6293
    // Cannot qualify members within a class.
6294
33
    Diag(Loc, diag::err_member_qualification)
6295
33
      << Name << SS.getRange();
6296
33
    SS.clear();
6297
6298
    // C++ constructors and destructors with incorrect scopes can break
6299
    // our AST invariants by having the wrong underlying types. If
6300
    // that's the case, then drop this declaration entirely.
6301
33
    if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6302
33
         Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6303
33
        !Context.hasSameType(Name.getCXXNameType(),
6304
3
                             Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6305
3
      return true;
6306
6307
30
    return false;
6308
33
  }
6309
6310
  // C++11 [dcl.meaning]p1:
6311
  //   [...] "The nested-name-specifier of the qualified declarator-id shall
6312
  //   not begin with a decltype-specifer"
6313
333k
  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6314
335k
  while (SpecLoc.getPrefix())
6315
1.81k
    SpecLoc = SpecLoc.getPrefix();
6316
333k
  if (isa_and_nonnull<DecltypeType>(
6317
333k
          SpecLoc.getNestedNameSpecifier()->getAsType()))
6318
4
    Diag(Loc, diag::err_decltype_in_declarator)
6319
4
      << SpecLoc.getTypeLoc().getSourceRange();
6320
6321
333k
  return false;
6322
333k
}
6323
6324
NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6325
41.7M
                                  MultiTemplateParamsArg TemplateParamLists) {
6326
  // TODO: consider using NameInfo for diagnostic.
6327
41.7M
  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6328
41.7M
  DeclarationName Name = NameInfo.getName();
6329
6330
  // All of these full declarators require an identifier.  If it doesn't have
6331
  // one, the ParsedFreeStandingDeclSpec action should be used.
6332
41.7M
  if (D.isDecompositionDeclarator()) {
6333
703
    return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6334
41.7M
  } else if (!Name) {
6335
5
    if (!D.isInvalidType())  // Reject this if we think it is valid.
6336
2
      Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6337
2
          << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6338
5
    return nullptr;
6339
41.7M
  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6340
2
    return nullptr;
6341
6342
  // The scope passed in may not be a decl scope.  Zip up the scope tree until
6343
  // we find one that is.
6344
42.8M
  
while (41.7M
(S->getFlags() & Scope::DeclScope) == 0 ||
6345
42.8M
         
(S->getFlags() & Scope::TemplateParamScope) != 041.7M
)
6346
1.14M
    S = S->getParent();
6347
6348
41.7M
  DeclContext *DC = CurContext;
6349
41.7M
  if (D.getCXXScopeSpec().isInvalid())
6350
0
    D.setInvalidType();
6351
41.7M
  else if (D.getCXXScopeSpec().isSet()) {
6352
331k
    if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6353
331k
                                        UPPC_DeclarationQualifier))
6354
0
      return nullptr;
6355
6356
331k
    bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6357
331k
    DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6358
331k
    if (!DC || 
isa<EnumDecl>(DC)331k
) {
6359
      // If we could not compute the declaration context, it's because the
6360
      // declaration context is dependent but does not refer to a class,
6361
      // class template, or class template partial specialization. Complain
6362
      // and return early, to avoid the coming semantic disaster.
6363
30
      Diag(D.getIdentifierLoc(),
6364
30
           diag::err_template_qualified_declarator_no_match)
6365
30
        << D.getCXXScopeSpec().getScopeRep()
6366
30
        << D.getCXXScopeSpec().getRange();
6367
30
      return nullptr;
6368
30
    }
6369
331k
    bool IsDependentContext = DC->isDependentContext();
6370
6371
331k
    if (!IsDependentContext &&
6372
331k
        
RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)37.9k
)
6373
0
      return nullptr;
6374
6375
    // If a class is incomplete, do not parse entities inside it.
6376
331k
    if (isa<CXXRecordDecl>(DC) && 
!cast<CXXRecordDecl>(DC)->hasDefinition()330k
) {
6377
7
      Diag(D.getIdentifierLoc(),
6378
7
           diag::err_member_def_undefined_record)
6379
7
        << Name << DC << D.getCXXScopeSpec().getRange();
6380
7
      return nullptr;
6381
7
    }
6382
331k
    if (!D.getDeclSpec().isFriendSpecified()) {
6383
331k
      if (diagnoseQualifiedDeclaration(
6384
331k
              D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6385
331k
              D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6386
66
        if (DC->isRecord())
6387
25
          return nullptr;
6388
6389
41
        D.setInvalidType();
6390
41
      }
6391
331k
    }
6392
6393
    // Check whether we need to rebuild the type of the given
6394
    // declaration in the current instantiation.
6395
331k
    if (EnteringContext && IsDependentContext &&
6396
331k
        
TemplateParamLists.size() != 0293k
) {
6397
293k
      ContextRAII SavedContext(*this, DC);
6398
293k
      if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6399
4
        D.setInvalidType();
6400
293k
    }
6401
331k
  }
6402
6403
41.7M
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6404
41.7M
  QualType R = TInfo->getType();
6405
6406
41.7M
  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6407
41.7M
                                      UPPC_DeclarationType))
6408
82
    D.setInvalidType();
6409
6410
41.7M
  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6411
41.7M
                        forRedeclarationInCurContext());
6412
6413
  // See if this is a redefinition of a variable in the same scope.
6414
41.7M
  if (!D.getCXXScopeSpec().isSet()) {
6415
41.4M
    bool IsLinkageLookup = false;
6416
41.4M
    bool CreateBuiltins = false;
6417
6418
    // If the declaration we're planning to build will be a function
6419
    // or object with linkage, then look for another declaration with
6420
    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6421
    //
6422
    // If the declaration we're planning to build will be declared with
6423
    // external linkage in the translation unit, create any builtin with
6424
    // the same name.
6425
41.4M
    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6426
2.12M
      /* Do nothing*/;
6427
39.2M
    else if (CurContext->isFunctionOrMethod() &&
6428
39.2M
             
(1.73M
D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern1.73M
||
6429
1.73M
              
R->isFunctionType()1.73M
)) {
6430
3.04k
      IsLinkageLookup = true;
6431
3.04k
      CreateBuiltins =
6432
3.04k
          CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6433
39.2M
    } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6434
39.2M
               
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static34.8M
)
6435
3.69M
      CreateBuiltins = true;
6436
6437
41.4M
    if (IsLinkageLookup) {
6438
3.04k
      Previous.clear(LookupRedeclarationWithLinkage);
6439
3.04k
      Previous.setRedeclarationKind(ForExternalRedeclaration);
6440
3.04k
    }
6441
6442
41.4M
    LookupName(Previous, S, CreateBuiltins);
6443
41.4M
  } else { // Something like "int foo::x;"
6444
331k
    LookupQualifiedName(Previous, DC);
6445
6446
    // C++ [dcl.meaning]p1:
6447
    //   When the declarator-id is qualified, the declaration shall refer to a
6448
    //  previously declared member of the class or namespace to which the
6449
    //  qualifier refers (or, in the case of a namespace, of an element of the
6450
    //  inline namespace set of that namespace (7.3.1)) or to a specialization
6451
    //  thereof; [...]
6452
    //
6453
    // Note that we already checked the context above, and that we do not have
6454
    // enough information to make sure that Previous contains the declaration
6455
    // we want to match. For example, given:
6456
    //
6457
    //   class X {
6458
    //     void f();
6459
    //     void f(float);
6460
    //   };
6461
    //
6462
    //   void X::f(int) { } // ill-formed
6463
    //
6464
    // In this case, Previous will point to the overload set
6465
    // containing the two f's declared in X, but neither of them
6466
    // matches.
6467
6468
331k
    RemoveUsingDecls(Previous);
6469
331k
  }
6470
6471
41.7M
  if (Previous.isSingleResult() &&
6472
41.7M
      
Previous.getFoundDecl()->isTemplateParameter()2.40M
) {
6473
    // Maybe we will complain about the shadowed template parameter.
6474
22
    if (!D.isInvalidType())
6475
22
      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6476
22
                                      Previous.getFoundDecl());
6477
6478
    // Just pretend that we didn't see the previous declaration.
6479
22
    Previous.clear();
6480
22
  }
6481
6482
41.7M
  if (!R->isFunctionType() && 
DiagnoseClassNameShadow(DC, NameInfo)5.19M
)
6483
    // Forget that the previous declaration is the injected-class-name.
6484
15
    Previous.clear();
6485
6486
  // In C++, the previous declaration we find might be a tag type
6487
  // (class or enum). In this case, the new declaration will hide the
6488
  // tag type. Note that this applies to functions, function templates, and
6489
  // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6490
41.7M
  if (Previous.isSingleTagDecl() &&
6491
41.7M
      
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef28.5k
&&
6492
41.7M
      
(2.78k
TemplateParamLists.size() == 02.78k
||
R->isFunctionType()10
))
6493
2.78k
    Previous.clear();
6494
6495
  // Check that there are no default arguments other than in the parameters
6496
  // of a function declaration (C++ only).
6497
41.7M
  if (getLangOpts().CPlusPlus)
6498
18.8M
    CheckExtraCXXDefaultArguments(D);
6499
6500
41.7M
  NamedDecl *New;
6501
6502
41.7M
  bool AddToScope = true;
6503
41.7M
  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6504
2.12M
    if (TemplateParamLists.size()) {
6505
1
      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6506
1
      return nullptr;
6507
1
    }
6508
6509
2.12M
    New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6510
39.6M
  } else if (R->isFunctionType()) {
6511
36.5M
    New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6512
36.5M
                                  TemplateParamLists,
6513
36.5M
                                  AddToScope);
6514
36.5M
  } else {
6515
3.09M
    New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6516
3.09M
                                  AddToScope);
6517
3.09M
  }
6518
6519
41.7M
  if (!New)
6520
199
    return nullptr;
6521
6522
  // If this has an identifier and is not a function template specialization,
6523
  // add it to the scope stack.
6524
41.7M
  if (New->getDeclName() && AddToScope)
6525
41.7M
    PushOnScopeChains(New, S);
6526
6527
41.7M
  if (isInOpenMPDeclareTargetContext())
6528
4.57k
    checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6529
6530
41.7M
  return New;
6531
41.7M
}
6532
6533
/// Helper method to turn variable array types into constant array
6534
/// types in certain situations which would otherwise be errors (for
6535
/// GCC compatibility).
6536
static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6537
                                                    ASTContext &Context,
6538
                                                    bool &SizeIsNegative,
6539
463
                                                    llvm::APSInt &Oversized) {
6540
  // This method tries to turn a variable array into a constant
6541
  // array even when the size isn't an ICE.  This is necessary
6542
  // for compatibility with code that depends on gcc's buggy
6543
  // constant expression folding, like struct {char x[(int)(char*)2];}
6544
463
  SizeIsNegative = false;
6545
463
  Oversized = 0;
6546
6547
463
  if (T->isDependentType())
6548
0
    return QualType();
6549
6550
463
  QualifierCollector Qs;
6551
463
  const Type *Ty = Qs.strip(T);
6552
6553
463
  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6554
4
    QualType Pointee = PTy->getPointeeType();
6555
4
    QualType FixedType =
6556
4
        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6557
4
                                            Oversized);
6558
4
    if (FixedType.isNull()) 
return FixedType2
;
6559
2
    FixedType = Context.getPointerType(FixedType);
6560
2
    return Qs.apply(Context, FixedType);
6561
4
  }
6562
459
  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6563
4
    QualType Inner = PTy->getInnerType();
6564
4
    QualType FixedType =
6565
4
        TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6566
4
                                            Oversized);
6567
4
    if (FixedType.isNull()) 
return FixedType2
;
6568
2
    FixedType = Context.getParenType(FixedType);
6569
2
    return Qs.apply(Context, FixedType);
6570
4
  }
6571
6572
455
  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6573
455
  if (!VLATy)
6574
15
    return QualType();
6575
6576
440
  QualType ElemTy = VLATy->getElementType();
6577
440
  if (ElemTy->isVariablyModifiedType()) {
6578
6
    ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6579
6
                                                 SizeIsNegative, Oversized);
6580
6
    if (ElemTy.isNull())
6581
2
      return QualType();
6582
6
  }
6583
6584
438
  Expr::EvalResult Result;
6585
438
  if (!VLATy->getSizeExpr() ||
6586
438
      !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6587
136
    return QualType();
6588
6589
302
  llvm::APSInt Res = Result.Val.getInt();
6590
6591
  // Check whether the array size is negative.
6592
302
  if (Res.isSigned() && 
Res.isNegative()92
) {
6593
4
    SizeIsNegative = true;
6594
4
    return QualType();
6595
4
  }
6596
6597
  // Check whether the array is too large to be addressed.
6598
298
  unsigned ActiveSizeBits =
6599
298
      (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6600
298
       !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6601
298
          ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6602
298
          : 
Res.getActiveBits()0
;
6603
298
  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6604
1
    Oversized = Res;
6605
1
    return QualType();
6606
1
  }
6607
6608
297
  QualType FoldedArrayType = Context.getConstantArrayType(
6609
297
      ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6610
297
  return Qs.apply(Context, FoldedArrayType);
6611
298
}
6612
6613
static void
6614
298
FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6615
298
  SrcTL = SrcTL.getUnqualifiedLoc();
6616
298
  DstTL = DstTL.getUnqualifiedLoc();
6617
298
  if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6618
2
    PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6619
2
    FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6620
2
                                      DstPTL.getPointeeLoc());
6621
2
    DstPTL.setStarLoc(SrcPTL.getStarLoc());
6622
2
    return;
6623
2
  }
6624
296
  if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6625
2
    ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6626
2
    FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6627
2
                                      DstPTL.getInnerLoc());
6628
2
    DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6629
2
    DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6630
2
    return;
6631
2
  }
6632
294
  ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6633
294
  ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6634
294
  TypeLoc SrcElemTL = SrcATL.getElementLoc();
6635
294
  TypeLoc DstElemTL = DstATL.getElementLoc();
6636
294
  if (VariableArrayTypeLoc SrcElemATL =
6637
294
          SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6638
3
    ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6639
3
    FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6640
291
  } else {
6641
291
    DstElemTL.initializeFullCopy(SrcElemTL);
6642
291
  }
6643
294
  DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6644
294
  DstATL.setSizeExpr(SrcATL.getSizeExpr());
6645
294
  DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6646
294
}
6647
6648
/// Helper method to turn variable array types into constant array
6649
/// types in certain situations which would otherwise be errors (for
6650
/// GCC compatibility).
6651
static TypeSourceInfo*
6652
TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6653
                                              ASTContext &Context,
6654
                                              bool &SizeIsNegative,
6655
447
                                              llvm::APSInt &Oversized) {
6656
447
  QualType FixedTy
6657
447
    = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6658
447
                                          SizeIsNegative, Oversized);
6659
447
  if (FixedTy.isNull())
6660
156
    return nullptr;
6661
291
  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6662
291
  FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6663
291
                                    FixedTInfo->getTypeLoc());
6664
291
  return FixedTInfo;
6665
447
}
6666
6667
/// Attempt to fold a variable-sized type to a constant-sized type, returning
6668
/// true if we were successful.
6669
bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6670
                                           QualType &T, SourceLocation Loc,
6671
296
                                           unsigned FailedFoldDiagID) {
6672
296
  bool SizeIsNegative;
6673
296
  llvm::APSInt Oversized;
6674
296
  TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6675
296
      TInfo, Context, SizeIsNegative, Oversized);
6676
296
  if (FixedTInfo) {
6677
222
    Diag(Loc, diag::ext_vla_folded_to_constant);
6678
222
    TInfo = FixedTInfo;
6679
222
    T = FixedTInfo->getType();
6680
222
    return true;
6681
222
  }
6682
6683
74
  if (SizeIsNegative)
6684
4
    Diag(Loc, diag::err_typecheck_negative_array_size);
6685
70
  else if (Oversized.getBoolValue())
6686
1
    Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6687
69
  else if (FailedFoldDiagID)
6688
47
    Diag(Loc, FailedFoldDiagID);
6689
74
  return false;
6690
296
}
6691
6692
/// Register the given locally-scoped extern "C" declaration so
6693
/// that it can be found later for redeclarations. We include any extern "C"
6694
/// declaration that is not visible in the translation unit here, not just
6695
/// function-scope declarations.
6696
void
6697
5.36M
Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6698
5.36M
  if (!getLangOpts().CPlusPlus &&
6699
5.36M
      
ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()3.81M
)
6700
    // Don't need to track declarations in the TU in C.
6701
3.80M
    return;
6702
6703
  // Note that we have a locally-scoped external with this name.
6704
1.55M
  Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6705
1.55M
}
6706
6707
34.7M
NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6708
  // FIXME: We can have multiple results via __attribute__((overloadable)).
6709
34.7M
  auto Result = Context.getExternCContextDecl()->lookup(Name);
6710
34.7M
  return Result.empty() ? 
nullptr34.7M
:
*Result.begin()16.8k
;
6711
34.7M
}
6712
6713
/// Diagnose function specifiers on a declaration of an identifier that
6714
/// does not identify a function.
6715
104M
void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6716
  // FIXME: We should probably indicate the identifier in question to avoid
6717
  // confusion for constructs like "virtual int a(), b;"
6718
104M
  if (DS.isVirtualSpecified())
6719
2
    Diag(DS.getVirtualSpecLoc(),
6720
2
         diag::err_virtual_non_function);
6721
6722
104M
  if (DS.hasExplicitSpecifier())
6723
1
    Diag(DS.getExplicitSpecLoc(),
6724
1
         diag::err_explicit_non_function);
6725
6726
104M
  if (DS.isNoreturnSpecified())
6727
18
    Diag(DS.getNoreturnSpecLoc(),
6728
18
         diag::err_noreturn_non_function);
6729
104M
}
6730
6731
NamedDecl*
6732
Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6733
2.12M
                             TypeSourceInfo *TInfo, LookupResult &Previous) {
6734
  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6735
2.12M
  if (D.getCXXScopeSpec().isSet()) {
6736
10
    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6737
10
      << D.getCXXScopeSpec().getRange();
6738
10
    D.setInvalidType();
6739
    // Pretend we didn't see the scope specifier.
6740
10
    DC = CurContext;
6741
10
    Previous.clear();
6742
10
  }
6743
6744
2.12M
  DiagnoseFunctionSpecifiers(D.getDeclSpec());
6745
6746
2.12M
  if (D.getDeclSpec().isInlineSpecified())
6747
2
    Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6748
2
        << getLangOpts().CPlusPlus17;
6749
2.12M
  if (D.getDeclSpec().hasConstexprSpecifier())
6750
7
    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6751
7
        << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6752
6753
2.12M
  if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6754
3
    if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6755
2
      Diag(D.getName().StartLocation,
6756
2
           diag::err_deduction_guide_invalid_specifier)
6757
2
          << "typedef";
6758
1
    else
6759
1
      Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6760
1
          << D.getName().getSourceRange();
6761
3
    return nullptr;
6762
3
  }
6763
6764
2.12M
  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6765
2.12M
  if (!NewTD) 
return nullptr0
;
6766
6767
  // Handle attributes prior to checking for duplicates in MergeVarDecl
6768
2.12M
  ProcessDeclAttributes(S, NewTD, D);
6769
6770
2.12M
  CheckTypedefForVariablyModifiedType(S, NewTD);
6771
6772
2.12M
  bool Redeclaration = D.isRedeclaration();
6773
2.12M
  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6774
2.12M
  D.setRedeclaration(Redeclaration);
6775
2.12M
  return ND;
6776
2.12M
}
6777
6778
void
6779
2.41M
Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6780
  // C99 6.7.7p2: If a typedef name specifies a variably modified type
6781
  // then it shall have block scope.
6782
  // Note that variably modified types must be fixed before merging the decl so
6783
  // that redeclarations will match.
6784
2.41M
  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6785
2.41M
  QualType T = TInfo->getType();
6786
2.41M
  if (T->isVariablyModifiedType()) {
6787
81
    setFunctionHasBranchProtectedScope();
6788
6789
81
    if (S->getFnParent() == nullptr) {
6790
18
      bool SizeIsNegative;
6791
18
      llvm::APSInt Oversized;
6792
18
      TypeSourceInfo *FixedTInfo =
6793
18
        TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6794
18
                                                      SizeIsNegative,
6795
18
                                                      Oversized);
6796
18
      if (FixedTInfo) {
6797
9
        Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6798
9
        NewTD->setTypeSourceInfo(FixedTInfo);
6799
9
      } else {
6800
9
        if (SizeIsNegative)
6801
0
          Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6802
9
        else if (T->isVariableArrayType())
6803
9
          Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6804
0
        else if (Oversized.getBoolValue())
6805
0
          Diag(NewTD->getLocation(), diag::err_array_too_large)
6806
0
            << toString(Oversized, 10);
6807
0
        else
6808
0
          Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6809
9
        NewTD->setInvalidDecl();
6810
9
      }
6811
18
    }
6812
81
  }
6813
2.41M
}
6814
6815
/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6816
/// declares a typedef-name, either using the 'typedef' type specifier or via
6817
/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6818
NamedDecl*
6819
Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6820
2.32M
                           LookupResult &Previous, bool &Redeclaration) {
6821
6822
  // Find the shadowed declaration before filtering for scope.
6823
2.32M
  NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6824
6825
  // Merge the decl with the existing one if appropriate. If the decl is
6826
  // in an outer scope, it isn't the same thing.
6827
2.32M
  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6828
2.32M
                       /*AllowInlineNamespace*/false);
6829
2.32M
  filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6830
2.32M
  if (!Previous.empty()) {
6831
31.7k
    Redeclaration = true;
6832
31.7k
    MergeTypedefNameDecl(S, NewTD, Previous);
6833
2.29M
  } else {
6834
2.29M
    inferGslPointerAttribute(NewTD);
6835
2.29M
  }
6836
6837
2.32M
  if (ShadowedDecl && 
!Redeclaration25
)
6838
15
    CheckShadow(NewTD, ShadowedDecl, Previous);
6839
6840
  // If this is the C FILE type, notify the AST context.
6841
2.32M
  if (IdentifierInfo *II = NewTD->getIdentifier())
6842
2.32M
    if (!NewTD->isInvalidDecl() &&
6843
2.32M
        
NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()2.32M
) {
6844
1.62M
      switch (II->getInterestingIdentifierID()) {
6845
1.76k
      case tok::InterestingIdentifierKind::FILE:
6846
1.76k
        Context.setFILEDecl(NewTD);
6847
1.76k
        break;
6848
324
      case tok::InterestingIdentifierKind::jmp_buf:
6849
324
        Context.setjmp_bufDecl(NewTD);
6850
324
        break;
6851
294
      case tok::InterestingIdentifierKind::sigjmp_buf:
6852
294
        Context.setsigjmp_bufDecl(NewTD);
6853
294
        break;
6854
976
      case tok::InterestingIdentifierKind::ucontext_t:
6855
976
        Context.setucontext_tDecl(NewTD);
6856
976
        break;
6857
734
      case tok::InterestingIdentifierKind::float_t:
6858
1.46k
      case tok::InterestingIdentifierKind::double_t:
6859
1.46k
        NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6860
1.46k
        break;
6861
1.61M
      default:
6862
1.61M
        break;
6863
1.62M
      }
6864
1.62M
    }
6865
6866
2.32M
  return NewTD;
6867
2.32M
}
6868
6869
/// Determines whether the given declaration is an out-of-scope
6870
/// previous declaration.
6871
///
6872
/// This routine should be invoked when name lookup has found a
6873
/// previous declaration (PrevDecl) that is not in the scope where a
6874
/// new declaration by the same name is being introduced. If the new
6875
/// declaration occurs in a local scope, previous declarations with
6876
/// linkage may still be considered previous declarations (C99
6877
/// 6.2.2p4-5, C++ [basic.link]p6).
6878
///
6879
/// \param PrevDecl the previous declaration found by name
6880
/// lookup
6881
///
6882
/// \param DC the context in which the new declaration is being
6883
/// declared.
6884
///
6885
/// \returns true if PrevDecl is an out-of-scope previous declaration
6886
/// for a new delcaration with the same name.
6887
static bool
6888
isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6889
1.69k
                                ASTContext &Context) {
6890
1.69k
  if (!PrevDecl)
6891
0
    return false;
6892
6893
1.69k
  if (!PrevDecl->hasLinkage())
6894
8
    return false;
6895
6896
1.68k
  if (Context.getLangOpts().CPlusPlus) {
6897
    // C++ [basic.link]p6:
6898
    //   If there is a visible declaration of an entity with linkage
6899
    //   having the same name and type, ignoring entities declared
6900
    //   outside the innermost enclosing namespace scope, the block
6901
    //   scope declaration declares that same entity and receives the
6902
    //   linkage of the previous declaration.
6903
1.55k
    DeclContext *OuterContext = DC->getRedeclContext();
6904
1.55k
    if (!OuterContext->isFunctionOrMethod())
6905
      // This rule only applies to block-scope declarations.
6906
1.07k
      return false;
6907
6908
482
    DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6909
482
    if (PrevOuterContext->isRecord())
6910
      // We found a member function: ignore it.
6911
21
      return false;
6912
6913
    // Find the innermost enclosing namespace for the new and
6914
    // previous declarations.
6915
461
    OuterContext = OuterContext->getEnclosingNamespaceContext();
6916
461
    PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6917
6918
    // The previous declaration is in a different namespace, so it
6919
    // isn't the same function.
6920
461
    if (!OuterContext->Equals(PrevOuterContext))
6921
2
      return false;
6922
461
  }
6923
6924
586
  return true;
6925
1.68k
}
6926
6927
17.8M
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6928
17.8M
  CXXScopeSpec &SS = D.getCXXScopeSpec();
6929
17.8M
  if (!SS.isSet()) 
return17.5M
;
6930
332k
  DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6931
332k
}
6932
6933
71.0k
bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6934
71.0k
  QualType type = decl->getType();
6935
71.0k
  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6936
71.0k
  if (lifetime == Qualifiers::OCL_Autoreleasing) {
6937
    // Various kinds of declaration aren't allowed to be __autoreleasing.
6938
41
    unsigned kind = -1U;
6939
41
    if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6940
34
      if (var->hasAttr<BlocksAttr>())
6941
2
        kind = 0; // __block
6942
32
      else if (!var->hasLocalStorage())
6943
10
        kind = 1; // global
6944
34
    } else 
if (7
isa<ObjCIvarDecl>(decl)7
) {
6945
7
      kind = 3; // ivar
6946
7
    } else 
if (0
isa<FieldDecl>(decl)0
) {
6947
0
      kind = 2; // field
6948
0
    }
6949
6950
41
    if (kind != -1U) {
6951
19
      Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6952
19
        << kind;
6953
19
    }
6954
70.9k
  } else if (lifetime == Qualifiers::OCL_None) {
6955
    // Try to infer lifetime.
6956
70.1k
    if (!type->isObjCLifetimeType())
6957
63.5k
      return false;
6958
6959
6.66k
    lifetime = type->getObjCARCImplicitLifetime();
6960
6.66k
    type = Context.getLifetimeQualifiedType(type, lifetime);
6961
6.66k
    decl->setType(type);
6962
6.66k
  }
6963
6964
7.51k
  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6965
    // Thread-local variables cannot have lifetime.
6966
6.00k
    if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6967
6.00k
        
var->getTLSKind()5.85k
) {
6968
16
      Diag(var->getLocation(), diag::err_arc_thread_ownership)
6969
16
        << var->getType();
6970
16
      return true;
6971
16
    }
6972
6.00k
  }
6973
6974
7.49k
  return false;
6975
7.51k
}
6976
6977
474k
void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6978
474k
  if (Decl->getType().hasAddressSpace())
6979
1.04k
    return;
6980
473k
  if (Decl->getType()->isDependentType())
6981
31
    return;
6982
473k
  if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6983
473k
    QualType Type = Var->getType();
6984
473k
    if (Type->isSamplerT() || 
Type->isVoidType()471k
)
6985
3.09k
      return;
6986
469k
    LangAS ImplAS = LangAS::opencl_private;
6987
    // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6988
    // __opencl_c_program_scope_global_variables feature, the address space
6989
    // for a variable at program scope or a static or extern variable inside
6990
    // a function are inferred to be __global.
6991
469k
    if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6992
469k
        
Var->hasGlobalStorage()250k
)
6993
423
      ImplAS = LangAS::opencl_global;
6994
    // If the original type from a decayed type is an array type and that array
6995
    // type has no address space yet, deduce it now.
6996
469k
    if (auto DT = dyn_cast<DecayedType>(Type)) {
6997
151
      auto OrigTy = DT->getOriginalType();
6998
151
      if (!OrigTy.hasAddressSpace() && 
OrigTy->isArrayType()141
) {
6999
        // Add the address space to the original array type and then propagate
7000
        // that to the element type through `getAsArrayType`.
7001
140
        OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7002
140
        OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7003
        // Re-generate the decayed type.
7004
140
        Type = Context.getDecayedType(OrigTy);
7005
140
      }
7006
151
    }
7007
469k
    Type = Context.getAddrSpaceQualType(Type, ImplAS);
7008
    // Apply any qualifiers (including address space) from the array type to
7009
    // the element type. This implements C99 6.7.3p8: "If the specification of
7010
    // an array type includes any type qualifiers, the element type is so
7011
    // qualified, not the array type."
7012
469k
    if (Type->isArrayType())
7013
115
      Type = QualType(Context.getAsArrayType(Type), 0);
7014
469k
    Decl->setType(Type);
7015
469k
  }
7016
473k
}
7017
7018
39.6M
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7019
  // Ensure that an auto decl is deduced otherwise the checks below might cache
7020
  // the wrong linkage.
7021
39.6M
  assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7022
7023
  // 'weak' only applies to declarations with external linkage.
7024
39.6M
  if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7025
302
    if (!ND.isExternallyVisible()) {
7026
10
      S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7027
10
      ND.dropAttr<WeakAttr>();
7028
10
    }
7029
302
  }
7030
39.6M
  if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7031
43
    if (ND.isExternallyVisible()) {
7032
3
      S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7033
3
      ND.dropAttr<WeakRefAttr>();
7034
3
      ND.dropAttr<AliasAttr>();
7035
3
    }
7036
43
  }
7037
7038
39.6M
  if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7039
3.09M
    if (VD->hasInit()) {
7040
1.38M
      if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7041
1
        assert(VD->isThisDeclarationADefinition() &&
7042
1
               !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7043
1
        S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7044
1
        VD->dropAttr<AliasAttr>();
7045
1
      }
7046
1.38M
    }
7047
3.09M
  }
7048
7049
  // 'selectany' only applies to externally visible variable declarations.
7050
  // It does not apply to functions.
7051
39.6M
  if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7052
77
    if (isa<FunctionDecl>(ND) || 
!ND.isExternallyVisible()70
) {
7053
19
      S.Diag(Attr->getLocation(),
7054
19
             diag::err_attribute_selectany_non_extern_data);
7055
19
      ND.dropAttr<SelectAnyAttr>();
7056
19
    }
7057
77
  }
7058
7059
39.6M
  if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7060
11.2k
    auto *VD = dyn_cast<VarDecl>(&ND);
7061
11.2k
    bool IsAnonymousNS = false;
7062
11.2k
    bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7063
11.2k
    if (VD) {
7064
3.46k
      const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7065
3.55k
      while (NS && 
!IsAnonymousNS97
) {
7066
96
        IsAnonymousNS = NS->isAnonymousNamespace();
7067
96
        NS = dyn_cast<NamespaceDecl>(NS->getParent());
7068
96
      }
7069
3.46k
    }
7070
    // dll attributes require external linkage. Static locals may have external
7071
    // linkage but still cannot be explicitly imported or exported.
7072
    // In Microsoft mode, a variable defined in anonymous namespace must have
7073
    // external linkage in order to be exported.
7074
11.2k
    bool AnonNSInMicrosoftMode = IsAnonymousNS && 
IsMicrosoft24
;
7075
11.2k
    if ((ND.isExternallyVisible() && 
AnonNSInMicrosoftMode10.8k
) ||
7076
11.2k
        (!AnonNSInMicrosoftMode &&
7077
11.2k
         
(11.2k
!ND.isExternallyVisible()11.2k
||
(10.8k
VD10.8k
&&
VD->isStaticLocal()3.26k
)))) {
7078
314
      S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7079
314
        << &ND << Attr;
7080
314
      ND.setInvalidDecl();
7081
314
    }
7082
11.2k
  }
7083
7084
  // Check the attributes on the function type, if any.
7085
39.6M
  if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7086
    // Don't declare this variable in the second operand of the for-statement;
7087
    // GCC miscompiles that by ending its lifetime before evaluating the
7088
    // third operand. See gcc.gnu.org/PR86769.
7089
36.5M
    AttributedTypeLoc ATL;
7090
36.5M
    for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7091
36.5M
         (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7092
36.5M
         
TL = ATL.getModifiedLoc()15.8k
) {
7093
      // The [[lifetimebound]] attribute can be applied to the implicit object
7094
      // parameter of a non-static member function (other than a ctor or dtor)
7095
      // by applying it to the function type.
7096
15.8k
      if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7097
8
        const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7098
8
        if (!MD || 
MD->isStatic()7
) {
7099
2
          S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7100
2
              << !MD << A->getRange();
7101
6
        } else if (isa<CXXConstructorDecl>(MD) || 
isa<CXXDestructorDecl>(MD)5
) {
7102
2
          S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7103
2
              << isa<CXXDestructorDecl>(MD) << A->getRange();
7104
2
        }
7105
8
      }
7106
15.8k
    }
7107
36.5M
  }
7108
39.6M
}
7109
7110
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7111
                                           NamedDecl *NewDecl,
7112
                                           bool IsSpecialization,
7113
485k
                                           bool IsDefinition) {
7114
485k
  if (OldDecl->isInvalidDecl() || 
NewDecl->isInvalidDecl()485k
)
7115
1.69k
    return;
7116
7117
484k
  bool IsTemplate = false;
7118
484k
  if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7119
71.7k
    OldDecl = OldTD->getTemplatedDecl();
7120
71.7k
    IsTemplate = true;
7121
71.7k
    if (!IsSpecialization)
7122
71.6k
      IsDefinition = false;
7123
71.7k
  }
7124
484k
  if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7125
0
    NewDecl = NewTD->getTemplatedDecl();
7126
0
    IsTemplate = true;
7127
0
  }
7128
7129
484k
  if (!OldDecl || !NewDecl)
7130
0
    return;
7131
7132
484k
  const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7133
484k
  const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7134
484k
  const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7135
484k
  const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7136
7137
  // dllimport and dllexport are inheritable attributes so we have to exclude
7138
  // inherited attribute instances.
7139
484k
  bool HasNewAttr = (NewImportAttr && 
!NewImportAttr->isInherited()2.29k
) ||
7140
484k
                    
(482k
NewExportAttr482k
&&
!NewExportAttr->isInherited()2.18k
);
7141
7142
  // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7143
  // the only exception being explicit specializations.
7144
  // Implicitly generated declarations are also excluded for now because there
7145
  // is no other way to switch these to use dllimport or dllexport.
7146
484k
  bool AddsAttr = !(OldImportAttr || 
OldExportAttr482k
) &&
HasNewAttr480k
;
7147
7148
484k
  if (AddsAttr && 
!IsSpecialization1.44k
&&
!OldDecl->isImplicit()968
) {
7149
    // Allow with a warning for free functions and global variables.
7150
909
    bool JustWarn = false;
7151
909
    if (!OldDecl->isCXXClassMember()) {
7152
255
      auto *VD = dyn_cast<VarDecl>(OldDecl);
7153
255
      if (VD && 
!VD->getDescribedVarTemplate()74
)
7154
64
        JustWarn = true;
7155
255
      auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7156
255
      if (FD && 
FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate181
)
7157
127
        JustWarn = true;
7158
255
    }
7159
7160
    // We cannot change a declaration that's been used because IR has already
7161
    // been emitted. Dllimported functions will still work though (modulo
7162
    // address equality) as they can use the thunk.
7163
909
    if (OldDecl->isUsed())
7164
35
      if (!isa<FunctionDecl>(OldDecl) || 
!NewImportAttr21
)
7165
25
        JustWarn = false;
7166
7167
909
    unsigned DiagID = JustWarn ? 
diag::warn_attribute_dll_redeclaration166
7168
909
                               : 
diag::err_attribute_dll_redeclaration743
;
7169
909
    S.Diag(NewDecl->getLocation(), DiagID)
7170
909
        << NewDecl
7171
909
        << (NewImportAttr ? 
(const Attr *)NewImportAttr488
:
NewExportAttr421
);
7172
909
    S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7173
909
    if (!JustWarn) {
7174
743
      NewDecl->setInvalidDecl();
7175
743
      return;
7176
743
    }
7177
909
  }
7178
7179
  // A redeclaration is not allowed to drop a dllimport attribute, the only
7180
  // exceptions being inline function definitions (except for function
7181
  // templates), local extern declarations, qualified friend declarations or
7182
  // special MSVC extension: in the last case, the declaration is treated as if
7183
  // it were marked dllexport.
7184
483k
  bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7185
483k
  bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7186
483k
  if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7187
    // Ignore static data because out-of-line definitions are diagnosed
7188
    // separately.
7189
61.3k
    IsStaticDataMember = VD->isStaticDataMember();
7190
61.3k
    IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7191
61.3k
                   VarDecl::DeclarationOnly;
7192
421k
  } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7193
421k
    IsInline = FD->isInlined();
7194
421k
    IsQualifiedFriend = FD->getQualifier() &&
7195
421k
                        
FD->getFriendObjectKind() == Decl::FOK_Declared272k
;
7196
421k
  }
7197
7198
483k
  if (OldImportAttr && 
!HasNewAttr1.58k
&&
7199
483k
      
(1.13k
!IsInline1.13k
||
(390
IsMicrosoftABI390
&&
IsTemplate302
)) &&
!IsStaticDataMember845
&&
7200
483k
      
!NewDecl->isLocalExternDecl()745
&&
!IsQualifiedFriend729
) {
7201
708
    if (IsMicrosoftABI && 
IsDefinition512
) {
7202
229
      if (IsSpecialization) {
7203
21
        S.Diag(
7204
21
            NewDecl->getLocation(),
7205
21
            diag::err_attribute_dllimport_function_specialization_definition);
7206
21
        S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7207
21
        NewDecl->dropAttr<DLLImportAttr>();
7208
208
      } else {
7209
208
        S.Diag(NewDecl->getLocation(),
7210
208
               diag::warn_redeclaration_without_import_attribute)
7211
208
            << NewDecl;
7212
208
        S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7213
208
        NewDecl->dropAttr<DLLImportAttr>();
7214
208
        NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7215
208
            S.Context, NewImportAttr->getRange()));
7216
208
      }
7217
479
    } else if (IsMicrosoftABI && 
IsSpecialization283
) {
7218
6
      assert(!IsDefinition);
7219
      // MSVC allows this. Keep the inherited attribute.
7220
473
    } else {
7221
473
      S.Diag(NewDecl->getLocation(),
7222
473
             diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7223
473
          << NewDecl << OldImportAttr;
7224
473
      S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7225
473
      S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7226
473
      OldDecl->dropAttr<DLLImportAttr>();
7227
473
      NewDecl->dropAttr<DLLImportAttr>();
7228
473
    }
7229
482k
  } else if (IsInline && 
OldImportAttr144k
&&
!IsMicrosoftABI317
) {
7230
    // In MinGW, seeing a function declared inline drops the dllimport
7231
    // attribute.
7232
88
    OldDecl->dropAttr<DLLImportAttr>();
7233
88
    NewDecl->dropAttr<DLLImportAttr>();
7234
88
    S.Diag(NewDecl->getLocation(),
7235
88
           diag::warn_dllimport_dropped_from_inline_function)
7236
88
        << NewDecl << OldImportAttr;
7237
88
  }
7238
7239
  // A specialization of a class template member function is processed here
7240
  // since it's a redeclaration. If the parent class is dllexport, the
7241
  // specialization inherits that attribute. This doesn't happen automatically
7242
  // since the parent class isn't instantiated until later.
7243
483k
  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7244
271k
    if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7245
271k
        
!NewImportAttr11.6k
&&
!NewExportAttr11.6k
) {
7246
11.6k
      if (const DLLExportAttr *ParentExportAttr =
7247
11.6k
              MD->getParent()->getAttr<DLLExportAttr>()) {
7248
2
        DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7249
2
        NewAttr->setInherited(true);
7250
2
        NewDecl->addAttr(NewAttr);
7251
2
      }
7252
11.6k
    }
7253
271k
  }
7254
483k
}
7255
7256
/// Given that we are within the definition of the given function,
7257
/// will that definition behave like C99's 'inline', where the
7258
/// definition is discarded except for optimization purposes?
7259
7.05k
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7260
  // Try to avoid calling GetGVALinkageForFunction.
7261
7262
  // All cases of this require the 'inline' keyword.
7263
7.05k
  if (!FD->isInlined()) 
return false6.31k
;
7264
7265
  // This is only possible in C++ with the gnu_inline attribute.
7266
745
  if (S.getLangOpts().CPlusPlus && 
!FD->hasAttr<GNUInlineAttr>()723
)
7267
723
    return false;
7268
7269
  // Okay, go ahead and call the relatively-more-expensive function.
7270
22
  return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7271
745
}
7272
7273
/// Determine whether a variable is extern "C" prior to attaching
7274
/// an initializer. We can't just call isExternC() here, because that
7275
/// will also compute and cache whether the declaration is externally
7276
/// visible, which might change when we attach the initializer.
7277
///
7278
/// This can only be used if the declaration is known to not be a
7279
/// redeclaration of an internal linkage declaration.
7280
///
7281
/// For instance:
7282
///
7283
///   auto x = []{};
7284
///
7285
/// Attaching the initializer here makes this declaration not externally
7286
/// visible, because its type has internal linkage.
7287
///
7288
/// FIXME: This is a hack.
7289
template<typename T>
7290
59.3M
static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7291
59.3M
  if (S.getLangOpts().CPlusPlus) {
7292
    // In C++, the overloadable attribute negates the effects of extern "C".
7293
37.6M
    if (!D->isInExternCContext() || 
D->template hasAttr<OverloadableAttr>()26.1M
)
7294
23.9M
      return false;
7295
7296
    // So do CUDA's host/device attributes.
7297
13.7M
    if (S.getLangOpts().CUDA && 
(12.3k
D->template hasAttr<CUDADeviceAttr>()12.3k
||
7298
12.3k
                                 
D->template hasAttr<CUDAHostAttr>()2.03k
))
7299
10.3k
      return false;
7300
13.7M
  }
7301
35.3M
  return D->isExternC();
7302
59.3M
}
SemaDecl.cpp:bool isIncompleteDeclExternC<clang::VarDecl>(clang::Sema&, clang::VarDecl const*)
Line
Count
Source
7290
5.15M
static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7291
5.15M
  if (S.getLangOpts().CPlusPlus) {
7292
    // In C++, the overloadable attribute negates the effects of extern "C".
7293
3.79M
    if (!D->isInExternCContext() || 
D->template hasAttr<OverloadableAttr>()256k
)
7294
3.53M
      return false;
7295
7296
    // So do CUDA's host/device attributes.
7297
256k
    if (S.getLangOpts().CUDA && 
(148
D->template hasAttr<CUDADeviceAttr>()148
||
7298
148
                                 D->template hasAttr<CUDAHostAttr>()))
7299
0
      return false;
7300
256k
  }
7301
1.61M
  return D->isExternC();
7302
5.15M
}
SemaDecl.cpp:bool isIncompleteDeclExternC<clang::FunctionDecl>(clang::Sema&, clang::FunctionDecl const*)
Line
Count
Source
7290
54.2M
static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7291
54.2M
  if (S.getLangOpts().CPlusPlus) {
7292
    // In C++, the overloadable attribute negates the effects of extern "C".
7293
33.8M
    if (!D->isInExternCContext() || 
D->template hasAttr<OverloadableAttr>()25.8M
)
7294
20.4M
      return false;
7295
7296
    // So do CUDA's host/device attributes.
7297
13.4M
    if (S.getLangOpts().CUDA && 
(12.2k
D->template hasAttr<CUDADeviceAttr>()12.2k
||
7298
12.2k
                                 
D->template hasAttr<CUDAHostAttr>()1.88k
))
7299
10.3k
      return false;
7300
13.4M
  }
7301
33.7M
  return D->isExternC();
7302
54.2M
}
7303
7304
3.09M
static bool shouldConsiderLinkage(const VarDecl *VD) {
7305
3.09M
  const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7306
3.09M
  if (DC->isFunctionOrMethod() || 
isa<OMPDeclareReductionDecl>(DC)1.36M
||
7307
3.09M
      
isa<OMPDeclareMapperDecl>(DC)1.36M
)
7308
1.73M
    return VD->hasExternalStorage();
7309
1.36M
  if (DC->isFileContext())
7310
1.06M
    return true;
7311
291k
  if (DC->isRecord())
7312
291k
    return false;
7313
0
  if (DC->getDeclKind() == Decl::HLSLBuffer)
7314
0
    return false;
7315
7316
0
  if (isa<RequiresExprBodyDecl>(DC))
7317
0
    return false;
7318
0
  llvm_unreachable("Unexpected context");
7319
0
}
7320
7321
36.5M
static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7322
36.5M
  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7323
36.5M
  if (DC->isFileContext() || 
DC->isFunctionOrMethod()1.93M
||
7324
36.5M
      
isa<OMPDeclareReductionDecl>(DC)1.93M
||
isa<OMPDeclareMapperDecl>(DC)1.93M
)
7325
34.6M
    return true;
7326
1.93M
  if (DC->isRecord())
7327
1.93M
    return false;
7328
0
  llvm_unreachable("Unexpected context");
7329
0
}
7330
7331
static bool hasParsedAttr(Scope *S, const Declarator &PD,
7332
1.85M
                          ParsedAttr::Kind Kind) {
7333
  // Check decl attributes on the DeclSpec.
7334
1.85M
  if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7335
788
    return true;
7336
7337
  // Walk the declarator structure, checking decl attributes that were in a type
7338
  // position to the decl itself.
7339
2.12M
  
for (unsigned I = 0, E = PD.getNumTypeObjects(); 1.85M
I != E;
++I263k
) {
7340
263k
    if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7341
122
      return true;
7342
263k
  }
7343
7344
  // Finally, check attributes on the decl itself.
7345
1.85M
  return PD.getAttributes().hasAttribute(Kind) ||
7346
1.85M
         
PD.getDeclarationAttributes().hasAttribute(Kind)1.85M
;
7347
1.85M
}
7348
7349
/// Adjust the \c DeclContext for a function or variable that might be a
7350
/// function-local external declaration.
7351
37.4M
bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7352
37.4M
  if (!DC->isFunctionOrMethod())
7353
37.4M
    return false;
7354
7355
  // If this is a local extern function or variable declared within a function
7356
  // template, don't add it into the enclosing namespace scope until it is
7357
  // instantiated; it might have a dependent type right now.
7358
3.35k
  if (DC->isDependentContext())
7359
180
    return true;
7360
7361
  // C++11 [basic.link]p7:
7362
  //   When a block scope declaration of an entity with linkage is not found to
7363
  //   refer to some other declaration, then that entity is a member of the
7364
  //   innermost enclosing namespace.
7365
  //
7366
  // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7367
  // semantically-enclosing namespace, not a lexically-enclosing one.
7368
6.57k
  
while (3.17k
!DC->isFileContext() &&
!isa<LinkageSpecDecl>(DC)3.47k
)
7369
3.40k
    DC = DC->getParent();
7370
3.17k
  return true;
7371
3.35k
}
7372
7373
/// Returns true if given declaration has external C language linkage.
7374
13
static bool isDeclExternC(const Decl *D) {
7375
13
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
7376
10
    return FD->isExternC();
7377
3
  if (const auto *VD = dyn_cast<VarDecl>(D))
7378
3
    return VD->isExternC();
7379
7380
0
  llvm_unreachable("Unknown type of decl!");
7381
0
}
7382
7383
/// Returns true if there hasn't been any invalid type diagnosed.
7384
4.42k
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7385
4.42k
  DeclContext *DC = NewVD->getDeclContext();
7386
4.42k
  QualType R = NewVD->getType();
7387
7388
  // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7389
  // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7390
  // argument.
7391
4.42k
  if (R->isImageType() || 
R->isPipeType()4.41k
) {
7392
24
    Se.Diag(NewVD->getLocation(),
7393
24
            diag::err_opencl_type_can_only_be_used_as_function_parameter)
7394
24
        << R;
7395
24
    NewVD->setInvalidDecl();
7396
24
    return false;
7397
24
  }
7398
7399
  // OpenCL v1.2 s6.9.r:
7400
  // The event type cannot be used to declare a program scope variable.
7401
  // OpenCL v2.0 s6.9.q:
7402
  // The clk_event_t and reserve_id_t types cannot be declared in program
7403
  // scope.
7404
4.39k
  if (NewVD->hasGlobalStorage() && 
!NewVD->isStaticLocal()1.06k
) {
7405
924
    if (R->isReserveIDT() || 
R->isClkEventT()918
||
R->isEventT()914
) {
7406
12
      Se.Diag(NewVD->getLocation(),
7407
12
              diag::err_invalid_type_for_program_scope_var)
7408
12
          << R;
7409
12
      NewVD->setInvalidDecl();
7410
12
      return false;
7411
12
    }
7412
924
  }
7413
7414
  // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7415
4.38k
  if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7416
4.38k
                                               Se.getLangOpts())) {
7417
4.37k
    QualType NR = R.getCanonicalType();
7418
5.62k
    while (NR->isPointerType() || 
NR->isMemberFunctionPointerType()4.39k
||
7419
5.62k
           
NR->isReferenceType()4.39k
) {
7420
1.24k
      if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7421
1.24k
          NR->isFunctionReferenceType()) {
7422
0
        Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7423
0
            << NR->isReferenceType();
7424
0
        NewVD->setInvalidDecl();
7425
0
        return false;
7426
0
      }
7427
1.24k
      NR = NR->getPointeeType();
7428
1.24k
    }
7429
4.37k
  }
7430
7431
4.38k
  if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7432
4.38k
                                               Se.getLangOpts())) {
7433
    // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7434
    // half array type (unless the cl_khr_fp16 extension is enabled).
7435
3.54k
    if (Se.Context.getBaseElementType(R)->isHalfType()) {
7436
6
      Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7437
6
      NewVD->setInvalidDecl();
7438
6
      return false;
7439
6
    }
7440
3.54k
  }
7441
7442
  // OpenCL v1.2 s6.9.r:
7443
  // The event type cannot be used with the __local, __constant and __global
7444
  // address space qualifiers.
7445
4.37k
  if (R->isEventT()) {
7446
13
    if (R.getAddressSpace() != LangAS::opencl_private) {
7447
2
      Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7448
2
      NewVD->setInvalidDecl();
7449
2
      return false;
7450
2
    }
7451
13
  }
7452
7453
4.37k
  if (R->isSamplerT()) {
7454
    // OpenCL v1.2 s6.9.b p4:
7455
    // The sampler type cannot be used with the __local and __global address
7456
    // space qualifiers.
7457
161
    if (R.getAddressSpace() == LangAS::opencl_local ||
7458
161
        
R.getAddressSpace() == LangAS::opencl_global155
) {
7459
18
      Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7460
18
      NewVD->setInvalidDecl();
7461
18
    }
7462
7463
    // OpenCL v1.2 s6.12.14.1:
7464
    // A global sampler must be declared with either the constant address
7465
    // space qualifier or with the const qualifier.
7466
161
    if (DC->isTranslationUnit() &&
7467
161
        
!(93
R.getAddressSpace() == LangAS::opencl_constant93
||
7468
93
          
R.isConstQualified()30
)) {
7469
12
      Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7470
12
      NewVD->setInvalidDecl();
7471
12
    }
7472
161
    if (NewVD->isInvalidDecl())
7473
24
      return false;
7474
161
  }
7475
7476
4.35k
  return true;
7477
4.37k
}
7478
7479
template <typename AttrTy>
7480
401
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7481
401
  const TypedefNameDecl *TND = TT->getDecl();
7482
401
  if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7483
8
    AttrTy *Clone = Attribute->clone(S.Context);
7484
8
    Clone->setInherited(true);
7485
8
    D->addAttr(Clone);
7486
8
  }
7487
401
}
7488
7489
// This function emits warning and a corresponding note based on the
7490
// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7491
// declarations of an annotated type must be const qualified.
7492
3.08M
void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7493
3.08M
  QualType VarType = VD->getType().getCanonicalType();
7494
7495
  // Ignore local declarations (for now) and those with const qualification.
7496
  // TODO: Local variables should not be allowed if their type declaration has
7497
  // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7498
3.08M
  if (!VD || VD->hasLocalStorage() || 
VD->getType().isConstQualified()1.36M
)
7499
2.90M
    return;
7500
7501
184k
  if (VarType->isArrayType()) {
7502
    // Retrieve element type for array declarations.
7503
9.32k
    VarType = S.getASTContext().getBaseElementType(VarType);
7504
9.32k
  }
7505
7506
184k
  const RecordDecl *RD = VarType->getAsRecordDecl();
7507
7508
  // Check if the record declaration is present and if it has any attributes.
7509
184k
  if (RD == nullptr)
7510
143k
    return;
7511
7512
41.1k
  if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7513
24
    S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7514
24
    S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7515
24
    return;
7516
24
  }
7517
41.1k
}
7518
7519
NamedDecl *Sema::ActOnVariableDeclarator(
7520
    Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7521
    LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7522
3.09M
    bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7523
3.09M
  QualType R = TInfo->getType();
7524
3.09M
  DeclarationName Name = GetNameForDeclarator(D).getName();
7525
7526
3.09M
  IdentifierInfo *II = Name.getAsIdentifierInfo();
7527
3.09M
  bool IsPlaceholderVariable = false;
7528
7529
3.09M
  if (D.isDecompositionDeclarator()) {
7530
    // Take the name of the first declarator as our name for diagnostic
7531
    // purposes.
7532
694
    auto &Decomp = D.getDecompositionDeclarator();
7533
694
    if (!Decomp.bindings().empty()) {
7534
682
      II = Decomp.bindings()[0].Name;
7535
682
      Name = II;
7536
682
    }
7537
3.09M
  } else if (!II) {
7538
19
    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7539
19
    return nullptr;
7540
19
  }
7541
7542
7543
3.09M
  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7544
3.09M
  StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7545
7546
3.09M
  if (LangOpts.CPlusPlus && 
(1.73M
DC->isClosure()1.73M
||
DC->isFunctionOrMethod()1.73M
) &&
7547
3.09M
      
SC != SC_Static1.21M
&&
SC != SC_Extern1.20M
&&
II1.20M
&&
II->isPlaceholder()1.20M
) {
7548
128
    IsPlaceholderVariable = true;
7549
128
    if (!Previous.empty()) {
7550
8
      NamedDecl *PrevDecl = *Previous.begin();
7551
8
      bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7552
8
          DC->getRedeclContext());
7553
8
      if (SameDC && 
isDeclInScope(PrevDecl, CurContext, S, false)3
)
7554
2
        DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7555
8
    }
7556
128
  }
7557
7558
  // dllimport globals without explicit storage class are treated as extern. We
7559
  // have to change the storage class this early to get the right DeclContext.
7560
3.09M
  if (SC == SC_None && 
!DC->isRecord()1.91M
&&
7561
3.09M
      
hasParsedAttr(S, D, ParsedAttr::AT_DLLImport)1.85M
&&
7562
3.09M
      
!hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)936
)
7563
840
    SC = SC_Extern;
7564
7565
3.09M
  DeclContext *OriginalDC = DC;
7566
3.09M
  bool IsLocalExternDecl = SC == SC_Extern &&
7567
3.09M
                           
adjustContextForLocalExternDecl(DC)920k
;
7568
7569
3.09M
  if (SCSpec == DeclSpec::SCS_mutable) {
7570
    // mutable can only appear on non-static class members, so it's always
7571
    // an error here
7572
4
    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7573
4
    D.setInvalidType();
7574
4
    SC = SC_None;
7575
4
  }
7576
7577
3.09M
  if (getLangOpts().CPlusPlus11 && 
SCSpec == DeclSpec::SCS_register1.68M
&&
7578
3.09M
      
!D.getAsmLabel()107
&& !getSourceManager().isInSystemMacro(
7579
89
                              D.getDeclSpec().getStorageClassSpecLoc())) {
7580
    // In C++11, the 'register' storage class specifier is deprecated.
7581
    // Suppress the warning in system macros, it's used in macros in some
7582
    // popular C system headers, such as in glibc's htonl() macro.
7583
79
    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7584
79
         getLangOpts().CPlusPlus17 ? 
diag::ext_register_storage_class11
7585
79
                                   : 
diag::warn_deprecated_register68
)
7586
79
      << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7587
79
  }
7588
7589
3.09M
  DiagnoseFunctionSpecifiers(D.getDeclSpec());
7590
7591
3.09M
  if (!DC->isRecord() && 
S->getFnParent() == nullptr2.79M
) {
7592
    // C99 6.9p2: The storage-class specifiers auto and register shall not
7593
    // appear in the declaration specifiers in an external declaration.
7594
    // Global Register+Asm is a GNU extension we support.
7595
1.06M
    if (SC == SC_Auto || 
(1.06M
SC == SC_Register1.06M
&&
!D.getAsmLabel()45
)) {
7596
9
      Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7597
9
      D.setInvalidType();
7598
9
    }
7599
1.06M
  }
7600
7601
  // If this variable has a VLA type and an initializer, try to
7602
  // fold to a constant-sized type. This is otherwise invalid.
7603
3.09M
  if (D.hasInitializer() && 
R->isVariableArrayType()1.09M
)
7604
37
    tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7605
37
                                    /*DiagID=*/0);
7606
7607
3.09M
  bool IsMemberSpecialization = false;
7608
3.09M
  bool IsVariableTemplateSpecialization = false;
7609
3.09M
  bool IsPartialSpecialization = false;
7610
3.09M
  bool IsVariableTemplate = false;
7611
3.09M
  VarDecl *NewVD = nullptr;
7612
3.09M
  VarTemplateDecl *NewTemplate = nullptr;
7613
3.09M
  TemplateParameterList *TemplateParams = nullptr;
7614
3.09M
  if (!getLangOpts().CPlusPlus) {
7615
1.35M
    NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7616
1.35M
                            II, R, TInfo, SC);
7617
7618
1.35M
    if (R->getContainedDeducedType())
7619
135
      ParsingInitForAutoVars.insert(NewVD);
7620
7621
1.35M
    if (D.isInvalidType())
7622
449
      NewVD->setInvalidDecl();
7623
7624
1.35M
    if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7625
1.35M
        
NewVD->hasLocalStorage()21
)
7626
13
      checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7627
13
                            NTCUC_AutoVar, NTCUK_Destruct);
7628
1.73M
  } else {
7629
1.73M
    bool Invalid = false;
7630
7631
1.73M
    if (DC->isRecord() && 
!CurContext->isRecord()291k
) {
7632
      // This is an out-of-line definition of a static data member.
7633
58.6k
      switch (SC) {
7634
58.6k
      case SC_None:
7635
58.6k
        break;
7636
3
      case SC_Static:
7637
3
        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7638
3
             diag::err_static_out_of_line)
7639
3
          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7640
3
        break;
7641
1
      case SC_Auto:
7642
1
      case SC_Register:
7643
3
      case SC_Extern:
7644
        // [dcl.stc] p2: The auto or register specifiers shall be applied only
7645
        // to names of variables declared in a block or to function parameters.
7646
        // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7647
        // of class members
7648
7649
3
        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7650
3
             diag::err_storage_class_for_static_member)
7651
3
          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7652
3
        break;
7653
0
      case SC_PrivateExtern:
7654
0
        llvm_unreachable("C storage class in c++!");
7655
58.6k
      }
7656
58.6k
    }
7657
7658
1.73M
    if (SC == SC_Static && 
CurContext->isRecord()246k
) {
7659
232k
      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7660
        // Walk up the enclosing DeclContexts to check for any that are
7661
        // incompatible with static data members.
7662
232k
        const DeclContext *FunctionOrMethod = nullptr;
7663
232k
        const CXXRecordDecl *AnonStruct = nullptr;
7664
1.17M
        for (DeclContext *Ctxt = DC; Ctxt; 
Ctxt = Ctxt->getParent()937k
) {
7665
937k
          if (Ctxt->isFunctionOrMethod()) {
7666
8
            FunctionOrMethod = Ctxt;
7667
8
            break;
7668
8
          }
7669
937k
          const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7670
937k
          if (ParentDecl && 
!ParentDecl->getDeclName()239k
) {
7671
26
            AnonStruct = ParentDecl;
7672
26
            break;
7673
26
          }
7674
937k
        }
7675
232k
        if (FunctionOrMethod) {
7676
          // C++ [class.static.data]p5: A local class shall not have static data
7677
          // members.
7678
8
          Diag(D.getIdentifierLoc(),
7679
8
               diag::err_static_data_member_not_allowed_in_local_class)
7680
8
              << Name << RD->getDeclName()
7681
8
              << llvm::to_underlying(RD->getTagKind());
7682
232k
        } else if (AnonStruct) {
7683
          // C++ [class.static.data]p4: Unnamed classes and classes contained
7684
          // directly or indirectly within unnamed classes shall not contain
7685
          // static data members.
7686
26
          Diag(D.getIdentifierLoc(),
7687
26
               diag::err_static_data_member_not_allowed_in_anon_struct)
7688
26
              << Name << llvm::to_underlying(AnonStruct->getTagKind());
7689
26
          Invalid = true;
7690
232k
        } else if (RD->isUnion()) {
7691
          // C++98 [class.union]p1: If a union contains a static data member,
7692
          // the program is ill-formed. C++11 drops this restriction.
7693
53
          Diag(D.getIdentifierLoc(),
7694
53
               getLangOpts().CPlusPlus11
7695
53
                 ? 
diag::warn_cxx98_compat_static_data_member_in_union52
7696
53
                 : 
diag::ext_static_data_member_in_union1
) << Name;
7697
53
        }
7698
232k
      }
7699
232k
    }
7700
7701
    // Match up the template parameter lists with the scope specifier, then
7702
    // determine whether we have a template or a template specialization.
7703
1.73M
    bool InvalidScope = false;
7704
1.73M
    TemplateParams = MatchTemplateParametersToScopeSpecifier(
7705
1.73M
        D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7706
1.73M
        D.getCXXScopeSpec(),
7707
1.73M
        D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7708
1.73M
            ? 
D.getName().TemplateId1.18k
7709
1.73M
            : 
nullptr1.73M
,
7710
1.73M
        TemplateParamLists,
7711
1.73M
        /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7712
1.73M
    Invalid |= InvalidScope;
7713
7714
1.73M
    if (TemplateParams) {
7715
7.36k
      if (!TemplateParams->size() &&
7716
7.36k
          
D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId638
) {
7717
        // There is an extraneous 'template<>' for this variable. Complain
7718
        // about it, but allow the declaration of the variable.
7719
8
        Diag(TemplateParams->getTemplateLoc(),
7720
8
             diag::err_template_variable_noparams)
7721
8
          << II
7722
8
          << SourceRange(TemplateParams->getTemplateLoc(),
7723
8
                         TemplateParams->getRAngleLoc());
7724
8
        TemplateParams = nullptr;
7725
7.35k
      } else {
7726
        // Check that we can declare a template here.
7727
7.35k
        if (CheckTemplateDeclScope(S, TemplateParams))
7728
7
          return nullptr;
7729
7730
7.35k
        if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7731
          // This is an explicit specialization or a partial specialization.
7732
1.18k
          IsVariableTemplateSpecialization = true;
7733
1.18k
          IsPartialSpecialization = TemplateParams->size() > 0;
7734
6.17k
        } else { // if (TemplateParams->size() > 0)
7735
          // This is a template declaration.
7736
6.17k
          IsVariableTemplate = true;
7737
7738
          // Only C++1y supports variable templates (N3651).
7739
6.17k
          Diag(D.getIdentifierLoc(),
7740
6.17k
               getLangOpts().CPlusPlus14
7741
6.17k
                   ? 
diag::warn_cxx11_compat_variable_template5.79k
7742
6.17k
                   : 
diag::ext_variable_template377
);
7743
6.17k
        }
7744
7.35k
      }
7745
1.72M
    } else {
7746
      // Check that we can declare a member specialization here.
7747
1.72M
      if (!TemplateParamLists.empty() && 
IsMemberSpecialization55.4k
&&
7748
1.72M
          
CheckTemplateDeclScope(S, TemplateParamLists.back())144
)
7749
1
        return nullptr;
7750
1.72M
      assert((Invalid ||
7751
1.72M
              D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7752
1.72M
             "should have a 'template<>' for this decl");
7753
1.72M
    }
7754
7755
1.73M
    if (IsVariableTemplateSpecialization) {
7756
1.18k
      SourceLocation TemplateKWLoc =
7757
1.18k
          TemplateParamLists.size() > 0
7758
1.18k
              ? 
TemplateParamLists[0]->getTemplateLoc()1.17k
7759
1.18k
              : 
SourceLocation()9
;
7760
1.18k
      DeclResult Res = ActOnVarTemplateSpecialization(
7761
1.18k
          S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7762
1.18k
          IsPartialSpecialization);
7763
1.18k
      if (Res.isInvalid())
7764
44
        return nullptr;
7765
1.13k
      NewVD = cast<VarDecl>(Res.get());
7766
1.13k
      AddToScope = false;
7767
1.73M
    } else if (D.isDecompositionDeclarator()) {
7768
694
      NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7769
694
                                        D.getIdentifierLoc(), R, TInfo, SC,
7770
694
                                        Bindings);
7771
694
    } else
7772
1.73M
      NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7773
1.73M
                              D.getIdentifierLoc(), II, R, TInfo, SC);
7774
7775
    // If this is supposed to be a variable template, create it as such.
7776
1.73M
    if (IsVariableTemplate) {
7777
6.17k
      NewTemplate =
7778
6.17k
          VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7779
6.17k
                                  TemplateParams, NewVD);
7780
6.17k
      NewVD->setDescribedVarTemplate(NewTemplate);
7781
6.17k
    }
7782
7783
    // If this decl has an auto type in need of deduction, make a note of the
7784
    // Decl so we can diagnose uses of it in its own initializer.
7785
1.73M
    if (R->getContainedDeducedType())
7786
75.7k
      ParsingInitForAutoVars.insert(NewVD);
7787
7788
1.73M
    if (D.isInvalidType() || 
Invalid1.73M
) {
7789
1.35k
      NewVD->setInvalidDecl();
7790
1.35k
      if (NewTemplate)
7791
1
        NewTemplate->setInvalidDecl();
7792
1.35k
    }
7793
7794
1.73M
    SetNestedNameSpecifier(*this, NewVD, D);
7795
7796
    // If we have any template parameter lists that don't directly belong to
7797
    // the variable (matching the scope specifier), store them.
7798
    // An explicit variable template specialization does not own any template
7799
    // parameter lists.
7800
1.73M
    bool IsExplicitSpecialization =
7801
1.73M
        IsVariableTemplateSpecialization && 
!IsPartialSpecialization1.13k
;
7802
1.73M
    unsigned VDTemplateParamLists =
7803
1.73M
        (TemplateParams && 
!IsExplicitSpecialization7.30k
) ?
16.70k
:
01.72M
;
7804
1.73M
    if (TemplateParamLists.size() > VDTemplateParamLists)
7805
56.1k
      NewVD->setTemplateParameterListsInfo(
7806
56.1k
          Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7807
1.73M
  }
7808
7809
3.09M
  if (D.getDeclSpec().isInlineSpecified()) {
7810
6.13k
    if (!getLangOpts().CPlusPlus) {
7811
1
      Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7812
1
          << 0;
7813
6.13k
    } else if (CurContext->isFunctionOrMethod()) {
7814
      // 'inline' is not allowed on block scope variable declaration.
7815
5
      Diag(D.getDeclSpec().getInlineSpecLoc(),
7816
5
           diag::err_inline_declaration_block_scope) << Name
7817
5
        << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7818
6.13k
    } else {
7819
6.13k
      Diag(D.getDeclSpec().getInlineSpecLoc(),
7820
6.13k
           getLangOpts().CPlusPlus17 ? 
diag::warn_cxx14_compat_inline_variable6.11k
7821
6.13k
                                     : 
diag::ext_inline_variable20
);
7822
6.13k
      NewVD->setInlineSpecified();
7823
6.13k
    }
7824
6.13k
  }
7825
7826
  // Set the lexical context. If the declarator has a C++ scope specifier, the
7827
  // lexical context will be different from the semantic context.
7828
3.09M
  NewVD->setLexicalDeclContext(CurContext);
7829
3.09M
  if (NewTemplate)
7830
6.17k
    NewTemplate->setLexicalDeclContext(CurContext);
7831
7832
3.09M
  if (IsLocalExternDecl) {
7833
944
    if (D.isDecompositionDeclarator())
7834
4
      for (auto *B : Bindings)
7835
5
        B->setLocalExternDecl();
7836
940
    else
7837
940
      NewVD->setLocalExternDecl();
7838
944
  }
7839
7840
3.09M
  bool EmitTLSUnsupportedError = false;
7841
3.09M
  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7842
    // C++11 [dcl.stc]p4:
7843
    //   When thread_local is applied to a variable of block scope the
7844
    //   storage-class-specifier static is implied if it does not appear
7845
    //   explicitly.
7846
    // Core issue: 'static' is not implied if the variable is declared
7847
    //   'extern'.
7848
995
    if (NewVD->hasLocalStorage() &&
7849
995
        
(108
SCSpec != DeclSpec::SCS_unspecified108
||
7850
108
         TSCS != DeclSpec::TSCS_thread_local ||
7851
108
         
!DC->isFunctionOrMethod()96
))
7852
12
      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7853
12
           diag::err_thread_non_global)
7854
12
        << DeclSpec::getSpecifierName(TSCS);
7855
983
    else if (!Context.getTargetInfo().isTLSSupported()) {
7856
39
      if (getLangOpts().CUDA || 
getLangOpts().OpenMPIsTargetDevice33
||
7857
39
          
getLangOpts().SYCLIsDevice21
) {
7858
        // Postpone error emission until we've collected attributes required to
7859
        // figure out whether it's a host or device variable and whether the
7860
        // error should be ignored.
7861
28
        EmitTLSUnsupportedError = true;
7862
        // We still need to mark the variable as TLS so it shows up in AST with
7863
        // proper storage class for other tools to use even if we're not going
7864
        // to emit any code for it.
7865
28
        NewVD->setTSCSpec(TSCS);
7866
28
      } else
7867
11
        Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7868
11
             diag::err_thread_unsupported);
7869
39
    } else
7870
944
      NewVD->setTSCSpec(TSCS);
7871
995
  }
7872
7873
3.09M
  switch (D.getDeclSpec().getConstexprSpecifier()) {
7874
2.88M
  case ConstexprSpecKind::Unspecified:
7875
2.88M
    break;
7876
7877
1
  case ConstexprSpecKind::Consteval:
7878
1
    Diag(D.getDeclSpec().getConstexprSpecLoc(),
7879
1
         diag::err_constexpr_wrong_decl_kind)
7880
1
        << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7881
1
    [[fallthrough]];
7882
7883
202k
  case ConstexprSpecKind::Constexpr:
7884
202k
    NewVD->setConstexpr(true);
7885
    // C++1z [dcl.spec.constexpr]p1:
7886
    //   A static data member declared with the constexpr specifier is
7887
    //   implicitly an inline variable.
7888
202k
    if (NewVD->isStaticDataMember() &&
7889
202k
        
(182k
getLangOpts().CPlusPlus17182k
||
7890
182k
         
Context.getTargetInfo().getCXXABI().isMicrosoft()171k
))
7891
10.8k
      NewVD->setImplicitlyInline();
7892
202k
    break;
7893
7894
84
  case ConstexprSpecKind::Constinit:
7895
84
    if (!NewVD->hasGlobalStorage())
7896
1
      Diag(D.getDeclSpec().getConstexprSpecLoc(),
7897
1
           diag::err_constinit_local_variable);
7898
83
    else
7899
83
      NewVD->addAttr(
7900
83
          ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7901
83
                                ConstInitAttr::Keyword_constinit));
7902
84
    break;
7903
3.09M
  }
7904
7905
  // C99 6.7.4p3
7906
  //   An inline definition of a function with external linkage shall
7907
  //   not contain a definition of a modifiable object with static or
7908
  //   thread storage duration...
7909
  // We only apply this when the function is required to be defined
7910
  // elsewhere, i.e. when the function is not 'extern inline'.  Note
7911
  // that a local variable with thread storage duration still has to
7912
  // be marked 'static'.  Also note that it's possible to get these
7913
  // semantics in C++ using __attribute__((gnu_inline)).
7914
3.09M
  if (SC == SC_Static && 
S->getFnParent() != nullptr255k
&&
7915
3.09M
      
!NewVD->getType().isConstQualified()9.26k
) {
7916
7.16k
    FunctionDecl *CurFD = getCurFunctionDecl();
7917
7.16k
    if (CurFD && 
isFunctionDefinitionDiscarded(*this, CurFD)7.05k
) {
7918
11
      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7919
11
           diag::warn_static_local_in_extern_inline);
7920
11
      MaybeSuggestAddingStaticToDecl(CurFD);
7921
11
    }
7922
7.16k
  }
7923
7924
3.09M
  if (D.getDeclSpec().isModulePrivateSpecified()) {
7925
9
    if (IsVariableTemplateSpecialization)
7926
0
      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7927
0
          << (IsPartialSpecialization ? 1 : 0)
7928
0
          << FixItHint::CreateRemoval(
7929
0
                 D.getDeclSpec().getModulePrivateSpecLoc());
7930
9
    else if (IsMemberSpecialization)
7931
1
      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7932
1
        << 2
7933
1
        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7934
8
    else if (NewVD->hasLocalStorage())
7935
2
      Diag(NewVD->getLocation(), diag::err_module_private_local)
7936
2
          << 0 << NewVD
7937
2
          << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7938
2
          << FixItHint::CreateRemoval(
7939
2
                 D.getDeclSpec().getModulePrivateSpecLoc());
7940
6
    else {
7941
6
      NewVD->setModulePrivate();
7942
6
      if (NewTemplate)
7943
0
        NewTemplate->setModulePrivate();
7944
6
      for (auto *B : Bindings)
7945
0
        B->setModulePrivate();
7946
6
    }
7947
9
  }
7948
7949
3.09M
  if (getLangOpts().OpenCL) {
7950
4.43k
    deduceOpenCLAddressSpace(NewVD);
7951
7952
4.43k
    DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7953
4.43k
    if (TSC != TSCS_unspecified) {
7954
3
      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7955
3
           diag::err_opencl_unknown_type_specifier)
7956
3
          << getLangOpts().getOpenCLVersionString()
7957
3
          << DeclSpec::getSpecifierName(TSC) << 1;
7958
3
      NewVD->setInvalidDecl();
7959
3
    }
7960
4.43k
  }
7961
7962
  // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7963
  // address space if the table has local storage (semantic checks elsewhere
7964
  // will produce an error anyway).
7965
3.09M
  if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7966
63.3k
    if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7967
63.3k
        
!NewVD->hasLocalStorage()32
) {
7968
28
      QualType Type = Context.getAddrSpaceQualType(
7969
28
          NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
7970
28
      NewVD->setType(Type);
7971
28
    }
7972
63.3k
  }
7973
7974
  // Handle attributes prior to checking for duplicates in MergeVarDecl
7975
3.09M
  ProcessDeclAttributes(S, NewVD, D);
7976
7977
  // FIXME: This is probably the wrong location to be doing this and we should
7978
  // probably be doing this for more attributes (especially for function
7979
  // pointer attributes such as format, warn_unused_result, etc.). Ideally
7980
  // the code to copy attributes would be generated by TableGen.
7981
3.09M
  if (R->isFunctionPointerType())
7982
4.17k
    if (const auto *TT = R->getAs<TypedefType>())
7983
401
      copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7984
7985
3.09M
  if (getLangOpts().CUDA || 
getLangOpts().OpenMPIsTargetDevice3.08M
||
7986
3.09M
      
getLangOpts().SYCLIsDevice3.07M
) {
7987
12.2k
    if (EmitTLSUnsupportedError &&
7988
12.2k
        
(28
(28
getLangOpts().CUDA28
&&
DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)6
) ||
7989
28
         
(24
getLangOpts().OpenMPIsTargetDevice24
&&
7990
24
          
OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)12
)))
7991
4
      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7992
4
           diag::err_thread_unsupported);
7993
7994
12.2k
    if (EmitTLSUnsupportedError &&
7995
12.2k
        
(28
LangOpts.SYCLIsDevice28
||
7996
28
         
(18
LangOpts.OpenMP18
&&
LangOpts.OpenMPIsTargetDevice12
)))
7997
22
      targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7998
    // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7999
    // storage [duration]."
8000
12.2k
    if (SC == SC_None && 
S->getFnParent() != nullptr11.0k
&&
8001
12.2k
        
(9.28k
NewVD->hasAttr<CUDASharedAttr>()9.28k
||
8002
9.28k
         
NewVD->hasAttr<CUDAConstantAttr>()9.24k
)) {
8003
35
      NewVD->setStorageClass(SC_Static);
8004
35
    }
8005
12.2k
  }
8006
8007
  // Ensure that dllimport globals without explicit storage class are treated as
8008
  // extern. The storage class is set above using parsed attributes. Now we can
8009
  // check the VarDecl itself.
8010
3.09M
  assert(!NewVD->hasAttr<DLLImportAttr>() ||
8011
3.09M
         NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8012
3.09M
         NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8013
8014
  // In auto-retain/release, infer strong retension for variables of
8015
  // retainable type.
8016
3.09M
  if (getLangOpts().ObjCAutoRefCount && 
inferObjCARCLifetime(NewVD)24.6k
)
8017
16
    NewVD->setInvalidDecl();
8018
8019
  // Handle GNU asm-label extension (encoded as an attribute).
8020
3.09M
  if (Expr *E = (Expr*)D.getAsmLabel()) {
8021
    // The parser guarantees this is a string.
8022
1.68k
    StringLiteral *SE = cast<StringLiteral>(E);
8023
1.68k
    StringRef Label = SE->getString();
8024
1.68k
    if (S->getFnParent() != nullptr) {
8025
906
      switch (SC) {
8026
1
      case SC_None:
8027
2
      case SC_Auto:
8028
2
        Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8029
2
        break;
8030
144
      case SC_Register:
8031
        // Local Named register
8032
144
        if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8033
144
            
DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())17
)
8034
17
          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8035
144
        break;
8036
758
      case SC_Static:
8037
759
      case SC_Extern:
8038
760
      case SC_PrivateExtern:
8039
760
        break;
8040
906
      }
8041
906
    } else 
if (777
SC == SC_Register777
) {
8042
      // Global Named register
8043
41
      if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8044
41
        const auto &TI = Context.getTargetInfo();
8045
41
        bool HasSizeMismatch;
8046
8047
41
        if (!TI.isValidGCCRegisterName(Label))
8048
0
          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8049
41
        else if (!TI.validateGlobalRegisterVariable(Label,
8050
41
                                                    Context.getTypeSize(R),
8051
41
                                                    HasSizeMismatch))
8052
1
          Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8053
40
        else if (HasSizeMismatch)
8054
1
          Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8055
41
      }
8056
8057
41
      if (!R->isIntegralType(Context) && 
!R->isPointerType()5
) {
8058
2
        Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
8059
2
        NewVD->setInvalidDecl(true);
8060
2
      }
8061
41
    }
8062
8063
1.68k
    NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8064
1.68k
                                        /*IsLiteralLabel=*/true,
8065
1.68k
                                        SE->getStrTokenLoc(0)));
8066
3.08M
  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8067
5
    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8068
5
      ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
8069
5
    if (I != ExtnameUndeclaredIdentifiers.end()) {
8070
3
      if (isDeclExternC(NewVD)) {
8071
1
        NewVD->addAttr(I->second);
8072
1
        ExtnameUndeclaredIdentifiers.erase(I);
8073
1
      } else
8074
2
        Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8075
2
            << /*Variable*/1 << NewVD;
8076
3
    }
8077
5
  }
8078
8079
  // Find the shadowed declaration before filtering for scope.
8080
3.09M
  NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8081
3.09M
                                ? 
getShadowedDeclaration(NewVD, Previous)3.03M
8082
3.09M
                                : 
nullptr58.8k
;
8083
8084
  // Don't consider existing declarations that are in a different
8085
  // scope and are out-of-semantic-context declarations (if the new
8086
  // declaration has linkage).
8087
3.09M
  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
8088
3.09M
                       D.getCXXScopeSpec().isNotEmpty() ||
8089
3.09M
                       
IsMemberSpecialization3.03M
||
8090
3.09M
                       
IsVariableTemplateSpecialization3.03M
);
8091
8092
  // Check whether the previous declaration is in the same block scope. This
8093
  // affects whether we merge types with it, per C++11 [dcl.array]p3.
8094
3.09M
  if (getLangOpts().CPlusPlus &&
8095
3.09M
      
NewVD->isLocalVarDecl()1.73M
&&
NewVD->hasExternalStorage()1.21M
)
8096
503
    NewVD->setPreviousDeclInSameBlockScope(
8097
503
        Previous.isSingleResult() && 
!Previous.isShadowed()144
&&
8098
503
        
isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)132
);
8099
8100
3.09M
  if (!getLangOpts().CPlusPlus) {
8101
1.35M
    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8102
1.73M
  } else {
8103
    // If this is an explicit specialization of a static data member, check it.
8104
1.73M
    if (IsMemberSpecialization && 
!NewVD->isInvalidDecl()239
&&
8105
1.73M
        
CheckMemberSpecialization(NewVD, Previous)230
)
8106
1
      NewVD->setInvalidDecl();
8107
8108
    // Merge the decl with the existing one if appropriate.
8109
1.73M
    if (!Previous.empty()) {
8110
61.9k
      if (Previous.isSingleResult() &&
8111
61.9k
          
isa<FieldDecl>(Previous.getFoundDecl())61.9k
&&
8112
61.9k
          
D.getCXXScopeSpec().isSet()4
) {
8113
        // The user tried to define a non-static data member
8114
        // out-of-line (C++ [dcl.meaning]p1).
8115
2
        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8116
2
          << D.getCXXScopeSpec().getRange();
8117
2
        Previous.clear();
8118
2
        NewVD->setInvalidDecl();
8119
2
      }
8120
1.67M
    } else if (D.getCXXScopeSpec().isSet()) {
8121
      // No previous declaration in the qualifying scope.
8122
28
      Diag(D.getIdentifierLoc(), diag::err_no_member)
8123
28
        << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8124
28
        << D.getCXXScopeSpec().getRange();
8125
28
      NewVD->setInvalidDecl();
8126
28
    }
8127
8128
1.73M
    if (!IsVariableTemplateSpecialization && 
!IsPlaceholderVariable1.73M
)
8129
1.73M
      D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8130
8131
    // CheckVariableDeclaration will set NewVD as invalid if something is in
8132
    // error like WebAssembly tables being declared as arrays with a non-zero
8133
    // size, but then parsing continues and emits further errors on that line.
8134
    // To avoid that we check here if it happened and return nullptr.
8135
1.73M
    if (NewVD->getType()->isWebAssemblyTableType() && 
NewVD->isInvalidDecl()16
)
8136
12
      return nullptr;
8137
8138
1.73M
    if (NewTemplate) {
8139
6.17k
      VarTemplateDecl *PrevVarTemplate =
8140
6.17k
          NewVD->getPreviousDecl()
8141
6.17k
              ? 
NewVD->getPreviousDecl()->getDescribedVarTemplate()429
8142
6.17k
              : 
nullptr5.74k
;
8143
8144
      // Check the template parameter list of this declaration, possibly
8145
      // merging in the template parameter list from the previous variable
8146
      // template declaration.
8147
6.17k
      if (CheckTemplateParameterList(
8148
6.17k
              TemplateParams,
8149
6.17k
              PrevVarTemplate ? 
PrevVarTemplate->getTemplateParameters()429
8150
6.17k
                              : 
nullptr5.74k
,
8151
6.17k
              (D.getCXXScopeSpec().isSet() && 
DC222
&&
DC->isRecord()222
&&
8152
6.17k
               
DC->isDependentContext()220
)
8153
6.17k
                  ? 
TPC_ClassTemplateMember85
8154
6.17k
                  : 
TPC_VarTemplate6.08k
))
8155
9
        NewVD->setInvalidDecl();
8156
8157
      // If we are providing an explicit specialization of a static variable
8158
      // template, make a note of that.
8159
6.17k
      if (PrevVarTemplate &&
8160
6.17k
          
PrevVarTemplate->getInstantiatedFromMemberTemplate()429
)
8161
26
        PrevVarTemplate->setMemberSpecialization();
8162
6.17k
    }
8163
1.73M
  }
8164
8165
  // Diagnose shadowed variables iff this isn't a redeclaration.
8166
3.09M
  if (!IsPlaceholderVariable && 
ShadowedDecl3.09M
&&
!D.isRedeclaration()159
)
8167
151
    CheckShadow(NewVD, ShadowedDecl, Previous);
8168
8169
3.09M
  ProcessPragmaWeak(S, NewVD);
8170
8171
  // If this is the first declaration of an extern C variable, update
8172
  // the map of such variables.
8173
3.09M
  if (NewVD->isFirstDecl() && 
!NewVD->isInvalidDecl()3.02M
&&
8174
3.09M
      
isIncompleteDeclExternC(*this, NewVD)3.02M
)
8175
948k
    RegisterLocallyScopedExternCDecl(NewVD, S);
8176
8177
3.09M
  if (getLangOpts().CPlusPlus && 
NewVD->isStaticLocal()1.73M
) {
8178
8.45k
    MangleNumberingContext *MCtx;
8179
8.45k
    Decl *ManglingContextDecl;
8180
8.45k
    std::tie(MCtx, ManglingContextDecl) =
8181
8.45k
        getCurrentMangleNumberContext(NewVD->getDeclContext());
8182
8.45k
    if (MCtx) {
8183
3.26k
      Context.setManglingNumber(
8184
3.26k
          NewVD, MCtx->getManglingNumber(
8185
3.26k
                     NewVD, getMSManglingNumber(getLangOpts(), S)));
8186
3.26k
      Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8187
3.26k
    }
8188
8.45k
  }
8189
8190
  // Special handling of variable named 'main'.
8191
3.09M
  if (Name.getAsIdentifierInfo() && 
Name.getAsIdentifierInfo()->isStr("main")3.09M
&&
8192
3.09M
      
NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit()25
&&
8193
3.09M
      
!getLangOpts().Freestanding17
&&
!NewVD->getDescribedVarTemplate()15
) {
8194
8195
    // C++ [basic.start.main]p3
8196
    // A program that declares a variable main at global scope is ill-formed.
8197
14
    if (getLangOpts().CPlusPlus)
8198
3
      Diag(D.getBeginLoc(), diag::err_main_global_variable);
8199
8200
    // In C, and external-linkage variable named main results in undefined
8201
    // behavior.
8202
11
    else if (NewVD->hasExternalFormalLinkage())
8203
10
      Diag(D.getBeginLoc(), diag::warn_main_redefined);
8204
14
  }
8205
8206
3.09M
  if (D.isRedeclaration() && 
!Previous.empty()62.0k
) {
8207
62.0k
    NamedDecl *Prev = Previous.getRepresentativeDecl();
8208
62.0k
    checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8209
62.0k
                                   D.isFunctionDefinition());
8210
62.0k
  }
8211
8212
3.09M
  if (NewTemplate) {
8213
6.17k
    if (NewVD->isInvalidDecl())
8214
115
      NewTemplate->setInvalidDecl();
8215
6.17k
    ActOnDocumentableDecl(NewTemplate);
8216
6.17k
    return NewTemplate;
8217
6.17k
  }
8218
8219
3.08M
  if (IsMemberSpecialization && 
!NewVD->isInvalidDecl()213
)
8220
197
    CompleteMemberSpecialization(NewVD, Previous);
8221
8222
3.08M
  emitReadOnlyPlacementAttrWarning(*this, NewVD);
8223
8224
3.08M
  return NewVD;
8225
3.09M
}
8226
8227
/// Enum describing the %select options in diag::warn_decl_shadow.
8228
enum ShadowedDeclKind {
8229
  SDK_Local,
8230
  SDK_Global,
8231
  SDK_StaticMember,
8232
  SDK_Field,
8233
  SDK_Typedef,
8234
  SDK_Using,
8235
  SDK_StructuredBinding
8236
};
8237
8238
/// Determine what kind of declaration we're shadowing.
8239
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8240
281
                                                const DeclContext *OldDC) {
8241
281
  if (isa<TypeAliasDecl>(ShadowedDecl))
8242
8
    return SDK_Using;
8243
273
  else if (isa<TypedefDecl>(ShadowedDecl))
8244
7
    return SDK_Typedef;
8245
266
  else if (isa<BindingDecl>(ShadowedDecl))
8246
3
    return SDK_StructuredBinding;
8247
263
  else if (isa<RecordDecl>(OldDC))
8248
6
    return isa<FieldDecl>(ShadowedDecl) ? 
SDK_Field4
:
SDK_StaticMember2
;
8249
8250
257
  return OldDC->isFileContext() ? 
SDK_Global67
:
SDK_Local190
;
8251
281
}
8252
8253
/// Return the location of the capture if the given lambda captures the given
8254
/// variable \p VD, or an invalid source location otherwise.
8255
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8256
155
                                         const VarDecl *VD) {
8257
155
  for (const Capture &Capture : LSI->Captures) {
8258
90
    if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8259
50
      return Capture.getLocation();
8260
90
  }
8261
105
  return SourceLocation();
8262
155
}
8263
8264
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8265
4.88M
                                     const LookupResult &R) {
8266
  // Only diagnose if we're shadowing an unambiguous field or variable.
8267
4.88M
  if (R.getResultKind() != LookupResult::Found)
8268
4.77M
    return false;
8269
8270
  // Return false if warning is ignored.
8271
110k
  return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8272
4.88M
}
8273
8274
/// Return the declaration shadowed by the given variable \p D, or null
8275
/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8276
NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8277
3.03M
                                        const LookupResult &R) {
8278
3.03M
  if (!shouldWarnIfShadowedDecl(Diags, R))
8279
3.03M
    return nullptr;
8280
8281
  // Don't diagnose declarations at file scope.
8282
227
  if (D->hasGlobalStorage() && 
!D->isStaticLocal()34
)
8283
2
    return nullptr;
8284
8285
225
  NamedDecl *ShadowedDecl = R.getFoundDecl();
8286
225
  return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? 
ShadowedDecl216
8287
225
                                                            : 
nullptr9
;
8288
227
}
8289
8290
/// Return the declaration shadowed by the given typedef \p D, or null
8291
/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8292
NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8293
2.32M
                                        const LookupResult &R) {
8294
  // Don't warn if typedef declaration is part of a class
8295
2.32M
  if (D->getDeclContext()->isRecord())
8296
470k
    return nullptr;
8297
8298
1.85M
  if (!shouldWarnIfShadowedDecl(Diags, R))
8299
1.85M
    return nullptr;
8300
8301
36
  NamedDecl *ShadowedDecl = R.getFoundDecl();
8302
36
  return isa<TypedefNameDecl>(ShadowedDecl) ? 
ShadowedDecl25
:
nullptr11
;
8303
1.85M
}
8304
8305
/// Return the declaration shadowed by the given variable \p D, or null
8306
/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8307
NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8308
1.34k
                                        const LookupResult &R) {
8309
1.34k
  if (!shouldWarnIfShadowedDecl(Diags, R))
8310
1.34k
    return nullptr;
8311
8312
8
  NamedDecl *ShadowedDecl = R.getFoundDecl();
8313
8
  return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8314
8
                                                            : 
nullptr0
;
8315
1.34k
}
8316
8317
/// Diagnose variable or built-in function shadowing.  Implements
8318
/// -Wshadow.
8319
///
8320
/// This method is called whenever a VarDecl is added to a "useful"
8321
/// scope.
8322
///
8323
/// \param ShadowedDecl the declaration that is shadowed by the given variable
8324
/// \param R the lookup of the name
8325
///
8326
void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8327
293
                       const LookupResult &R) {
8328
293
  DeclContext *NewDC = D->getDeclContext();
8329
8330
293
  if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8331
    // Fields are not shadowed by variables in C++ static methods.
8332
14
    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8333
14
      if (MD->isStatic())
8334
2
        return;
8335
8336
    // Fields shadowed by constructor parameters are a special case. Usually
8337
    // the constructor initializes the field with the parameter.
8338
12
    if (isa<CXXConstructorDecl>(NewDC))
8339
8
      if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8340
        // Remember that this was shadowed so we can either warn about its
8341
        // modification or its existence depending on warning settings.
8342
8
        ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8343
8
        return;
8344
8
      }
8345
12
  }
8346
8347
283
  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8348
220
    if (shadowedVar->isExternC()) {
8349
      // For shadowing external vars, make sure that we point to the global
8350
      // declaration, not a locally scoped extern declaration.
8351
11
      for (auto *I : shadowedVar->redecls())
8352
11
        if (I->isFileVarDecl()) {
8353
11
          ShadowedDecl = I;
8354
11
          break;
8355
11
        }
8356
11
    }
8357
8358
283
  DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8359
8360
283
  unsigned WarningDiag = diag::warn_decl_shadow;
8361
283
  SourceLocation CaptureLoc;
8362
283
  if (isa<VarDecl>(D) && 
isa<VarDecl>(ShadowedDecl)198
&&
NewDC195
&&
8363
283
      
isa<CXXMethodDecl>(NewDC)195
) {
8364
173
    if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8365
173
      if (RD->isLambda() && 
OldDC->Encloses(NewDC->getLexicalParent())170
) {
8366
155
        if (RD->getLambdaCaptureDefault() == LCD_None) {
8367
          // Try to avoid warnings for lambdas with an explicit capture list.
8368
85
          const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8369
          // Warn only when the lambda captures the shadowed decl explicitly.
8370
85
          CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8371
85
          if (CaptureLoc.isInvalid())
8372
60
            WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8373
85
        } else {
8374
          // Remember that this was shadowed so we can avoid the warning if the
8375
          // shadowed decl isn't captured and the warning settings allow it.
8376
70
          cast<LambdaScopeInfo>(getCurFunction())
8377
70
              ->ShadowingDecls.push_back(
8378
70
                  {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8379
70
          return;
8380
70
        }
8381
155
      }
8382
8383
103
      if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8384
        // A variable can't shadow a local variable in an enclosing scope, if
8385
        // they are separated by a non-capturing declaration context.
8386
102
        for (DeclContext *ParentDC = NewDC;
8387
212
             ParentDC && !ParentDC->Equals(OldDC);
8388
112
             
ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)110
) {
8389
          // Only block literals, captured statements, and lambda expressions
8390
          // can capture; other scopes don't.
8391
112
          if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8392
112
              !isLambdaCallOperator(ParentDC)) {
8393
2
            return;
8394
2
          }
8395
112
        }
8396
102
      }
8397
103
    }
8398
173
  }
8399
8400
  // Never warn about shadowing a placeholder variable.
8401
211
  if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8402
0
    return;
8403
8404
  // Only warn about certain kinds of shadowing for class members.
8405
211
  if (NewDC && NewDC->isRecord()) {
8406
    // In particular, don't warn about shadowing non-class members.
8407
0
    if (!OldDC->isRecord())
8408
0
      return;
8409
8410
    // TODO: should we warn about static data members shadowing
8411
    // static data members from base classes?
8412
8413
    // TODO: don't diagnose for inaccessible shadowed members.
8414
    // This is hard to do perfectly because we might friend the
8415
    // shadowing context, but that's just a false negative.
8416
0
  }
8417
8418
8419
211
  DeclarationName Name = R.getLookupName();
8420
8421
  // Emit warning and note.
8422
211
  ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8423
211
  Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8424
211
  if (!CaptureLoc.isInvalid())
8425
25
    Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8426
25
        << Name << /*explicitly*/ 1;
8427
211
  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8428
211
}
8429
8430
/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8431
/// when these variables are captured by the lambda.
8432
12.4k
void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8433
12.4k
  for (const auto &Shadow : LSI->ShadowingDecls) {
8434
70
    const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8435
    // Try to avoid the warning when the shadowed decl isn't captured.
8436
70
    SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8437
70
    const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8438
70
    Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8439
70
                                       ? 
diag::warn_decl_shadow_uncaptured_local45
8440
70
                                       : 
diag::warn_decl_shadow25
)
8441
70
        << Shadow.VD->getDeclName()
8442
70
        << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8443
70
    if (!CaptureLoc.isInvalid())
8444
25
      Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8445
25
          << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8446
70
    Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8447
70
  }
8448
12.4k
}
8449
8450
/// Check -Wshadow without the advantage of a previous lookup.
8451
9.28M
void Sema::CheckShadow(Scope *S, VarDecl *D) {
8452
9.28M
  if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8453
9.28M
    return;
8454
8455
179
  LookupResult R(*this, D->getDeclName(), D->getLocation(),
8456
179
                 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8457
179
  LookupName(R, S);
8458
179
  if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8459
57
    CheckShadow(D, ShadowedDecl, R);
8460
179
}
8461
8462
/// Check if 'E', which is an expression that is about to be modified, refers
8463
/// to a constructor parameter that shadows a field.
8464
2.97M
void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8465
  // Quickly ignore expressions that can't be shadowing ctor parameters.
8466
2.97M
  if (!getLangOpts().CPlusPlus || 
ShadowingDecls.empty()2.28M
)
8467
2.97M
    return;
8468
5
  E = E->IgnoreParenImpCasts();
8469
5
  auto *DRE = dyn_cast<DeclRefExpr>(E);
8470
5
  if (!DRE)
8471
0
    return;
8472
5
  const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8473
5
  auto I = ShadowingDecls.find(D);
8474
5
  if (I == ShadowingDecls.end())
8475
1
    return;
8476
4
  const NamedDecl *ShadowedDecl = I->second;
8477
4
  const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8478
4
  Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8479
4
  Diag(D->getLocation(), diag::note_var_declared_here) << D;
8480
4
  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8481
8482
  // Avoid issuing multiple warnings about the same decl.
8483
4
  ShadowingDecls.erase(I);
8484
4
}
8485
8486
/// Check for conflict between this global or extern "C" declaration and
8487
/// previous global or extern "C" declarations. This is only used in C++.
8488
template<typename T>
8489
static bool checkGlobalOrExternCConflict(
8490
13.5M
    Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8491
13.5M
  assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8492
13.5M
  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8493
8494
13.5M
  if (!Prev && 
IsGlobal13.5M
&&
!isIncompleteDeclExternC(S, ND)13.5M
) {
8495
    // The common case: this global doesn't conflict with any extern "C"
8496
    // declaration.
8497
12.7M
    return false;
8498
12.7M
  }
8499
8500
841k
  if (Prev) {
8501
16.6k
    if (!IsGlobal || 
isIncompleteDeclExternC(S, ND)16.6k
) {
8502
      // Both the old and new declarations have C language linkage. This is a
8503
      // redeclaration.
8504
95
      Previous.clear();
8505
95
      Previous.addDecl(Prev);
8506
95
      return true;
8507
95
    }
8508
8509
    // This is a global, non-extern "C" declaration, and there is a previous
8510
    // non-global extern "C" declaration. Diagnose if this is a variable
8511
    // declaration.
8512
16.5k
    if (!isa<VarDecl>(ND))
8513
16.5k
      return false;
8514
824k
  } else {
8515
    // The declaration is extern "C". Check for any declaration in the
8516
    // translation unit which might conflict.
8517
824k
    if (IsGlobal) {
8518
      // We have already performed the lookup into the translation unit.
8519
823k
      IsGlobal = false;
8520
823k
      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8521
823k
           I != E; 
++I12
) {
8522
12
        if (isa<VarDecl>(*I)) {
8523
0
          Prev = *I;
8524
0
          break;
8525
0
        }
8526
12
      }
8527
823k
    } else {
8528
1.13k
      DeclContext::lookup_result R =
8529
1.13k
          S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8530
1.13k
      for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8531
1.14k
           I != E; 
++I12
) {
8532
33
        if (isa<VarDecl>(*I)) {
8533
21
          Prev = *I;
8534
21
          break;
8535
21
        }
8536
        // FIXME: If we have any other entity with this name in global scope,
8537
        // the declaration is ill-formed, but that is a defect: it breaks the
8538
        // 'stat' hack, for instance. Only variables can have mangled name
8539
        // clashes with extern "C" declarations, so only they deserve a
8540
        // diagnostic.
8541
33
      }
8542
1.13k
    }
8543
8544
824k
    if (!Prev)
8545
824k
      return false;
8546
824k
  }
8547
8548
  // Use the first declaration's location to ensure we point at something which
8549
  // is lexically inside an extern "C" linkage-spec.
8550
39
  assert(Prev && "should have found a previous declaration to diagnose");
8551
39
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8552
8
    Prev = FD->getFirstDecl();
8553
31
  else
8554
31
    Prev = cast<VarDecl>(Prev)->getFirstDecl();
8555
8556
39
  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8557
39
    << IsGlobal << ND;
8558
39
  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8559
39
    << IsGlobal;
8560
39
  return false;
8561
39
}
SemaDecl.cpp:bool checkGlobalOrExternCConflict<clang::VarDecl>(clang::Sema&, clang::VarDecl const*, bool, clang::LookupResult&)
Line
Count
Source
8490
189k
    Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8491
189k
  assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8492
189k
  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8493
8494
189k
  if (!Prev && 
IsGlobal189k
&&
!isIncompleteDeclExternC(S, ND)189k
) {
8495
    // The common case: this global doesn't conflict with any extern "C"
8496
    // declaration.
8497
71.4k
    return false;
8498
71.4k
  }
8499
8500
118k
  if (Prev) {
8501
34
    if (!IsGlobal || 
isIncompleteDeclExternC(S, ND)18
) {
8502
      // Both the old and new declarations have C language linkage. This is a
8503
      // redeclaration.
8504
16
      Previous.clear();
8505
16
      Previous.addDecl(Prev);
8506
16
      return true;
8507
16
    }
8508
8509
    // This is a global, non-extern "C" declaration, and there is a previous
8510
    // non-global extern "C" declaration. Diagnose if this is a variable
8511
    // declaration.
8512
18
    if (!isa<VarDecl>(ND))
8513
0
      return false;
8514
118k
  } else {
8515
    // The declaration is extern "C". Check for any declaration in the
8516
    // translation unit which might conflict.
8517
118k
    if (IsGlobal) {
8518
      // We have already performed the lookup into the translation unit.
8519
117k
      IsGlobal = false;
8520
117k
      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8521
117k
           I != E; 
++I0
) {
8522
0
        if (isa<VarDecl>(*I)) {
8523
0
          Prev = *I;
8524
0
          break;
8525
0
        }
8526
0
      }
8527
117k
    } else {
8528
100
      DeclContext::lookup_result R =
8529
100
          S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8530
100
      for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8531
108
           I != E; 
++I8
) {
8532
15
        if (isa<VarDecl>(*I)) {
8533
7
          Prev = *I;
8534
7
          break;
8535
7
        }
8536
        // FIXME: If we have any other entity with this name in global scope,
8537
        // the declaration is ill-formed, but that is a defect: it breaks the
8538
        // 'stat' hack, for instance. Only variables can have mangled name
8539
        // clashes with extern "C" declarations, so only they deserve a
8540
        // diagnostic.
8541
15
      }
8542
100
    }
8543
8544
118k
    if (!Prev)
8545
118k
      return false;
8546
118k
  }
8547
8548
  // Use the first declaration's location to ensure we point at something which
8549
  // is lexically inside an extern "C" linkage-spec.
8550
25
  assert(Prev && "should have found a previous declaration to diagnose");
8551
25
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8552
8
    Prev = FD->getFirstDecl();
8553
17
  else
8554
17
    Prev = cast<VarDecl>(Prev)->getFirstDecl();
8555
8556
25
  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8557
25
    << IsGlobal << ND;
8558
25
  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8559
25
    << IsGlobal;
8560
25
  return false;
8561
25
}
SemaDecl.cpp:bool checkGlobalOrExternCConflict<clang::FunctionDecl>(clang::Sema&, clang::FunctionDecl const*, bool, clang::LookupResult&)
Line
Count
Source
8490
13.4M
    Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8491
13.4M
  assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8492
13.4M
  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8493
8494
13.4M
  if (!Prev && 
IsGlobal13.3M
&&
!isIncompleteDeclExternC(S, ND)13.3M
) {
8495
    // The common case: this global doesn't conflict with any extern "C"
8496
    // declaration.
8497
12.6M
    return false;
8498
12.6M
  }
8499
8500
723k
  if (Prev) {
8501
16.6k
    if (!IsGlobal || 
isIncompleteDeclExternC(S, ND)16.5k
) {
8502
      // Both the old and new declarations have C language linkage. This is a
8503
      // redeclaration.
8504
79
      Previous.clear();
8505
79
      Previous.addDecl(Prev);
8506
79
      return true;
8507
79
    }
8508
8509
    // This is a global, non-extern "C" declaration, and there is a previous
8510
    // non-global extern "C" declaration. Diagnose if this is a variable
8511
    // declaration.
8512
16.5k
    if (!isa<VarDecl>(ND))
8513
16.5k
      return false;
8514
706k
  } else {
8515
    // The declaration is extern "C". Check for any declaration in the
8516
    // translation unit which might conflict.
8517
706k
    if (IsGlobal) {
8518
      // We have already performed the lookup into the translation unit.
8519
705k
      IsGlobal = false;
8520
705k
      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8521
705k
           I != E; 
++I12
) {
8522
12
        if (isa<VarDecl>(*I)) {
8523
0
          Prev = *I;
8524
0
          break;
8525
0
        }
8526
12
      }
8527
705k
    } else {
8528
1.03k
      DeclContext::lookup_result R =
8529
1.03k
          S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8530
1.03k
      for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8531
1.03k
           I != E; 
++I4
) {
8532
18
        if (isa<VarDecl>(*I)) {
8533
14
          Prev = *I;
8534
14
          break;
8535
14
        }
8536
        // FIXME: If we have any other entity with this name in global scope,
8537
        // the declaration is ill-formed, but that is a defect: it breaks the
8538
        // 'stat' hack, for instance. Only variables can have mangled name
8539
        // clashes with extern "C" declarations, so only they deserve a
8540
        // diagnostic.
8541
18
      }
8542
1.03k
    }
8543
8544
706k
    if (!Prev)
8545
706k
      return false;
8546
706k
  }
8547
8548
  // Use the first declaration's location to ensure we point at something which
8549
  // is lexically inside an extern "C" linkage-spec.
8550
14
  assert(Prev && "should have found a previous declaration to diagnose");
8551
14
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8552
0
    Prev = FD->getFirstDecl();
8553
14
  else
8554
14
    Prev = cast<VarDecl>(Prev)->getFirstDecl();
8555
8556
14
  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8557
14
    << IsGlobal << ND;
8558
14
  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8559
14
    << IsGlobal;
8560
14
  return false;
8561
14
}
8562
8563
/// Apply special rules for handling extern "C" declarations. Returns \c true
8564
/// if we have found that this is a redeclaration of some prior entity.
8565
///
8566
/// Per C++ [dcl.link]p6:
8567
///   Two declarations [for a function or variable] with C language linkage
8568
///   with the same name that appear in different scopes refer to the same
8569
///   [entity]. An entity with C language linkage shall not be declared with
8570
///   the same name as an entity in global scope.
8571
template<typename T>
8572
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8573
41.8M
                                                  LookupResult &Previous) {
8574
41.8M
  if (!S.getLangOpts().CPlusPlus) {
8575
    // In C, when declaring a global variable, look for a corresponding 'extern'
8576
    // variable declared in function scope. We don't need this in C++, because
8577
    // we find local extern decls in the surrounding file-scope DeclContext.
8578
21.7M
    if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8579
21.1M
      if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8580
62
        Previous.clear();
8581
62
        Previous.addDecl(Prev);
8582
62
        return true;
8583
62
      }
8584
21.1M
    }
8585
21.7M
    return false;
8586
21.7M
  }
8587
8588
  // A declaration in the translation unit can conflict with an extern "C"
8589
  // declaration.
8590
20.1M
  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8591
13.5M
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8592
8593
  // An extern "C" declaration can conflict with a declaration in the
8594
  // translation unit or can be a redeclaration of an extern "C" declaration
8595
  // in another scope.
8596
6.59M
  if (isIncompleteDeclExternC(S,ND))
8597
1.21k
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8598
8599
  // Neither global nor extern "C": nothing to do.
8600
6.59M
  return false;
8601
6.59M
}
SemaDecl.cpp:bool checkForConflictWithNonVisibleExternC<clang::VarDecl>(clang::Sema&, clang::VarDecl const*, clang::LookupResult&)
Line
Count
Source
8573
3.47M
                                                  LookupResult &Previous) {
8574
3.47M
  if (!S.getLangOpts().CPlusPlus) {
8575
    // In C, when declaring a global variable, look for a corresponding 'extern'
8576
    // variable declared in function scope. We don't need this in C++, because
8577
    // we find local extern decls in the surrounding file-scope DeclContext.
8578
1.35M
    if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8579
837k
      if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8580
12
        Previous.clear();
8581
12
        Previous.addDecl(Prev);
8582
12
        return true;
8583
12
      }
8584
837k
    }
8585
1.35M
    return false;
8586
1.35M
  }
8587
8588
  // A declaration in the translation unit can conflict with an extern "C"
8589
  // declaration.
8590
2.12M
  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8591
189k
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8592
8593
  // An extern "C" declaration can conflict with a declaration in the
8594
  // translation unit or can be a redeclaration of an extern "C" declaration
8595
  // in another scope.
8596
1.93M
  if (isIncompleteDeclExternC(S,ND))
8597
116
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8598
8599
  // Neither global nor extern "C": nothing to do.
8600
1.93M
  return false;
8601
1.93M
}
SemaDecl.cpp:bool checkForConflictWithNonVisibleExternC<clang::FunctionDecl>(clang::Sema&, clang::FunctionDecl const*, clang::LookupResult&)
Line
Count
Source
8573
38.4M
                                                  LookupResult &Previous) {
8574
38.4M
  if (!S.getLangOpts().CPlusPlus) {
8575
    // In C, when declaring a global variable, look for a corresponding 'extern'
8576
    // variable declared in function scope. We don't need this in C++, because
8577
    // we find local extern decls in the surrounding file-scope DeclContext.
8578
20.3M
    if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8579
20.3M
      if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8580
50
        Previous.clear();
8581
50
        Previous.addDecl(Prev);
8582
50
        return true;
8583
50
      }
8584
20.3M
    }
8585
20.3M
    return false;
8586
20.3M
  }
8587
8588
  // A declaration in the translation unit can conflict with an extern "C"
8589
  // declaration.
8590
18.0M
  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8591
13.4M
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8592
8593
  // An extern "C" declaration can conflict with a declaration in the
8594
  // translation unit or can be a redeclaration of an extern "C" declaration
8595
  // in another scope.
8596
4.66M
  if (isIncompleteDeclExternC(S,ND))
8597
1.09k
    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8598
8599
  // Neither global nor extern "C": nothing to do.
8600
4.65M
  return false;
8601
4.66M
}
8602
8603
3.63M
void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8604
  // If the decl is already known invalid, don't check it.
8605
3.63M
  if (NewVD->isInvalidDecl())
8606
1.84k
    return;
8607
8608
3.63M
  QualType T = NewVD->getType();
8609
8610
  // Defer checking an 'auto' type until its initializer is attached.
8611
3.63M
  if (T->isUndeducedType())
8612
84.9k
    return;
8613
8614
3.54M
  if (NewVD->hasAttrs())
8615
822k
    CheckAlignasUnderalignment(NewVD);
8616
8617
3.54M
  if (T->isObjCObjectType()) {
8618
44
    Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8619
44
      << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8620
44
    T = Context.getObjCObjectPointerType(T);
8621
44
    NewVD->setType(T);
8622
44
  }
8623
8624
  // Emit an error if an address space was applied to decl with local storage.
8625
  // This includes arrays of objects with address space qualifiers, but not
8626
  // automatic variables that point to other address spaces.
8627
  // ISO/IEC TR 18037 S5.1.2
8628
3.54M
  if (!getLangOpts().OpenCL && 
NewVD->hasLocalStorage()3.54M
&&
8629
3.54M
      
T.getAddressSpace() != LangAS::Default1.90M
) {
8630
9
    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8631
9
    NewVD->setInvalidDecl();
8632
9
    return;
8633
9
  }
8634
8635
  // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8636
  // scope.
8637
3.54M
  if (getLangOpts().OpenCLVersion == 120 &&
8638
3.54M
      !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8639
973
                                            getLangOpts()) &&
8640
3.54M
      
NewVD->isStaticLocal()973
) {
8641
8
    Diag(NewVD->getLocation(), diag::err_static_function_scope);
8642
8
    NewVD->setInvalidDecl();
8643
8
    return;
8644
8
  }
8645
8646
3.54M
  if (getLangOpts().OpenCL) {
8647
4.42k
    if (!diagnoseOpenCLTypes(*this, NewVD))
8648
68
      return;
8649
8650
    // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8651
4.35k
    if (NewVD->hasAttr<BlocksAttr>()) {
8652
2
      Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8653
2
      return;
8654
2
    }
8655
8656
4.35k
    if (T->isBlockPointerType()) {
8657
      // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8658
      // can't use 'extern' storage class.
8659
159
      if (!T.isConstQualified()) {
8660
0
        Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8661
0
            << 0 /*const*/;
8662
0
        NewVD->setInvalidDecl();
8663
0
        return;
8664
0
      }
8665
159
      if (NewVD->hasExternalStorage()) {
8666
4
        Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8667
4
        NewVD->setInvalidDecl();
8668
4
        return;
8669
4
      }
8670
159
    }
8671
8672
    // FIXME: Adding local AS in C++ for OpenCL might make sense.
8673
4.34k
    if (NewVD->isFileVarDecl() || 
NewVD->isStaticLocal()3.66k
||
8674
4.34k
        
NewVD->hasExternalStorage()3.51k
) {
8675
902
      if (!T->isSamplerT() && 
!T->isDependentType()827
&&
8676
902
          
!(825
T.getAddressSpace() == LangAS::opencl_constant825
||
8677
825
            
(662
T.getAddressSpace() == LangAS::opencl_global662
&&
8678
662
             getOpenCLOptions().areProgramScopeVariablesSupported(
8679
507
                 getLangOpts())))) {
8680
179
        int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8681
179
        if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8682
68
          Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8683
68
              << Scope << "global or constant";
8684
111
        else
8685
111
          Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8686
111
              << Scope << "constant";
8687
179
        NewVD->setInvalidDecl();
8688
179
        return;
8689
179
      }
8690
3.44k
    } else {
8691
3.44k
      if (T.getAddressSpace() == LangAS::opencl_global) {
8692
35
        Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8693
35
            << 1 /*is any function*/ << "global";
8694
35
        NewVD->setInvalidDecl();
8695
35
        return;
8696
35
      }
8697
3.40k
      if (T.getAddressSpace() == LangAS::opencl_constant ||
8698
3.40k
          
T.getAddressSpace() == LangAS::opencl_local3.27k
) {
8699
309
        FunctionDecl *FD = getCurFunctionDecl();
8700
        // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8701
        // in functions.
8702
309
        if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8703
36
          if (T.getAddressSpace() == LangAS::opencl_constant)
8704
18
            Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8705
18
                << 0 /*non-kernel only*/ << "constant";
8706
18
          else
8707
18
            Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8708
18
                << 0 /*non-kernel only*/ << "local";
8709
36
          NewVD->setInvalidDecl();
8710
36
          return;
8711
36
        }
8712
        // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8713
        // in the outermost scope of a kernel function.
8714
273
        if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8715
273
          if (!getCurScope()->isFunctionScope()) {
8716
18
            if (T.getAddressSpace() == LangAS::opencl_constant)
8717
9
              Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8718
9
                  << "constant";
8719
9
            else
8720
9
              Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8721
9
                  << "local";
8722
18
            NewVD->setInvalidDecl();
8723
18
            return;
8724
18
          }
8725
273
        }
8726
3.10k
      } else if (T.getAddressSpace() != LangAS::opencl_private &&
8727
                 // If we are parsing a template we didn't deduce an addr
8728
                 // space yet.
8729
3.10k
                 
T.getAddressSpace() != LangAS::Default97
) {
8730
        // Do not allow other address spaces on automatic variable.
8731
31
        Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8732
31
        NewVD->setInvalidDecl();
8733
31
        return;
8734
31
      }
8735
3.40k
    }
8736
4.34k
  }
8737
8738
3.54M
  if (NewVD->hasLocalStorage() && 
T.isObjCGCWeak()1.91M
8739
3.54M
      && 
!NewVD->hasAttr<BlocksAttr>()11
) {
8740
2
    if (getLangOpts().getGC() != LangOptions::NonGC)
8741
2
      Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8742
0
    else {
8743
0
      assert(!getLangOpts().ObjCAutoRefCount);
8744
0
      Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8745
0
    }
8746
2
  }
8747
8748
  // WebAssembly tables must be static with a zero length and can't be
8749
  // declared within functions.
8750
3.54M
  if (T->isWebAssemblyTableType()) {
8751
32
    if (getCurScope()->getParent()) { // Parent is null at top-level
8752
14
      Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8753
14
      NewVD->setInvalidDecl();
8754
14
      return;
8755
14
    }
8756
18
    if (NewVD->getStorageClass() != SC_Static) {
8757
2
      Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8758
2
      NewVD->setInvalidDecl();
8759
2
      return;
8760
2
    }
8761
16
    const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8762
16
    if (!ATy || 
ATy->getSize().getSExtValue() != 010
) {
8763
8
      Diag(NewVD->getLocation(),
8764
8
           diag::err_typecheck_wasm_table_must_have_zero_length);
8765
8
      NewVD->setInvalidDecl();
8766
8
      return;
8767
8
    }
8768
16
  }
8769
8770
3.54M
  bool isVM = T->isVariablyModifiedType();
8771
3.54M
  if (isVM || 
NewVD->hasAttr<CleanupAttr>()3.54M
||
8772
3.54M
      
NewVD->hasAttr<BlocksAttr>()3.54M
)
8773
3.70k
    setFunctionHasBranchProtectedScope();
8774
8775
3.54M
  if ((isVM && 
NewVD->hasLinkage()3.15k
) ||
8776
3.54M
      
(3.54M
T->isVariableArrayType()3.54M
&&
NewVD->hasGlobalStorage()2.92k
)) {
8777
133
    bool SizeIsNegative;
8778
133
    llvm::APSInt Oversized;
8779
133
    TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8780
133
        NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8781
133
    QualType FixedT;
8782
133
    if (FixedTInfo &&  
T == NewVD->getTypeSourceInfo()->getType()60
)
8783
58
      FixedT = FixedTInfo->getType();
8784
75
    else if (FixedTInfo) {
8785
      // Type and type-as-written are canonically different. We need to fix up
8786
      // both types separately.
8787
2
      FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8788
2
                                                   Oversized);
8789
2
    }
8790
133
    if ((!FixedTInfo || 
FixedT.isNull()60
) &&
T->isVariableArrayType()73
) {
8791
70
      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8792
      // FIXME: This won't give the correct result for
8793
      // int a[10][n];
8794
70
      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8795
8796
70
      if (NewVD->isFileVarDecl())
8797
57
        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8798
57
        << SizeRange;
8799
13
      else if (NewVD->isStaticLocal())
8800
6
        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8801
6
        << SizeRange;
8802
7
      else
8803
7
        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8804
7
        << SizeRange;
8805
70
      NewVD->setInvalidDecl();
8806
70
      return;
8807
70
    }
8808
8809
63
    if (!FixedTInfo) {
8810
3
      if (NewVD->isFileVarDecl())
8811
2
        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8812
1
      else
8813
1
        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8814
3
      NewVD->setInvalidDecl();
8815
3
      return;
8816
3
    }
8817
8818
60
    Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8819
60
    NewVD->setType(FixedT);
8820
60
    NewVD->setTypeSourceInfo(FixedTInfo);
8821
60
  }
8822
8823
3.54M
  if (T->isVoidType()) {
8824
    // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8825
    //                    of objects and functions.
8826
50
    if (NewVD->isThisDeclarationADefinition() || 
getLangOpts().CPlusPlus15
) {
8827
41
      Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8828
41
        << T;
8829
41
      NewVD->setInvalidDecl();
8830
41
      return;
8831
41
    }
8832
50
  }
8833
8834
3.54M
  if (!NewVD->hasLocalStorage() && 
NewVD->hasAttr<BlocksAttr>()1.63M
) {
8835
3
    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8836
3
    NewVD->setInvalidDecl();
8837
3
    return;
8838
3
  }
8839
8840
3.54M
  if (!NewVD->hasLocalStorage() && 
T->isSizelessType()1.63M
&&
8841
3.54M
      
!T.isWebAssemblyReferenceType()43
) {
8842
35
    Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8843
35
    NewVD->setInvalidDecl();
8844
35
    return;
8845
35
  }
8846
8847
3.54M
  if (isVM && 
NewVD->hasAttr<BlocksAttr>()3.08k
) {
8848
2
    Diag(NewVD->getLocation(), diag::err_block_on_vm);
8849
2
    NewVD->setInvalidDecl();
8850
2
    return;
8851
2
  }
8852
8853
3.54M
  if (NewVD->isConstexpr() && 
!T->isDependentType()376k
&&
8854
3.54M
      RequireLiteralType(NewVD->getLocation(), T,
8855
370k
                         diag::err_constexpr_var_non_literal)) {
8856
36
    NewVD->setInvalidDecl();
8857
36
    return;
8858
36
  }
8859
8860
  // PPC MMA non-pointer types are not allowed as non-local variable types.
8861
3.54M
  if (Context.getTargetInfo().getTriple().isPPC64() &&
8862
3.54M
      
!NewVD->isLocalVarDecl()38.0k
&&
8863
3.54M
      
CheckPPCMMAType(T, NewVD->getLocation())6.51k
) {
8864
12
    NewVD->setInvalidDecl();
8865
12
    return;
8866
12
  }
8867
8868
  // Check that SVE types are only used in functions with SVE available.
8869
3.54M
  if (T->isSVESizelessBuiltinType() && 
isa<FunctionDecl>(CurContext)496
) {
8870
495
    const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8871
495
    llvm::StringMap<bool> CallerFeatureMap;
8872
495
    Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8873
495
    if (!Builtin::evaluateRequiredTargetFeatures(
8874
495
        "sve", CallerFeatureMap)) {
8875
2
      Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8876
2
      NewVD->setInvalidDecl();
8877
2
      return;
8878
2
    }
8879
495
  }
8880
8881
3.54M
  if (T->isRVVType())
8882
65
    checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext));
8883
3.54M
}
8884
8885
/// Perform semantic checking on a newly-created variable
8886
/// declaration.
8887
///
8888
/// This routine performs all of the type-checking required for a
8889
/// variable declaration once it has been built. It is used both to
8890
/// check variables after they have been parsed and their declarators
8891
/// have been translated into a declaration, and to check variables
8892
/// that have been instantiated from a template.
8893
///
8894
/// Sets NewVD->isInvalidDecl() if an error was encountered.
8895
///
8896
/// Returns true if the variable declaration is a redeclaration.
8897
3.55M
bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8898
3.55M
  CheckVariableDeclarationType(NewVD);
8899
8900
  // If the decl is already known invalid, don't check it.
8901
3.55M
  if (NewVD->isInvalidDecl())
8902
2.44k
    return false;
8903
8904
  // If we did not find anything by this name, look for a non-visible
8905
  // extern "C" declaration with the same name.
8906
3.54M
  if (Previous.empty() &&
8907
3.54M
      
checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)3.47M
)
8908
28
    Previous.setShadowed();
8909
8910
3.54M
  if (!Previous.empty()) {
8911
71.2k
    MergeVarDecl(NewVD, Previous);
8912
71.2k
    return true;
8913
71.2k
  }
8914
3.47M
  return false;
8915
3.54M
}
8916
8917
/// AddOverriddenMethods - See if a method overrides any in the base classes,
8918
/// and if so, check that it's a valid override and remember it.
8919
3.01M
bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8920
3.01M
  llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8921
8922
  // Look for methods in base classes that this method might override.
8923
3.01M
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8924
3.01M
                     /*DetectVirtual=*/false);
8925
3.71M
  auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8926
3.71M
    CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8927
3.71M
    DeclarationName Name = MD->getDeclName();
8928
8929
3.71M
    if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8930
      // We really want to find the base class destructor here.
8931
602k
      QualType T = Context.getTypeDeclType(BaseRecord);
8932
602k
      CanQualType CT = Context.getCanonicalType(T);
8933
602k
      Name = Context.DeclarationNames.getCXXDestructorName(CT);
8934
602k
    }
8935
8936
3.71M
    for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8937
871k
      CXXMethodDecl *BaseMD =
8938
871k
          dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8939
871k
      if (!BaseMD || 
!BaseMD->isVirtual()868k
||
8940
871k
          IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8941
85.5k
                     /*ConsiderCudaAttrs=*/true))
8942
788k
        continue;
8943
82.4k
      if (!CheckExplicitObjectOverride(MD, BaseMD))
8944
14
        continue;
8945
82.4k
      if (Overridden.insert(BaseMD).second) {
8946
82.4k
        MD->addOverriddenMethod(BaseMD);
8947
82.4k
        CheckOverridingFunctionReturnType(MD, BaseMD);
8948
82.4k
        CheckOverridingFunctionAttributes(MD, BaseMD);
8949
82.4k
        CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8950
82.4k
        CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8951
82.4k
      }
8952
8953
      // A method can only override one function from each base class. We
8954
      // don't track indirectly overridden methods from bases of bases.
8955
82.4k
      return true;
8956
82.4k
    }
8957
8958
3.63M
    return false;
8959
3.71M
  };
8960
8961
3.01M
  DC->lookupInBases(VisitBase, Paths);
8962
3.01M
  return !Overridden.empty();
8963
3.01M
}
8964
8965
namespace {
8966
  // Struct for holding all of the extra arguments needed by
8967
  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8968
  struct ActOnFDArgs {
8969
    Scope *S;
8970
    Declarator &D;
8971
    MultiTemplateParamsArg TemplateParamLists;
8972
    bool AddToScope;
8973
  };
8974
} // end anonymous namespace
8975
8976
namespace {
8977
8978
// Callback to only accept typo corrections that have a non-zero edit distance.
8979
// Also only accept corrections that have the same parent decl.
8980
class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8981
 public:
8982
  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8983
                            CXXRecordDecl *Parent)
8984
131
      : Context(Context), OriginalFD(TypoFD),
8985
131
        ExpectedParent(Parent ? 
Parent->getCanonicalDecl()96
:
nullptr35
) {}
8986
8987
289
  bool ValidateCandidate(const TypoCorrection &candidate) override {
8988
289
    if (candidate.getEditDistance() == 0)
8989
32
      return false;
8990
8991
257
    SmallVector<unsigned, 1> MismatchedParams;
8992
257
    for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8993
257
                                          CDeclEnd = candidate.end();
8994
515
         CDecl != CDeclEnd; 
++CDecl258
) {
8995
295
      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8996
8997
295
      if (FD && 
!FD->hasBody()227
&&
8998
295
          
hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)148
) {
8999
115
        if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9000
67
          CXXRecordDecl *Parent = MD->getParent();
9001
67
          if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9002
7
            return true;
9003
67
        } else 
if (48
!ExpectedParent48
) {
9004
30
          return true;
9005
30
        }
9006
115
      }
9007
295
    }
9008
9009
220
    return false;
9010
257
  }
9011
9012
72
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
9013
72
    return std::make_unique<DifferentNameValidatorCCC>(*this);
9014
72
  }
9015
9016
 private:
9017
  ASTContext &Context;
9018
  FunctionDecl *OriginalFD;
9019
  CXXRecordDecl *ExpectedParent;
9020
};
9021
9022
} // end anonymous namespace
9023
9024
28
void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9025
28
  TypoCorrectedFunctionDefinitions.insert(F);
9026
28
}
9027
9028
/// Generate diagnostics for an invalid function redeclaration.
9029
///
9030
/// This routine handles generating the diagnostic messages for an invalid
9031
/// function redeclaration, including finding possible similar declarations
9032
/// or performing typo correction if there are no previous declarations with
9033
/// the same name.
9034
///
9035
/// Returns a NamedDecl iff typo correction was performed and substituting in
9036
/// the new declaration name does not cause new errors.
9037
static NamedDecl *DiagnoseInvalidRedeclaration(
9038
    Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9039
131
    ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9040
131
  DeclarationName Name = NewFD->getDeclName();
9041
131
  DeclContext *NewDC = NewFD->getDeclContext();
9042
131
  SmallVector<unsigned, 1> MismatchedParams;
9043
131
  SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9044
131
  TypoCorrection Correction;
9045
131
  bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9046
131
  unsigned DiagMsg =
9047
131
    IsLocalFriend ? 
diag::err_no_matching_local_friend10
:
9048
131
    
NewFD->getFriendObjectKind()121
?
diag::err_qualified_friend_no_match12
:
9049
121
    
diag::err_member_decl_does_not_match109
;
9050
131
  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9051
131
                    IsLocalFriend ? 
Sema::LookupLocalFriendName10
9052
131
                                  : 
Sema::LookupOrdinaryName121
,
9053
131
                    Sema::ForVisibleRedeclaration);
9054
9055
131
  NewFD->setInvalidDecl();
9056
131
  if (IsLocalFriend)
9057
10
    SemaRef.LookupName(Prev, S);
9058
121
  else
9059
121
    SemaRef.LookupQualifiedName(Prev, NewDC);
9060
131
  assert(!Prev.isAmbiguous() &&
9061
131
         "Cannot have an ambiguity in previous-declaration lookup");
9062
131
  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9063
131
  DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9064
131
                                MD ? 
MD->getParent()96
:
nullptr35
);
9065
131
  if (!Prev.empty()) {
9066
59
    for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9067
149
         Func != FuncEnd; 
++Func90
) {
9068
90
      FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9069
90
      if (FD &&
9070
90
          
hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)66
) {
9071
        // Add 1 to the index so that 0 can mean the mismatch didn't
9072
        // involve a parameter
9073
33
        unsigned ParamNum =
9074
33
            MismatchedParams.empty() ? 
026
:
MismatchedParams.front() + 17
;
9075
33
        NearMatches.push_back(std::make_pair(FD, ParamNum));
9076
33
      }
9077
90
    }
9078
  // If the qualified name lookup yielded nothing, try typo correction
9079
72
  } else if ((Correction = SemaRef.CorrectTypo(
9080
72
                  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9081
72
                  &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9082
72
                  IsLocalFriend ? 
nullptr9
:
NewDC63
))) {
9083
    // Set up everything for the call to ActOnFunctionDeclarator
9084
30
    ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9085
30
                              ExtraArgs.D.getIdentifierLoc());
9086
30
    Previous.clear();
9087
30
    Previous.setLookupName(Correction.getCorrection());
9088
30
    for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9089
30
                                    CDeclEnd = Correction.end();
9090
61
         CDecl != CDeclEnd; 
++CDecl31
) {
9091
31
      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9092
31
      if (FD && !FD->hasBody() &&
9093
31
          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9094
30
        Previous.addDecl(FD);
9095
30
      }
9096
31
    }
9097
30
    bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9098
9099
30
    NamedDecl *Result;
9100
    // Retry building the function declaration with the new previous
9101
    // declarations, and with errors suppressed.
9102
30
    {
9103
      // Trap errors.
9104
30
      Sema::SFINAETrap Trap(SemaRef);
9105
9106
      // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9107
      // pieces need to verify the typo-corrected C++ declaration and hopefully
9108
      // eliminate the need for the parameter pack ExtraArgs.
9109
30
      Result = SemaRef.ActOnFunctionDeclarator(
9110
30
          ExtraArgs.S, ExtraArgs.D,
9111
30
          Correction.getCorrectionDecl()->getDeclContext(),
9112
30
          NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9113
30
          ExtraArgs.AddToScope);
9114
9115
30
      if (Trap.hasErrorOccurred())
9116
2
        Result = nullptr;
9117
30
    }
9118
9119
30
    if (Result) {
9120
      // Determine which correction we picked.
9121
28
      Decl *Canonical = Result->getCanonicalDecl();
9122
28
      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9123
56
           I != E; 
++I28
)
9124
28
        if ((*I)->getCanonicalDecl() == Canonical)
9125
28
          Correction.setCorrectionDecl(*I);
9126
9127
      // Let Sema know about the correction.
9128
28
      SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
9129
28
      SemaRef.diagnoseTypo(
9130
28
          Correction,
9131
28
          SemaRef.PDiag(IsLocalFriend
9132
28
                          ? 
diag::err_no_matching_local_friend_suggest7
9133
28
                          : 
diag::err_member_decl_does_not_match_suggest21
)
9134
28
            << Name << NewDC << IsDefinition);
9135
28
      return Result;
9136
28
    }
9137
9138
    // Pretend the typo correction never occurred
9139
2
    ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9140
2
                              ExtraArgs.D.getIdentifierLoc());
9141
2
    ExtraArgs.D.setRedeclaration(wasRedeclaration);
9142
2
    Previous.clear();
9143
2
    Previous.setLookupName(Name);
9144
2
  }
9145
9146
103
  SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9147
103
      << Name << NewDC << IsDefinition << NewFD->getLocation();
9148
9149
103
  bool NewFDisConst = false;
9150
103
  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9151
90
    NewFDisConst = NewMD->isConst();
9152
9153
103
  for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9154
103
       NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9155
136
       NearMatch != NearMatchEnd; 
++NearMatch33
) {
9156
33
    FunctionDecl *FD = NearMatch->first;
9157
33
    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9158
33
    bool FDisConst = MD && 
MD->isConst()31
;
9159
33
    bool IsMember = MD || 
!IsLocalFriend2
;
9160
9161
    // FIXME: These notes are poorly worded for the local friend case.
9162
33
    if (unsigned Idx = NearMatch->second) {
9163
7
      ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9164
7
      SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9165
7
      if (Loc.isInvalid()) 
Loc = FD->getLocation()0
;
9166
7
      SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9167
7
                                 : 
diag::note_local_decl_close_param_match0
)
9168
7
        << Idx << FDParam->getType()
9169
7
        << NewFD->getParamDecl(Idx - 1)->getType();
9170
26
    } else if (FDisConst != NewFDisConst) {
9171
17
      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9172
17
          << NewFDisConst << FD->getSourceRange().getEnd()
9173
17
          << (NewFDisConst
9174
17
                  ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9175
4
                                                 .getConstQualifierLoc())
9176
17
                  : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9177
13
                                                   .getRParenLoc()
9178
13
                                                   .getLocWithOffset(1),
9179
13
                                               " const"));
9180
17
    } else
9181
9
      SemaRef.Diag(FD->getLocation(),
9182
9
                   IsMember ? 
diag::note_member_def_close_match8
9183
9
                            : 
diag::note_local_decl_close_match1
);
9184
33
  }
9185
103
  return nullptr;
9186
131
}
9187
9188
36.5M
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9189
36.5M
  switch (D.getDeclSpec().getStorageClassSpec()) {
9190
0
  default: llvm_unreachable("Unknown storage class!");
9191
14
  case DeclSpec::SCS_auto:
9192
21
  case DeclSpec::SCS_register:
9193
24
  case DeclSpec::SCS_mutable:
9194
24
    SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9195
24
                 diag::err_typecheck_sclass_func);
9196
24
    D.getMutableDeclSpec().ClearStorageClassSpecs();
9197
24
    D.setInvalidType();
9198
24
    break;
9199
4.07M
  case DeclSpec::SCS_unspecified: break;
9200
1.15M
  case DeclSpec::SCS_extern:
9201
1.15M
    if (D.getDeclSpec().isExternInLinkageSpec())
9202
32.8k
      return SC_None;
9203
1.12M
    return SC_Extern;
9204
31.3M
  case DeclSpec::SCS_static: {
9205
31.3M
    if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9206
      // C99 6.7.1p5:
9207
      //   The declaration of an identifier for a function that has
9208
      //   block scope shall have no explicit storage-class specifier
9209
      //   other than extern
9210
      // See also (C++ [dcl.stc]p4).
9211
1
      SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9212
1
                   diag::err_static_block_func);
9213
1
      break;
9214
1
    } else
9215
31.3M
      return SC_Static;
9216
31.3M
  }
9217
8
  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9218
36.5M
  }
9219
9220
  // No explicit storage class has already been returned
9221
4.07M
  return SC_None;
9222
36.5M
}
9223
9224
static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9225
                                           DeclContext *DC, QualType &R,
9226
                                           TypeSourceInfo *TInfo,
9227
                                           StorageClass SC,
9228
36.5M
                                           bool &IsVirtualOkay) {
9229
36.5M
  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9230
36.5M
  DeclarationName Name = NameInfo.getName();
9231
9232
36.5M
  FunctionDecl *NewFD = nullptr;
9233
36.5M
  bool isInline = D.getDeclSpec().isInlineSpecified();
9234
9235
36.5M
  if (!SemaRef.getLangOpts().CPlusPlus) {
9236
    // Determine whether the function was written with a prototype. This is
9237
    // true when:
9238
    //   - there is a prototype in the declarator, or
9239
    //   - the type R of the function is some kind of typedef or other non-
9240
    //     attributed reference to a type name (which eventually refers to a
9241
    //     function type). Note, we can't always look at the adjusted type to
9242
    //     check this case because attributes may cause a non-function
9243
    //     declarator to still have a function type. e.g.,
9244
    //       typedef void func(int a);
9245
    //       __attribute__((noreturn)) func other_func; // This has a prototype
9246
20.4M
    bool HasPrototype =
9247
20.4M
        (D.isFunctionDeclarator() && 
D.getFunctionTypeInfo().hasPrototype20.4M
) ||
9248
20.4M
        
(9.18k
D.getDeclSpec().isTypeRep()9.18k
&&
9249
9.18k
         SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9250
3.60k
             ->isFunctionProtoType()) ||
9251
20.4M
        
(9.13k
!R->getAsAdjusted<FunctionType>()9.13k
&&
R->isFunctionProtoType()26
);
9252
20.4M
    assert(
9253
20.4M
        (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9254
20.4M
        "Strict prototypes are required");
9255
9256
20.4M
    NewFD = FunctionDecl::Create(
9257
20.4M
        SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9258
20.4M
        SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9259
20.4M
        ConstexprSpecKind::Unspecified,
9260
20.4M
        /*TrailingRequiresClause=*/nullptr);
9261
20.4M
    if (D.isInvalidType())
9262
71
      NewFD->setInvalidDecl();
9263
9264
20.4M
    return NewFD;
9265
20.4M
  }
9266
9267
16.1M
  ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9268
9269
16.1M
  ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9270
16.1M
  if (ConstexprKind == ConstexprSpecKind::Constinit) {
9271
3
    SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9272
3
                 diag::err_constexpr_wrong_decl_kind)
9273
3
        << static_cast<int>(ConstexprKind);
9274
3
    ConstexprKind = ConstexprSpecKind::Unspecified;
9275
3
    D.getMutableDeclSpec().ClearConstexprSpec();
9276
3
  }
9277
16.1M
  Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9278
9279
16.1M
  SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9280
9281
16.1M
  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9282
    // This is a C++ constructor declaration.
9283
414k
    assert(DC->isRecord() &&
9284
414k
           "Constructors can only be declared in a member context");
9285
9286
414k
    R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9287
414k
    return CXXConstructorDecl::Create(
9288
414k
        SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9289
414k
        TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9290
414k
        isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9291
414k
        InheritedConstructor(), TrailingRequiresClause);
9292
9293
15.7M
  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9294
    // This is a C++ destructor declaration.
9295
68.3k
    if (DC->isRecord()) {
9296
68.3k
      R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9297
68.3k
      CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9298
68.3k
      CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9299
68.3k
          SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9300
68.3k
          SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9301
68.3k
          /*isImplicitlyDeclared=*/false, ConstexprKind,
9302
68.3k
          TrailingRequiresClause);
9303
      // User defined destructors start as not selected if the class definition is still
9304
      // not done.
9305
68.3k
      if (Record->isBeingDefined())
9306
61.8k
        NewDD->setIneligibleOrNotSelected(true);
9307
9308
      // If the destructor needs an implicit exception specification, set it
9309
      // now. FIXME: It'd be nice to be able to create the right type to start
9310
      // with, but the type needs to reference the destructor declaration.
9311
68.3k
      if (SemaRef.getLangOpts().CPlusPlus11)
9312
67.7k
        SemaRef.AdjustDestructorExceptionSpec(NewDD);
9313
9314
68.3k
      IsVirtualOkay = true;
9315
68.3k
      return NewDD;
9316
9317
68.3k
    } else {
9318
2
      SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9319
2
      D.setInvalidType();
9320
9321
      // Create a FunctionDecl to satisfy the function definition parsing
9322
      // code path.
9323
2
      return FunctionDecl::Create(
9324
2
          SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9325
2
          TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9326
2
          /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9327
2
    }
9328
9329
15.6M
  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9330
17.2k
    if (!DC->isRecord()) {
9331
4
      SemaRef.Diag(D.getIdentifierLoc(),
9332
4
           diag::err_conv_function_not_member);
9333
4
      return nullptr;
9334
4
    }
9335
9336
17.2k
    SemaRef.CheckConversionDeclarator(D, R, SC);
9337
17.2k
    if (D.isInvalidType())
9338
65
      return nullptr;
9339
9340
17.1k
    IsVirtualOkay = true;
9341
17.1k
    return CXXConversionDecl::Create(
9342
17.1k
        SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9343
17.1k
        TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9344
17.1k
        ExplicitSpecifier, ConstexprKind, SourceLocation(),
9345
17.1k
        TrailingRequiresClause);
9346
9347
15.6M
  } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9348
1.60k
    if (TrailingRequiresClause)
9349
1
      SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9350
1
                   diag::err_trailing_requires_clause_on_deduction_guide)
9351
1
          << TrailingRequiresClause->getSourceRange();
9352
1.60k
    if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9353
21
      return nullptr;
9354
1.58k
    return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9355
1.58k
                                         ExplicitSpecifier, NameInfo, R, TInfo,
9356
1.58k
                                         D.getEndLoc());
9357
15.6M
  } else if (DC->isRecord()) {
9358
    // If the name of the function is the same as the name of the record,
9359
    // then this must be an invalid constructor that has a return type.
9360
    // (The parser checks for a return type and makes the declarator a
9361
    // constructor if it has no return type).
9362
1.43M
    if (Name.getAsIdentifierInfo() &&
9363
1.43M
        
Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()1.11M
){
9364
21
      SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9365
21
        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9366
21
        << SourceRange(D.getIdentifierLoc());
9367
21
      return nullptr;
9368
21
    }
9369
9370
    // This is a C++ method declaration.
9371
1.43M
    CXXMethodDecl *Ret = CXXMethodDecl::Create(
9372
1.43M
        SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9373
1.43M
        TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9374
1.43M
        ConstexprKind, SourceLocation(), TrailingRequiresClause);
9375
1.43M
    IsVirtualOkay = !Ret->isStatic();
9376
1.43M
    return Ret;
9377
14.2M
  } else {
9378
14.2M
    bool isFriend =
9379
14.2M
        SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9380
14.2M
    if (!isFriend && 
SemaRef.CurContext->isRecord()14.1M
)
9381
2
      return nullptr;
9382
9383
    // Determine whether the function was written with a
9384
    // prototype. This true when:
9385
    //   - we're in C++ (where every function has a prototype),
9386
14.2M
    return FunctionDecl::Create(
9387
14.2M
        SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9388
14.2M
        SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9389
14.2M
        true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9390
14.2M
  }
9391
16.1M
}
9392
9393
enum OpenCLParamType {
9394
  ValidKernelParam,
9395
  PtrPtrKernelParam,
9396
  PtrKernelParam,
9397
  InvalidAddrSpacePtrKernelParam,
9398
  InvalidKernelParam,
9399
  RecordKernelParam
9400
};
9401
9402
899
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9403
  // Size dependent types are just typedefs to normal integer types
9404
  // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9405
  // integers other than by their names.
9406
899
  StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9407
9408
  // Remove typedefs one by one until we reach a typedef
9409
  // for a size dependent type.
9410
899
  QualType DesugaredTy = Ty;
9411
1.76k
  do {
9412
1.76k
    ArrayRef<StringRef> Names(SizeTypeNames);
9413
1.76k
    auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9414
1.76k
    if (Names.end() != Match)
9415
14
      return true;
9416
9417
1.74k
    Ty = DesugaredTy;
9418
1.74k
    DesugaredTy = Ty.getSingleStepDesugaredType(C);
9419
1.74k
  } while (DesugaredTy != Ty);
9420
9421
885
  return false;
9422
899
}
9423
9424
1.46k
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9425
1.46k
  if (PT->isDependentType())
9426
2
    return InvalidKernelParam;
9427
9428
1.46k
  if (PT->isPointerType() || 
PT->isReferenceType()919
) {
9429
567
    QualType PointeeType = PT->getPointeeType();
9430
567
    if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9431
567
        
PointeeType.getAddressSpace() == LangAS::opencl_private557
||
9432
567
        
PointeeType.getAddressSpace() == LangAS::Default539
)
9433
28
      return InvalidAddrSpacePtrKernelParam;
9434
9435
539
    if (PointeeType->isPointerType()) {
9436
      // This is a pointer to pointer parameter.
9437
      // Recursively check inner type.
9438
28
      OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9439
28
      if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9440
28
          
ParamKind == InvalidKernelParam24
)
9441
5
        return ParamKind;
9442
9443
      // OpenCL v3.0 s6.11.a:
9444
      // A restriction to pass pointers to pointers only applies to OpenCL C
9445
      // v1.2 or below.
9446
23
      if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9447
19
        return ValidKernelParam;
9448
9449
4
      return PtrPtrKernelParam;
9450
23
    }
9451
9452
    // C++ for OpenCL v1.0 s2.4:
9453
    // Moreover the types used in parameters of the kernel functions must be:
9454
    // Standard layout types for pointer parameters. The same applies to
9455
    // reference if an implementation supports them in kernel parameters.
9456
511
    if (S.getLangOpts().OpenCLCPlusPlus &&
9457
511
        !S.getOpenCLOptions().isAvailableOption(
9458
78
            "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9459
56
     auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9460
56
     bool IsStandardLayoutType = true;
9461
56
     if (CXXRec) {
9462
       // If template type is not ODR-used its definition is only available
9463
       // in the template definition not its instantiation.
9464
       // FIXME: This logic doesn't work for types that depend on template
9465
       // parameter (PR58590).
9466
11
       if (!CXXRec->hasDefinition())
9467
1
         CXXRec = CXXRec->getTemplateInstantiationPattern();
9468
11
       if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9469
3
         IsStandardLayoutType = false;
9470
11
     }
9471
56
     if (!PointeeType->isAtomicType() && 
!PointeeType->isVoidType()52
&&
9472
56
        
!IsStandardLayoutType48
)
9473
3
      return InvalidKernelParam;
9474
56
    }
9475
9476
    // OpenCL v1.2 s6.9.p:
9477
    // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9478
508
    if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9479
266
      return ValidKernelParam;
9480
9481
242
    return PtrKernelParam;
9482
508
  }
9483
9484
  // OpenCL v1.2 s6.9.k:
9485
  // Arguments to kernel functions in a program cannot be declared with the
9486
  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9487
  // uintptr_t or a struct and/or union that contain fields declared to be one
9488
  // of these built-in scalar types.
9489
899
  if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9490
14
    return InvalidKernelParam;
9491
9492
885
  if (PT->isImageType())
9493
211
    return PtrKernelParam;
9494
9495
674
  if (PT->isBooleanType() || 
PT->isEventT()664
||
PT->isReserveIDT()663
)
9496
17
    return InvalidKernelParam;
9497
9498
  // OpenCL extension spec v1.2 s9.5:
9499
  // This extension adds support for half scalar and vector types as built-in
9500
  // types that can be used for arithmetic operations, conversions etc.
9501
657
  if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9502
657
      
PT->isHalfType()523
)
9503
4
    return InvalidKernelParam;
9504
9505
  // Look into an array argument to check if it has a forbidden type.
9506
653
  if (PT->isArrayType()) {
9507
37
    const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9508
    // Call ourself to check an underlying type of an array. Since the
9509
    // getPointeeOrArrayElementType returns an innermost type which is not an
9510
    // array, this recursive call only happens once.
9511
37
    return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9512
37
  }
9513
9514
  // C++ for OpenCL v1.0 s2.4:
9515
  // Moreover the types used in parameters of the kernel functions must be:
9516
  // Trivial and standard-layout types C++17 [basic.types] (plain old data
9517
  // types) for parameters passed by value;
9518
616
  if (S.getLangOpts().OpenCLCPlusPlus &&
9519
616
      !S.getOpenCLOptions().isAvailableOption(
9520
57
          "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9521
616
      
!PT->isOpenCLSpecificType()39
&&
!PT.isPODType(S.Context)27
)
9522
3
    return InvalidKernelParam;
9523
9524
613
  if (PT->isRecordType())
9525
122
    return RecordKernelParam;
9526
9527
491
  return ValidKernelParam;
9528
613
}
9529
9530
static void checkIsValidOpenCLKernelParameter(
9531
  Sema &S,
9532
  Declarator &D,
9533
  ParmVarDecl *Param,
9534
1.34k
  llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9535
1.34k
  QualType PT = Param->getType();
9536
9537
  // Cache the valid types we encounter to avoid rechecking structs that are
9538
  // used again
9539
1.34k
  if (ValidTypes.count(PT.getTypePtr()))
9540
154
    return;
9541
9542
1.19k
  switch (getOpenCLKernelParameterType(S, PT)) {
9543
3
  case PtrPtrKernelParam:
9544
    // OpenCL v3.0 s6.11.a:
9545
    // A kernel function argument cannot be declared as a pointer to a pointer
9546
    // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9547
3
    S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9548
3
    D.setInvalidType();
9549
3
    return;
9550
9551
12
  case InvalidAddrSpacePtrKernelParam:
9552
    // OpenCL v1.0 s6.5:
9553
    // __kernel function arguments declared to be a pointer of a type can point
9554
    // to one of the following address spaces only : __global, __local or
9555
    // __constant.
9556
12
    S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9557
12
    D.setInvalidType();
9558
12
    return;
9559
9560
    // OpenCL v1.2 s6.9.k:
9561
    // Arguments to kernel functions in a program cannot be declared with the
9562
    // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9563
    // uintptr_t or a struct and/or union that contain fields declared to be
9564
    // one of these built-in scalar types.
9565
9566
31
  case InvalidKernelParam:
9567
    // OpenCL v1.2 s6.8 n:
9568
    // A kernel function argument cannot be declared
9569
    // of event_t type.
9570
    // Do not diagnose half type since it is diagnosed as invalid argument
9571
    // type for any function elsewhere.
9572
31
    if (!PT->isHalfType()) {
9573
27
      S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9574
9575
      // Explain what typedefs are involved.
9576
27
      const TypedefType *Typedef = nullptr;
9577
49
      while ((Typedef = PT->getAs<TypedefType>())) {
9578
22
        SourceLocation Loc = Typedef->getDecl()->getLocation();
9579
        // SourceLocation may be invalid for a built-in type.
9580
22
        if (Loc.isValid())
9581
14
          S.Diag(Loc, diag::note_entity_declared_at) << PT;
9582
22
        PT = Typedef->desugar();
9583
22
      }
9584
27
    }
9585
9586
31
    D.setInvalidType();
9587
31
    return;
9588
9589
447
  case PtrKernelParam:
9590
1.05k
  case ValidKernelParam:
9591
1.05k
    ValidTypes.insert(PT.getTypePtr());
9592
1.05k
    return;
9593
9594
94
  case RecordKernelParam:
9595
94
    break;
9596
1.19k
  }
9597
9598
  // Track nested structs we will inspect
9599
94
  SmallVector<const Decl *, 4> VisitStack;
9600
9601
  // Track where we are in the nested structs. Items will migrate from
9602
  // VisitStack to HistoryStack as we do the DFS for bad field.
9603
94
  SmallVector<const FieldDecl *, 4> HistoryStack;
9604
94
  HistoryStack.push_back(nullptr);
9605
9606
  // At this point we already handled everything except of a RecordType or
9607
  // an ArrayType of a RecordType.
9608
94
  assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9609
94
  const RecordType *RecTy =
9610
94
      PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9611
94
  const RecordDecl *OrigRecDecl = RecTy->getDecl();
9612
9613
94
  VisitStack.push_back(RecTy->getDecl());
9614
94
  assert(VisitStack.back() && "First decl null?");
9615
9616
187
  
do 94
{
9617
187
    const Decl *Next = VisitStack.pop_back_val();
9618
187
    if (!Next) {
9619
69
      assert(!HistoryStack.empty());
9620
      // Found a marker, we have gone up a level
9621
69
      if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9622
6
        ValidTypes.insert(Hist->getType().getTypePtr());
9623
9624
69
      continue;
9625
69
    }
9626
9627
    // Adds everything except the original parameter declaration (which is not a
9628
    // field itself) to the history stack.
9629
118
    const RecordDecl *RD;
9630
118
    if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9631
24
      HistoryStack.push_back(Field);
9632
9633
24
      QualType FieldTy = Field->getType();
9634
      // Other field types (known to be valid or invalid) are handled while we
9635
      // walk around RecordDecl::fields().
9636
24
      assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9637
24
             "Unexpected type.");
9638
24
      const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9639
9640
24
      RD = FieldRecTy->castAs<RecordType>()->getDecl();
9641
94
    } else {
9642
94
      RD = cast<RecordDecl>(Next);
9643
94
    }
9644
9645
    // Add a null marker so we know when we've gone back up a level
9646
118
    VisitStack.push_back(nullptr);
9647
9648
210
    for (const auto *FD : RD->fields()) {
9649
210
      QualType QT = FD->getType();
9650
9651
210
      if (ValidTypes.count(QT.getTypePtr()))
9652
0
        continue;
9653
9654
210
      OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9655
210
      if (ParamType == ValidKernelParam)
9656
151
        continue;
9657
9658
59
      if (ParamType == RecordKernelParam) {
9659
28
        VisitStack.push_back(FD);
9660
28
        continue;
9661
28
      }
9662
9663
      // OpenCL v1.2 s6.9.p:
9664
      // Arguments to kernel functions that are declared to be a struct or union
9665
      // do not allow OpenCL objects to be passed as elements of the struct or
9666
      // union. This restriction was lifted in OpenCL v2.0 with the introduction
9667
      // of SVM.
9668
31
      if (ParamType == PtrKernelParam || 
ParamType == PtrPtrKernelParam28
||
9669
31
          
ParamType == InvalidAddrSpacePtrKernelParam28
) {
9670
19
        S.Diag(Param->getLocation(),
9671
19
               diag::err_record_with_pointers_kernel_param)
9672
19
          << PT->isUnionType()
9673
19
          << PT;
9674
19
      } else {
9675
12
        S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9676
12
      }
9677
9678
31
      S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9679
31
          << OrigRecDecl->getDeclName();
9680
9681
      // We have an error, now let's go back up through history and show where
9682
      // the offending field came from
9683
31
      for (ArrayRef<const FieldDecl *>::const_iterator
9684
31
               I = HistoryStack.begin() + 1,
9685
31
               E = HistoryStack.end();
9686
49
           I != E; 
++I18
) {
9687
18
        const FieldDecl *OuterField = *I;
9688
18
        S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9689
18
          << OuterField->getType();
9690
18
      }
9691
9692
31
      S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9693
31
        << QT->isPointerType()
9694
31
        << QT;
9695
31
      D.setInvalidType();
9696
31
      return;
9697
59
    }
9698
156
  } while (!VisitStack.empty());
9699
94
}
9700
9701
/// Find the DeclContext in which a tag is implicitly declared if we see an
9702
/// elaborated type specifier in the specified context, and lookup finds
9703
/// nothing.
9704
20.5M
static DeclContext *getTagInjectionContext(DeclContext *DC) {
9705
20.5M
  while (!DC->isFileContext() && 
!DC->isFunctionOrMethod()15.0k
)
9706
13.8k
    DC = DC->getParent();
9707
20.5M
  return DC;
9708
20.5M
}
9709
9710
/// Find the Scope in which a tag is implicitly declared if we see an
9711
/// elaborated type specifier in the specified context, and lookup finds
9712
/// nothing.
9713
130k
static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9714
145k
  while (S->isClassScope() ||
9715
145k
         
(142k
LangOpts.CPlusPlus142k
&&
9716
142k
          
S->isFunctionPrototypeScope()29.0k
) ||
9717
145k
         
((S->getFlags() & Scope::DeclScope) == 0)141k
||
9718
145k
         
(141k
S->getEntity()141k
&&
S->getEntity()->isTransparentContext()141k
))
9719
15.4k
    S = S->getParent();
9720
130k
  return S;
9721
130k
}
9722
9723
/// Determine whether a declaration matches a known function in namespace std.
9724
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9725
4.68k
                         unsigned BuiltinID) {
9726
4.68k
  switch (BuiltinID) {
9727
1
  case Builtin::BI__GetExceptionInfo:
9728
    // No type checking whatsoever.
9729
1
    return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9730
9731
1.04k
  case Builtin::BIaddressof:
9732
1.04k
  case Builtin::BI__addressof:
9733
2.15k
  case Builtin::BIforward:
9734
2.16k
  case Builtin::BIforward_like:
9735
4.14k
  case Builtin::BImove:
9736
4.63k
  case Builtin::BImove_if_noexcept:
9737
4.68k
  case Builtin::BIas_const: {
9738
    // Ensure that we don't treat the algorithm
9739
    //   OutputIt std::move(InputIt, InputIt, OutputIt)
9740
    // as the builtin std::move.
9741
4.68k
    const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9742
4.68k
    return FPT->getNumParams() == 1 && 
!FPT->isVariadic()3.77k
;
9743
4.63k
  }
9744
9745
0
  default:
9746
0
    return false;
9747
4.68k
  }
9748
4.68k
}
9749
9750
NamedDecl*
9751
Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9752
                              TypeSourceInfo *TInfo, LookupResult &Previous,
9753
                              MultiTemplateParamsArg TemplateParamListsRef,
9754
36.5M
                              bool &AddToScope) {
9755
36.5M
  QualType R = TInfo->getType();
9756
9757
36.5M
  assert(R->isFunctionType());
9758
36.5M
  if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9759
2
    Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9760
9761
36.5M
  SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9762
36.5M
  llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9763
36.5M
  if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9764
506
    if (!TemplateParamLists.empty() &&
9765
506
        
Invented->getDepth() == TemplateParamLists.back()->getDepth()157
)
9766
156
      TemplateParamLists.back() = Invented;
9767
350
    else
9768
350
      TemplateParamLists.push_back(Invented);
9769
506
  }
9770
9771
  // TODO: consider using NameInfo for diagnostic.
9772
36.5M
  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9773
36.5M
  DeclarationName Name = NameInfo.getName();
9774
36.5M
  StorageClass SC = getFunctionStorageClass(*this, D);
9775
9776
36.5M
  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9777
9
    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9778
9
         diag::err_invalid_thread)
9779
9
      << DeclSpec::getSpecifierName(TSCS);
9780
9781
36.5M
  if (D.isFirstDeclarationOfMember())
9782
1.66M
    adjustMemberFunctionCC(
9783
1.66M
        R, !(D.isStaticMember() || 
D.isExplicitObjectMemberFunction()1.48M
),
9784
1.66M
        D.isCtorOrDtor(), D.getIdentifierLoc());
9785
9786
36.5M
  bool isFriend = false;
9787
36.5M
  FunctionTemplateDecl *FunctionTemplate = nullptr;
9788
36.5M
  bool isMemberSpecialization = false;
9789
36.5M
  bool isFunctionTemplateSpecialization = false;
9790
9791
36.5M
  bool HasExplicitTemplateArgs = false;
9792
36.5M
  TemplateArgumentListInfo TemplateArgs;
9793
9794
36.5M
  bool isVirtualOkay = false;
9795
9796
36.5M
  DeclContext *OriginalDC = DC;
9797
36.5M
  bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9798
9799
36.5M
  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9800
36.5M
                                              isVirtualOkay);
9801
36.5M
  if (!NewFD) 
return nullptr113
;
9802
9803
36.5M
  if (OriginalLexicalContext && 
OriginalLexicalContext->isObjCContainer()139
)
9804
139
    NewFD->setTopLevelDeclInObjCContainer();
9805
9806
  // Set the lexical context. If this is a function-scope declaration, or has a
9807
  // C++ scope specifier, or is the object of a friend declaration, the lexical
9808
  // context will be different from the semantic context.
9809
36.5M
  NewFD->setLexicalDeclContext(CurContext);
9810
9811
36.5M
  if (IsLocalExternDecl)
9812
2.20k
    NewFD->setLocalExternDecl();
9813
9814
36.5M
  if (getLangOpts().CPlusPlus) {
9815
    // The rules for implicit inlines changed in C++20 for methods and friends
9816
    // with an in-class definition (when such a definition is not attached to
9817
    // the global module).  User-specified 'inline' overrides this (set when
9818
    // the function decl is created above).
9819
    // FIXME: We need a better way to separate C++ standard and clang modules.
9820
16.1M
    bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9821
16.1M
                               
!NewFD->getOwningModule()120k
||
9822
16.1M
                               
NewFD->getOwningModule()->isGlobalModule()915
||
9823
16.1M
                               
NewFD->getOwningModule()->isHeaderLikeModule()659
;
9824
16.1M
    bool isInline = D.getDeclSpec().isInlineSpecified();
9825
16.1M
    bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9826
16.1M
    bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9827
16.1M
    isFriend = D.getDeclSpec().isFriendSpecified();
9828
16.1M
    if (isFriend && 
!isInline40.7k
&&
D.isFunctionDefinition()40.1k
) {
9829
      // Pre-C++20 [class.friend]p5
9830
      //   A function can be defined in a friend declaration of a
9831
      //   class . . . . Such a function is implicitly inline.
9832
      // Post C++20 [class.friend]p7
9833
      //   Such a function is implicitly an inline function if it is attached
9834
      //   to the global module.
9835
19.3k
      NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9836
19.3k
    }
9837
9838
    // If this is a method defined in an __interface, and is not a constructor
9839
    // or an overloaded operator, then set the pure flag (isVirtual will already
9840
    // return true).
9841
16.1M
    if (const CXXRecordDecl *Parent =
9842
16.1M
          dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9843
1.93M
      if (Parent->isInterface() && 
cast<CXXMethodDecl>(NewFD)->isUserProvided()13
)
9844
13
        NewFD->setPure(true);
9845
9846
      // C++ [class.union]p2
9847
      //   A union can have member functions, but not virtual functions.
9848
1.93M
      if (isVirtual && 
Parent->isUnion()76.3k
) {
9849
2
        Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9850
2
        NewFD->setInvalidDecl();
9851
2
      }
9852
1.93M
      if ((Parent->isClass() || 
Parent->isStruct()457k
) &&
9853
1.93M
          
Parent->hasAttr<SYCLSpecialClassAttr>()1.93M
&&
9854
1.93M
          
NewFD->getKind() == Decl::Kind::CXXMethod30
&&
NewFD->getIdentifier()25
&&
9855
1.93M
          
NewFD->getName() == "__init"21
&&
D.isFunctionDefinition()20
) {
9856
14
        if (auto *Def = Parent->getDefinition())
9857
14
          Def->setInitMethod(true);
9858
14
      }
9859
1.93M
    }
9860
9861
16.1M
    SetNestedNameSpecifier(*this, NewFD, D);
9862
16.1M
    isMemberSpecialization = false;
9863
16.1M
    isFunctionTemplateSpecialization = false;
9864
16.1M
    if (D.isInvalidType())
9865
281
      NewFD->setInvalidDecl();
9866
9867
    // Match up the template parameter lists with the scope specifier, then
9868
    // determine whether we have a template or a template specialization.
9869
16.1M
    bool Invalid = false;
9870
16.1M
    TemplateParameterList *TemplateParams =
9871
16.1M
        MatchTemplateParametersToScopeSpecifier(
9872
16.1M
            D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9873
16.1M
            D.getCXXScopeSpec(),
9874
16.1M
            D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9875
16.1M
                ? 
D.getName().TemplateId5.21k
9876
16.1M
                : 
nullptr16.1M
,
9877
16.1M
            TemplateParamLists, isFriend, isMemberSpecialization,
9878
16.1M
            Invalid);
9879
16.1M
    if (TemplateParams) {
9880
      // Check that we can declare a template here.
9881
864k
      if (CheckTemplateDeclScope(S, TemplateParams))
9882
13
        NewFD->setInvalidDecl();
9883
9884
864k
      if (TemplateParams->size() > 0) {
9885
        // This is a function template
9886
9887
        // A destructor cannot be a template.
9888
861k
        if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9889
4
          Diag(NewFD->getLocation(), diag::err_destructor_template);
9890
4
          NewFD->setInvalidDecl();
9891
4
        }
9892
9893
        // If we're adding a template to a dependent context, we may need to
9894
        // rebuilding some of the types used within the template parameter list,
9895
        // now that we know what the current instantiation is.
9896
861k
        if (DC->isDependentContext()) {
9897
253k
          ContextRAII SavedContext(*this, DC);
9898
253k
          if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9899
0
            Invalid = true;
9900
253k
        }
9901
9902
861k
        FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9903
861k
                                                        NewFD->getLocation(),
9904
861k
                                                        Name, TemplateParams,
9905
861k
                                                        NewFD);
9906
861k
        FunctionTemplate->setLexicalDeclContext(CurContext);
9907
861k
        NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9908
9909
        // For source fidelity, store the other template param lists.
9910
861k
        if (TemplateParamLists.size() > 1) {
9911
47.2k
          NewFD->setTemplateParameterListsInfo(Context,
9912
47.2k
              ArrayRef<TemplateParameterList *>(TemplateParamLists)
9913
47.2k
                  .drop_back(1));
9914
47.2k
        }
9915
861k
      } else {
9916
        // This is a function template specialization.
9917
3.41k
        isFunctionTemplateSpecialization = true;
9918
        // For source fidelity, store all the template param lists.
9919
3.41k
        if (TemplateParamLists.size() > 0)
9920
3.41k
          NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9921
9922
        // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9923
3.41k
        if (isFriend) {
9924
          // We want to remove the "template<>", found here.
9925
3
          SourceRange RemoveRange = TemplateParams->getSourceRange();
9926
9927
          // If we remove the template<> and the name is not a
9928
          // template-id, we're actually silently creating a problem:
9929
          // the friend declaration will refer to an untemplated decl,
9930
          // and clearly the user wants a template specialization.  So
9931
          // we need to insert '<>' after the name.
9932
3
          SourceLocation InsertLoc;
9933
3
          if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9934
0
            InsertLoc = D.getName().getSourceRange().getEnd();
9935
0
            InsertLoc = getLocForEndOfToken(InsertLoc);
9936
0
          }
9937
9938
3
          Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9939
3
            << Name << RemoveRange
9940
3
            << FixItHint::CreateRemoval(RemoveRange)
9941
3
            << FixItHint::CreateInsertion(InsertLoc, "<>");
9942
3
          Invalid = true;
9943
3
        }
9944
3.41k
      }
9945
15.2M
    } else {
9946
      // Check that we can declare a template here.
9947
15.2M
      if (!TemplateParamLists.empty() && 
isMemberSpecialization202k
&&
9948
15.2M
          
CheckTemplateDeclScope(S, TemplateParamLists.back())11.7k
)
9949
1
        NewFD->setInvalidDecl();
9950
9951
      // All template param lists were matched against the scope specifier:
9952
      // this is NOT (an explicit specialization of) a template.
9953
15.2M
      if (TemplateParamLists.size() > 0)
9954
        // For source fidelity, store all the template param lists.
9955
202k
        NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9956
15.2M
    }
9957
9958
16.1M
    if (Invalid) {
9959
33
      NewFD->setInvalidDecl();
9960
33
      if (FunctionTemplate)
9961
2
        FunctionTemplate->setInvalidDecl();
9962
33
    }
9963
9964
    // C++ [dcl.fct.spec]p5:
9965
    //   The virtual specifier shall only be used in declarations of
9966
    //   nonstatic class member functions that appear within a
9967
    //   member-specification of a class declaration; see 10.3.
9968
    //
9969
16.1M
    if (isVirtual && 
!NewFD->isInvalidDecl()76.3k
) {
9970
76.2k
      if (!isVirtualOkay) {
9971
4
        Diag(D.getDeclSpec().getVirtualSpecLoc(),
9972
4
             diag::err_virtual_non_function);
9973
76.2k
      } else if (!CurContext->isRecord()) {
9974
        // 'virtual' was specified outside of the class.
9975
12
        Diag(D.getDeclSpec().getVirtualSpecLoc(),
9976
12
             diag::err_virtual_out_of_class)
9977
12
          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9978
76.2k
      } else if (NewFD->getDescribedFunctionTemplate()) {
9979
        // C++ [temp.mem]p3:
9980
        //  A member function template shall not be virtual.
9981
1
        Diag(D.getDeclSpec().getVirtualSpecLoc(),
9982
1
             diag::err_virtual_member_function_template)
9983
1
          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9984
76.2k
      } else {
9985
        // Okay: Add virtual to the method.
9986
76.2k
        NewFD->setVirtualAsWritten(true);
9987
76.2k
      }
9988
9989
76.2k
      if (getLangOpts().CPlusPlus14 &&
9990
76.2k
          
NewFD->getReturnType()->isUndeducedType()9.40k
)
9991
18
        Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9992
76.2k
    }
9993
9994
16.1M
    if (getLangOpts().CPlusPlus14 &&
9995
16.1M
        
(12.8M
NewFD->isDependentContext()12.8M
||
9996
12.8M
         
(12.6M
isFriend12.6M
&&
CurContext->isDependentContext()4.13k
)) &&
9997
16.1M
        
NewFD->getReturnType()->isUndeducedType()254k
) {
9998
      // If the function template is referenced directly (for instance, as a
9999
      // member of the current instantiation), pretend it has a dependent type.
10000
      // This is not really justified by the standard, but is the only sane
10001
      // thing to do.
10002
      // FIXME: For a friend function, we have not marked the function as being
10003
      // a friend yet, so 'isDependentContext' on the FD doesn't work.
10004
2.53k
      const FunctionProtoType *FPT =
10005
2.53k
          NewFD->getType()->castAs<FunctionProtoType>();
10006
2.53k
      QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
10007
2.53k
      NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
10008
2.53k
                                             FPT->getExtProtoInfo()));
10009
2.53k
    }
10010
10011
    // C++ [dcl.fct.spec]p3:
10012
    //  The inline specifier shall not appear on a block scope function
10013
    //  declaration.
10014
16.1M
    if (isInline && 
!NewFD->isInvalidDecl()13.0M
) {
10015
13.0M
      if (CurContext->isFunctionOrMethod()) {
10016
        // 'inline' is not allowed on block scope function declaration.
10017
2
        Diag(D.getDeclSpec().getInlineSpecLoc(),
10018
2
             diag::err_inline_declaration_block_scope) << Name
10019
2
          << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10020
2
      }
10021
13.0M
    }
10022
10023
    // C++ [dcl.fct.spec]p6:
10024
    //  The explicit specifier shall be used only in the declaration of a
10025
    //  constructor or conversion function within its class definition;
10026
    //  see 12.3.1 and 12.3.2.
10027
16.1M
    if (hasExplicit && 
!NewFD->isInvalidDecl()117k
&&
10028
16.1M
        
!isa<CXXDeductionGuideDecl>(NewFD)117k
) {
10029
117k
      if (!CurContext->isRecord()) {
10030
        // 'explicit' was specified outside of the class.
10031
14
        Diag(D.getDeclSpec().getExplicitSpecLoc(),
10032
14
             diag::err_explicit_out_of_class)
10033
14
            << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10034
117k
      } else if (!isa<CXXConstructorDecl>(NewFD) &&
10035
117k
                 
!isa<CXXConversionDecl>(NewFD)7.43k
) {
10036
        // 'explicit' was specified on a function that wasn't a constructor
10037
        // or conversion function.
10038
5
        Diag(D.getDeclSpec().getExplicitSpecLoc(),
10039
5
             diag::err_explicit_non_ctor_or_conv_function)
10040
5
            << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10041
5
      }
10042
117k
    }
10043
10044
16.1M
    ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10045
16.1M
    if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10046
      // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10047
      // are implicitly inline.
10048
270k
      NewFD->setImplicitlyInline();
10049
10050
      // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10051
      // be either constructors or to return a literal type. Therefore,
10052
      // destructors cannot be declared constexpr.
10053
270k
      if (isa<CXXDestructorDecl>(NewFD) &&
10054
270k
          
(242
!getLangOpts().CPlusPlus20242
||
10055
242
           
ConstexprKind == ConstexprSpecKind::Consteval235
)) {
10056
11
        Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10057
11
            << static_cast<int>(ConstexprKind);
10058
11
        NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10059
11
                                    ? 
ConstexprSpecKind::Unspecified4
10060
11
                                    : 
ConstexprSpecKind::Constexpr7
);
10061
11
      }
10062
      // C++20 [dcl.constexpr]p2: An allocation function, or a
10063
      // deallocation function shall not be declared with the consteval
10064
      // specifier.
10065
270k
      if (ConstexprKind == ConstexprSpecKind::Consteval &&
10066
270k
          
(417
NewFD->getOverloadedOperator() == OO_New417
||
10067
417
           
NewFD->getOverloadedOperator() == OO_Array_New416
||
10068
417
           
NewFD->getOverloadedOperator() == OO_Delete415
||
10069
417
           
NewFD->getOverloadedOperator() == OO_Array_Delete414
)) {
10070
4
        Diag(D.getDeclSpec().getConstexprSpecLoc(),
10071
4
             diag::err_invalid_consteval_decl_kind)
10072
4
            << NewFD;
10073
4
        NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10074
4
      }
10075
270k
    }
10076
10077
    // If __module_private__ was specified, mark the function accordingly.
10078
16.1M
    if (D.getDeclSpec().isModulePrivateSpecified()) {
10079
9
      if (isFunctionTemplateSpecialization) {
10080
1
        SourceLocation ModulePrivateLoc
10081
1
          = D.getDeclSpec().getModulePrivateSpecLoc();
10082
1
        Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10083
1
          << 0
10084
1
          << FixItHint::CreateRemoval(ModulePrivateLoc);
10085
8
      } else {
10086
8
        NewFD->setModulePrivate();
10087
8
        if (FunctionTemplate)
10088
3
          FunctionTemplate->setModulePrivate();
10089
8
      }
10090
9
    }
10091
10092
16.1M
    if (isFriend) {
10093
40.7k
      if (FunctionTemplate) {
10094
14.1k
        FunctionTemplate->setObjectOfFriendDecl();
10095
14.1k
        FunctionTemplate->setAccess(AS_public);
10096
14.1k
      }
10097
40.7k
      NewFD->setObjectOfFriendDecl();
10098
40.7k
      NewFD->setAccess(AS_public);
10099
40.7k
    }
10100
10101
    // If a function is defined as defaulted or deleted, mark it as such now.
10102
    // We'll do the relevant checks on defaulted / deleted functions later.
10103
16.1M
    switch (D.getFunctionDefinitionKind()) {
10104
13.1M
    case FunctionDefinitionKind::Declaration:
10105
16.0M
    case FunctionDefinitionKind::Definition:
10106
16.0M
      break;
10107
10108
47.1k
    case FunctionDefinitionKind::Defaulted:
10109
47.1k
      NewFD->setDefaulted();
10110
47.1k
      break;
10111
10112
32.0k
    case FunctionDefinitionKind::Deleted:
10113
32.0k
      NewFD->setDeletedAsWritten();
10114
32.0k
      break;
10115
16.1M
    }
10116
10117
16.1M
    if (isa<CXXMethodDecl>(NewFD) && 
DC == CurContext1.93M
&&
10118
16.1M
        
D.isFunctionDefinition()1.66M
&&
!isInline1.09M
) {
10119
      // Pre C++20 [class.mfct]p2:
10120
      //   A member function may be defined (8.4) in its class definition, in
10121
      //   which case it is an inline member function (7.1.2)
10122
      // Post C++20 [class.mfct]p1:
10123
      //   If a member function is attached to the global module and is defined
10124
      //   in its class definition, it is inline.
10125
1.05M
      NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10126
1.05M
    }
10127
10128
16.1M
    if (SC == SC_Static && 
isa<CXXMethodDecl>(NewFD)12.6M
&&
10129
16.1M
        
!CurContext->isRecord()180k
) {
10130
      // C++ [class.static]p1:
10131
      //   A data or function member of a class may be declared static
10132
      //   in a class definition, in which case it is a static member of
10133
      //   the class.
10134
10135
      // Complain about the 'static' specifier if it's on an out-of-line
10136
      // member function definition.
10137
10138
      // MSVC permits the use of a 'static' storage specifier on an out-of-line
10139
      // member function template declaration and class member template
10140
      // declaration (MSVC versions before 2015), warn about this.
10141
10
      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10142
10
           ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10143
10
             cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10144
10
           
(8
getLangOpts().MSVCCompat8
&&
NewFD->getDescribedFunctionTemplate()2
))
10145
10
           ? 
diag::ext_static_out_of_line4
:
diag::err_static_out_of_line6
)
10146
10
        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10147
10
    }
10148
10149
    // C++11 [except.spec]p15:
10150
    //   A deallocation function with no exception-specification is treated
10151
    //   as if it were specified with noexcept(true).
10152
16.1M
    const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10153
16.1M
    if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10154
16.1M
         
Name.getCXXOverloadedOperator() == OO_Array_Delete16.1M
) &&
10155
16.1M
        
getLangOpts().CPlusPlus118.28k
&&
FPT8.11k
&&
!FPT->hasExceptionSpec()8.11k
)
10156
992
      NewFD->setType(Context.getFunctionType(
10157
992
          FPT->getReturnType(), FPT->getParamTypes(),
10158
992
          FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10159
10160
    // C++20 [dcl.inline]/7
10161
    // If an inline function or variable that is attached to a named module
10162
    // is declared in a definition domain, it shall be defined in that
10163
    // domain.
10164
    // So, if the current declaration does not have a definition, we must
10165
    // check at the end of the TU (or when the PMF starts) to see that we
10166
    // have a definition at that point.
10167
16.1M
    if (isInline && 
!D.isFunctionDefinition()13.0M
&&
getLangOpts().CPlusPlus2011.7M
&&
10168
16.1M
        
NewFD->hasOwningModule()22.9k
&&
NewFD->getOwningModule()->isNamedModule()4
) {
10169
4
      PendingInlineFuncDecls.insert(NewFD);
10170
4
    }
10171
16.1M
  }
10172
10173
  // Filter out previous declarations that don't match the scope.
10174
36.5M
  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10175
36.5M
                       D.getCXXScopeSpec().isNotEmpty() ||
10176
36.5M
                       
isMemberSpecialization36.3M
||
10177
36.5M
                       
isFunctionTemplateSpecialization36.3M
);
10178
10179
  // Handle GNU asm-label extension (encoded as an attribute).
10180
36.5M
  if (Expr *E = (Expr*) D.getAsmLabel()) {
10181
    // The parser guarantees this is a string.
10182
57.5k
    StringLiteral *SE = cast<StringLiteral>(E);
10183
57.5k
    NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10184
57.5k
                                        /*IsLiteralLabel=*/true,
10185
57.5k
                                        SE->getStrTokenLoc(0)));
10186
36.5M
  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10187
14
    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10188
14
      ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10189
14
    if (I != ExtnameUndeclaredIdentifiers.end()) {
10190
9
      if (isDeclExternC(NewFD)) {
10191
4
        NewFD->addAttr(I->second);
10192
4
        ExtnameUndeclaredIdentifiers.erase(I);
10193
4
      } else
10194
5
        Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10195
5
            << /*Variable*/0 << NewFD;
10196
9
    }
10197
14
  }
10198
10199
  // Copy the parameter declarations from the declarator D to the function
10200
  // declaration NewFD, if they are available.  First scavenge them into Params.
10201
36.5M
  SmallVector<ParmVarDecl*, 16> Params;
10202
36.5M
  unsigned FTIIdx;
10203
36.5M
  if (D.isFunctionDeclarator(FTIIdx)) {
10204
36.5M
    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10205
10206
    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10207
    // function that takes no arguments, not a function that takes a
10208
    // single void argument.
10209
    // We let through "const void" here because Sema::GetTypeForDeclarator
10210
    // already checks for that case.
10211
36.5M
    if (FTIHasNonVoidParameters(FTI) && 
FTI.Params[0].Param35.4M
) {
10212
129M
      for (unsigned i = 0, e = FTI.NumParams; i != e; 
++i93.5M
) {
10213
93.5M
        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10214
93.5M
        assert(Param->getDeclContext() != NewFD && "Was set before ?");
10215
93.5M
        Param->setDeclContext(NewFD);
10216
93.5M
        Params.push_back(Param);
10217
10218
93.5M
        if (Param->isInvalidDecl())
10219
578
          NewFD->setInvalidDecl();
10220
93.5M
      }
10221
35.4M
    }
10222
10223
36.5M
    if (!getLangOpts().CPlusPlus) {
10224
      // In C, find all the tag declarations from the prototype and move them
10225
      // into the function DeclContext. Remove them from the surrounding tag
10226
      // injection context of the function, which is typically but not always
10227
      // the TU.
10228
20.4M
      DeclContext *PrototypeTagContext =
10229
20.4M
          getTagInjectionContext(NewFD->getLexicalDeclContext());
10230
20.4M
      for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10231
456
        auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10232
10233
        // We don't want to reparent enumerators. Look at their parent enum
10234
        // instead.
10235
456
        if (!TD) {
10236
37
          if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10237
37
            TD = cast<EnumDecl>(ECD->getDeclContext());
10238
37
        }
10239
456
        if (!TD)
10240
0
          continue;
10241
456
        DeclContext *TagDC = TD->getLexicalDeclContext();
10242
456
        if (!TagDC->containsDecl(TD))
10243
11
          continue;
10244
445
        TagDC->removeDecl(TD);
10245
445
        TD->setDeclContext(NewFD);
10246
445
        NewFD->addDecl(TD);
10247
10248
        // Preserve the lexical DeclContext if it is not the surrounding tag
10249
        // injection context of the FD. In this example, the semantic context of
10250
        // E will be f and the lexical context will be S, while both the
10251
        // semantic and lexical contexts of S will be f:
10252
        //   void f(struct S { enum E { a } f; } s);
10253
445
        if (TagDC != PrototypeTagContext)
10254
19
          TD->setLexicalDeclContext(TagDC);
10255
445
      }
10256
20.4M
    }
10257
36.5M
  } else 
if (const FunctionProtoType *196
FT196
= R->getAs<FunctionProtoType>()) {
10258
    // When we're declaring a function with a typedef, typeof, etc as in the
10259
    // following example, we'll need to synthesize (unnamed)
10260
    // parameters for use in the declaration.
10261
    //
10262
    // @code
10263
    // typedef void fn(int);
10264
    // fn f;
10265
    // @endcode
10266
10267
    // Synthesize a parameter for each argument type.
10268
190
    for (const auto &AI : FT->param_types()) {
10269
111
      ParmVarDecl *Param =
10270
111
          BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10271
111
      Param->setScopeInfo(0, Params.size());
10272
111
      Params.push_back(Param);
10273
111
    }
10274
190
  } else {
10275
6
    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10276
6
           "Should not need args for typedef of non-prototype fn");
10277
6
  }
10278
10279
  // Finally, we know we have the right number of parameters, install them.
10280
36.5M
  NewFD->setParams(Params);
10281
10282
36.5M
  if (D.getDeclSpec().isNoreturnSpecified())
10283
73
    NewFD->addAttr(
10284
73
        C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10285
10286
  // Functions returning a variably modified type violate C99 6.7.5.2p2
10287
  // because all functions have linkage.
10288
36.5M
  if (!NewFD->isInvalidDecl() &&
10289
36.5M
      
NewFD->getReturnType()->isVariablyModifiedType()36.5M
) {
10290
3
    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10291
3
    NewFD->setInvalidDecl();
10292
3
  }
10293
10294
  // Apply an implicit SectionAttr if '#pragma clang section text' is active
10295
36.5M
  if (PragmaClangTextSection.Valid && 
D.isFunctionDefinition()12
&&
10296
36.5M
      
!NewFD->hasAttr<SectionAttr>()8
)
10297
8
    NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10298
8
        Context, PragmaClangTextSection.SectionName,
10299
8
        PragmaClangTextSection.PragmaLocation));
10300
10301
  // Apply an implicit SectionAttr if #pragma code_seg is active.
10302
36.5M
  if (CodeSegStack.CurrentValue && 
D.isFunctionDefinition()66
&&
10303
36.5M
      
!NewFD->hasAttr<SectionAttr>()52
) {
10304
52
    NewFD->addAttr(SectionAttr::CreateImplicit(
10305
52
        Context, CodeSegStack.CurrentValue->getString(),
10306
52
        CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10307
52
    if (UnifySection(CodeSegStack.CurrentValue->getString(),
10308
52
                     ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10309
52
                         ASTContext::PSF_Read,
10310
52
                     NewFD))
10311
1
      NewFD->dropAttr<SectionAttr>();
10312
52
  }
10313
10314
  // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10315
  // active.
10316
36.5M
  if (StrictGuardStackCheckStack.CurrentValue && 
D.isFunctionDefinition()1
&&
10317
36.5M
      
!NewFD->hasAttr<StrictGuardStackCheckAttr>()1
)
10318
1
    NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10319
1
        Context, PragmaClangTextSection.PragmaLocation));
10320
10321
  // Apply an implicit CodeSegAttr from class declspec or
10322
  // apply an implicit SectionAttr from #pragma code_seg if active.
10323
36.5M
  if (!NewFD->hasAttr<CodeSegAttr>()) {
10324
36.5M
    if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10325
36.5M
                                                                 D.isFunctionDefinition())) {
10326
60
      NewFD->addAttr(SAttr);
10327
60
    }
10328
36.5M
  }
10329
10330
  // Handle attributes.
10331
36.5M
  ProcessDeclAttributes(S, NewFD, D);
10332
36.5M
  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10333
36.5M
  if (NewTVA && 
!NewTVA->isDefaultVersion()138
&&
10334
36.5M
      
!Context.getTargetInfo().hasFeature("fmv")138
) {
10335
    // Don't add to scope fmv functions declarations if fmv disabled
10336
31
    AddToScope = false;
10337
31
    return NewFD;
10338
31
  }
10339
10340
36.5M
  if (getLangOpts().OpenCL || 
getLangOpts().HLSL36.2M
) {
10341
    // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10342
    // type.
10343
    //
10344
    // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10345
    // type declaration will generate a compilation error.
10346
317k
    LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10347
317k
    if (AddressSpace != LangAS::Default) {
10348
40
      Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10349
40
      NewFD->setInvalidDecl();
10350
40
    }
10351
317k
  }
10352
10353
36.5M
  if (!getLangOpts().CPlusPlus) {
10354
    // Perform semantic checking on the function declaration.
10355
20.4M
    if (!NewFD->isInvalidDecl() && 
NewFD->isMain()20.4M
)
10356
1.94k
      CheckMain(NewFD, D.getDeclSpec());
10357
10358
20.4M
    if (!NewFD->isInvalidDecl() && 
NewFD->isMSVCRTEntryPoint()20.4M
)
10359
49
      CheckMSVCRTEntryPoint(NewFD);
10360
10361
20.4M
    if (!NewFD->isInvalidDecl())
10362
20.4M
      D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10363
20.4M
                                                  isMemberSpecialization,
10364
20.4M
                                                  D.isFunctionDefinition()));
10365
266
    else if (!Previous.empty())
10366
      // Recover gracefully from an invalid redeclaration.
10367
29
      D.setRedeclaration(true);
10368
20.4M
    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10369
20.4M
            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10370
20.4M
           "previous declaration set still overloaded");
10371
10372
    // Diagnose no-prototype function declarations with calling conventions that
10373
    // don't support variadic calls. Only do this in C and do it after merging
10374
    // possibly prototyped redeclarations.
10375
20.4M
    const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10376
20.4M
    if (isa<FunctionNoProtoType>(FT) && 
!D.isFunctionDefinition()8.92k
) {
10377
4.30k
      CallingConv CC = FT->getExtInfo().getCC();
10378
4.30k
      if (!supportsVariadicCall(CC)) {
10379
        // Windows system headers sometimes accidentally use stdcall without
10380
        // (void) parameters, so we relax this to a warning.
10381
14
        int DiagID =
10382
14
            CC == CC_X86StdCall ? 
diag::warn_cconv_knr3
:
diag::err_cconv_knr11
;
10383
14
        Diag(NewFD->getLocation(), DiagID)
10384
14
            << FunctionType::getNameForCallConv(CC);
10385
14
      }
10386
4.30k
    }
10387
10388
20.4M
   if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10389
20.4M
       
NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()20.4M
)
10390
3
     checkNonTrivialCUnion(NewFD->getReturnType(),
10391
3
                           NewFD->getReturnTypeSourceRange().getBegin(),
10392
3
                           NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10393
20.4M
  } else {
10394
    // C++11 [replacement.functions]p3:
10395
    //  The program's definitions shall not be specified as inline.
10396
    //
10397
    // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10398
    //
10399
    // Suppress the diagnostic if the function is __attribute__((used)), since
10400
    // that forces an external definition to be emitted.
10401
16.1M
    if (D.getDeclSpec().isInlineSpecified() &&
10402
16.1M
        
NewFD->isReplaceableGlobalAllocationFunction()13.0M
&&
10403
16.1M
        
!NewFD->hasAttr<UsedAttr>()172
)
10404
168
      Diag(D.getDeclSpec().getInlineSpecLoc(),
10405
168
           diag::ext_operator_new_delete_declared_inline)
10406
168
        << NewFD->getDeclName();
10407
10408
    // If the declarator is a template-id, translate the parser's template
10409
    // argument list into our AST format.
10410
16.1M
    if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10411
5.21k
      TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
10412
5.21k
      TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10413
5.21k
      TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10414
5.21k
      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10415
5.21k
                                         TemplateId->NumArgs);
10416
5.21k
      translateTemplateArguments(TemplateArgsPtr,
10417
5.21k
                                 TemplateArgs);
10418
10419
5.21k
      HasExplicitTemplateArgs = true;
10420
10421
5.21k
      if (NewFD->isInvalidDecl()) {
10422
8
        HasExplicitTemplateArgs = false;
10423
5.21k
      } else if (FunctionTemplate) {
10424
        // Function template with explicit template arguments.
10425
13
        Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10426
13
          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10427
10428
13
        HasExplicitTemplateArgs = false;
10429
5.19k
      } else if (isFriend) {
10430
        // "friend void foo<>(int);" is an implicit specialization decl.
10431
2.31k
        isFunctionTemplateSpecialization = true;
10432
2.88k
      } else {
10433
2.88k
        assert(isFunctionTemplateSpecialization &&
10434
2.88k
               "should have a 'template<>' for this decl");
10435
2.88k
      }
10436
16.1M
    } else if (isFriend && 
isFunctionTemplateSpecialization38.4k
) {
10437
      // This combination is only possible in a recovery case;  the user
10438
      // wrote something like:
10439
      //   template <> friend void foo(int);
10440
      // which we're recovering from as if the user had written:
10441
      //   friend void foo<>(int);
10442
      // Go ahead and fake up a template id.
10443
0
      HasExplicitTemplateArgs = true;
10444
0
      TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10445
0
      TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10446
0
    }
10447
10448
    // We do not add HD attributes to specializations here because
10449
    // they may have different constexpr-ness compared to their
10450
    // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10451
    // may end up with different effective targets. Instead, a
10452
    // specialization inherits its target attributes from its template
10453
    // in the CheckFunctionTemplateSpecialization() call below.
10454
16.1M
    if (getLangOpts().CUDA && 
!isFunctionTemplateSpecialization17.8k
)
10455
17.8k
      maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10456
10457
    // Handle explict specializations of function templates
10458
    // and friend function declarations with an explicit
10459
    // template argument list.
10460
16.1M
    if (isFunctionTemplateSpecialization) {
10461
5.73k
      bool isDependentSpecialization = false;
10462
5.73k
      if (isFriend) {
10463
        // For friend function specializations, this is a dependent
10464
        // specialization if its semantic context is dependent, its
10465
        // type is dependent, or if its template-id is dependent.
10466
2.32k
        isDependentSpecialization =
10467
2.32k
            DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10468
2.32k
            
(69
HasExplicitTemplateArgs69
&&
10469
69
             TemplateSpecializationType::
10470
66
                 anyInstantiationDependentTemplateArguments(
10471
66
                     TemplateArgs.arguments()));
10472
2.32k
        assert((!isDependentSpecialization ||
10473
2.32k
                (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10474
2.32k
               "dependent friend function specialization without template "
10475
2.32k
               "args");
10476
3.41k
      } else {
10477
        // For class-scope explicit specializations of function templates,
10478
        // if the lexical context is dependent, then the specialization
10479
        // is dependent.
10480
3.41k
        isDependentSpecialization =
10481
3.41k
            CurContext->isRecord() && 
CurContext->isDependentContext()208
;
10482
3.41k
      }
10483
10484
5.73k
      TemplateArgumentListInfo *ExplicitTemplateArgs =
10485
5.73k
          HasExplicitTemplateArgs ? 
&TemplateArgs5.19k
:
nullptr536
;
10486
5.73k
      if (isDependentSpecialization) {
10487
        // If it's a dependent specialization, it may not be possible
10488
        // to determine the primary template (for explicit specializations)
10489
        // or befriended declaration (for friends) until the enclosing
10490
        // template is instantiated. In such cases, we store the declarations
10491
        // found by name lookup and defer resolution until instantiation.
10492
2.32k
        if (CheckDependentFunctionTemplateSpecialization(
10493
2.32k
                NewFD, ExplicitTemplateArgs, Previous))
10494
9
          NewFD->setInvalidDecl();
10495
3.41k
      } else if (!NewFD->isInvalidDecl()) {
10496
3.39k
        if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10497
3.39k
                                                Previous))
10498
85
          NewFD->setInvalidDecl();
10499
3.39k
      }
10500
10501
      // C++ [dcl.stc]p1:
10502
      //   A storage-class-specifier shall not be specified in an explicit
10503
      //   specialization (14.7.3)
10504
      // FIXME: We should be checking this for dependent specializations.
10505
5.73k
      FunctionTemplateSpecializationInfo *Info =
10506
5.73k
          NewFD->getTemplateSpecializationInfo();
10507
5.73k
      if (Info && 
SC != SC_None3.30k
) {
10508
5
        if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10509
1
          Diag(NewFD->getLocation(),
10510
1
               diag::err_explicit_specialization_inconsistent_storage_class)
10511
1
            << SC
10512
1
            << FixItHint::CreateRemoval(
10513
1
                                      D.getDeclSpec().getStorageClassSpecLoc());
10514
10515
4
        else
10516
4
          Diag(NewFD->getLocation(),
10517
4
               diag::ext_explicit_specialization_storage_class)
10518
4
            << FixItHint::CreateRemoval(
10519
4
                                      D.getDeclSpec().getStorageClassSpecLoc());
10520
5
      }
10521
16.1M
    } else if (isMemberSpecialization && 
isa<CXXMethodDecl>(NewFD)11.8k
) {
10522
11.8k
      if (CheckMemberSpecialization(NewFD, Previous))
10523
7
          NewFD->setInvalidDecl();
10524
11.8k
    }
10525
10526
    // Perform semantic checking on the function declaration.
10527
16.1M
    if (!NewFD->isInvalidDecl() && 
NewFD->isMain()16.1M
)
10528
8.45k
      CheckMain(NewFD, D.getDeclSpec());
10529
10530
16.1M
    if (!NewFD->isInvalidDecl() && 
NewFD->isMSVCRTEntryPoint()16.1M
)
10531
198
      CheckMSVCRTEntryPoint(NewFD);
10532
10533
16.1M
    if (!NewFD->isInvalidDecl())
10534
16.1M
      D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10535
16.1M
                                                  isMemberSpecialization,
10536
16.1M
                                                  D.isFunctionDefinition()));
10537
864
    else if (!Previous.empty())
10538
      // Recover gracefully from an invalid redeclaration.
10539
226
      D.setRedeclaration(true);
10540
10541
16.1M
    assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10542
16.1M
            !D.isRedeclaration() ||
10543
16.1M
            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10544
16.1M
           "previous declaration set still overloaded");
10545
10546
16.1M
    NamedDecl *PrincipalDecl = (FunctionTemplate
10547
16.1M
                                ? 
cast<NamedDecl>(FunctionTemplate)861k
10548
16.1M
                                : 
NewFD15.2M
);
10549
10550
16.1M
    if (isFriend && 
NewFD->getPreviousDecl()40.7k
) {
10551
3.99k
      AccessSpecifier Access = AS_public;
10552
3.99k
      if (!NewFD->isInvalidDecl())
10553
3.99k
        Access = NewFD->getPreviousDecl()->getAccess();
10554
10555
3.99k
      NewFD->setAccess(Access);
10556
3.99k
      if (FunctionTemplate) 
FunctionTemplate->setAccess(Access)1.37k
;
10557
3.99k
    }
10558
10559
16.1M
    if (NewFD->isOverloadedOperator() && 
!DC->isRecord()489k
&&
10560
16.1M
        
PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)167k
)
10561
143k
      PrincipalDecl->setNonMemberOperator();
10562
10563
    // If we have a function template, check the template parameter
10564
    // list. This will check and merge default template arguments.
10565
16.1M
    if (FunctionTemplate) {
10566
861k
      FunctionTemplateDecl *PrevTemplate =
10567
861k
                                     FunctionTemplate->getPreviousDecl();
10568
861k
      CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10569
861k
                       PrevTemplate ? 
PrevTemplate->getTemplateParameters()71.2k
10570
861k
                                    : 
nullptr790k
,
10571
861k
                            D.getDeclSpec().isFriendSpecified()
10572
861k
                              ? 
(14.1k
D.isFunctionDefinition()14.1k
10573
14.1k
                                   ? 
TPC_FriendFunctionTemplateDefinition630
10574
14.1k
                                   : 
TPC_FriendFunctionTemplate13.5k
)
10575
861k
                              : 
(847k
D.getCXXScopeSpec().isSet()847k
&&
10576
847k
                                 
DC52.7k
&&
DC->isRecord()52.7k
&&
10577
847k
                                 
DC->isDependentContext()52.7k
)
10578
847k
                                  ? 
TPC_ClassTemplateMember47.1k
10579
847k
                                  : 
TPC_FunctionTemplate800k
);
10580
861k
    }
10581
10582
16.1M
    if (NewFD->isInvalidDecl()) {
10583
      // Ignore all the rest of this.
10584
16.1M
    } else if (!D.isRedeclaration()) {
10585
15.8M
      struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10586
15.8M
                                       AddToScope };
10587
      // Fake up an access specifier if it's supposed to be a class member.
10588
15.8M
      if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10589
1.66M
        NewFD->setAccess(AS_public);
10590
10591
      // Qualified decls generally require a previous declaration.
10592
15.8M
      if (D.getCXXScopeSpec().isSet()) {
10593
        // ...with the major exception of templated-scope or
10594
        // dependent-scope friend declarations.
10595
10596
        // TODO: we currently also suppress this check in dependent
10597
        // contexts because (1) the parameter depth will be off when
10598
        // matching friend templates and (2) we might actually be
10599
        // selecting a friend based on a dependent factor.  But there
10600
        // are situations where these conditions don't apply and we
10601
        // can actually do this check immediately.
10602
        //
10603
        // Unless the scope is dependent, it's always an error if qualified
10604
        // redeclaration lookup found nothing at all. Diagnose that now;
10605
        // nothing will diagnose that error later.
10606
232
        if (isFriend &&
10607
232
            
(100
D.getCXXScopeSpec().getScopeRep()->isDependent()100
||
10608
100
             
(46
!Previous.empty()46
&&
CurContext->isDependentContext()35
))) {
10609
          // ignore these
10610
144
        } else if (NewFD->isCPUDispatchMultiVersion() ||
10611
144
                   
NewFD->isCPUSpecificMultiVersion()136
) {
10612
          // ignore this, we allow the redeclaration behavior here to create new
10613
          // versions of the function.
10614
121
        } else {
10615
          // The user tried to provide an out-of-line definition for a
10616
          // function that is a member of a class or namespace, but there
10617
          // was no such member function declared (C++ [class.mfct]p2,
10618
          // C++ [namespace.memdef]p2). For example:
10619
          //
10620
          // class X {
10621
          //   void f() const;
10622
          // };
10623
          //
10624
          // void X::f() { } // ill-formed
10625
          //
10626
          // Complain about this problem, and attempt to suggest close
10627
          // matches (e.g., those that differ only in cv-qualifiers and
10628
          // whether the parameter types are references).
10629
10630
121
          if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10631
121
                  *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10632
21
            AddToScope = ExtraArgs.AddToScope;
10633
21
            return Result;
10634
21
          }
10635
121
        }
10636
10637
        // Unqualified local friend declarations are required to resolve
10638
        // to something.
10639
15.8M
      } else if (isFriend && 
cast<CXXRecordDecl>(CurContext)->isLocalClass()36.2k
) {
10640
10
        if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10641
10
                *this, Previous, NewFD, ExtraArgs, true, S)) {
10642
7
          AddToScope = ExtraArgs.AddToScope;
10643
7
          return Result;
10644
7
        }
10645
10
      }
10646
15.8M
    } else 
if (340k
!D.isFunctionDefinition()340k
&&
10647
340k
               
isa<CXXMethodDecl>(NewFD)28.8k
&&
NewFD->isOutOfLine()11.8k
&&
10648
340k
               
!isFriend11.8k
&&
!isFunctionTemplateSpecialization11.5k
&&
10649
340k
               
!isMemberSpecialization11.4k
) {
10650
      // An out-of-line member function declaration must also be a
10651
      // definition (C++ [class.mfct]p2).
10652
      // Note that this is not the case for explicit specializations of
10653
      // function templates or member functions of class templates, per
10654
      // C++ [temp.expl.spec]p2. We also allow these declarations as an
10655
      // extension for compatibility with old SWIG code which likes to
10656
      // generate them.
10657
1
      Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10658
1
        << D.getCXXScopeSpec().getRange();
10659
1
    }
10660
16.1M
  }
10661
10662
36.5M
  if (getLangOpts().HLSL && 
D.isFunctionDefinition()11.3k
) {
10663
    // Any top level function could potentially be specified as an entry.
10664
652
    if (!NewFD->isInvalidDecl() && 
S->getDepth() == 0642
&&
Name.isIdentifier()601
)
10665
601
      ActOnHLSLTopLevelFunction(NewFD);
10666
10667
652
    if (NewFD->hasAttr<HLSLShaderAttr>())
10668
81
      CheckHLSLEntryPoint(NewFD);
10669
652
  }
10670
10671
  // If this is the first declaration of a library builtin function, add
10672
  // attributes as appropriate.
10673
36.5M
  if (!D.isRedeclaration()) {
10674
36.1M
    if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10675
35.2M
      if (unsigned BuiltinID = II->getBuiltinID()) {
10676
328k
        bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10677
328k
        if (!InStdNamespace &&
10678
328k
            
NewFD->getDeclContext()->getRedeclContext()->isFileContext()320k
) {
10679
317k
          if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10680
            // Validate the type matches unless this builtin is specified as
10681
            // matching regardless of its declared type.
10682
160k
            if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10683
603
              NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10684
160k
            } else {
10685
160k
              ASTContext::GetBuiltinTypeError Error;
10686
160k
              LookupNecessaryTypesForBuiltin(S, BuiltinID);
10687
160k
              QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10688
10689
160k
              if (!Error && 
!BuiltinType.isNull()160k
&&
10690
160k
                  Context.hasSameFunctionTypeIgnoringExceptionSpec(
10691
160k
                      NewFD->getType(), BuiltinType))
10692
138k
                NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10693
160k
            }
10694
160k
          }
10695
317k
        } else 
if (11.5k
InStdNamespace11.5k
&&
NewFD->isInStdNamespace()8.23k
&&
10696
11.5k
                   
isStdBuiltin(Context, NewFD, BuiltinID)4.68k
) {
10697
3.77k
          NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10698
3.77k
        }
10699
328k
      }
10700
35.2M
    }
10701
36.1M
  }
10702
10703
36.5M
  ProcessPragmaWeak(S, NewFD);
10704
36.5M
  checkAttributesAfterMerging(*this, *NewFD);
10705
10706
36.5M
  AddKnownFunctionAttributes(NewFD);
10707
10708
36.5M
  if (NewFD->hasAttr<OverloadableAttr>() &&
10709
36.5M
      
!NewFD->getType()->getAs<FunctionProtoType>()15.0M
) {
10710
3
    Diag(NewFD->getLocation(),
10711
3
         diag::err_attribute_overloadable_no_prototype)
10712
3
      << NewFD;
10713
3
    NewFD->dropAttr<OverloadableAttr>();
10714
3
  }
10715
10716
  // If there's a #pragma GCC visibility in scope, and this isn't a class
10717
  // member, set the visibility of this function.
10718
36.5M
  if (!DC->isRecord() && 
NewFD->isExternallyVisible()34.6M
)
10719
3.46M
    AddPushedVisibilityAttribute(NewFD);
10720
10721
  // If there's a #pragma clang arc_cf_code_audited in scope, consider
10722
  // marking the function.
10723
36.5M
  AddCFAuditedAttribute(NewFD);
10724
10725
  // If this is a function definition, check if we have to apply any
10726
  // attributes (i.e. optnone and no_builtin) due to a pragma.
10727
36.5M
  if (D.isFunctionDefinition()) {
10728
5.71M
    AddRangeBasedOptnone(NewFD);
10729
5.71M
    AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10730
5.71M
    AddSectionMSAllocText(NewFD);
10731
5.71M
    ModifyFnAttributesMSPragmaOptimize(NewFD);
10732
5.71M
  }
10733
10734
  // If this is the first declaration of an extern C variable, update
10735
  // the map of such variables.
10736
36.5M
  if (NewFD->isFirstDecl() && 
!NewFD->isInvalidDecl()36.1M
&&
10737
36.5M
      
isIncompleteDeclExternC(*this, NewFD)36.1M
)
10738
2.32M
    RegisterLocallyScopedExternCDecl(NewFD, S);
10739
10740
  // Set this FunctionDecl's range up to the right paren.
10741
36.5M
  NewFD->setRangeEnd(D.getSourceRange().getEnd());
10742
10743
36.5M
  if (D.isRedeclaration() && 
!Previous.empty()423k
) {
10744
423k
    NamedDecl *Prev = Previous.getRepresentativeDecl();
10745
423k
    checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10746
423k
                                   isMemberSpecialization ||
10747
423k
                                       
isFunctionTemplateSpecialization411k
,
10748
423k
                                   D.isFunctionDefinition());
10749
423k
  }
10750
10751
36.5M
  if (getLangOpts().CUDA) {
10752
17.8k
    IdentifierInfo *II = NewFD->getIdentifier();
10753
17.8k
    if (II && 
II->isStr(getCudaConfigureFuncName())16.5k
&&
10754
17.8k
        
!NewFD->isInvalidDecl()309
&&
10755
17.8k
        
NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()309
) {
10756
309
      if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10757
2
        Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10758
2
            << getCudaConfigureFuncName();
10759
309
      Context.setcudaConfigureCallDecl(NewFD);
10760
309
    }
10761
10762
    // Variadic functions, other than a *declaration* of printf, are not allowed
10763
    // in device-side CUDA code, unless someone passed
10764
    // -fcuda-allow-variadic-functions.
10765
17.8k
    if (!getLangOpts().CUDAAllowVariadicFunctions && 
NewFD->isVariadic()17.8k
&&
10766
17.8k
        
(206
NewFD->hasAttr<CUDADeviceAttr>()206
||
10767
206
         
NewFD->hasAttr<CUDAGlobalAttr>()20
) &&
10768
17.8k
        
!(186
II186
&&
II->isStr("printf")186
&&
NewFD->isExternC()186
&&
10769
186
          !D.isFunctionDefinition())) {
10770
0
      Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10771
0
    }
10772
17.8k
  }
10773
10774
36.5M
  MarkUnusedFileScopedDecl(NewFD);
10775
10776
10777
10778
36.5M
  if (getLangOpts().OpenCL && 
NewFD->hasAttr<OpenCLKernelAttr>()305k
) {
10779
    // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10780
1.27k
    if (SC == SC_Static) {
10781
11
      Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10782
11
      D.setInvalidType();
10783
11
    }
10784
10785
    // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10786
1.27k
    if (!NewFD->getReturnType()->isVoidType()) {
10787
2
      SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10788
2
      Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10789
2
          << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10790
2
                                : 
FixItHint()0
);
10791
2
      D.setInvalidType();
10792
2
    }
10793
10794
1.27k
    llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10795
1.27k
    for (auto *Param : NewFD->parameters())
10796
1.34k
      checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10797
10798
1.27k
    if (getLangOpts().OpenCLCPlusPlus) {
10799
217
      if (DC->isRecord()) {
10800
2
        Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10801
2
        D.setInvalidType();
10802
2
      }
10803
217
      if (FunctionTemplate) {
10804
4
        Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10805
4
        D.setInvalidType();
10806
4
      }
10807
217
    }
10808
1.27k
  }
10809
10810
36.5M
  if (getLangOpts().CPlusPlus) {
10811
    // Precalculate whether this is a friend function template with a constraint
10812
    // that depends on an enclosing template, per [temp.friend]p9.
10813
16.1M
    if (isFriend && 
FunctionTemplate40.7k
&&
10814
16.1M
        
FriendConstraintsDependOnEnclosingTemplate(NewFD)14.1k
)
10815
163
      NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10816
10817
16.1M
    if (FunctionTemplate) {
10818
861k
      if (NewFD->isInvalidDecl())
10819
478
        FunctionTemplate->setInvalidDecl();
10820
861k
      return FunctionTemplate;
10821
861k
    }
10822
10823
15.2M
    if (isMemberSpecialization && 
!NewFD->isInvalidDecl()11.8k
)
10824
11.7k
      CompleteMemberSpecialization(NewFD, Previous);
10825
15.2M
  }
10826
10827
91.6M
  
for (const ParmVarDecl *Param : NewFD->parameters())35.7M
{
10828
91.6M
    QualType PT = Param->getType();
10829
10830
    // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10831
    // types.
10832
91.6M
    if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10833
249k
      if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10834
202
        QualType ElemTy = PipeTy->getElementType();
10835
202
          if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10836
6
            Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10837
6
            D.setInvalidType();
10838
6
          }
10839
202
      }
10840
249k
    }
10841
    // WebAssembly tables can't be used as function parameters.
10842
91.6M
    if (Context.getTargetInfo().getTriple().isWasm()) {
10843
1.42k
      if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10844
4
        Diag(Param->getTypeSpecStartLoc(),
10845
4
             diag::err_wasm_table_as_function_parameter);
10846
4
        D.setInvalidType();
10847
4
      }
10848
1.42k
    }
10849
91.6M
  }
10850
10851
  // Diagnose availability attributes. Availability cannot be used on functions
10852
  // that are run during load/unload.
10853
35.7M
  if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10854
1.07M
    if (NewFD->hasAttr<ConstructorAttr>()) {
10855
2
      Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10856
2
          << 1;
10857
2
      NewFD->dropAttr<AvailabilityAttr>();
10858
2
    }
10859
1.07M
    if (NewFD->hasAttr<DestructorAttr>()) {
10860
2
      Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10861
2
          << 2;
10862
2
      NewFD->dropAttr<AvailabilityAttr>();
10863
2
    }
10864
1.07M
  }
10865
10866
  // Diagnose no_builtin attribute on function declaration that are not a
10867
  // definition.
10868
  // FIXME: We should really be doing this in
10869
  // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10870
  // the FunctionDecl and at this point of the code
10871
  // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10872
  // because Sema::ActOnStartOfFunctionDef has not been called yet.
10873
35.7M
  if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10874
30
    switch (D.getFunctionDefinitionKind()) {
10875
1
    case FunctionDefinitionKind::Defaulted:
10876
2
    case FunctionDefinitionKind::Deleted:
10877
2
      Diag(NBA->getLocation(),
10878
2
           diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10879
2
          << NBA->getSpelling();
10880
2
      break;
10881
3
    case FunctionDefinitionKind::Declaration:
10882
3
      Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10883
3
          << NBA->getSpelling();
10884
3
      break;
10885
25
    case FunctionDefinitionKind::Definition:
10886
25
      break;
10887
30
    }
10888
10889
35.7M
  return NewFD;
10890
35.7M
}
10891
10892
/// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10893
/// when __declspec(code_seg) "is applied to a class, all member functions of
10894
/// the class and nested classes -- this includes compiler-generated special
10895
/// member functions -- are put in the specified segment."
10896
/// The actual behavior is a little more complicated. The Microsoft compiler
10897
/// won't check outer classes if there is an active value from #pragma code_seg.
10898
/// The CodeSeg is always applied from the direct parent but only from outer
10899
/// classes when the #pragma code_seg stack is empty. See:
10900
/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10901
/// available since MS has removed the page.
10902
36.8M
static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10903
36.8M
  const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10904
36.8M
  if (!Method)
10905
34.6M
    return nullptr;
10906
2.17M
  const CXXRecordDecl *Parent = Method->getParent();
10907
2.17M
  if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10908
96
    Attr *NewAttr = SAttr->clone(S.getASTContext());
10909
96
    NewAttr->setImplicit(true);
10910
96
    return NewAttr;
10911
96
  }
10912
10913
  // The Microsoft compiler won't check outer classes for the CodeSeg
10914
  // when the #pragma code_seg stack is active.
10915
2.17M
  if (S.CodeSegStack.CurrentValue)
10916
30
   return nullptr;
10917
10918
2.22M
  
while (2.17M
(Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10919
45.0k
    if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10920
12
      Attr *NewAttr = SAttr->clone(S.getASTContext());
10921
12
      NewAttr->setImplicit(true);
10922
12
      return NewAttr;
10923
12
    }
10924
45.0k
  }
10925
2.17M
  return nullptr;
10926
2.17M
}
10927
10928
/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10929
/// containing class. Otherwise it will return implicit SectionAttr if the
10930
/// function is a definition and there is an active value on CodeSegStack
10931
/// (from the current #pragma code-seg value).
10932
///
10933
/// \param FD Function being declared.
10934
/// \param IsDefinition Whether it is a definition or just a declaration.
10935
/// \returns A CodeSegAttr or SectionAttr to apply to the function or
10936
///          nullptr if no attribute should be added.
10937
Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10938
36.8M
                                                       bool IsDefinition) {
10939
36.8M
  if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10940
108
    return A;
10941
36.8M
  if (!FD->hasAttr<SectionAttr>() && 
IsDefinition36.8M
&&
10942
36.8M
      
CodeSegStack.CurrentValue5.95M
)
10943
7
    return SectionAttr::CreateImplicit(
10944
7
        getASTContext(), CodeSegStack.CurrentValue->getString(),
10945
7
        CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10946
36.8M
  return nullptr;
10947
36.8M
}
10948
10949
/// Determines if we can perform a correct type check for \p D as a
10950
/// redeclaration of \p PrevDecl. If not, we can generally still perform a
10951
/// best-effort check.
10952
///
10953
/// \param NewD The new declaration.
10954
/// \param OldD The old declaration.
10955
/// \param NewT The portion of the type of the new declaration to check.
10956
/// \param OldT The portion of the type of the old declaration to check.
10957
bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10958
173
                                          QualType NewT, QualType OldT) {
10959
173
  if (!NewD->getLexicalDeclContext()->isDependentContext())
10960
116
    return true;
10961
10962
  // For dependently-typed local extern declarations and friends, we can't
10963
  // perform a correct type check in general until instantiation:
10964
  //
10965
  //   int f();
10966
  //   template<typename T> void g() { T f(); }
10967
  //
10968
  // (valid if g() is only instantiated with T = int).
10969
57
  if (NewT->isDependentType() &&
10970
57
      
(45
NewD->isLocalExternDecl()45
||
NewD->getFriendObjectKind()42
))
10971
45
    return false;
10972
10973
  // Similarly, if the previous declaration was a dependent local extern
10974
  // declaration, we don't really know its type yet.
10975
12
  if (OldT->isDependentType() && 
OldD->isLocalExternDecl()0
)
10976
0
    return false;
10977
10978
12
  return true;
10979
12
}
10980
10981
/// Checks if the new declaration declared in dependent context must be
10982
/// put in the same redeclaration chain as the specified declaration.
10983
///
10984
/// \param D Declaration that is checked.
10985
/// \param PrevDecl Previous declaration found with proper lookup method for the
10986
///                 same declaration name.
10987
/// \returns True if D must be added to the redeclaration chain which PrevDecl
10988
///          belongs to.
10989
///
10990
356k
bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10991
356k
  if (!D->getLexicalDeclContext()->isDependentContext())
10992
356k
    return true;
10993
10994
  // Don't chain dependent friend function definitions until instantiation, to
10995
  // permit cases like
10996
  //
10997
  //   void func();
10998
  //   template<typename T> class C1 { friend void func() {} };
10999
  //   template<typename T> class C2 { friend void func() {} };
11000
  //
11001
  // ... which is valid if only one of C1 and C2 is ever instantiated.
11002
  //
11003
  // FIXME: This need only apply to function definitions. For now, we proxy
11004
  // this by checking for a file-scope function. We do not want this to apply
11005
  // to friend declarations nominating member functions, because that gets in
11006
  // the way of access checks.
11007
242
  if (D->getFriendObjectKind() && 
D->getDeclContext()->isFileContext()240
)
11008
222
    return false;
11009
11010
20
  auto *VD = dyn_cast<ValueDecl>(D);
11011
20
  auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11012
20
  return !VD || !PrevVD ||
11013
20
         canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11014
20
                                        PrevVD->getType());
11015
242
}
11016
11017
/// Check the target or target_version attribute of the function for
11018
/// MultiVersion validity.
11019
///
11020
/// Returns true if there was an error, false otherwise.
11021
420
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11022
420
  const auto *TA = FD->getAttr<TargetAttr>();
11023
420
  const auto *TVA = FD->getAttr<TargetVersionAttr>();
11024
420
  assert(
11025
420
      (TA || TVA) &&
11026
420
      "MultiVersion candidate requires a target or target_version attribute");
11027
420
  const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11028
420
  enum ErrType { Feature = 0, Architecture = 1 };
11029
11030
420
  if (TA) {
11031
369
    ParsedTargetAttr ParseInfo =
11032
369
        S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11033
369
    if (!ParseInfo.CPU.empty() && 
!TargetInfo.validateCpuIs(ParseInfo.CPU)172
) {
11034
0
      S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11035
0
          << Architecture << ParseInfo.CPU;
11036
0
      return true;
11037
0
    }
11038
369
    for (const auto &Feat : ParseInfo.Features) {
11039
110
      auto BareFeat = StringRef{Feat}.substr(1);
11040
110
      if (Feat[0] == '-') {
11041
1
        S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11042
1
            << Feature << ("no-" + BareFeat).str();
11043
1
        return true;
11044
1
      }
11045
11046
109
      if (!TargetInfo.validateCpuSupports(BareFeat) ||
11047
109
          !TargetInfo.isValidFeatureName(BareFeat)) {
11048
0
        S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11049
0
            << Feature << BareFeat;
11050
0
        return true;
11051
0
      }
11052
109
    }
11053
369
  }
11054
11055
419
  if (TVA) {
11056
51
    llvm::SmallVector<StringRef, 8> Feats;
11057
51
    TVA->getFeatures(Feats);
11058
79
    for (const auto &Feat : Feats) {
11059
79
      if (!TargetInfo.validateCpuSupports(Feat)) {
11060
0
        S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11061
0
            << Feature << Feat;
11062
0
        return true;
11063
0
      }
11064
79
    }
11065
51
  }
11066
419
  return false;
11067
419
}
11068
11069
// Provide a white-list of attributes that are allowed to be combined with
11070
// multiversion functions.
11071
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11072
36
                                           MultiVersionKind MVKind) {
11073
  // Note: this list/diagnosis must match the list in
11074
  // checkMultiversionAttributesAllSame.
11075
36
  switch (Kind) {
11076
23
  default:
11077
23
    return false;
11078
7
  case attr::Used:
11079
7
    return MVKind == MultiVersionKind::Target;
11080
3
  case attr::NonNull:
11081
6
  case attr::NoThrow:
11082
6
    return true;
11083
36
  }
11084
36
}
11085
11086
static bool checkNonMultiVersionCompatAttributes(Sema &S,
11087
                                                 const FunctionDecl *FD,
11088
                                                 const FunctionDecl *CausedFD,
11089
933
                                                 MultiVersionKind MVKind) {
11090
933
  const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11091
24
    S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11092
24
        << static_cast<unsigned>(MVKind) << A;
11093
24
    if (CausedFD)
11094
4
      S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11095
24
    return true;
11096
24
  };
11097
11098
933
  for (const Attr *A : FD->attrs()) {
11099
923
    switch (A->getKind()) {
11100
58
    case attr::CPUDispatch:
11101
321
    case attr::CPUSpecific:
11102
321
      if (MVKind != MultiVersionKind::CPUDispatch &&
11103
321
          
MVKind != MultiVersionKind::CPUSpecific263
)
11104
0
        return Diagnose(S, A);
11105
321
      break;
11106
403
    case attr::Target:
11107
403
      if (MVKind != MultiVersionKind::Target)
11108
0
        return Diagnose(S, A);
11109
403
      break;
11110
403
    case attr::TargetVersion:
11111
79
      if (MVKind != MultiVersionKind::TargetVersion)
11112
0
        return Diagnose(S, A);
11113
79
      break;
11114
84
    case attr::TargetClones:
11115
84
      if (MVKind != MultiVersionKind::TargetClones)
11116
0
        return Diagnose(S, A);
11117
84
      break;
11118
84
    default:
11119
36
      if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11120
24
        return Diagnose(S, A);
11121
12
      break;
11122
923
    }
11123
923
  }
11124
909
  return false;
11125
933
}
11126
11127
bool Sema::areMultiversionVariantFunctionsCompatible(
11128
    const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11129
    const PartialDiagnostic &NoProtoDiagID,
11130
    const PartialDiagnosticAt &NoteCausedDiagIDAt,
11131
    const PartialDiagnosticAt &NoSupportDiagIDAt,
11132
    const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11133
2.85k
    bool ConstexprSupported, bool CLinkageMayDiffer) {
11134
2.85k
  enum DoesntSupport {
11135
2.85k
    FuncTemplates = 0,
11136
2.85k
    VirtFuncs = 1,
11137
2.85k
    DeducedReturn = 2,
11138
2.85k
    Constructors = 3,
11139
2.85k
    Destructors = 4,
11140
2.85k
    DeletedFuncs = 5,
11141
2.85k
    DefaultedFuncs = 6,
11142
2.85k
    ConstexprFuncs = 7,
11143
2.85k
    ConstevalFuncs = 8,
11144
2.85k
    Lambda = 9,
11145
2.85k
  };
11146
2.85k
  enum Different {
11147
2.85k
    CallingConv = 0,
11148
2.85k
    ReturnType = 1,
11149
2.85k
    ConstexprSpec = 2,
11150
2.85k
    InlineSpec = 3,
11151
2.85k
    Linkage = 4,
11152
2.85k
    LanguageLinkage = 5,
11153
2.85k
  };
11154
11155
2.85k
  if (NoProtoDiagID.getDiagID() != 0 && 
OldFD761
&&
11156
2.85k
      
!OldFD->getType()->getAs<FunctionProtoType>()463
) {
11157
2
    Diag(OldFD->getLocation(), NoProtoDiagID);
11158
2
    Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11159
2
    return true;
11160
2
  }
11161
11162
2.85k
  if (NoProtoDiagID.getDiagID() != 0 &&
11163
2.85k
      
!NewFD->getType()->getAs<FunctionProtoType>()759
)
11164
1
    return Diag(NewFD->getLocation(), NoProtoDiagID);
11165
11166
2.85k
  if (!TemplatesSupported &&
11167
2.85k
      
NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate758
)
11168
10
    return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11169
10
           << FuncTemplates;
11170
11171
2.84k
  if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11172
465
    if (NewCXXFD->isVirtual())
11173
10
      return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11174
10
             << VirtFuncs;
11175
11176
455
    if (isa<CXXConstructorDecl>(NewCXXFD))
11177
2
      return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11178
2
             << Constructors;
11179
11180
453
    if (isa<CXXDestructorDecl>(NewCXXFD))
11181
2
      return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11182
2
             << Destructors;
11183
453
  }
11184
11185
2.82k
  if (NewFD->isDeleted())
11186
2
    return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11187
2
           << DeletedFuncs;
11188
11189
2.82k
  if (NewFD->isDefaulted())
11190
2
    return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11191
2
           << DefaultedFuncs;
11192
11193
2.82k
  if (!ConstexprSupported && 
NewFD->isConstexpr()2.39k
)
11194
6
    return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11195
6
           << (NewFD->isConsteval() ? 
ConstevalFuncs0
: ConstexprFuncs);
11196
11197
2.81k
  QualType NewQType = Context.getCanonicalType(NewFD->getType());
11198
2.81k
  const auto *NewType = cast<FunctionType>(NewQType);
11199
2.81k
  QualType NewReturnType = NewType->getReturnType();
11200
11201
2.81k
  if (NewReturnType->isUndeducedType())
11202
1
    return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11203
1
           << DeducedReturn;
11204
11205
  // Ensure the return type is identical.
11206
2.81k
  if (OldFD) {
11207
2.53k
    QualType OldQType = Context.getCanonicalType(OldFD->getType());
11208
2.53k
    const auto *OldType = cast<FunctionType>(OldQType);
11209
2.53k
    FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11210
2.53k
    FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11211
11212
2.53k
    if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11213
3
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11214
11215
2.53k
    QualType OldReturnType = OldType->getReturnType();
11216
11217
2.53k
    if (OldReturnType != NewReturnType)
11218
10
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11219
11220
2.52k
    if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11221
4
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11222
11223
2.52k
    if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11224
12
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11225
11226
2.50k
    if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11227
13
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11228
11229
2.49k
    if (!CLinkageMayDiffer && 
OldFD->isExternC() != NewFD->isExternC()429
)
11230
3
      return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11231
11232
2.49k
    if (CheckEquivalentExceptionSpec(
11233
2.49k
            OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11234
2.49k
            NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11235
11
      return true;
11236
2.49k
  }
11237
2.76k
  return false;
11238
2.81k
}
11239
11240
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11241
                                             const FunctionDecl *NewFD,
11242
                                             bool CausesMV,
11243
792
                                             MultiVersionKind MVKind) {
11244
792
  if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11245
4
    S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11246
4
    if (OldFD)
11247
2
      S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11248
4
    return true;
11249
4
  }
11250
11251
788
  bool IsCPUSpecificCPUDispatchMVKind =
11252
788
      MVKind == MultiVersionKind::CPUDispatch ||
11253
788
      
MVKind == MultiVersionKind::CPUSpecific730
;
11254
11255
788
  if (CausesMV && 
OldFD462
&&
11256
788
      
checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)149
)
11257
4
    return true;
11258
11259
784
  if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11260
20
    return true;
11261
11262
  // Only allow transition to MultiVersion if it hasn't been used.
11263
764
  if (OldFD && 
CausesMV466
&&
OldFD->isUsed(false)143
)
11264
3
    return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11265
11266
761
  return S.areMultiversionVariantFunctionsCompatible(
11267
761
      OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11268
761
      PartialDiagnosticAt(NewFD->getLocation(),
11269
761
                          S.PDiag(diag::note_multiversioning_caused_here)),
11270
761
      PartialDiagnosticAt(NewFD->getLocation(),
11271
761
                          S.PDiag(diag::err_multiversion_doesnt_support)
11272
761
                              << static_cast<unsigned>(MVKind)),
11273
761
      PartialDiagnosticAt(NewFD->getLocation(),
11274
761
                          S.PDiag(diag::err_multiversion_diff)),
11275
761
      /*TemplatesSupported=*/false,
11276
761
      /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11277
761
      /*CLinkageMayDiffer=*/false);
11278
764
}
11279
11280
/// Check the validity of a multiversion function declaration that is the
11281
/// first of its kind. Also sets the multiversion'ness' of the function itself.
11282
///
11283
/// This sets NewFD->isInvalidDecl() to true if there was an error.
11284
///
11285
/// Returns true if there was an error, false otherwise.
11286
1.59M
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11287
1.59M
  MultiVersionKind MVKind = FD->getMultiVersionKind();
11288
1.59M
  assert(MVKind != MultiVersionKind::None &&
11289
1.59M
         "Function lacks multiversion attribute");
11290
1.59M
  const auto *TA = FD->getAttr<TargetAttr>();
11291
1.59M
  const auto *TVA = FD->getAttr<TargetVersionAttr>();
11292
  // Target and target_version only causes MV if it is default, otherwise this
11293
  // is a normal function.
11294
1.59M
  if ((TA && 
!TA->isDefaultVersion()1.59M
) ||
(365
TVA365
&&
!TVA->isDefaultVersion()50
))
11295
1.59M
    return false;
11296
11297
315
  if ((TA || 
TVA272
) &&
CheckMultiVersionValue(S, FD)43
) {
11298
0
    FD->setInvalidDecl();
11299
0
    return true;
11300
0
  }
11301
11302
315
  if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11303
35
    FD->setInvalidDecl();
11304
35
    return true;
11305
35
  }
11306
11307
280
  FD->setIsMultiVersion();
11308
280
  return false;
11309
315
}
11310
11311
94
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11312
97
  for (const Decl *D = FD->getPreviousDecl(); D; 
D = D->getPreviousDecl()3
) {
11313
6
    if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11314
3
      return true;
11315
6
  }
11316
11317
91
  return false;
11318
94
}
11319
11320
static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11321
                                             FunctionDecl *NewFD,
11322
                                             bool &Redeclaration,
11323
                                             NamedDecl *&OldDecl,
11324
147
                                             LookupResult &Previous) {
11325
147
  const auto *NewTA = NewFD->getAttr<TargetAttr>();
11326
147
  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11327
147
  const auto *OldTA = OldFD->getAttr<TargetAttr>();
11328
147
  const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11329
  // If the old decl is NOT MultiVersioned yet, and we don't cause that
11330
  // to change, this is a simple redeclaration.
11331
147
  if ((NewTA && 
!NewTA->isDefaultVersion()118
&&
11332
147
       
(100
!OldTA100
||
OldTA->getFeaturesStr() == NewTA->getFeaturesStr()94
)) ||
11333
147
      
(139
NewTVA139
&&
!NewTVA->isDefaultVersion()29
&&
11334
139
       
(29
!OldTVA29
||
OldTVA->getName() == NewTVA->getName()27
)))
11335
11
    return false;
11336
11337
  // Otherwise, this decl causes MultiVersioning.
11338
136
  if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11339
136
                                       NewTVA ? 
MultiVersionKind::TargetVersion26
11340
136
                                              : 
MultiVersionKind::Target110
)) {
11341
40
    NewFD->setInvalidDecl();
11342
40
    return true;
11343
40
  }
11344
11345
96
  if (CheckMultiVersionValue(S, NewFD)) {
11346
0
    NewFD->setInvalidDecl();
11347
0
    return true;
11348
0
  }
11349
11350
  // If this is 'default', permit the forward declaration.
11351
96
  if (!OldFD->isMultiVersion() &&
11352
96
      ((NewTA && 
NewTA->isDefaultVersion()84
&&
!OldTA15
) ||
11353
96
       
(91
NewTVA91
&&
NewTVA->isDefaultVersion()12
&&
!OldTVA0
))) {
11354
5
    Redeclaration = true;
11355
5
    OldDecl = OldFD;
11356
5
    OldFD->setIsMultiVersion();
11357
5
    NewFD->setIsMultiVersion();
11358
5
    return false;
11359
5
  }
11360
11361
91
  if (CheckMultiVersionValue(S, OldFD)) {
11362
0
    S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11363
0
    NewFD->setInvalidDecl();
11364
0
    return true;
11365
0
  }
11366
11367
91
  if (NewTA) {
11368
79
    ParsedTargetAttr OldParsed =
11369
79
        S.getASTContext().getTargetInfo().parseTargetAttr(
11370
79
            OldTA->getFeaturesStr());
11371
79
    llvm::sort(OldParsed.Features);
11372
79
    ParsedTargetAttr NewParsed =
11373
79
        S.getASTContext().getTargetInfo().parseTargetAttr(
11374
79
            NewTA->getFeaturesStr());
11375
    // Sort order doesn't matter, it just needs to be consistent.
11376
79
    llvm::sort(NewParsed.Features);
11377
79
    if (OldParsed == NewParsed) {
11378
1
      S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11379
1
      S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11380
1
      NewFD->setInvalidDecl();
11381
1
      return true;
11382
1
    }
11383
79
  }
11384
11385
90
  if (NewTVA) {
11386
12
    llvm::SmallVector<StringRef, 8> Feats;
11387
12
    OldTVA->getFeatures(Feats);
11388
12
    llvm::sort(Feats);
11389
12
    llvm::SmallVector<StringRef, 8> NewFeats;
11390
12
    NewTVA->getFeatures(NewFeats);
11391
12
    llvm::sort(NewFeats);
11392
11393
12
    if (Feats == NewFeats) {
11394
1
      S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11395
1
      S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11396
1
      NewFD->setInvalidDecl();
11397
1
      return true;
11398
1
    }
11399
12
  }
11400
11401
94
  
for (const auto *FD : OldFD->redecls())89
{
11402
94
    const auto *CurTA = FD->getAttr<TargetAttr>();
11403
94
    const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11404
    // We allow forward declarations before ANY multiversioning attributes, but
11405
    // nothing after the fact.
11406
94
    if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11407
94
        
(3
(3
NewTA3
&&
(3
!CurTA3
||
CurTA->isInherited()3
)) ||
11408
3
         
(2
NewTVA2
&&
(0
!CurTVA0
||
CurTVA->isInherited()0
)))) {
11409
1
      S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11410
1
          << (NewTA ? 0 : 
20
);
11411
1
      S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11412
1
      NewFD->setInvalidDecl();
11413
1
      return true;
11414
1
    }
11415
94
  }
11416
11417
88
  OldFD->setIsMultiVersion();
11418
88
  NewFD->setIsMultiVersion();
11419
88
  Redeclaration = false;
11420
88
  OldDecl = nullptr;
11421
88
  Previous.clear();
11422
88
  return false;
11423
89
}
11424
11425
static bool MultiVersionTypesCompatible(MultiVersionKind Old,
11426
400
                                        MultiVersionKind New) {
11427
400
  if (Old == New || 
Old == MultiVersionKind::None70
||
11428
400
      
New == MultiVersionKind::None48
)
11429
364
    return true;
11430
11431
36
  return (Old == MultiVersionKind::CPUDispatch &&
11432
36
          
New == MultiVersionKind::CPUSpecific12
) ||
11433
36
         
(24
Old == MultiVersionKind::CPUSpecific24
&&
11434
24
          
New == MultiVersionKind::CPUDispatch21
);
11435
400
}
11436
11437
/// Check the validity of a new function declaration being added to an existing
11438
/// multiversioned declaration collection.
11439
static bool CheckMultiVersionAdditionalDecl(
11440
    Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11441
    MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11442
    const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11443
400
    bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11444
400
  const auto *NewTA = NewFD->getAttr<TargetAttr>();
11445
400
  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11446
400
  MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11447
  // Disallow mixing of multiversioning types.
11448
400
  if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11449
3
    S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11450
3
    S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11451
3
    NewFD->setInvalidDecl();
11452
3
    return true;
11453
3
  }
11454
11455
397
  ParsedTargetAttr NewParsed;
11456
397
  if (NewTA) {
11457
187
    NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11458
187
        NewTA->getFeaturesStr());
11459
187
    llvm::sort(NewParsed.Features);
11460
187
  }
11461
397
  llvm::SmallVector<StringRef, 8> NewFeats;
11462
397
  if (NewTVA) {
11463
27
    NewTVA->getFeatures(NewFeats);
11464
27
    llvm::sort(NewFeats);
11465
27
  }
11466
11467
397
  bool UseMemberUsingDeclRules =
11468
397
      S.CurContext->isRecord() && 
!NewFD->getFriendObjectKind()33
;
11469
11470
397
  bool MayNeedOverloadableChecks =
11471
397
      AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11472
11473
  // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11474
  // of a previous member of the MultiVersion set.
11475
2.53k
  for (NamedDecl *ND : Previous) {
11476
2.53k
    FunctionDecl *CurFD = ND->getAsFunction();
11477
2.53k
    if (!CurFD || CurFD->isInvalidDecl())
11478
6
      continue;
11479
2.52k
    if (MayNeedOverloadableChecks &&
11480
2.52k
        
S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)370
)
11481
89
      continue;
11482
11483
2.44k
    if (NewMVKind == MultiVersionKind::None &&
11484
2.44k
        
OldMVKind == MultiVersionKind::TargetVersion12
) {
11485
9
      NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11486
9
          S.Context, "default", NewFD->getSourceRange()));
11487
9
      NewFD->setIsMultiVersion();
11488
9
      NewMVKind = MultiVersionKind::TargetVersion;
11489
9
      if (!NewTVA) {
11490
9
        NewTVA = NewFD->getAttr<TargetVersionAttr>();
11491
9
        NewTVA->getFeatures(NewFeats);
11492
9
        llvm::sort(NewFeats);
11493
9
      }
11494
9
    }
11495
11496
2.44k
    switch (NewMVKind) {
11497
3
    case MultiVersionKind::None:
11498
3
      assert(OldMVKind == MultiVersionKind::TargetClones &&
11499
3
             "Only target_clones can be omitted in subsequent declarations");
11500
3
      break;
11501
1.04k
    case MultiVersionKind::Target: {
11502
1.04k
      const auto *CurTA = CurFD->getAttr<TargetAttr>();
11503
1.04k
      if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11504
24
        NewFD->setIsMultiVersion();
11505
24
        Redeclaration = true;
11506
24
        OldDecl = ND;
11507
24
        return false;
11508
24
      }
11509
11510
1.01k
      ParsedTargetAttr CurParsed =
11511
1.01k
          S.getASTContext().getTargetInfo().parseTargetAttr(
11512
1.01k
              CurTA->getFeaturesStr());
11513
1.01k
      llvm::sort(CurParsed.Features);
11514
1.01k
      if (CurParsed == NewParsed) {
11515
0
        S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11516
0
        S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11517
0
        NewFD->setInvalidDecl();
11518
0
        return true;
11519
0
      }
11520
1.01k
      break;
11521
1.01k
    }
11522
1.01k
    case MultiVersionKind::TargetVersion: {
11523
155
      const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11524
155
      if (CurTVA->getName() == NewTVA->getName()) {
11525
9
        NewFD->setIsMultiVersion();
11526
9
        Redeclaration = true;
11527
9
        OldDecl = ND;
11528
9
        return false;
11529
9
      }
11530
146
      llvm::SmallVector<StringRef, 8> CurFeats;
11531
146
      if (CurTVA) {
11532
146
        CurTVA->getFeatures(CurFeats);
11533
146
        llvm::sort(CurFeats);
11534
146
      }
11535
146
      if (CurFeats == NewFeats) {
11536
0
        S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11537
0
        S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11538
0
        NewFD->setInvalidDecl();
11539
0
        return true;
11540
0
      }
11541
146
      break;
11542
146
    }
11543
146
    case MultiVersionKind::TargetClones: {
11544
14
      const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11545
14
      Redeclaration = true;
11546
14
      OldDecl = CurFD;
11547
14
      NewFD->setIsMultiVersion();
11548
11549
14
      if (CurClones && 
NewClones11
&&
11550
14
          
(11
CurClones->featuresStrs_size() != NewClones->featuresStrs_size()11
||
11551
11
           !std::equal(CurClones->featuresStrs_begin(),
11552
10
                       CurClones->featuresStrs_end(),
11553
10
                       NewClones->featuresStrs_begin()))) {
11554
3
        S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11555
3
        S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11556
3
        NewFD->setInvalidDecl();
11557
3
        return true;
11558
3
      }
11559
11560
11
      return false;
11561
14
    }
11562
1.18k
    case MultiVersionKind::CPUSpecific:
11563
1.22k
    case MultiVersionKind::CPUDispatch: {
11564
1.22k
      const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11565
1.22k
      const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11566
      // Handle CPUDispatch/CPUSpecific versions.
11567
      // Only 1 CPUDispatch function is allowed, this will make it go through
11568
      // the redeclaration errors.
11569
1.22k
      if (NewMVKind == MultiVersionKind::CPUDispatch &&
11570
1.22k
          
CurFD->hasAttr<CPUDispatchAttr>()39
) {
11571
3
        if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11572
3
            std::equal(
11573
3
                CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11574
3
                NewCPUDisp->cpus_begin(),
11575
3
                [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11576
3
                  return Cur->getName() == New->getName();
11577
3
                })) {
11578
2
          NewFD->setIsMultiVersion();
11579
2
          Redeclaration = true;
11580
2
          OldDecl = ND;
11581
2
          return false;
11582
2
        }
11583
11584
        // If the declarations don't match, this is an error condition.
11585
1
        S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11586
1
        S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11587
1
        NewFD->setInvalidDecl();
11588
1
        return true;
11589
3
      }
11590
1.22k
      if (NewMVKind == MultiVersionKind::CPUSpecific && 
CurCPUSpec1.18k
) {
11591
1.16k
        if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11592
1.16k
            std::equal(
11593
1.15k
                CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11594
1.15k
                NewCPUSpec->cpus_begin(),
11595
1.15k
                [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11596
1.15k
                  return Cur->getName() == New->getName();
11597
1.15k
                })) {
11598
3
          NewFD->setIsMultiVersion();
11599
3
          Redeclaration = true;
11600
3
          OldDecl = ND;
11601
3
          return false;
11602
3
        }
11603
11604
        // Only 1 version of CPUSpecific is allowed for each CPU.
11605
1.15k
        
for (const IdentifierInfo *CurII : CurCPUSpec->cpus())1.15k
{
11606
1.16k
          for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11607
1.16k
            if (CurII == NewII) {
11608
2
              S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11609
2
                  << NewII;
11610
2
              S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11611
2
              NewFD->setInvalidDecl();
11612
2
              return true;
11613
2
            }
11614
1.16k
          }
11615
1.15k
        }
11616
1.15k
      }
11617
1.21k
      break;
11618
1.22k
    }
11619
2.44k
    }
11620
2.44k
  }
11621
11622
  // Else, this is simply a non-redecl case.  Checking the 'value' is only
11623
  // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11624
  // handled in the attribute adding step.
11625
342
  if ((NewMVKind == MultiVersionKind::TargetVersion ||
11626
342
       
NewMVKind == MultiVersionKind::Target315
) &&
11627
342
      
CheckMultiVersionValue(S, NewFD)190
) {
11628
1
    NewFD->setInvalidDecl();
11629
1
    return true;
11630
1
  }
11631
11632
341
  if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11633
341
                                       !OldFD->isMultiVersion(), NewMVKind)) {
11634
14
    NewFD->setInvalidDecl();
11635
14
    return true;
11636
14
  }
11637
11638
  // Permit forward declarations in the case where these two are compatible.
11639
327
  if (!OldFD->isMultiVersion()) {
11640
14
    OldFD->setIsMultiVersion();
11641
14
    NewFD->setIsMultiVersion();
11642
14
    Redeclaration = true;
11643
14
    OldDecl = OldFD;
11644
14
    return false;
11645
14
  }
11646
11647
313
  NewFD->setIsMultiVersion();
11648
313
  Redeclaration = false;
11649
313
  OldDecl = nullptr;
11650
313
  Previous.clear();
11651
313
  return false;
11652
327
}
11653
11654
/// Check the validity of a mulitversion function declaration.
11655
/// Also sets the multiversion'ness' of the function itself.
11656
///
11657
/// This sets NewFD->isInvalidDecl() to true if there was an error.
11658
///
11659
/// Returns true if there was an error, false otherwise.
11660
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11661
                                      bool &Redeclaration, NamedDecl *&OldDecl,
11662
38.8M
                                      LookupResult &Previous) {
11663
38.8M
  const auto *NewTA = NewFD->getAttr<TargetAttr>();
11664
38.8M
  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11665
38.8M
  const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11666
38.8M
  const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11667
38.8M
  const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11668
38.8M
  MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11669
11670
  // Main isn't allowed to become a multiversion function, however it IS
11671
  // permitted to have 'main' be marked with the 'target' optimization hint,
11672
  // for 'target_version' only default is allowed.
11673
38.8M
  if (NewFD->isMain()) {
11674
10.3k
    if (MVKind != MultiVersionKind::None &&
11675
10.3k
        
!(2
MVKind == MultiVersionKind::Target2
&&
!NewTA->isDefaultVersion()0
) &&
11676
10.3k
        
!(2
MVKind == MultiVersionKind::TargetVersion2
&&
11677
2
          
NewTVA->isDefaultVersion()1
)) {
11678
2
      S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11679
2
      NewFD->setInvalidDecl();
11680
2
      return true;
11681
2
    }
11682
10.3k
    return false;
11683
10.3k
  }
11684
11685
  // Target attribute on AArch64 is not used for multiversioning
11686
38.8M
  if (NewTA && 
S.getASTContext().getTargetInfo().getTriple().isAArch64()2.88M
)
11687
1.28M
    return false;
11688
11689
37.5M
  if (!OldDecl || 
!OldDecl->getAsFunction()440k
||
11690
37.5M
      OldDecl->getDeclContext()->getRedeclContext() !=
11691
37.1M
          NewFD->getDeclContext()->getRedeclContext()) {
11692
    // If there's no previous declaration, AND this isn't attempting to cause
11693
    // multiversioning, this isn't an error condition.
11694
37.1M
    if (MVKind == MultiVersionKind::None)
11695
35.5M
      return false;
11696
1.59M
    return CheckMultiVersionFirstFunction(S, NewFD);
11697
37.1M
  }
11698
11699
427k
  FunctionDecl *OldFD = OldDecl->getAsFunction();
11700
11701
427k
  if (!OldFD->isMultiVersion() && 
MVKind == MultiVersionKind::None427k
) {
11702
427k
    if (NewTVA || !OldFD->getAttr<TargetVersionAttr>())
11703
427k
      return false;
11704
10
    if (!NewFD->getType()->getAs<FunctionProtoType>()) {
11705
      // Multiversion declaration doesn't have prototype.
11706
1
      S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
11707
1
      NewFD->setInvalidDecl();
11708
9
    } else {
11709
      // No "target_version" attribute is equivalent to "default" attribute.
11710
9
      NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11711
9
          S.Context, "default", NewFD->getSourceRange()));
11712
9
      NewFD->setIsMultiVersion();
11713
9
      OldFD->setIsMultiVersion();
11714
9
      OldDecl = OldFD;
11715
9
      Redeclaration = true;
11716
9
    }
11717
10
    return true;
11718
427k
  }
11719
11720
  // Multiversioned redeclarations aren't allowed to omit the attribute, except
11721
  // for target_clones and target_version.
11722
554
  if (OldFD->isMultiVersion() && 
MVKind == MultiVersionKind::None385
&&
11723
554
      
OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones17
&&
11724
554
      
OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion14
) {
11725
5
    S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11726
5
        << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11727
5
    NewFD->setInvalidDecl();
11728
5
    return true;
11729
5
  }
11730
11731
549
  if (!OldFD->isMultiVersion()) {
11732
169
    switch (MVKind) {
11733
118
    case MultiVersionKind::Target:
11734
147
    case MultiVersionKind::TargetVersion:
11735
147
      return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11736
147
                                              OldDecl, Previous);
11737
7
    case MultiVersionKind::TargetClones:
11738
7
      if (OldFD->isUsed(false)) {
11739
2
        NewFD->setInvalidDecl();
11740
2
        return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11741
2
      }
11742
5
      OldFD->setIsMultiVersion();
11743
5
      break;
11744
11745
7
    case MultiVersionKind::CPUDispatch:
11746
15
    case MultiVersionKind::CPUSpecific:
11747
15
    case MultiVersionKind::None:
11748
15
      break;
11749
169
    }
11750
169
  }
11751
11752
  // At this point, we have a multiversion function decl (in OldFD) AND an
11753
  // appropriate attribute in the current function decl.  Resolve that these are
11754
  // still compatible with previous declarations.
11755
400
  return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11756
400
                                         NewCPUSpec, NewClones, Redeclaration,
11757
400
                                         OldDecl, Previous);
11758
549
}
11759
11760
/// Perform semantic checking of a new function declaration.
11761
///
11762
/// Performs semantic analysis of the new function declaration
11763
/// NewFD. This routine performs all semantic checking that does not
11764
/// require the actual declarator involved in the declaration, and is
11765
/// used both for the declaration of functions as they are parsed
11766
/// (called via ActOnDeclarator) and for the declaration of functions
11767
/// that have been instantiated via C++ template instantiation (called
11768
/// via InstantiateDecl).
11769
///
11770
/// \param IsMemberSpecialization whether this new function declaration is
11771
/// a member specialization (that replaces any definition provided by the
11772
/// previous declaration).
11773
///
11774
/// This sets NewFD->isInvalidDecl() to true if there was an error.
11775
///
11776
/// \returns true if the function declaration is a redeclaration.
11777
bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11778
                                    LookupResult &Previous,
11779
                                    bool IsMemberSpecialization,
11780
38.8M
                                    bool DeclIsDefn) {
11781
38.8M
  assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11782
38.8M
         "Variably modified return types are not handled here");
11783
11784
  // Determine whether the type of this function should be merged with
11785
  // a previous visible declaration. This never happens for functions in C++,
11786
  // and always happens in C if the previous declaration was visible.
11787
38.8M
  bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11788
38.8M
                               
!Previous.isShadowed()20.4M
;
11789
11790
38.8M
  bool Redeclaration = false;
11791
38.8M
  NamedDecl *OldDecl = nullptr;
11792
38.8M
  bool MayNeedOverloadableChecks = false;
11793
11794
  // Merge or overload the declaration with an existing declaration of
11795
  // the same name, if appropriate.
11796
38.8M
  if (!Previous.empty()) {
11797
    // Determine whether NewFD is an overload of PrevDecl or
11798
    // a declaration that requires merging. If it's an overload,
11799
    // there's no more work to do here; we'll just add the new
11800
    // function to the scope.
11801
15.2M
    if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11802
82.0k
      NamedDecl *Candidate = Previous.getRepresentativeDecl();
11803
82.0k
      if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11804
82.0k
        Redeclaration = true;
11805
82.0k
        OldDecl = Candidate;
11806
82.0k
      }
11807
15.1M
    } else {
11808
15.1M
      MayNeedOverloadableChecks = true;
11809
15.1M
      switch (CheckOverload(S, NewFD, Previous, OldDecl,
11810
15.1M
                            /*NewIsUsingDecl*/ false)) {
11811
357k
      case Ovl_Match:
11812
357k
        Redeclaration = true;
11813
357k
        break;
11814
11815
37
      case Ovl_NonFunction:
11816
37
        Redeclaration = true;
11817
37
        break;
11818
11819
14.7M
      case Ovl_Overload:
11820
14.7M
        Redeclaration = false;
11821
14.7M
        break;
11822
15.1M
      }
11823
15.1M
    }
11824
15.2M
  }
11825
11826
  // Check for a previous extern "C" declaration with this name.
11827
38.8M
  if (!Redeclaration &&
11828
38.8M
      
checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)38.4M
) {
11829
129
    if (!Previous.empty()) {
11830
      // This is an extern "C" declaration with the same name as a previous
11831
      // declaration, and thus redeclares that entity...
11832
129
      Redeclaration = true;
11833
129
      OldDecl = Previous.getFoundDecl();
11834
129
      MergeTypeWithPrevious = false;
11835
11836
      // ... except in the presence of __attribute__((overloadable)).
11837
129
      if (OldDecl->hasAttr<OverloadableAttr>() ||
11838
129
          
NewFD->hasAttr<OverloadableAttr>()113
) {
11839
17
        if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11840
14
          MayNeedOverloadableChecks = true;
11841
14
          Redeclaration = false;
11842
14
          OldDecl = nullptr;
11843
14
        }
11844
17
      }
11845
129
    }
11846
129
  }
11847
11848
38.8M
  if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11849
121
    return Redeclaration;
11850
11851
  // PPC MMA non-pointer types are not allowed as function return types.
11852
38.8M
  if (Context.getTargetInfo().getTriple().isPPC64() &&
11853
38.8M
      
CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())56.2k
) {
11854
20
    NewFD->setInvalidDecl();
11855
20
  }
11856
11857
  // C++11 [dcl.constexpr]p8:
11858
  //   A constexpr specifier for a non-static member function that is not
11859
  //   a constructor declares that member function to be const.
11860
  //
11861
  // This needs to be delayed until we know whether this is an out-of-line
11862
  // definition of a static member function.
11863
  //
11864
  // This rule is not present in C++1y, so we produce a backwards
11865
  // compatibility warning whenever it happens in C++11.
11866
38.8M
  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11867
38.8M
  if (!getLangOpts().CPlusPlus14 && 
MD25.6M
&&
MD->isConstexpr()3.41M
&&
11868
38.8M
      
!MD->isStatic()566k
&&
!isa<CXXConstructorDecl>(MD)352k
&&
11869
38.8M
      
!isa<CXXDestructorDecl>(MD)62.4k
&&
!MD->getMethodQualifiers().hasConst()62.4k
) {
11870
75
    CXXMethodDecl *OldMD = nullptr;
11871
75
    if (OldDecl)
11872
13
      OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11873
75
    if (!OldMD || 
!OldMD->isStatic()12
) {
11874
69
      const FunctionProtoType *FPT =
11875
69
        MD->getType()->castAs<FunctionProtoType>();
11876
69
      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11877
69
      EPI.TypeQuals.addConst();
11878
69
      MD->setType(Context.getFunctionType(FPT->getReturnType(),
11879
69
                                          FPT->getParamTypes(), EPI));
11880
11881
      // Warn that we did this, if we're not performing template instantiation.
11882
      // In that case, we'll have warned already when the template was defined.
11883
69
      if (!inTemplateInstantiation()) {
11884
27
        SourceLocation AddConstLoc;
11885
27
        if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11886
27
                .IgnoreParens().getAs<FunctionTypeLoc>())
11887
27
          AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11888
11889
27
        Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11890
27
          << FixItHint::CreateInsertion(AddConstLoc, " const");
11891
27
      }
11892
69
    }
11893
75
  }
11894
11895
38.8M
  if (Redeclaration) {
11896
    // NewFD and OldDecl represent declarations that need to be
11897
    // merged.
11898
439k
    if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11899
439k
                          DeclIsDefn)) {
11900
874
      NewFD->setInvalidDecl();
11901
874
      return Redeclaration;
11902
874
    }
11903
11904
438k
    Previous.clear();
11905
438k
    Previous.addDecl(OldDecl);
11906
11907
438k
    if (FunctionTemplateDecl *OldTemplateDecl =
11908
438k
            dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11909
82.1k
      auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11910
82.1k
      FunctionTemplateDecl *NewTemplateDecl
11911
82.1k
        = NewFD->getDescribedFunctionTemplate();
11912
82.1k
      assert(NewTemplateDecl && "Template/non-template mismatch");
11913
11914
      // The call to MergeFunctionDecl above may have created some state in
11915
      // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11916
      // can add it as a redeclaration.
11917
82.1k
      NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11918
11919
82.1k
      NewFD->setPreviousDeclaration(OldFD);
11920
82.1k
      if (NewFD->isCXXClassMember()) {
11921
52.7k
        NewFD->setAccess(OldTemplateDecl->getAccess());
11922
52.7k
        NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11923
52.7k
      }
11924
11925
      // If this is an explicit specialization of a member that is a function
11926
      // template, mark it as a member specialization.
11927
82.1k
      if (IsMemberSpecialization &&
11928
82.1k
          
NewTemplateDecl->getInstantiatedFromMemberTemplate()72
) {
11929
72
        NewTemplateDecl->setMemberSpecialization();
11930
72
        assert(OldTemplateDecl->isMemberSpecialization());
11931
        // Explicit specializations of a member template do not inherit deleted
11932
        // status from the parent member template that they are specializing.
11933
72
        if (OldFD->isDeleted()) {
11934
          // FIXME: This assert will not hold in the presence of modules.
11935
4
          assert(OldFD->getCanonicalDecl() == OldFD);
11936
          // FIXME: We need an update record for this AST mutation.
11937
4
          OldFD->setDeletedAsWritten(false);
11938
4
        }
11939
72
      }
11940
11941
356k
    } else {
11942
356k
      if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11943
356k
        auto *OldFD = cast<FunctionDecl>(OldDecl);
11944
        // This needs to happen first so that 'inline' propagates.
11945
356k
        NewFD->setPreviousDeclaration(OldFD);
11946
356k
        if (NewFD->isCXXClassMember())
11947
219k
          NewFD->setAccess(OldFD->getAccess());
11948
356k
      }
11949
356k
    }
11950
38.4M
  } else if (!getLangOpts().CPlusPlus && 
MayNeedOverloadableChecks20.3M
&&
11951
38.4M
             
!NewFD->getAttr<OverloadableAttr>()7.50M
) {
11952
28
    assert((Previous.empty() ||
11953
28
            llvm::any_of(Previous,
11954
28
                         [](const NamedDecl *ND) {
11955
28
                           return ND->hasAttr<OverloadableAttr>();
11956
28
                         })) &&
11957
28
           "Non-redecls shouldn't happen without overloadable present");
11958
11959
34
    
auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) 28
{
11960
34
      const auto *FD = dyn_cast<FunctionDecl>(ND);
11961
34
      return FD && !FD->hasAttr<OverloadableAttr>();
11962
34
    });
11963
11964
28
    if (OtherUnmarkedIter != Previous.end()) {
11965
7
      Diag(NewFD->getLocation(),
11966
7
           diag::err_attribute_overloadable_multiple_unmarked_overloads);
11967
7
      Diag((*OtherUnmarkedIter)->getLocation(),
11968
7
           diag::note_attribute_overloadable_prev_overload)
11969
7
          << false;
11970
11971
7
      NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11972
7
    }
11973
28
  }
11974
11975
38.8M
  if (LangOpts.OpenMP)
11976
174k
    ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11977
11978
  // Semantic checking for this function declaration (in isolation).
11979
11980
38.8M
  if (getLangOpts().CPlusPlus) {
11981
    // C++-specific checks.
11982
18.4M
    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11983
1.13M
      CheckConstructor(Constructor);
11984
17.2M
    } else if (CXXDestructorDecl *Destructor =
11985
17.2M
                   dyn_cast<CXXDestructorDecl>(NewFD)) {
11986
      // We check here for invalid destructor names.
11987
      // If we have a friend destructor declaration that is dependent, we can't
11988
      // diagnose right away because cases like this are still valid:
11989
      // template <class T> struct A { friend T::X::~Y(); };
11990
      // struct B { struct Y { ~Y(); }; using X = Y; };
11991
      // template struct A<B>;
11992
221k
      if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
11993
221k
          
!Destructor->getFunctionObjectParameterType()->isDependentType()47
) {
11994
221k
        CXXRecordDecl *Record = Destructor->getParent();
11995
221k
        QualType ClassType = Context.getTypeDeclType(Record);
11996
11997
221k
        DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
11998
221k
            Context.getCanonicalType(ClassType));
11999
221k
        if (NewFD->getDeclName() != Name) {
12000
15
          Diag(NewFD->getLocation(), diag::err_destructor_name);
12001
15
          NewFD->setInvalidDecl();
12002
15
          return Redeclaration;
12003
15
        }
12004
221k
      }
12005
17.0M
    } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12006
2.07k
      if (auto *TD = Guide->getDescribedFunctionTemplate())
12007
1.47k
        CheckDeductionGuideTemplate(TD);
12008
12009
      // A deduction guide is not on the list of entities that can be
12010
      // explicitly specialized.
12011
2.07k
      if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12012
4
        Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12013
4
            << /*explicit specialization*/ 1;
12014
2.07k
    }
12015
12016
    // Find any virtual functions that this function overrides.
12017
18.4M
    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12018
3.99M
      if (!Method->isFunctionTemplateSpecialization() &&
12019
3.99M
          
!Method->getDescribedFunctionTemplate()3.88M
&&
12020
3.99M
          
Method->isCanonicalDecl()3.23M
) {
12021
3.01M
        AddOverriddenMethods(Method->getParent(), Method);
12022
3.01M
      }
12023
3.99M
      if (Method->isVirtual() && 
NewFD->getTrailingRequiresClause()249k
)
12024
        // C++2a [class.virtual]p6
12025
        // A virtual method shall not have a requires-clause.
12026
4
        Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
12027
4
             diag::err_constrained_virtual_method);
12028
12029
3.99M
      if (Method->isStatic())
12030
407k
        checkThisInStaticMemberFunctionType(Method);
12031
3.99M
    }
12032
12033
    // C++20: dcl.decl.general p4:
12034
    // The optional requires-clause ([temp.pre]) in an init-declarator or
12035
    // member-declarator shall be present only if the declarator declares a
12036
    // templated function ([dcl.fct]).
12037
18.4M
    if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
12038
      // [temp.pre]/8:
12039
      // An entity is templated if it is
12040
      // - a template,
12041
      // - an entity defined ([basic.def]) or created ([class.temporary]) in a
12042
      // templated entity,
12043
      // - a member of a templated entity,
12044
      // - an enumerator for an enumeration that is a templated entity, or
12045
      // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
12046
      // appearing in the declaration of a templated entity. [Note 6: A local
12047
      // class, a local or block variable, or a friend function defined in a
12048
      // templated entity is a templated entity.  — end note]
12049
      //
12050
      // A templated function is a function template or a function that is
12051
      // templated. A templated class is a class template or a class that is
12052
      // templated. A templated variable is a variable template or a variable
12053
      // that is templated.
12054
12055
2.13k
      if (!NewFD->getDescribedFunctionTemplate() && // -a template
12056
          // defined... in a templated entity
12057
2.13k
          
!(1.50k
DeclIsDefn1.50k
&&
NewFD->isTemplated()693
) &&
12058
          // a member of a templated entity
12059
2.13k
          
!(815
isa<CXXMethodDecl>(NewFD)815
&&
NewFD->isTemplated()615
) &&
12060
          // Don't complain about instantiations, they've already had these
12061
          // rules + others enforced.
12062
2.13k
          
!NewFD->isTemplateInstantiation()744
) {
12063
12
        Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
12064
12
      }
12065
2.13k
    }
12066
12067
18.4M
    if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12068
33.4k
      ActOnConversionDeclarator(Conversion);
12069
12070
    // Extra checking for C++ overloaded operators (C++ [over.oper]).
12071
18.4M
    if (NewFD->isOverloadedOperator() &&
12072
18.4M
        
CheckOverloadedOperatorDeclaration(NewFD)824k
) {
12073
189
      NewFD->setInvalidDecl();
12074
189
      return Redeclaration;
12075
189
    }
12076
12077
    // Extra checking for C++0x literal operators (C++0x [over.literal]).
12078
18.4M
    if (NewFD->getLiteralIdentifier() &&
12079
18.4M
        
CheckLiteralOperatorDeclaration(NewFD)1.14k
) {
12080
39
      NewFD->setInvalidDecl();
12081
39
      return Redeclaration;
12082
39
    }
12083
12084
    // In C++, check default arguments now that we have merged decls. Unless
12085
    // the lexical context is the class, because in this case this is done
12086
    // during delayed parsing anyway.
12087
18.4M
    if (!CurContext->isRecord())
12088
14.7M
      CheckCXXDefaultArguments(NewFD);
12089
12090
    // If this function is declared as being extern "C", then check to see if
12091
    // the function returns a UDT (class, struct, or union type) that is not C
12092
    // compatible, and if it does, warn the user.
12093
    // But, issue any diagnostic on the first declaration only.
12094
18.4M
    if (Previous.empty() && 
NewFD->isExternC()10.7M
) {
12095
711k
      QualType R = NewFD->getReturnType();
12096
711k
      if (R->isIncompleteType() && 
!R->isVoidType()71.7k
)
12097
2
        Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12098
2
            << NewFD << R;
12099
711k
      else if (!R.isPODType(Context) && 
!R->isVoidType()71.8k
&&
12100
711k
               
!R->isObjCObjectPointerType()23
)
12101
23
        Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12102
711k
    }
12103
12104
    // C++1z [dcl.fct]p6:
12105
    //   [...] whether the function has a non-throwing exception-specification
12106
    //   [is] part of the function type
12107
    //
12108
    // This results in an ABI break between C++14 and C++17 for functions whose
12109
    // declared type includes an exception-specification in a parameter or
12110
    // return type. (Exception specifications on the function itself are OK in
12111
    // most cases, and exception specifications are not permitted in most other
12112
    // contexts where they could make it into a mangling.)
12113
18.4M
    if (!getLangOpts().CPlusPlus17 && 
!NewFD->getPrimaryTemplate()5.33M
) {
12114
12.3M
      auto HasNoexcept = [&](QualType T) -> bool {
12115
        // Strip off declarator chunks that could be between us and a function
12116
        // type. We don't need to look far, exception specifications are very
12117
        // restricted prior to C++17.
12118
12.3M
        if (auto *RT = T->getAs<ReferenceType>())
12119
2.77M
          T = RT->getPointeeType();
12120
9.62M
        else if (T->isAnyPointerType())
12121
1.95M
          T = T->getPointeeType();
12122
7.66M
        else if (auto *MPT = T->getAs<MemberPointerType>())
12123
5.33k
          T = MPT->getPointeeType();
12124
12.3M
        if (auto *FPT = T->getAs<FunctionProtoType>())
12125
50.4k
          if (FPT->isNothrow())
12126
38
            return true;
12127
12.3M
        return false;
12128
12.3M
      };
12129
12130
5.05M
      auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12131
5.05M
      bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12132
5.05M
      for (QualType T : FPT->param_types())
12133
7.33M
        AnyNoexcept |= HasNoexcept(T);
12134
5.05M
      if (AnyNoexcept)
12135
36
        Diag(NewFD->getLocation(),
12136
36
             diag::warn_cxx17_compat_exception_spec_in_signature)
12137
36
            << NewFD;
12138
5.05M
    }
12139
12140
18.4M
    if (!Redeclaration && 
LangOpts.CUDA18.0M
)
12141
20.1k
      checkCUDATargetOverload(NewFD, Previous);
12142
18.4M
  }
12143
12144
  // Check if the function definition uses any AArch64 SME features without
12145
  // having the '+sme' feature enabled.
12146
38.8M
  if (DeclIsDefn) {
12147
6.30M
    bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12148
6.30M
    bool UsesZA = NewFD->hasAttr<ArmNewZAAttr>();
12149
6.30M
    if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12150
6.29M
      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12151
6.29M
      UsesSM |=
12152
6.29M
          EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
12153
6.29M
      UsesZA |= EPI.AArch64SMEAttributes & FunctionType::SME_PStateZASharedMask;
12154
6.29M
    }
12155
12156
6.30M
    if (UsesSM || 
UsesZA6.29M
) {
12157
873
      llvm::StringMap<bool> FeatureMap;
12158
873
      Context.getFunctionFeatureMap(FeatureMap, NewFD);
12159
873
      if (!FeatureMap.contains("sme")) {
12160
5
        if (UsesSM)
12161
3
          Diag(NewFD->getLocation(),
12162
3
               diag::err_sme_definition_using_sm_in_non_sme_target);
12163
2
        else
12164
2
          Diag(NewFD->getLocation(),
12165
2
               diag::err_sme_definition_using_za_in_non_sme_target);
12166
5
      }
12167
873
    }
12168
6.30M
  }
12169
12170
38.8M
  return Redeclaration;
12171
38.8M
}
12172
12173
10.3k
void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
12174
  // C++11 [basic.start.main]p3:
12175
  //   A program that [...] declares main to be inline, static or
12176
  //   constexpr is ill-formed.
12177
  // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
12178
  //   appear in a declaration of main.
12179
  // static main is not an error under C99, but we should warn about it.
12180
  // We accept _Noreturn main as an extension.
12181
10.3k
  if (FD->getStorageClass() == SC_Static)
12182
5
    Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12183
5
         ? 
diag::err_static_main3
:
diag::warn_static_main2
)
12184
5
      << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12185
10.3k
  if (FD->isInlineSpecified())
12186
5
    Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12187
5
      << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12188
10.3k
  if (DS.isNoreturnSpecified()) {
12189
3
    SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12190
3
    SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12191
3
    Diag(NoreturnLoc, diag::ext_noreturn_main);
12192
3
    Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12193
3
      << FixItHint::CreateRemoval(NoreturnRange);
12194
3
  }
12195
10.3k
  if (FD->isConstexpr()) {
12196
4
    Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12197
4
        << FD->isConsteval()
12198
4
        << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12199
4
    FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12200
4
  }
12201
12202
10.3k
  if (getLangOpts().OpenCL) {
12203
4
    Diag(FD->getLocation(), diag::err_opencl_no_main)
12204
4
        << FD->hasAttr<OpenCLKernelAttr>();
12205
4
    FD->setInvalidDecl();
12206
4
    return;
12207
4
  }
12208
12209
  // Functions named main in hlsl are default entries, but don't have specific
12210
  // signatures they are required to conform to.
12211
10.3k
  if (getLangOpts().HLSL)
12212
21
    return;
12213
12214
10.3k
  QualType T = FD->getType();
12215
10.3k
  assert(T->isFunctionType() && "function decl is not of function type");
12216
10.3k
  const FunctionType* FT = T->castAs<FunctionType>();
12217
12218
  // Set default calling convention for main()
12219
10.3k
  if (FT->getCallConv() != CC_C) {
12220
18
    FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12221
18
    FD->setType(QualType(FT, 0));
12222
18
    T = Context.getCanonicalType(FD->getType());
12223
18
  }
12224
12225
10.3k
  if (getLangOpts().GNUMode && 
!getLangOpts().CPlusPlus5.59k
) {
12226
    // In C with GNU extensions we allow main() to have non-integer return
12227
    // type, but we should warn about the extension, and we disable the
12228
    // implicit-return-zero rule.
12229
12230
    // GCC in C mode accepts qualified 'int'.
12231
1.82k
    if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12232
1.81k
      FD->setHasImplicitReturnZero(true);
12233
11
    else {
12234
11
      Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12235
11
      SourceRange RTRange = FD->getReturnTypeSourceRange();
12236
11
      if (RTRange.isValid())
12237
9
        Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12238
9
            << FixItHint::CreateReplacement(RTRange, "int");
12239
11
    }
12240
8.54k
  } else {
12241
    // In C and C++, main magically returns 0 if you fall off the end;
12242
    // set the flag which tells us that.
12243
    // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12244
12245
    // All the standards say that main() should return 'int'.
12246
8.54k
    if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12247
8.53k
      FD->setHasImplicitReturnZero(true);
12248
10
    else {
12249
      // Otherwise, this is just a flat-out error.
12250
10
      SourceRange RTRange = FD->getReturnTypeSourceRange();
12251
10
      Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12252
10
          << (RTRange.isValid() ? 
FixItHint::CreateReplacement(RTRange, "int")9
12253
10
                                : 
FixItHint()1
);
12254
10
      FD->setInvalidDecl(true);
12255
10
    }
12256
8.54k
  }
12257
12258
  // Treat protoless main() as nullary.
12259
10.3k
  if (isa<FunctionNoProtoType>(FT)) 
return553
;
12260
12261
9.81k
  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12262
9.81k
  unsigned nparams = FTP->getNumParams();
12263
9.81k
  assert(FD->getNumParams() == nparams);
12264
12265
9.81k
  bool HasExtraParameters = (nparams > 3);
12266
12267
9.81k
  if (FTP->isVariadic()) {
12268
3
    Diag(FD->getLocation(), diag::ext_variadic_main);
12269
    // FIXME: if we had information about the location of the ellipsis, we
12270
    // could add a FixIt hint to remove it as a parameter.
12271
3
  }
12272
12273
  // Darwin passes an undocumented fourth argument of type char**.  If
12274
  // other platforms start sprouting these, the logic below will start
12275
  // getting shifty.
12276
9.81k
  if (nparams == 4 && 
Context.getTargetInfo().getTriple().isOSDarwin()0
)
12277
0
    HasExtraParameters = false;
12278
12279
9.81k
  if (HasExtraParameters) {
12280
0
    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12281
0
    FD->setInvalidDecl(true);
12282
0
    nparams = 3;
12283
0
  }
12284
12285
  // FIXME: a lot of the following diagnostics would be improved
12286
  // if we had some location information about types.
12287
12288
9.81k
  QualType CharPP =
12289
9.81k
    Context.getPointerType(Context.getPointerType(Context.CharTy));
12290
9.81k
  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12291
12292
20.8k
  for (unsigned i = 0; i < nparams; 
++i11.0k
) {
12293
11.0k
    QualType AT = FTP->getParamType(i);
12294
12295
11.0k
    bool mismatch = true;
12296
12297
11.0k
    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12298
10.0k
      mismatch = false;
12299
1.04k
    else if (Expected[i] == CharPP) {
12300
      // As an extension, the following forms are okay:
12301
      //   char const **
12302
      //   char const * const *
12303
      //   char * const *
12304
12305
1.04k
      QualifierCollector qs;
12306
1.04k
      const PointerType* PT;
12307
1.04k
      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12308
1.04k
          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12309
1.04k
          Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12310
1.04k
                              Context.CharTy)) {
12311
1.04k
        qs.removeConst();
12312
1.04k
        mismatch = !qs.empty();
12313
1.04k
      }
12314
1.04k
    }
12315
12316
11.0k
    if (mismatch) {
12317
1
      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12318
      // TODO: suggest replacing given type with expected type
12319
1
      FD->setInvalidDecl(true);
12320
1
    }
12321
11.0k
  }
12322
12323
9.81k
  if (nparams == 1 && 
!FD->isInvalidDecl()3
) {
12324
2
    Diag(FD->getLocation(), diag::warn_main_one_arg);
12325
2
  }
12326
12327
9.81k
  if (!FD->isInvalidDecl() && 
FD->getDescribedFunctionTemplate()9.80k
) {
12328
3
    Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12329
3
    FD->setInvalidDecl();
12330
3
  }
12331
9.81k
}
12332
12333
243
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12334
12335
  // Default calling convention for main and wmain is __cdecl
12336
243
  if (FD->getName() == "main" || 
FD->getName() == "wmain"27
)
12337
223
    return false;
12338
12339
  // Default calling convention for MinGW is __cdecl
12340
20
  const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12341
20
  if (T.isWindowsGNUEnvironment())
12342
3
    return false;
12343
12344
  // Default calling convention for WinMain, wWinMain and DllMain
12345
  // is __stdcall on 32 bit Windows
12346
17
  if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12347
8
    return true;
12348
12349
9
  return false;
12350
17
}
12351
12352
247
void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12353
247
  QualType T = FD->getType();
12354
247
  assert(T->isFunctionType() && "function decl is not of function type");
12355
247
  const FunctionType *FT = T->castAs<FunctionType>();
12356
12357
  // Set an implicit return of 'zero' if the function can return some integral,
12358
  // enumeration, pointer or nullptr type.
12359
247
  if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12360
247
      
FT->getReturnType()->isAnyPointerType()2
||
12361
247
      
FT->getReturnType()->isNullPtrType()2
)
12362
    // DllMain is exempt because a return value of zero means it failed.
12363
245
    if (FD->getName() != "DllMain")
12364
238
      FD->setHasImplicitReturnZero(true);
12365
12366
  // Explicity specified calling conventions are applied to MSVC entry points
12367
247
  if (!hasExplicitCallingConv(T)) {
12368
243
    if (isDefaultStdCall(FD, *this)) {
12369
8
      if (FT->getCallConv() != CC_X86StdCall) {
12370
8
        FT = Context.adjustFunctionType(
12371
8
            FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12372
8
        FD->setType(QualType(FT, 0));
12373
8
      }
12374
235
    } else if (FT->getCallConv() != CC_C) {
12375
5
      FT = Context.adjustFunctionType(FT,
12376
5
                                      FT->getExtInfo().withCallingConv(CC_C));
12377
5
      FD->setType(QualType(FT, 0));
12378
5
    }
12379
243
  }
12380
12381
247
  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12382
1
    Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12383
1
    FD->setInvalidDecl();
12384
1
  }
12385
247
}
12386
12387
601
void Sema::ActOnHLSLTopLevelFunction(FunctionDecl *FD) {
12388
601
  auto &TargetInfo = getASTContext().getTargetInfo();
12389
12390
601
  if (FD->getName() != TargetInfo.getTargetOpts().HLSLEntry)
12391
570
    return;
12392
12393
31
  StringRef Env = TargetInfo.getTriple().getEnvironmentName();
12394
31
  HLSLShaderAttr::ShaderType ShaderType;
12395
31
  if (HLSLShaderAttr::ConvertStrToShaderType(Env, ShaderType)) {
12396
27
    if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) {
12397
      // The entry point is already annotated - check that it matches the
12398
      // triple.
12399
3
      if (Shader->getType() != ShaderType) {
12400
1
        Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
12401
1
            << Shader;
12402
1
        FD->setInvalidDecl();
12403
1
      }
12404
24
    } else {
12405
      // Implicitly add the shader attribute if the entry function isn't
12406
      // explicitly annotated.
12407
24
      FD->addAttr(HLSLShaderAttr::CreateImplicit(Context, ShaderType,
12408
24
                                                 FD->getBeginLoc()));
12409
24
    }
12410
27
  } else {
12411
4
    switch (TargetInfo.getTriple().getEnvironment()) {
12412
0
    case llvm::Triple::UnknownEnvironment:
12413
4
    case llvm::Triple::Library:
12414
4
      break;
12415
0
    default:
12416
0
      llvm_unreachable("Unhandled environment in triple");
12417
4
    }
12418
4
  }
12419
31
}
12420
12421
81
void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
12422
81
  const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
12423
81
  assert(ShaderAttr && "Entry point has no shader attribute");
12424
81
  HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12425
12426
81
  switch (ST) {
12427
5
  case HLSLShaderAttr::Pixel:
12428
8
  case HLSLShaderAttr::Vertex:
12429
9
  case HLSLShaderAttr::Geometry:
12430
10
  case HLSLShaderAttr::Hull:
12431
12
  case HLSLShaderAttr::Domain:
12432
13
  case HLSLShaderAttr::RayGeneration:
12433
14
  case HLSLShaderAttr::Intersection:
12434
14
  case HLSLShaderAttr::AnyHit:
12435
14
  case HLSLShaderAttr::ClosestHit:
12436
14
  case HLSLShaderAttr::Miss:
12437
14
  case HLSLShaderAttr::Callable:
12438
14
    if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) {
12439
4
      DiagnoseHLSLAttrStageMismatch(NT, ST,
12440
4
                                    {HLSLShaderAttr::Compute,
12441
4
                                     HLSLShaderAttr::Amplification,
12442
4
                                     HLSLShaderAttr::Mesh});
12443
4
      FD->setInvalidDecl();
12444
4
    }
12445
14
    break;
12446
12447
62
  case HLSLShaderAttr::Compute:
12448
63
  case HLSLShaderAttr::Amplification:
12449
67
  case HLSLShaderAttr::Mesh:
12450
67
    if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12451
1
      Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12452
1
          << HLSLShaderAttr::ConvertShaderTypeToStr(ST);
12453
1
      FD->setInvalidDecl();
12454
1
    }
12455
67
    break;
12456
81
  }
12457
12458
81
  for (ParmVarDecl *Param : FD->parameters()) {
12459
20
    if (const auto *AnnotationAttr = Param->getAttr<HLSLAnnotationAttr>()) {
12460
19
      CheckHLSLSemanticAnnotation(FD, Param, AnnotationAttr);
12461
19
    } else {
12462
      // FIXME: Handle struct parameters where annotations are on struct fields.
12463
      // See: https://github.com/llvm/llvm-project/issues/57875
12464
1
      Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12465
1
      Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12466
1
      FD->setInvalidDecl();
12467
1
    }
12468
20
  }
12469
  // FIXME: Verify return type semantic annotation.
12470
81
}
12471
12472
void Sema::CheckHLSLSemanticAnnotation(
12473
    FunctionDecl *EntryPoint, const Decl *Param,
12474
19
    const HLSLAnnotationAttr *AnnotationAttr) {
12475
19
  auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>();
12476
19
  assert(ShaderAttr && "Entry point has no shader attribute");
12477
19
  HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12478
12479
19
  switch (AnnotationAttr->getKind()) {
12480
4
  case attr::HLSLSV_DispatchThreadID:
12481
19
  case attr::HLSLSV_GroupIndex:
12482
19
    if (ST == HLSLShaderAttr::Compute)
12483
11
      return;
12484
8
    DiagnoseHLSLAttrStageMismatch(AnnotationAttr, ST,
12485
8
                                  {HLSLShaderAttr::Compute});
12486
8
    break;
12487
0
  default:
12488
0
    llvm_unreachable("Unknown HLSLAnnotationAttr");
12489
19
  }
12490
19
}
12491
12492
void Sema::DiagnoseHLSLAttrStageMismatch(
12493
    const Attr *A, HLSLShaderAttr::ShaderType Stage,
12494
12
    std::initializer_list<HLSLShaderAttr::ShaderType> AllowedStages) {
12495
12
  SmallVector<StringRef, 8> StageStrings;
12496
12
  llvm::transform(AllowedStages, std::back_inserter(StageStrings),
12497
20
                  [](HLSLShaderAttr::ShaderType ST) {
12498
20
                    return StringRef(
12499
20
                        HLSLShaderAttr::ConvertShaderTypeToStr(ST));
12500
20
                  });
12501
12
  Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
12502
12
      << A << HLSLShaderAttr::ConvertShaderTypeToStr(Stage)
12503
12
      << (AllowedStages.size() != 1) << join(StageStrings, ", ");
12504
12
}
12505
12506
12.7k
bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
12507
  // FIXME: Need strict checking.  In C89, we need to check for
12508
  // any assignment, increment, decrement, function-calls, or
12509
  // commas outside of a sizeof.  In C99, it's the same list,
12510
  // except that the aforementioned are allowed in unevaluated
12511
  // expressions.  Everything else falls under the
12512
  // "may accept other forms of constant expressions" exception.
12513
  //
12514
  // Regular C++ code will not end up here (exceptions: language extensions,
12515
  // OpenCL C++ etc), so the constant expression rules there don't matter.
12516
12.7k
  if (Init->isValueDependent()) {
12517
55
    assert(Init->containsErrors() &&
12518
55
           "Dependent code should only occur in error-recovery path.");
12519
55
    return true;
12520
55
  }
12521
12.7k
  const Expr *Culprit;
12522
12.7k
  if (Init->isConstantInitializer(Context, false, &Culprit))
12523
12.6k
    return false;
12524
124
  Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12525
124
    << Culprit->getSourceRange();
12526
124
  return true;
12527
12.7k
}
12528
12529
namespace {
12530
  // Visits an initialization expression to see if OrigDecl is evaluated in
12531
  // its own initialization and throws a warning if it does.
12532
  class SelfReferenceChecker
12533
      : public EvaluatedExprVisitor<SelfReferenceChecker> {
12534
    Sema &S;
12535
    Decl *OrigDecl;
12536
    bool isRecordType;
12537
    bool isPODType;
12538
    bool isReferenceType;
12539
12540
    bool isInitList;
12541
    llvm::SmallVector<unsigned, 4> InitFieldIndex;
12542
12543
  public:
12544
    typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12545
12546
652k
    SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12547
652k
                                                    S(S), OrigDecl(OrigDecl) {
12548
652k
      isPODType = false;
12549
652k
      isRecordType = false;
12550
652k
      isReferenceType = false;
12551
652k
      isInitList = false;
12552
652k
      if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12553
652k
        isPODType = VD->getType().isPODType(S.Context);
12554
652k
        isRecordType = VD->getType()->isRecordType();
12555
652k
        isReferenceType = VD->getType()->isReferenceType();
12556
652k
      }
12557
652k
    }
12558
12559
    // For most expressions, just call the visitor.  For initializer lists,
12560
    // track the index of the field being initialized since fields are
12561
    // initialized in order allowing use of previously initialized fields.
12562
716k
    void CheckExpr(Expr *E) {
12563
716k
      InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12564
716k
      if (!InitList) {
12565
702k
        Visit(E);
12566
702k
        return;
12567
702k
      }
12568
12569
      // Track and increment the index here.
12570
13.3k
      isInitList = true;
12571
13.3k
      InitFieldIndex.push_back(0);
12572
63.2k
      for (auto *Child : InitList->children()) {
12573
63.2k
        CheckExpr(cast<Expr>(Child));
12574
63.2k
        ++InitFieldIndex.back();
12575
63.2k
      }
12576
13.3k
      InitFieldIndex.pop_back();
12577
13.3k
    }
12578
12579
    // Returns true if MemberExpr is checked and no further checking is needed.
12580
    // Returns false if additional checking is required.
12581
163
    bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12582
163
      llvm::SmallVector<FieldDecl*, 4> Fields;
12583
163
      Expr *Base = E;
12584
163
      bool ReferenceField = false;
12585
12586
      // Get the field members used.
12587
275
      while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12588
181
        FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12589
181
        if (!FD)
12590
69
          return false;
12591
112
        Fields.push_back(FD);
12592
112
        if (FD->getType()->isReferenceType())
12593
23
          ReferenceField = true;
12594
112
        Base = ME->getBase()->IgnoreParenImpCasts();
12595
112
      }
12596
12597
      // Keep checking only if the base Decl is the same.
12598
94
      DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12599
94
      if (!DRE || 
DRE->getDecl() != OrigDecl77
)
12600
30
        return false;
12601
12602
      // A reference field can be bound to an unininitialized field.
12603
64
      if (CheckReference && 
!ReferenceField27
)
12604
12
        return true;
12605
12606
      // Convert FieldDecls to their index number.
12607
52
      llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12608
52
      for (const FieldDecl *I : llvm::reverse(Fields))
12609
69
        UsedFieldIndex.push_back(I->getFieldIndex());
12610
12611
      // See if a warning is needed by checking the first difference in index
12612
      // numbers.  If field being used has index less than the field being
12613
      // initialized, then the use is safe.
12614
52
      for (auto UsedIter = UsedFieldIndex.begin(),
12615
52
                UsedEnd = UsedFieldIndex.end(),
12616
52
                OrigIter = InitFieldIndex.begin(),
12617
52
                OrigEnd = InitFieldIndex.end();
12618
73
           UsedIter != UsedEnd && 
OrigIter != OrigEnd60
;
++UsedIter, ++OrigIter21
) {
12619
60
        if (*UsedIter < *OrigIter)
12620
29
          return true;
12621
31
        if (*UsedIter > *OrigIter)
12622
10
          break;
12623
31
      }
12624
12625
      // TODO: Add a different warning which will print the field names.
12626
23
      HandleDeclRefExpr(DRE);
12627
23
      return true;
12628
52
    }
12629
12630
    // For most expressions, the cast is directly above the DeclRefExpr.
12631
    // For conditional operators, the cast can be outside the conditional
12632
    // operator if both expressions are DeclRefExpr's.
12633
305k
    void HandleValue(Expr *E) {
12634
305k
      E = E->IgnoreParens();
12635
305k
      if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12636
271k
        HandleDeclRefExpr(DRE);
12637
271k
        return;
12638
271k
      }
12639
12640
34.5k
      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12641
4.29k
        Visit(CO->getCond());
12642
4.29k
        HandleValue(CO->getTrueExpr());
12643
4.29k
        HandleValue(CO->getFalseExpr());
12644
4.29k
        return;
12645
4.29k
      }
12646
12647
30.2k
      if (BinaryConditionalOperator *BCO =
12648
30.2k
              dyn_cast<BinaryConditionalOperator>(E)) {
12649
8
        Visit(BCO->getCond());
12650
8
        HandleValue(BCO->getFalseExpr());
12651
8
        return;
12652
8
      }
12653
12654
30.2k
      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12655
77
        HandleValue(OVE->getSourceExpr());
12656
77
        return;
12657
77
      }
12658
12659
30.1k
      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12660
79
        if (BO->getOpcode() == BO_Comma) {
12661
41
          Visit(BO->getLHS());
12662
41
          HandleValue(BO->getRHS());
12663
41
          return;
12664
41
        }
12665
79
      }
12666
12667
30.1k
      if (isa<MemberExpr>(E)) {
12668
6.50k
        if (isInitList) {
12669
59
          if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12670
59
                                      false /*CheckReference*/))
12671
37
            return;
12672
59
        }
12673
12674
6.46k
        Expr *Base = E->IgnoreParenImpCasts();
12675
13.9k
        while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12676
          // Check for static member variables and don't warn on them.
12677
7.48k
          if (!isa<FieldDecl>(ME->getMemberDecl()))
12678
14
            return;
12679
7.47k
          Base = ME->getBase()->IgnoreParenImpCasts();
12680
7.47k
        }
12681
6.44k
        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12682
5.20k
          HandleDeclRefExpr(DRE);
12683
6.44k
        return;
12684
6.46k
      }
12685
12686
23.6k
      Visit(E);
12687
23.6k
    }
12688
12689
    // Reference types not handled in HandleValue are handled here since all
12690
    // uses of references are bad, not just r-value uses.
12691
146k
    void VisitDeclRefExpr(DeclRefExpr *E) {
12692
146k
      if (isReferenceType)
12693
46.5k
        HandleDeclRefExpr(E);
12694
146k
    }
12695
12696
467k
    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12697
467k
      if (E->getCastKind() == CK_LValueToRValue) {
12698
254k
        HandleValue(E->getSubExpr());
12699
254k
        return;
12700
254k
      }
12701
12702
212k
      Inherited::VisitImplicitCastExpr(E);
12703
212k
    }
12704
12705
24.6k
    void VisitMemberExpr(MemberExpr *E) {
12706
24.6k
      if (isInitList) {
12707
104
        if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12708
27
          return;
12709
104
      }
12710
12711
      // Don't warn on arrays since they can be treated as pointers.
12712
24.6k
      if (E->getType()->canDecayToPointerType()) 
return803
;
12713
12714
      // Warn when a non-static method call is followed by non-static member
12715
      // field accesses, which is followed by a DeclRefExpr.
12716
23.8k
      CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12717
23.8k
      bool Warn = (MD && 
!MD->isStatic()16.0k
);
12718
23.8k
      Expr *Base = E->getBase()->IgnoreParenImpCasts();
12719
24.3k
      while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12720
542
        if (!isa<FieldDecl>(ME->getMemberDecl()))
12721
0
          Warn = false;
12722
542
        Base = ME->getBase()->IgnoreParenImpCasts();
12723
542
      }
12724
12725
23.8k
      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12726
13.2k
        if (Warn)
12727
11.4k
          HandleDeclRefExpr(DRE);
12728
13.2k
        return;
12729
13.2k
      }
12730
12731
      // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12732
      // Visit that expression.
12733
10.6k
      Visit(Base);
12734
10.6k
    }
12735
12736
8.86k
    void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12737
8.86k
      Expr *Callee = E->getCallee();
12738
12739
8.86k
      if (isa<UnresolvedLookupExpr>(Callee))
12740
2.70k
        return Inherited::VisitCXXOperatorCallExpr(E);
12741
12742
6.15k
      Visit(Callee);
12743
6.15k
      for (auto Arg: E->arguments())
12744
15.2k
        HandleValue(Arg->IgnoreParenImpCasts());
12745
6.15k
    }
12746
12747
68.5k
    void VisitUnaryOperator(UnaryOperator *E) {
12748
      // For POD record types, addresses of its own members are well-defined.
12749
68.5k
      if (E->getOpcode() == UO_AddrOf && 
isRecordType11.4k
&&
12750
68.5k
          
isa<MemberExpr>(E->getSubExpr()->IgnoreParens())3.35k
) {
12751
228
        if (!isPODType)
12752
153
          HandleValue(E->getSubExpr());
12753
228
        return;
12754
228
      }
12755
12756
68.2k
      if (E->isIncrementDecrementOp()) {
12757
97
        HandleValue(E->getSubExpr());
12758
97
        return;
12759
97
      }
12760
12761
68.1k
      Inherited::VisitUnaryOperator(E);
12762
68.1k
    }
12763
12764
206
    void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12765
12766
82.1k
    void VisitCXXConstructExpr(CXXConstructExpr *E) {
12767
82.1k
      if (E->getConstructor()->isCopyConstructor()) {
12768
20.3k
        Expr *ArgExpr = E->getArg(0);
12769
20.3k
        if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12770
9
          if (ILE->getNumInits() == 1)
12771
9
            ArgExpr = ILE->getInit(0);
12772
20.3k
        if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12773
11.5k
          if (ICE->getCastKind() == CK_NoOp)
12774
11.4k
            ArgExpr = ICE->getSubExpr();
12775
20.3k
        HandleValue(ArgExpr);
12776
20.3k
        return;
12777
20.3k
      }
12778
61.8k
      Inherited::VisitCXXConstructExpr(E);
12779
61.8k
    }
12780
12781
82.7k
    void VisitCallExpr(CallExpr *E) {
12782
      // Treat std::move as a use.
12783
82.7k
      if (E->isCallToStdMove()) {
12784
6.36k
        HandleValue(E->getArg(0));
12785
6.36k
        return;
12786
6.36k
      }
12787
12788
76.3k
      Inherited::VisitCallExpr(E);
12789
76.3k
    }
12790
12791
187k
    void VisitBinaryOperator(BinaryOperator *E) {
12792
187k
      if (E->isCompoundAssignmentOp()) {
12793
40
        HandleValue(E->getLHS());
12794
40
        Visit(E->getRHS());
12795
40
        return;
12796
40
      }
12797
12798
187k
      Inherited::VisitBinaryOperator(E);
12799
187k
    }
12800
12801
    // A custom visitor for BinaryConditionalOperator is needed because the
12802
    // regular visitor would check the condition and true expression separately
12803
    // but both point to the same place giving duplicate diagnostics.
12804
18
    void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12805
18
      Visit(E->getCond());
12806
18
      Visit(E->getFalseExpr());
12807
18
    }
12808
12809
334k
    void HandleDeclRefExpr(DeclRefExpr *DRE) {
12810
334k
      Decl* ReferenceDecl = DRE->getDecl();
12811
334k
      if (OrigDecl != ReferenceDecl) 
return334k
;
12812
285
      unsigned diag;
12813
285
      if (isReferenceType) {
12814
31
        diag = diag::warn_uninit_self_reference_in_reference_init;
12815
254
      } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12816
58
        diag = diag::warn_static_self_reference_in_init;
12817
196
      } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12818
196
                 
isa<NamespaceDecl>(OrigDecl->getDeclContext())121
||
12819
196
                 
DRE->getDecl()->getType()->isRecordType()63
) {
12820
188
        diag = diag::warn_uninit_self_reference_in_init;
12821
188
      } else {
12822
        // Local variables will be handled by the CFG analysis.
12823
8
        return;
12824
8
      }
12825
12826
277
      S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12827
277
                            S.PDiag(diag)
12828
277
                                << DRE->getDecl() << OrigDecl->getLocation()
12829
277
                                << DRE->getSourceRange());
12830
277
    }
12831
  };
12832
12833
  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12834
  static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12835
652k
                                 bool DirectInit) {
12836
    // Parameters arguments are occassionially constructed with itself,
12837
    // for instance, in recursive functions.  Skip them.
12838
652k
    if (isa<ParmVarDecl>(OrigDecl))
12839
0
      return;
12840
12841
652k
    E = E->IgnoreParens();
12842
12843
    // Skip checking T a = a where T is not a record or reference type.
12844
    // Doing so is a way to silence uninitialized warnings.
12845
652k
    if (!DirectInit && 
!cast<VarDecl>(OrigDecl)->getType()->isRecordType()610k
)
12846
555k
      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12847
141k
        if (ICE->getCastKind() == CK_LValueToRValue)
12848
98.7k
          if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12849
93.9k
            if (DRE->getDecl() == OrigDecl)
12850
31
              return;
12851
12852
652k
    SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12853
652k
  }
12854
} // end anonymous namespace
12855
12856
namespace {
12857
  // Simple wrapper to add the name of a variable or (if no variable is
12858
  // available) a DeclarationName into a diagnostic.
12859
  struct VarDeclOrName {
12860
    VarDecl *VDecl;
12861
    DeclarationName Name;
12862
12863
    friend const Sema::SemaDiagnosticBuilder &
12864
65
    operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12865
65
      return VN.VDecl ? 
Diag << VN.VDecl38
:
Diag << VN.Name27
;
12866
65
    }
12867
  };
12868
} // end anonymous namespace
12869
12870
QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12871
                                            DeclarationName Name, QualType Type,
12872
                                            TypeSourceInfo *TSI,
12873
                                            SourceRange Range, bool DirectInit,
12874
85.0k
                                            Expr *Init) {
12875
85.0k
  bool IsInitCapture = !VDecl;
12876
85.0k
  assert((!VDecl || !VDecl->isInitCapture()) &&
12877
85.0k
         "init captures are expected to be deduced prior to initialization");
12878
12879
85.0k
  VarDeclOrName VN{VDecl, Name};
12880
12881
85.0k
  DeducedType *Deduced = Type->getContainedDeducedType();
12882
85.0k
  assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12883
12884
  // Diagnose auto array declarations in C23, unless it's a supported extension.
12885
85.0k
  if (getLangOpts().C23 && 
Type->isArrayType()94
&&
12886
85.0k
      
!isa_and_present<StringLiteral, InitListExpr>(Init)7
) {
12887
2
      Diag(Range.getBegin(), diag::err_auto_not_allowed)
12888
2
          << (int)Deduced->getContainedAutoType()->getKeyword()
12889
2
          << /*in array decl*/ 23 << Range;
12890
2
    return QualType();
12891
2
  }
12892
12893
  // C++11 [dcl.spec.auto]p3
12894
85.0k
  if (!Init) {
12895
60
    assert(VDecl && "no init for init capture deduction?");
12896
12897
    // Except for class argument deduction, and then for an initializing
12898
    // declaration only, i.e. no static at class scope or extern.
12899
60
    if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12900
60
        
VDecl->hasExternalStorage()17
||
12901
60
        
VDecl->isStaticDataMember()16
) {
12902
46
      Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12903
46
        << VDecl->getDeclName() << Type;
12904
46
      return QualType();
12905
46
    }
12906
60
  }
12907
12908
85.0k
  ArrayRef<Expr*> DeduceInits;
12909
85.0k
  if (Init)
12910
85.0k
    DeduceInits = Init;
12911
12912
85.0k
  auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12913
85.0k
  if (DirectInit && 
PL461
)
12914
349
    DeduceInits = PL->exprs();
12915
12916
85.0k
  if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12917
475
    assert(VDecl && "non-auto type for init capture deduction?");
12918
475
    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12919
475
    InitializationKind Kind = InitializationKind::CreateForInit(
12920
475
        VDecl->getLocation(), DirectInit, Init);
12921
    // FIXME: Initialization should not be taking a mutable list of inits.
12922
475
    SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12923
475
    return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12924
475
                                                       InitsCopy, PL);
12925
475
  }
12926
12927
84.5k
  if (DirectInit) {
12928
255
    if (auto *IL = dyn_cast<InitListExpr>(Init))
12929
26
      DeduceInits = IL->inits();
12930
255
  }
12931
12932
  // Deduction only works if we have exactly one source expression.
12933
84.5k
  if (DeduceInits.empty()) {
12934
    // It isn't possible to write this directly, but it is possible to
12935
    // end up in this situation with "auto x(some_pack...);"
12936
9
    Diag(Init->getBeginLoc(), IsInitCapture
12937
9
                                  ? 
diag::err_init_capture_no_expression4
12938
9
                                  : 
diag::err_auto_var_init_no_expression5
)
12939
9
        << VN << Type << Range;
12940
9
    return QualType();
12941
9
  }
12942
12943
84.5k
  if (DeduceInits.size() > 1) {
12944
25
    Diag(DeduceInits[1]->getBeginLoc(),
12945
25
         IsInitCapture ? 
diag::err_init_capture_multiple_expressions9
12946
25
                       : 
diag::err_auto_var_init_multiple_expressions16
)
12947
25
        << VN << Type << Range;
12948
25
    return QualType();
12949
25
  }
12950
12951
84.5k
  Expr *DeduceInit = DeduceInits[0];
12952
84.5k
  if (DirectInit && 
isa<InitListExpr>(DeduceInit)221
) {
12953
24
    Diag(Init->getBeginLoc(), IsInitCapture
12954
24
                                  ? 
diag::err_init_capture_paren_braces12
12955
24
                                  : 
diag::err_auto_var_init_paren_braces12
)
12956
24
        << isa<InitListExpr>(Init) << VN << Type << Range;
12957
24
    return QualType();
12958
24
  }
12959
12960
  // Expressions default to 'id' when we're in a debugger.
12961
84.4k
  bool DefaultedAnyToId = false;
12962
84.4k
  if (getLangOpts().DebuggerCastResultToId &&
12963
84.4k
      
Init->getType() == Context.UnknownAnyTy2
&&
!IsInitCapture2
) {
12964
2
    ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12965
2
    if (Result.isInvalid()) {
12966
0
      return QualType();
12967
0
    }
12968
2
    Init = Result.get();
12969
2
    DefaultedAnyToId = true;
12970
2
  }
12971
12972
  // C++ [dcl.decomp]p1:
12973
  //   If the assignment-expression [...] has array type A and no ref-qualifier
12974
  //   is present, e has type cv A
12975
84.4k
  if (VDecl && 
isa<DecompositionDecl>(VDecl)83.7k
&&
12976
84.4k
      
Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType())678
&&
12977
84.4k
      
DeduceInit->getType()->isConstantArrayType()443
)
12978
91
    return Context.getQualifiedType(DeduceInit->getType(),
12979
91
                                    Type.getQualifiers());
12980
12981
84.3k
  QualType DeducedType;
12982
84.3k
  TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12983
84.3k
  TemplateDeductionResult Result =
12984
84.3k
      DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12985
84.3k
  if (Result != TDK_Success && 
Result != TDK_AlreadyDiagnosed87
) {
12986
46
    if (!IsInitCapture)
12987
44
      DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12988
2
    else if (isa<InitListExpr>(Init))
12989
1
      Diag(Range.getBegin(),
12990
1
           diag::err_init_capture_deduction_failure_from_init_list)
12991
1
          << VN
12992
1
          << (DeduceInit->getType().isNull() ? 
TSI->getType()0
12993
1
                                             : DeduceInit->getType())
12994
1
          << DeduceInit->getSourceRange();
12995
1
    else
12996
1
      Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12997
1
          << VN << TSI->getType()
12998
1
          << (DeduceInit->getType().isNull() ? 
TSI->getType()0
12999
1
                                             : DeduceInit->getType())
13000
1
          << DeduceInit->getSourceRange();
13001
46
  }
13002
13003
  // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13004
  // 'id' instead of a specific object type prevents most of our usual
13005
  // checks.
13006
  // We only want to warn outside of template instantiations, though:
13007
  // inside a template, the 'id' could have come from a parameter.
13008
84.3k
  if (!inTemplateInstantiation() && 
!DefaultedAnyToId75.1k
&&
!IsInitCapture75.1k
&&
13009
84.3k
      
!DeducedType.isNull()74.6k
&&
DeducedType->isObjCIdType()74.5k
) {
13010
5
    SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13011
5
    Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13012
5
  }
13013
13014
84.3k
  return DeducedType;
13015
84.4k
}
13016
13017
bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13018
84.3k
                                         Expr *Init) {
13019
84.3k
  assert(!Init || !Init->containsErrors());
13020
84.3k
  QualType DeducedType = deduceVarTypeFromInitializer(
13021
84.3k
      VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13022
84.3k
      VDecl->getSourceRange(), DirectInit, Init);
13023
84.3k
  if (DeducedType.isNull()) {
13024
266
    VDecl->setInvalidDecl();
13025
266
    return true;
13026
266
  }
13027
13028
84.0k
  VDecl->setType(DeducedType);
13029
84.0k
  assert(VDecl->isLinkageValid());
13030
13031
  // In ARC, infer lifetime.
13032
84.0k
  if (getLangOpts().ObjCAutoRefCount && 
inferObjCARCLifetime(VDecl)148
)
13033
0
    VDecl->setInvalidDecl();
13034
13035
84.0k
  if (getLangOpts().OpenCL)
13036
44
    deduceOpenCLAddressSpace(VDecl);
13037
13038
  // If this is a redeclaration, check that the type we just deduced matches
13039
  // the previously declared type.
13040
84.0k
  if (VarDecl *Old = VDecl->getPreviousDecl()) {
13041
    // We never need to merge the type, because we cannot form an incomplete
13042
    // array of auto, nor deduce such a type.
13043
8
    MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13044
8
  }
13045
13046
  // Check the deduced type is valid for a variable declaration.
13047
84.0k
  CheckVariableDeclarationType(VDecl);
13048
84.0k
  return VDecl->isInvalidDecl();
13049
84.0k
}
13050
13051
void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13052
28
                                              SourceLocation Loc) {
13053
28
  if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13054
6
    Init = EWC->getSubExpr();
13055
13056
28
  if (auto *CE = dyn_cast<ConstantExpr>(Init))
13057
2
    Init = CE->getSubExpr();
13058
13059
28
  QualType InitType = Init->getType();
13060
28
  assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13061
28
          InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13062
28
         "shouldn't be called if type doesn't have a non-trivial C struct");
13063
28
  if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13064
26
    for (auto *I : ILE->inits()) {
13065
26
      if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13066
26
          
!I->getType().hasNonTrivialToPrimitiveCopyCUnion()17
)
13067
17
        continue;
13068
9
      SourceLocation SL = I->getExprLoc();
13069
9
      checkNonTrivialCUnionInInitializer(I, SL.isValid() ? 
SL5
:
Loc4
);
13070
9
    }
13071
17
    return;
13072
17
  }
13073
13074
11
  if (isa<ImplicitValueInitExpr>(Init)) {
13075
4
    if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13076
4
      checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
13077
4
                            NTCUK_Init);
13078
7
  } else {
13079
    // Assume all other explicit initializers involving copying some existing
13080
    // object.
13081
    // TODO: ignore any explicit initializers where we can guarantee
13082
    // copy-elision.
13083
7
    if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13084
7
      checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
13085
7
  }
13086
11
}
13087
13088
namespace {
13089
13090
1.82M
bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13091
  // Ignore unavailable fields. A field can be marked as unavailable explicitly
13092
  // in the source code or implicitly by the compiler if it is in a union
13093
  // defined in a system header and has non-trivial ObjC ownership
13094
  // qualifications. We don't want those fields to participate in determining
13095
  // whether the containing union is non-trivial.
13096
1.82M
  return FD->hasAttr<UnavailableAttr>();
13097
1.82M
}
13098
13099
struct DiagNonTrivalCUnionDefaultInitializeVisitor
13100
    : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13101
                                    void> {
13102
  using Super =
13103
      DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13104
                                    void>;
13105
13106
  DiagNonTrivalCUnionDefaultInitializeVisitor(
13107
      QualType OrigTy, SourceLocation OrigLoc,
13108
      Sema::NonTrivialCUnionContext UseContext, Sema &S)
13109
13
      : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13110
13111
  void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13112
46
                     const FieldDecl *FD, bool InNonTrivialUnion) {
13113
46
    if (const auto *AT = S.Context.getAsArrayType(QT))
13114
0
      return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13115
0
                                     InNonTrivialUnion);
13116
46
    return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13117
46
  }
13118
13119
  void visitARCStrong(QualType QT, const FieldDecl *FD,
13120
17
                      bool InNonTrivialUnion) {
13121
17
    if (InNonTrivialUnion)
13122
13
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13123
13
          << 1 << 0 << QT << FD->getName();
13124
17
  }
13125
13126
12
  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13127
12
    if (InNonTrivialUnion)
13128
12
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13129
12
          << 1 << 0 << QT << FD->getName();
13130
12
  }
13131
13132
17
  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13133
17
    const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13134
17
    if (RD->isUnion()) {
13135
13
      if (OrigLoc.isValid()) {
13136
13
        bool IsUnion = false;
13137
13
        if (auto *OrigRD = OrigTy->getAsRecordDecl())
13138
13
          IsUnion = OrigRD->isUnion();
13139
13
        S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13140
13
            << 0 << OrigTy << IsUnion << UseContext;
13141
        // Reset OrigLoc so that this diagnostic is emitted only once.
13142
13
        OrigLoc = SourceLocation();
13143
13
      }
13144
13
      InNonTrivialUnion = true;
13145
13
    }
13146
13147
17
    if (InNonTrivialUnion)
13148
13
      S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13149
13
          << 0 << 0 << QT.getUnqualifiedType() << "";
13150
13151
17
    for (const FieldDecl *FD : RD->fields())
13152
33
      if (!shouldIgnoreForRecordTriviality(FD))
13153
33
        asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13154
17
  }
13155
13156
0
  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13157
13158
  // The non-trivial C union type or the struct/union type that contains a
13159
  // non-trivial C union.
13160
  QualType OrigTy;
13161
  SourceLocation OrigLoc;
13162
  Sema::NonTrivialCUnionContext UseContext;
13163
  Sema &S;
13164
};
13165
13166
struct DiagNonTrivalCUnionDestructedTypeVisitor
13167
    : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13168
  using Super =
13169
      DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13170
13171
  DiagNonTrivalCUnionDestructedTypeVisitor(
13172
      QualType OrigTy, SourceLocation OrigLoc,
13173
      Sema::NonTrivialCUnionContext UseContext, Sema &S)
13174
38
      : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13175
13176
  void visitWithKind(QualType::DestructionKind DK, QualType QT,
13177
148
                     const FieldDecl *FD, bool InNonTrivialUnion) {
13178
148
    if (const auto *AT = S.Context.getAsArrayType(QT))
13179
0
      return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13180
0
                                     InNonTrivialUnion);
13181
148
    return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13182
148
  }
13183
13184
  void visitARCStrong(QualType QT, const FieldDecl *FD,
13185
56
                      bool InNonTrivialUnion) {
13186
56
    if (InNonTrivialUnion)
13187
38
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13188
38
          << 1 << 1 << QT << FD->getName();
13189
56
  }
13190
13191
36
  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13192
36
    if (InNonTrivialUnion)
13193
36
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13194
36
          << 1 << 1 << QT << FD->getName();
13195
36
  }
13196
13197
56
  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13198
56
    const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13199
56
    if (RD->isUnion()) {
13200
38
      if (OrigLoc.isValid()) {
13201
38
        bool IsUnion = false;
13202
38
        if (auto *OrigRD = OrigTy->getAsRecordDecl())
13203
38
          IsUnion = OrigRD->isUnion();
13204
38
        S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13205
38
            << 1 << OrigTy << IsUnion << UseContext;
13206
        // Reset OrigLoc so that this diagnostic is emitted only once.
13207
38
        OrigLoc = SourceLocation();
13208
38
      }
13209
38
      InNonTrivialUnion = true;
13210
38
    }
13211
13212
56
    if (InNonTrivialUnion)
13213
38
      S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13214
38
          << 0 << 1 << QT.getUnqualifiedType() << "";
13215
13216
56
    for (const FieldDecl *FD : RD->fields())
13217
111
      if (!shouldIgnoreForRecordTriviality(FD))
13218
110
        asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13219
56
  }
13220
13221
0
  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13222
  void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13223
0
                          bool InNonTrivialUnion) {}
13224
13225
  // The non-trivial C union type or the struct/union type that contains a
13226
  // non-trivial C union.
13227
  QualType OrigTy;
13228
  SourceLocation OrigLoc;
13229
  Sema::NonTrivialCUnionContext UseContext;
13230
  Sema &S;
13231
};
13232
13233
struct DiagNonTrivalCUnionCopyVisitor
13234
    : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13235
  using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13236
13237
  DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13238
                                 Sema::NonTrivialCUnionContext UseContext,
13239
                                 Sema &S)
13240
30
      : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13241
13242
  void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13243
112
                     const FieldDecl *FD, bool InNonTrivialUnion) {
13244
112
    if (const auto *AT = S.Context.getAsArrayType(QT))
13245
0
      return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13246
0
                                     InNonTrivialUnion);
13247
112
    return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13248
112
  }
13249
13250
  void visitARCStrong(QualType QT, const FieldDecl *FD,
13251
42
                      bool InNonTrivialUnion) {
13252
42
    if (InNonTrivialUnion)
13253
30
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13254
30
          << 1 << 2 << QT << FD->getName();
13255
42
  }
13256
13257
28
  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13258
28
    if (InNonTrivialUnion)
13259
28
      S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13260
28
          << 1 << 2 << QT << FD->getName();
13261
28
  }
13262
13263
42
  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13264
42
    const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13265
42
    if (RD->isUnion()) {
13266
30
      if (OrigLoc.isValid()) {
13267
30
        bool IsUnion = false;
13268
30
        if (auto *OrigRD = OrigTy->getAsRecordDecl())
13269
30
          IsUnion = OrigRD->isUnion();
13270
30
        S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13271
30
            << 2 << OrigTy << IsUnion << UseContext;
13272
        // Reset OrigLoc so that this diagnostic is emitted only once.
13273
30
        OrigLoc = SourceLocation();
13274
30
      }
13275
30
      InNonTrivialUnion = true;
13276
30
    }
13277
13278
42
    if (InNonTrivialUnion)
13279
30
      S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13280
30
          << 0 << 2 << QT.getUnqualifiedType() << "";
13281
13282
42
    for (const FieldDecl *FD : RD->fields())
13283
83
      if (!shouldIgnoreForRecordTriviality(FD))
13284
82
        asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13285
42
  }
13286
13287
  void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13288
112
                const FieldDecl *FD, bool InNonTrivialUnion) {}
13289
0
  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13290
  void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13291
0
                            bool InNonTrivialUnion) {}
13292
13293
  // The non-trivial C union type or the struct/union type that contains a
13294
  // non-trivial C union.
13295
  QualType OrigTy;
13296
  SourceLocation OrigLoc;
13297
  Sema::NonTrivialCUnionContext UseContext;
13298
  Sema &S;
13299
};
13300
13301
} // namespace
13302
13303
void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13304
                                 NonTrivialCUnionContext UseContext,
13305
60
                                 unsigned NonTrivialKind) {
13306
60
  assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13307
60
          QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13308
60
          QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13309
60
         "shouldn't be called if type doesn't have a non-trivial C union");
13310
13311
60
  if ((NonTrivialKind & NTCUK_Init) &&
13312
60
      
QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()13
)
13313
13
    DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13314
13
        .visit(QT, nullptr, false);
13315
60
  if ((NonTrivialKind & NTCUK_Destruct) &&
13316
60
      
QT.hasNonTrivialToPrimitiveDestructCUnion()38
)
13317
38
    DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13318
38
        .visit(QT, nullptr, false);
13319
60
  if ((NonTrivialKind & NTCUK_Copy) && 
QT.hasNonTrivialToPrimitiveCopyCUnion()30
)
13320
30
    DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13321
30
        .visit(QT, nullptr, false);
13322
60
}
13323
13324
/// AddInitializerToDecl - Adds the initializer Init to the
13325
/// declaration dcl. If DirectInit is true, this is C++ direct
13326
/// initialization rather than copy initialization.
13327
2.60M
void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13328
  // If there is no declaration, there was an error parsing it.  Just ignore
13329
  // the initializer.
13330
2.60M
  if (!RealDecl || 
RealDecl->isInvalidDecl()2.60M
) {
13331
707
    CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13332
707
    return;
13333
707
  }
13334
13335
2.60M
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13336
    // Pure-specifiers are handled in ActOnPureSpecifier.
13337
23
    Diag(Method->getLocation(), diag::err_member_function_initialization)
13338
23
      << Method->getDeclName() << Init->getSourceRange();
13339
23
    Method->setInvalidDecl();
13340
23
    return;
13341
23
  }
13342
13343
2.60M
  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13344
2.60M
  if (!VDecl) {
13345
9
    assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13346
9
    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13347
9
    RealDecl->setInvalidDecl();
13348
9
    return;
13349
9
  }
13350
13351
  // WebAssembly tables can't be used to initialise a variable.
13352
2.60M
  if (Init && !Init->getType().isNull() &&
13353
2.60M
      
Init->getType()->isWebAssemblyTableType()2.50M
) {
13354
2
    Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13355
2
    VDecl->setInvalidDecl();
13356
2
    return;
13357
2
  }
13358
13359
  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13360
2.60M
  if (VDecl->getType()->isUndeducedType()) {
13361
    // Attempt typo correction early so that the type of the init expression can
13362
    // be deduced based on the chosen correction if the original init contains a
13363
    // TypoExpr.
13364
84.4k
    ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13365
84.4k
    if (!Res.isUsable()) {
13366
      // There are unresolved typos in Init, just drop them.
13367
      // FIXME: improve the recovery strategy to preserve the Init.
13368
80
      RealDecl->setInvalidDecl();
13369
80
      return;
13370
80
    }
13371
84.3k
    if (Res.get()->containsErrors()) {
13372
      // Invalidate the decl as we don't know the type for recovery-expr yet.
13373
69
      RealDecl->setInvalidDecl();
13374
69
      VDecl->setInit(Res.get());
13375
69
      return;
13376
69
    }
13377
84.2k
    Init = Res.get();
13378
13379
84.2k
    if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13380
216
      return;
13381
84.2k
  }
13382
13383
  // dllimport cannot be used on variable definitions.
13384
2.60M
  if (VDecl->hasAttr<DLLImportAttr>() && 
!VDecl->isStaticDataMember()447
) {
13385
146
    Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13386
146
    VDecl->setInvalidDecl();
13387
146
    return;
13388
146
  }
13389
13390
  // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13391
  // the identifier has external or internal linkage, the declaration shall
13392
  // have no initializer for the identifier.
13393
  // C++14 [dcl.init]p5 is the same restriction for C++.
13394
2.60M
  if (VDecl->isLocalVarDecl() && 
VDecl->hasExternalStorage()2.00M
) {
13395
11
    Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13396
11
    VDecl->setInvalidDecl();
13397
11
    return;
13398
11
  }
13399
13400
2.60M
  if (!VDecl->getType()->isDependentType()) {
13401
    // A definition must end up with a complete type, which means it must be
13402
    // complete with the restriction that an array type might be completed by
13403
    // the initializer; note that later code assumes this restriction.
13404
2.08M
    QualType BaseDeclType = VDecl->getType();
13405
2.08M
    if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13406
6.74k
      BaseDeclType = Array->getElementType();
13407
2.08M
    if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13408
2.08M
                            diag::err_typecheck_decl_incomplete_type)) {
13409
55
      RealDecl->setInvalidDecl();
13410
55
      return;
13411
55
    }
13412
13413
    // The variable can not have an abstract class type.
13414
2.08M
    if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13415
2.08M
                               diag::err_abstract_type_in_decl,
13416
2.08M
                               AbstractVariableType))
13417
0
      VDecl->setInvalidDecl();
13418
2.08M
  }
13419
13420
  // C++ [module.import/6] external definitions are not permitted in header
13421
  // units.
13422
2.60M
  if (getLangOpts().CPlusPlusModules && 
currentModuleIsHeaderUnit()48.1k
&&
13423
2.60M
      
!VDecl->isInvalidDecl()10
&&
VDecl->isThisDeclarationADefinition()10
&&
13424
2.60M
      
VDecl->getFormalLinkage() == Linkage::External9
&&
!VDecl->isInline()7
&&
13425
2.60M
      
!VDecl->isTemplated()5
&&
!isa<VarTemplateSpecializationDecl>(VDecl)2
) {
13426
1
    Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13427
1
    VDecl->setInvalidDecl();
13428
1
  }
13429
13430
  // If adding the initializer will turn this declaration into a definition,
13431
  // and we already have a definition for this variable, diagnose or otherwise
13432
  // handle the situation.
13433
2.60M
  if (VarDecl *Def = VDecl->getDefinition())
13434
2.15M
    if (Def != VDecl &&
13435
2.15M
        
(34
!VDecl->isStaticDataMember()34
||
VDecl->isOutOfLine()7
) &&
13436
2.15M
        
!VDecl->isThisDeclarationADemotedDefinition()33
&&
13437
2.15M
        
checkVarDeclRedefinition(Def, VDecl)19
)
13438
19
      return;
13439
13440
2.60M
  if (getLangOpts().CPlusPlus) {
13441
    // C++ [class.static.data]p4
13442
    //   If a static data member is of const integral or const
13443
    //   enumeration type, its declaration in the class definition can
13444
    //   specify a constant-initializer which shall be an integral
13445
    //   constant expression (5.19). In that case, the member can appear
13446
    //   in integral constant expressions. The member shall still be
13447
    //   defined in a namespace scope if it is used in the program and the
13448
    //   namespace scope definition shall not contain an initializer.
13449
    //
13450
    // We already performed a redefinition check above, but for static
13451
    // data members we also need to check whether there was an in-class
13452
    // declaration with an initializer.
13453
2.50M
    if (VDecl->isStaticDataMember() && 
VDecl->getCanonicalDecl()->hasInit()458k
) {
13454
18
      Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13455
18
          << VDecl->getDeclName();
13456
18
      Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13457
18
           diag::note_previous_initializer)
13458
18
          << 0;
13459
18
      return;
13460
18
    }
13461
13462
2.50M
    if (VDecl->hasLocalStorage())
13463
1.98M
      setFunctionHasBranchProtectedScope();
13464
13465
2.50M
    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13466
21
      VDecl->setInvalidDecl();
13467
21
      return;
13468
21
    }
13469
2.50M
  }
13470
13471
  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13472
  // a kernel function cannot be initialized."
13473
2.60M
  if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13474
6
    Diag(VDecl->getLocation(), diag::err_local_cant_init);
13475
6
    VDecl->setInvalidDecl();
13476
6
    return;
13477
6
  }
13478
13479
  // The LoaderUninitialized attribute acts as a definition (of undef).
13480
2.60M
  if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13481
4
    Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13482
4
    VDecl->setInvalidDecl();
13483
4
    return;
13484
4
  }
13485
13486
  // Get the decls type and save a reference for later, since
13487
  // CheckInitializerTypes may change it.
13488
2.60M
  QualType DclT = VDecl->getType(), SavT = DclT;
13489
13490
  // Expressions default to 'id' when we're in a debugger
13491
  // and we are assigning it to a variable of Objective-C pointer type.
13492
2.60M
  if (getLangOpts().DebuggerCastResultToId && 
DclT->isObjCObjectPointerType()89
&&
13493
2.60M
      
Init->getType() == Context.UnknownAnyTy57
) {
13494
6
    ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13495
6
    if (Result.isInvalid()) {
13496
0
      VDecl->setInvalidDecl();
13497
0
      return;
13498
0
    }
13499
6
    Init = Result.get();
13500
6
  }
13501
13502
  // Perform the initialization.
13503
2.60M
  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13504
2.60M
  bool IsParenListInit = false;
13505
2.60M
  if (!VDecl->isInvalidDecl()) {
13506
2.60M
    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13507
2.60M
    InitializationKind Kind = InitializationKind::CreateForInit(
13508
2.60M
        VDecl->getLocation(), DirectInit, Init);
13509
13510
2.60M
    MultiExprArg Args = Init;
13511
2.60M
    if (CXXDirectInit)
13512
101k
      Args = MultiExprArg(CXXDirectInit->getExprs(),
13513
101k
                          CXXDirectInit->getNumExprs());
13514
13515
    // Try to correct any TypoExprs in the initialization arguments.
13516
5.26M
    for (size_t Idx = 0; Idx < Args.size(); 
++Idx2.65M
) {
13517
2.65M
      ExprResult Res = CorrectDelayedTyposInExpr(
13518
2.65M
          Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13519
2.65M
          [this, Entity, Kind](Expr *E) {
13520
91
            InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13521
91
            return Init.Failed() ? 
ExprError()10
:
E81
;
13522
91
          });
13523
2.65M
      if (Res.isInvalid()) {
13524
4
        VDecl->setInvalidDecl();
13525
2.65M
      } else if (Res.get() != Args[Idx]) {
13526
211
        Args[Idx] = Res.get();
13527
211
      }
13528
2.65M
    }
13529
2.60M
    if (VDecl->isInvalidDecl())
13530
4
      return;
13531
13532
2.60M
    InitializationSequence InitSeq(*this, Entity, Kind, Args,
13533
2.60M
                                   /*TopLevelOfInitList=*/false,
13534
2.60M
                                   /*TreatUnavailableAsInvalid=*/false);
13535
2.60M
    ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13536
2.60M
    if (Result.isInvalid()) {
13537
      // If the provided initializer fails to initialize the var decl,
13538
      // we attach a recovery expr for better recovery.
13539
3.05k
      auto RecoveryExpr =
13540
3.05k
          CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13541
3.05k
      if (RecoveryExpr.get())
13542
3.04k
        VDecl->setInit(RecoveryExpr.get());
13543
3.05k
      return;
13544
3.05k
    }
13545
13546
2.60M
    Init = Result.getAs<Expr>();
13547
2.60M
    IsParenListInit = !InitSeq.steps().empty() &&
13548
2.60M
                      InitSeq.step_begin()->Kind ==
13549
1.93M
                          InitializationSequence::SK_ParenthesizedListInit;
13550
2.60M
    QualType VDeclType = VDecl->getType();
13551
2.60M
    if (Init && 
!Init->getType().isNull()2.60M
&&
13552
2.60M
        
!Init->getType()->isDependentType()2.52M
&&
!VDeclType->isDependentType()1.96M
&&
13553
2.60M
        
Context.getAsIncompleteArrayType(VDeclType)1.93M
&&
13554
2.60M
        
Context.getAsIncompleteArrayType(Init->getType())6.62k
) {
13555
      // Bail out if it is not possible to deduce array size from the
13556
      // initializer.
13557
1
      Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13558
1
          << VDeclType;
13559
1
      VDecl->setInvalidDecl();
13560
1
      return;
13561
1
    }
13562
2.60M
  }
13563
13564
  // Check for self-references within variable initializers.
13565
  // Variables declared within a function/method body (except for references)
13566
  // are handled by a dataflow analysis.
13567
  // This is undefined behavior in C++, but valid in C.
13568
2.60M
  if (getLangOpts().CPlusPlus)
13569
2.50M
    if (!VDecl->hasLocalStorage() || 
VDecl->getType()->isRecordType()1.98M
||
13570
2.50M
        
VDecl->getType()->isReferenceType()1.90M
)
13571
652k
      CheckSelfReference(*this, RealDecl, Init, DirectInit);
13572
13573
  // If the type changed, it means we had an incomplete type that was
13574
  // completed by the initializer. For example:
13575
  //   int ary[] = { 1, 3, 5 };
13576
  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13577
2.60M
  if (!VDecl->isInvalidDecl() && 
(DclT != SavT)2.60M
)
13578
6.62k
    VDecl->setType(DclT);
13579
13580
2.60M
  if (!VDecl->isInvalidDecl()) {
13581
2.60M
    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13582
13583
2.60M
    if (VDecl->hasAttr<BlocksAttr>())
13584
177
      checkRetainCycles(VDecl, Init);
13585
13586
    // It is safe to assign a weak reference into a strong variable.
13587
    // Although this code can still have problems:
13588
    //   id x = self.weakProp;
13589
    //   id y = self.weakProp;
13590
    // we do not warn to warn spuriously when 'x' and 'y' are on separate
13591
    // paths through the function. This should be revisited if
13592
    // -Wrepeated-use-of-weak is made flow-sensitive.
13593
2.60M
    if (FunctionScopeInfo *FSI = getCurFunction())
13594
2.28M
      if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13595
2.28M
           
VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)2.28M
) &&
13596
2.28M
          !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13597
922
                           Init->getBeginLoc()))
13598
27
        FSI->markSafeWeakUse(Init);
13599
2.60M
  }
13600
13601
  // The initialization is usually a full-expression.
13602
  //
13603
  // FIXME: If this is a braced initialization of an aggregate, it is not
13604
  // an expression, and each individual field initializer is a separate
13605
  // full-expression. For instance, in:
13606
  //
13607
  //   struct Temp { ~Temp(); };
13608
  //   struct S { S(Temp); };
13609
  //   struct T { S a, b; } t = { Temp(), Temp() }
13610
  //
13611
  // we should destroy the first Temp before constructing the second.
13612
2.60M
  ExprResult Result =
13613
2.60M
      ActOnFinishFullExpr(Init, VDecl->getLocation(),
13614
2.60M
                          /*DiscardedValue*/ false, VDecl->isConstexpr());
13615
2.60M
  if (Result.isInvalid()) {
13616
4
    VDecl->setInvalidDecl();
13617
4
    return;
13618
4
  }
13619
2.60M
  Init = Result.get();
13620
13621
  // Attach the initializer to the decl.
13622
2.60M
  VDecl->setInit(Init);
13623
13624
2.60M
  if (VDecl->isLocalVarDecl()) {
13625
    // Don't check the initializer if the declaration is malformed.
13626
2.00M
    if (VDecl->isInvalidDecl()) {
13627
      // do nothing
13628
13629
    // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13630
    // This is true even in C++ for OpenCL.
13631
2.00M
    } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13632
117
      CheckForConstantInitializer(Init, DclT);
13633
13634
    // Otherwise, C++ does not restrict the initializer.
13635
2.00M
    } else if (getLangOpts().CPlusPlus) {
13636
      // do nothing
13637
13638
    // C99 6.7.8p4: All the expressions in an initializer for an object that has
13639
    // static storage duration shall be constant expressions or string literals.
13640
1.91M
    } else 
if (91.1k
VDecl->getStorageClass() == SC_Static91.1k
) {
13641
501
      CheckForConstantInitializer(Init, DclT);
13642
13643
    // C89 is stricter than C99 for aggregate initializers.
13644
    // C89 6.5.7p3: All the expressions [...] in an initializer list
13645
    // for an object that has aggregate or union type shall be
13646
    // constant expressions.
13647
90.6k
    } else if (!getLangOpts().C99 && 
VDecl->getType()->isAggregateType()241
&&
13648
90.6k
               
isa<InitListExpr>(Init)23
) {
13649
18
      const Expr *Culprit;
13650
18
      if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13651
2
        Diag(Culprit->getExprLoc(),
13652
2
             diag::ext_aggregate_init_not_constant)
13653
2
          << Culprit->getSourceRange();
13654
2
      }
13655
18
    }
13656
13657
2.00M
    if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13658
39.0k
      if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13659
308
        if (VDecl->hasLocalStorage())
13660
304
          BE->getBlockDecl()->setCanAvoidCopyToHeap();
13661
2.00M
  } else 
if (597k
VDecl->isStaticDataMember()597k
&&
!VDecl->isInline()458k
&&
13662
597k
             
VDecl->getLexicalDeclContext()->isRecord()446k
) {
13663
    // This is an in-class initialization for a static data member, e.g.,
13664
    //
13665
    // struct S {
13666
    //   static const int value = 17;
13667
    // };
13668
13669
    // C++ [class.mem]p4:
13670
    //   A member-declarator can contain a constant-initializer only
13671
    //   if it declares a static member (9.4) of const integral or
13672
    //   const enumeration type, see 9.4.2.
13673
    //
13674
    // C++11 [class.static.data]p3:
13675
    //   If a non-volatile non-inline const static data member is of integral
13676
    //   or enumeration type, its declaration in the class definition can
13677
    //   specify a brace-or-equal-initializer in which every initializer-clause
13678
    //   that is an assignment-expression is a constant expression. A static
13679
    //   data member of literal type can be declared in the class definition
13680
    //   with the constexpr specifier; if so, its declaration shall specify a
13681
    //   brace-or-equal-initializer in which every initializer-clause that is
13682
    //   an assignment-expression is a constant expression.
13683
13684
    // Do nothing on dependent types.
13685
443k
    if (DclT->isDependentType()) {
13686
13687
    // Allow any 'static constexpr' members, whether or not they are of literal
13688
    // type. We separately check that every constexpr variable is of literal
13689
    // type.
13690
436k
    } else if (VDecl->isConstexpr()) {
13691
13692
    // Require constness.
13693
269k
    } else 
if (167k
!DclT.isConstQualified()167k
) {
13694
23
      Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13695
23
        << Init->getSourceRange();
13696
23
      VDecl->setInvalidDecl();
13697
13698
    // We allow integer constant expressions in all cases.
13699
167k
    } else if (DclT->isIntegralOrEnumerationType()) {
13700
      // Check whether the expression is a constant expression.
13701
167k
      SourceLocation Loc;
13702
167k
      if (getLangOpts().CPlusPlus11 && 
DclT.isVolatileQualified()166k
)
13703
        // In C++11, a non-constexpr const static data member with an
13704
        // in-class initializer cannot be volatile.
13705
2
        Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13706
167k
      else if (Init->isValueDependent())
13707
39.4k
        ; // Nothing to check.
13708
127k
      else if (Init->isIntegerConstantExpr(Context, &Loc))
13709
127k
        ; // Ok, it's an ICE!
13710
50
      else if (Init->getType()->isScopedEnumeralType() &&
13711
50
               
Init->isCXX11ConstantExpr(Context)37
)
13712
37
        ; // Ok, it is a scoped-enum constant expression.
13713
13
      else if (Init->isEvaluatable(Context)) {
13714
        // If we can constant fold the initializer through heroics, accept it,
13715
        // but report this as a use of an extension for -pedantic.
13716
5
        Diag(Loc, diag::ext_in_class_initializer_non_constant)
13717
5
          << Init->getSourceRange();
13718
8
      } else {
13719
        // Otherwise, this is some crazy unknown case.  Report the issue at the
13720
        // location provided by the isIntegerConstantExpr failed check.
13721
8
        Diag(Loc, diag::err_in_class_initializer_non_constant)
13722
8
          << Init->getSourceRange();
13723
8
        VDecl->setInvalidDecl();
13724
8
      }
13725
13726
    // We allow foldable floating-point constants as an extension.
13727
167k
    } else 
if (31
DclT->isFloatingType()31
) { // also permits complex, which is ok
13728
      // In C++98, this is a GNU extension. In C++11, it is not, but we support
13729
      // it anyway and provide a fixit to add the 'constexpr'.
13730
21
      if (getLangOpts().CPlusPlus11) {
13731
11
        Diag(VDecl->getLocation(),
13732
11
             diag::ext_in_class_initializer_float_type_cxx11)
13733
11
            << DclT << Init->getSourceRange();
13734
11
        Diag(VDecl->getBeginLoc(),
13735
11
             diag::note_in_class_initializer_float_type_cxx11)
13736
11
            << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13737
11
      } else {
13738
10
        Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13739
10
          << DclT << Init->getSourceRange();
13740
13741
10
        if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13742
1
          Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13743
1
            << Init->getSourceRange();
13744
1
          VDecl->setInvalidDecl();
13745
1
        }
13746
10
      }
13747
13748
    // Suggest adding 'constexpr' in C++11 for literal types.
13749
21
    } else 
if (10
getLangOpts().CPlusPlus1110
&&
DclT->isLiteralType(Context)8
) {
13750
4
      Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13751
4
          << DclT << Init->getSourceRange()
13752
4
          << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13753
4
      VDecl->setConstexpr(true);
13754
13755
6
    } else {
13756
6
      Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13757
6
        << DclT << Init->getSourceRange();
13758
6
      VDecl->setInvalidDecl();
13759
6
    }
13760
443k
  } else 
if (153k
VDecl->isFileVarDecl()153k
) {
13761
    // In C, extern is typically used to avoid tentative definitions when
13762
    // declaring variables in headers, but adding an intializer makes it a
13763
    // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13764
    // In C++, extern is often used to give implictly static const variables
13765
    // external linkage, so don't warn in that case. If selectany is present,
13766
    // this might be header code intended for C and C++ inclusion, so apply the
13767
    // C++ rules.
13768
70.3k
    if (VDecl->getStorageClass() == SC_Extern &&
13769
70.3k
        
(390
(390
!getLangOpts().CPlusPlus390
&&
!VDecl->hasAttr<SelectAnyAttr>()24
) ||
13770
390
         
!Context.getBaseElementType(VDecl->getType()).isConstQualified()374
) &&
13771
70.3k
        
!(105
getLangOpts().CPlusPlus105
&&
VDecl->isExternC()85
) &&
13772
70.3k
        
!isTemplateInstantiation(VDecl->getTemplateSpecializationKind())102
)
13773
62
      Diag(VDecl->getLocation(), diag::warn_extern_init);
13774
13775
    // In Microsoft C++ mode, a const variable defined in namespace scope has
13776
    // external linkage by default if the variable is declared with
13777
    // __declspec(dllexport).
13778
70.3k
    if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13779
70.3k
        
getLangOpts().CPlusPlus3.68k
&&
VDecl->getType().isConstQualified()3.33k
&&
13780
70.3k
        
VDecl->hasAttr<DLLExportAttr>()474
&&
VDecl->getDefinition()65
)
13781
65
      VDecl->setStorageClass(SC_Extern);
13782
13783
    // C99 6.7.8p4. All file scoped initializers need to be constant.
13784
70.3k
    if (!getLangOpts().CPlusPlus && 
!VDecl->isInvalidDecl()11.7k
)
13785
11.7k
      CheckForConstantInitializer(Init, DclT);
13786
70.3k
  }
13787
13788
2.60M
  QualType InitType = Init->getType();
13789
2.60M
  if (!InitType.isNull() &&
13790
2.60M
      
(2.52M
InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()2.52M
||
13791
2.52M
       
InitType.hasNonTrivialToPrimitiveCopyCUnion()2.52M
))
13792
12
    checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13793
13794
  // We will represent direct-initialization similarly to copy-initialization:
13795
  //    int x(1);  -as-> int x = 1;
13796
  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13797
  //
13798
  // Clients that want to distinguish between the two forms, can check for
13799
  // direct initializer using VarDecl::getInitStyle().
13800
  // A major benefit is that clients that don't particularly care about which
13801
  // exactly form was it (like the CodeGen) can handle both cases without
13802
  // special case code.
13803
13804
  // C++ 8.5p11:
13805
  // The form of initialization (using parentheses or '=') is generally
13806
  // insignificant, but does matter when the entity being initialized has a
13807
  // class type.
13808
2.60M
  if (CXXDirectInit) {
13809
101k
    assert(DirectInit && "Call-style initializer must be direct init.");
13810
101k
    VDecl->setInitStyle(IsParenListInit ? 
VarDecl::ParenListInit109
13811
101k
                                        : 
VarDecl::CallInit100k
);
13812
2.50M
  } else if (DirectInit) {
13813
    // This must be list-initialization. No other way is direct-initialization.
13814
10.0k
    VDecl->setInitStyle(VarDecl::ListInit);
13815
10.0k
  }
13816
13817
2.60M
  if (LangOpts.OpenMP &&
13818
2.60M
      
(1.18M
LangOpts.OpenMPIsTargetDevice1.18M
||
!LangOpts.OMPTargetTriples.empty()1.16M
) &&
13819
2.60M
      
VDecl->isFileVarDecl()126k
)
13820
2.20k
    DeclsToCheckForDeferredDiags.insert(VDecl);
13821
2.60M
  CheckCompleteVariableDeclaration(VDecl);
13822
2.60M
}
13823
13824
/// ActOnInitializerError - Given that there was an error parsing an
13825
/// initializer for the given declaration, try to at least re-establish
13826
/// invariants such as whether a variable's type is either dependent or
13827
/// complete.
13828
1.92k
void Sema::ActOnInitializerError(Decl *D) {
13829
  // Our main concern here is re-establishing invariants like "a
13830
  // variable's type is either dependent or complete".
13831
1.92k
  if (!D || D->isInvalidDecl()) 
return47
;
13832
13833
1.87k
  VarDecl *VD = dyn_cast<VarDecl>(D);
13834
1.87k
  if (!VD) 
return3
;
13835
13836
  // Bindings are not usable if we can't make sense of the initializer.
13837
1.87k
  if (auto *DD = dyn_cast<DecompositionDecl>(D))
13838
13
    for (auto *BD : DD->bindings())
13839
17
      BD->setInvalidDecl();
13840
13841
  // Auto types are meaningless if we can't make sense of the initializer.
13842
1.87k
  if (VD->getType()->isUndeducedType()) {
13843
368
    D->setInvalidDecl();
13844
368
    return;
13845
368
  }
13846
13847
1.50k
  QualType Ty = VD->getType();
13848
1.50k
  if (Ty->isDependentType()) 
return1
;
13849
13850
  // Require a complete type.
13851
1.50k
  if (RequireCompleteType(VD->getLocation(),
13852
1.50k
                          Context.getBaseElementType(Ty),
13853
1.50k
                          diag::err_typecheck_decl_incomplete_type)) {
13854
3
    VD->setInvalidDecl();
13855
3
    return;
13856
3
  }
13857
13858
  // Require a non-abstract type.
13859
1.50k
  if (RequireNonAbstractType(VD->getLocation(), Ty,
13860
1.50k
                             diag::err_abstract_type_in_decl,
13861
1.50k
                             AbstractVariableType)) {
13862
0
    VD->setInvalidDecl();
13863
0
    return;
13864
0
  }
13865
13866
  // Don't bother complaining about constructors or destructors,
13867
  // though.
13868
1.50k
}
13869
13870
33.9M
void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13871
  // If there is no declaration, there was an error parsing it. Just ignore it.
13872
33.9M
  if (!RealDecl)
13873
57.8k
    return;
13874
13875
33.9M
  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13876
1.84M
    QualType Type = Var->getType();
13877
13878
    // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13879
1.84M
    if (isa<DecompositionDecl>(RealDecl)) {
13880
19
      Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13881
19
      Var->setInvalidDecl();
13882
19
      return;
13883
19
    }
13884
13885
1.84M
    if (Type->isUndeducedType() &&
13886
1.84M
        
DeduceVariableDeclarationType(Var, false, nullptr)62
)
13887
57
      return;
13888
13889
    // C++11 [class.static.data]p3: A static data member can be declared with
13890
    // the constexpr specifier; if so, its declaration shall specify
13891
    // a brace-or-equal-initializer.
13892
    // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13893
    // the definition of a variable [...] or the declaration of a static data
13894
    // member.
13895
1.84M
    if (Var->isConstexpr() && 
!Var->isThisDeclarationADefinition()52.7k
&&
13896
1.84M
        
!Var->isThisDeclarationADemotedDefinition()2.59k
) {
13897
2.59k
      if (Var->isStaticDataMember()) {
13898
        // C++1z removes the relevant rule; the in-class declaration is always
13899
        // a definition there.
13900
2.58k
        if (!getLangOpts().CPlusPlus17 &&
13901
2.58k
            
!Context.getTargetInfo().getCXXABI().isMicrosoft()43
) {
13902
6
          Diag(Var->getLocation(),
13903
6
               diag::err_constexpr_static_mem_var_requires_init)
13904
6
              << Var;
13905
6
          Var->setInvalidDecl();
13906
6
          return;
13907
6
        }
13908
2.58k
      } else {
13909
18
        Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13910
18
        Var->setInvalidDecl();
13911
18
        return;
13912
18
      }
13913
2.59k
    }
13914
13915
    // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13916
    // be initialized.
13917
1.84M
    if (!Var->isInvalidDecl() &&
13918
1.84M
        
Var->getType().getAddressSpace() == LangAS::opencl_constant1.84M
&&
13919
1.84M
        
Var->getStorageClass() != SC_Extern38
&&
!Var->getInit()16
) {
13920
16
      bool HasConstExprDefaultConstructor = false;
13921
16
      if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13922
44
        for (auto *Ctor : RD->ctors()) {
13923
44
          if (Ctor->isConstexpr() && 
Ctor->getNumParams() == 024
&&
13924
44
              Ctor->getMethodQualifiers().getAddressSpace() ==
13925
7
                  LangAS::opencl_constant) {
13926
7
            HasConstExprDefaultConstructor = true;
13927
7
          }
13928
44
        }
13929
8
      }
13930
16
      if (!HasConstExprDefaultConstructor) {
13931
9
        Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13932
9
        Var->setInvalidDecl();
13933
9
        return;
13934
9
      }
13935
16
    }
13936
13937
1.84M
    if (!Var->isInvalidDecl() && 
RealDecl->hasAttr<LoaderUninitializedAttr>()1.84M
) {
13938
75
      if (Var->getStorageClass() == SC_Extern) {
13939
5
        Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13940
5
            << Var;
13941
5
        Var->setInvalidDecl();
13942
5
        return;
13943
5
      }
13944
70
      if (RequireCompleteType(Var->getLocation(), Var->getType(),
13945
70
                              diag::err_typecheck_decl_incomplete_type)) {
13946
3
        Var->setInvalidDecl();
13947
3
        return;
13948
3
      }
13949
67
      if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13950
19
        if (!RD->hasTrivialDefaultConstructor()) {
13951
1
          Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13952
1
          Var->setInvalidDecl();
13953
1
          return;
13954
1
        }
13955
19
      }
13956
      // The declaration is unitialized, no need for further checks.
13957
66
      return;
13958
67
    }
13959
13960
1.84M
    VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13961
1.84M
    if (!Var->isInvalidDecl() && 
DefKind != VarDecl::DeclarationOnly1.84M
&&
13962
1.84M
        
Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()861k
)
13963
9
      checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13964
9
                            NTCUC_DefaultInitializedObject, NTCUK_Init);
13965
13966
13967
1.84M
    switch (DefKind) {
13968
852k
    case VarDecl::Definition:
13969
852k
      if (!Var->isStaticDataMember() || 
!Var->getAnyInitializer()52.9k
)
13970
803k
        break;
13971
13972
      // We have an out-of-line definition of a static data member
13973
      // that has an in-class initializer, so we type-check this like
13974
      // a declaration.
13975
      //
13976
852k
      
[[fallthrough]];48.6k
13977
13978
1.02M
    case VarDecl::DeclarationOnly:
13979
      // It's only a declaration.
13980
13981
      // Block scope. C99 6.7p7: If an identifier for an object is
13982
      // declared with no linkage (C99 6.2.2p6), the type for the
13983
      // object shall be complete.
13984
1.02M
      if (!Type->isDependentType() && 
Var->isLocalVarDecl()1.02M
&&
13985
1.02M
          
!Var->hasLinkage()955
&&
!Var->isInvalidDecl()0
&&
13986
1.02M
          RequireCompleteType(Var->getLocation(), Type,
13987
0
                              diag::err_typecheck_decl_incomplete_type))
13988
0
        Var->setInvalidDecl();
13989
13990
      // Make sure that the type is not abstract.
13991
1.02M
      if (!Type->isDependentType() && 
!Var->isInvalidDecl()1.02M
&&
13992
1.02M
          RequireNonAbstractType(Var->getLocation(), Type,
13993
1.02M
                                 diag::err_abstract_type_in_decl,
13994
1.02M
                                 AbstractVariableType))
13995
0
        Var->setInvalidDecl();
13996
1.02M
      if (!Type->isDependentType() && 
!Var->isInvalidDecl()1.02M
&&
13997
1.02M
          
Var->getStorageClass() == SC_PrivateExtern1.02M
) {
13998
35
        Diag(Var->getLocation(), diag::warn_private_extern);
13999
35
        Diag(Var->getLocation(), diag::note_private_extern);
14000
35
      }
14001
14002
1.02M
      if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14003
1.02M
          
!Var->isInvalidDecl()13
)
14004
13
        ExternalDeclarations.push_back(Var);
14005
14006
1.02M
      return;
14007
14008
11.1k
    case VarDecl::TentativeDefinition:
14009
      // File scope. C99 6.9.2p2: A declaration of an identifier for an
14010
      // object that has file scope without an initializer, and without a
14011
      // storage-class specifier or with the storage-class specifier "static",
14012
      // constitutes a tentative definition. Note: A tentative definition with
14013
      // external linkage is valid (C99 6.2.2p5).
14014
11.1k
      if (!Var->isInvalidDecl()) {
14015
10.7k
        if (const IncompleteArrayType *ArrayT
14016
10.7k
                                    = Context.getAsIncompleteArrayType(Type)) {
14017
55
          if (RequireCompleteSizedType(
14018
55
                  Var->getLocation(), ArrayT->getElementType(),
14019
55
                  diag::err_array_incomplete_or_sizeless_type))
14020
0
            Var->setInvalidDecl();
14021
10.7k
        } else if (Var->getStorageClass() == SC_Static) {
14022
          // C99 6.9.2p3: If the declaration of an identifier for an object is
14023
          // a tentative definition and has internal linkage (C99 6.2.2p3), the
14024
          // declared type shall not be an incomplete type.
14025
          // NOTE: code such as the following
14026
          //     static struct s;
14027
          //     struct s { int a; };
14028
          // is accepted by gcc. Hence here we issue a warning instead of
14029
          // an error and we do not invalidate the static declaration.
14030
          // NOTE: to avoid multiple warnings, only check the first declaration.
14031
515
          if (Var->isFirstDecl())
14032
484
            RequireCompleteType(Var->getLocation(), Type,
14033
484
                                diag::ext_typecheck_decl_incomplete_type);
14034
515
        }
14035
10.7k
      }
14036
14037
      // Record the tentative definition; we're done.
14038
11.1k
      if (!Var->isInvalidDecl())
14039
10.7k
        TentativeDefinitions.push_back(Var);
14040
11.1k
      return;
14041
1.84M
    }
14042
14043
    // Provide a specific diagnostic for uninitialized variable
14044
    // definitions with incomplete array type.
14045
803k
    if (Type->isIncompleteArrayType()) {
14046
21
      if (Var->isConstexpr())
14047
3
        Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14048
3
            << Var;
14049
18
      else
14050
18
        Diag(Var->getLocation(),
14051
18
             diag::err_typecheck_incomplete_array_needs_initializer);
14052
21
      Var->setInvalidDecl();
14053
21
      return;
14054
21
    }
14055
14056
    // Provide a specific diagnostic for uninitialized variable
14057
    // definitions with reference type.
14058
803k
    if (Type->isReferenceType()) {
14059
25
      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14060
25
          << Var << SourceRange(Var->getLocation(), Var->getLocation());
14061
25
      return;
14062
25
    }
14063
14064
    // Do not attempt to type-check the default initializer for a
14065
    // variable with dependent type.
14066
803k
    if (Type->isDependentType())
14067
58.0k
      return;
14068
14069
745k
    if (Var->isInvalidDecl())
14070
1.55k
      return;
14071
14072
744k
    if (!Var->hasAttr<AliasAttr>()) {
14073
744k
      if (RequireCompleteType(Var->getLocation(),
14074
744k
                              Context.getBaseElementType(Type),
14075
744k
                              diag::err_typecheck_decl_incomplete_type)) {
14076
290
        Var->setInvalidDecl();
14077
290
        return;
14078
290
      }
14079
744k
    } else {
14080
61
      return;
14081
61
    }
14082
14083
    // The variable can not have an abstract class type.
14084
743k
    if (RequireNonAbstractType(Var->getLocation(), Type,
14085
743k
                               diag::err_abstract_type_in_decl,
14086
743k
                               AbstractVariableType)) {
14087
27
      Var->setInvalidDecl();
14088
27
      return;
14089
27
    }
14090
14091
    // Check for jumps past the implicit initializer.  C++0x
14092
    // clarifies that this applies to a "variable with automatic
14093
    // storage duration", not a "local variable".
14094
    // C++11 [stmt.dcl]p3
14095
    //   A program that jumps from a point where a variable with automatic
14096
    //   storage duration is not in scope to a point where it is in scope is
14097
    //   ill-formed unless the variable has scalar type, class type with a
14098
    //   trivial default constructor and a trivial destructor, a cv-qualified
14099
    //   version of one of these types, or an array of one of the preceding
14100
    //   types and is declared without an initializer.
14101
743k
    if (getLangOpts().CPlusPlus && 
Var->hasLocalStorage()282k
) {
14102
232k
      if (const RecordType *Record
14103
232k
            = Context.getBaseElementType(Type)->getAs<RecordType>()) {
14104
66.6k
        CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14105
        // Mark the function (if we're in one) for further checking even if the
14106
        // looser rules of C++11 do not require such checks, so that we can
14107
        // diagnose incompatibilities with C++98.
14108
66.6k
        if (!CXXRecord->isPOD())
14109
44.6k
          setFunctionHasBranchProtectedScope();
14110
66.6k
      }
14111
232k
    }
14112
    // In OpenCL, we can't initialize objects in the __local address space,
14113
    // even implicitly, so don't synthesize an implicit initializer.
14114
743k
    if (getLangOpts().OpenCL &&
14115
743k
        
Var->getType().getAddressSpace() == LangAS::opencl_local1.79k
)
14116
144
      return;
14117
    // C++03 [dcl.init]p9:
14118
    //   If no initializer is specified for an object, and the
14119
    //   object is of (possibly cv-qualified) non-POD class type (or
14120
    //   array thereof), the object shall be default-initialized; if
14121
    //   the object is of const-qualified type, the underlying class
14122
    //   type shall have a user-declared default
14123
    //   constructor. Otherwise, if no initializer is specified for
14124
    //   a non- static object, the object and its subobjects, if
14125
    //   any, have an indeterminate initial value); if the object
14126
    //   or any of its subobjects are of const-qualified type, the
14127
    //   program is ill-formed.
14128
    // C++0x [dcl.init]p11:
14129
    //   If no initializer is specified for an object, the object is
14130
    //   default-initialized; [...].
14131
743k
    InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14132
743k
    InitializationKind Kind
14133
743k
      = InitializationKind::CreateDefault(Var->getLocation());
14134
14135
743k
    InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14136
743k
    ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14137
14138
743k
    if (Init.get()) {
14139
96.0k
      Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14140
      // This is important for template substitution.
14141
96.0k
      Var->setInitStyle(VarDecl::CallInit);
14142
647k
    } else if (Init.isInvalid()) {
14143
      // If default-init fails, attach a recovery-expr initializer to track
14144
      // that initialization was attempted and failed.
14145
218
      auto RecoveryExpr =
14146
218
          CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14147
218
      if (RecoveryExpr.get())
14148
218
        Var->setInit(RecoveryExpr.get());
14149
218
    }
14150
14151
743k
    CheckCompleteVariableDeclaration(Var);
14152
743k
  }
14153
33.9M
}
14154
14155
1.85k
void Sema::ActOnCXXForRangeDecl(Decl *D) {
14156
  // If there is no declaration, there was an error parsing it. Ignore it.
14157
1.85k
  if (!D)
14158
2
    return;
14159
14160
1.85k
  VarDecl *VD = dyn_cast<VarDecl>(D);
14161
1.85k
  if (!VD) {
14162
3
    Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14163
3
    D->setInvalidDecl();
14164
3
    return;
14165
3
  }
14166
14167
1.84k
  VD->setCXXForRangeDecl(true);
14168
14169
  // for-range-declaration cannot be given a storage class specifier.
14170
1.84k
  int Error = -1;
14171
1.84k
  switch (VD->getStorageClass()) {
14172
1.83k
  case SC_None:
14173
1.83k
    break;
14174
4
  case SC_Extern:
14175
4
    Error = 0;
14176
4
    break;
14177
4
  case SC_Static:
14178
4
    Error = 1;
14179
4
    break;
14180
0
  case SC_PrivateExtern:
14181
0
    Error = 2;
14182
0
    break;
14183
0
  case SC_Auto:
14184
0
    Error = 3;
14185
0
    break;
14186
3
  case SC_Register:
14187
3
    Error = 4;
14188
3
    break;
14189
1.84k
  }
14190
14191
  // for-range-declaration cannot be given a storage class specifier con't.
14192
1.84k
  switch (VD->getTSCSpec()) {
14193
3
  case TSCS_thread_local:
14194
3
    Error = 6;
14195
3
    break;
14196
0
  case TSCS___thread:
14197
0
  case TSCS__Thread_local:
14198
1.84k
  case TSCS_unspecified:
14199
1.84k
    break;
14200
1.84k
  }
14201
14202
1.84k
  if (Error != -1) {
14203
14
    Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14204
14
        << VD << Error;
14205
14
    D->setInvalidDecl();
14206
14
  }
14207
1.84k
}
14208
14209
StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14210
                                            IdentifierInfo *Ident,
14211
6
                                            ParsedAttributes &Attrs) {
14212
  // C++1y [stmt.iter]p1:
14213
  //   A range-based for statement of the form
14214
  //      for ( for-range-identifier : for-range-initializer ) statement
14215
  //   is equivalent to
14216
  //      for ( auto&& for-range-identifier : for-range-initializer ) statement
14217
6
  DeclSpec DS(Attrs.getPool().getFactory());
14218
14219
6
  const char *PrevSpec;
14220
6
  unsigned DiagID;
14221
6
  DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14222
6
                     getPrintingPolicy());
14223
14224
6
  Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14225
6
  D.SetIdentifier(Ident, IdentLoc);
14226
6
  D.takeAttributes(Attrs);
14227
14228
6
  D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14229
6
                IdentLoc);
14230
6
  Decl *Var = ActOnDeclarator(S, D);
14231
6
  cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14232
6
  FinalizeDeclaration(Var);
14233
6
  return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14234
6
                       Attrs.Range.getEnd().isValid() ? 
Attrs.Range.getEnd()3
14235
6
                                                      : 
IdentLoc3
);
14236
6
}
14237
14238
3.35M
void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14239
3.35M
  if (var->isInvalidDecl()) 
return54
;
14240
14241
3.35M
  MaybeAddCUDAConstantAttr(var);
14242
14243
3.35M
  if (getLangOpts().OpenCL) {
14244
    // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14245
    // initialiser
14246
3.62k
    if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14247
3.62k
        
!var->hasInit()155
) {
14248
2
      Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14249
2
          << 1 /*Init*/;
14250
2
      var->setInvalidDecl();
14251
2
      return;
14252
2
    }
14253
3.62k
  }
14254
14255
  // In Objective-C, don't allow jumps past the implicit initialization of a
14256
  // local retaining variable.
14257
3.35M
  if (getLangOpts().ObjC &&
14258
3.35M
      
var->hasLocalStorage()142k
) {
14259
111k
    switch (var->getType().getObjCLifetime()) {
14260
109k
    case Qualifiers::OCL_None:
14261
109k
    case Qualifiers::OCL_ExplicitNone:
14262
109k
    case Qualifiers::OCL_Autoreleasing:
14263
109k
      break;
14264
14265
252
    case Qualifiers::OCL_Weak:
14266
1.47k
    case Qualifiers::OCL_Strong:
14267
1.47k
      setFunctionHasBranchProtectedScope();
14268
1.47k
      break;
14269
111k
    }
14270
111k
  }
14271
14272
3.35M
  if (var->hasLocalStorage() &&
14273
3.35M
      
var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct2.77M
)
14274
85
    setFunctionHasBranchProtectedScope();
14275
14276
  // Warn about externally-visible variables being defined without a
14277
  // prior declaration.  We only want to do this for global
14278
  // declarations, but we also specifically need to avoid doing it for
14279
  // class members because the linkage of an anonymous class can
14280
  // change if it's later given a typedef name.
14281
3.35M
  if (var->isThisDeclarationADefinition() &&
14282
3.35M
      
var->getDeclContext()->getRedeclContext()->isFileContext()2.91M
&&
14283
3.35M
      
var->isExternallyVisible()106k
&&
var->hasLinkage()76.7k
&&
14284
3.35M
      
!var->isInline()76.7k
&&
!var->getDescribedVarTemplate()67.1k
&&
14285
3.35M
      
var->getStorageClass() != SC_Register66.3k
&&
14286
3.35M
      
!isa<VarTemplatePartialSpecializationDecl>(var)66.3k
&&
14287
3.35M
      
!isTemplateInstantiation(var->getTemplateSpecializationKind())66.1k
&&
14288
3.35M
      !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14289
65.3k
                                  var->getLocation())) {
14290
    // Find a previous declaration that's not a definition.
14291
13
    VarDecl *prev = var->getPreviousDecl();
14292
16
    while (prev && 
prev->isThisDeclarationADefinition()5
)
14293
3
      prev = prev->getPreviousDecl();
14294
14295
13
    if (!prev) {
14296
11
      Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14297
11
      Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14298
11
          << /* variable */ 0;
14299
11
    }
14300
13
  }
14301
14302
  // Cache the result of checking for constant initialization.
14303
3.35M
  std::optional<bool> CacheHasConstInit;
14304
3.35M
  const Expr *CacheCulprit = nullptr;
14305
3.35M
  auto checkConstInit = [&]() mutable {
14306
7.02k
    if (!CacheHasConstInit)
14307
7.01k
      CacheHasConstInit = var->getInit()->isConstantInitializer(
14308
7.01k
            Context, var->getType()->isReferenceType(), &CacheCulprit);
14309
7.02k
    return *CacheHasConstInit;
14310
7.02k
  };
14311
14312
3.35M
  if (var->getTLSKind() == VarDecl::TLS_Static) {
14313
340
    if (var->getType().isDestructedType()) {
14314
      // GNU C++98 edits for __thread, [basic.start.term]p3:
14315
      //   The type of an object with thread storage duration shall not
14316
      //   have a non-trivial destructor.
14317
3
      Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14318
3
      if (getLangOpts().CPlusPlus11)
14319
1
        Diag(var->getLocation(), diag::note_use_thread_local);
14320
337
    } else if (getLangOpts().CPlusPlus && 
var->hasInit()219
) {
14321
82
      if (!checkConstInit()) {
14322
        // GNU C++98 edits for __thread, [basic.start.init]p4:
14323
        //   An object of thread storage duration shall not require dynamic
14324
        //   initialization.
14325
        // FIXME: Need strict checking here.
14326
15
        Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14327
15
          << CacheCulprit->getSourceRange();
14328
15
        if (getLangOpts().CPlusPlus11)
14329
9
          Diag(var->getLocation(), diag::note_use_thread_local);
14330
15
      }
14331
82
    }
14332
340
  }
14333
14334
14335
3.35M
  if (!var->getType()->isStructureType() && 
var->hasInit()3.26M
&&
14336
3.35M
      
isa<InitListExpr>(var->getInit())2.62M
) {
14337
25.9k
    const auto *ILE = cast<InitListExpr>(var->getInit());
14338
25.9k
    unsigned NumInits = ILE->getNumInits();
14339
25.9k
    if (NumInits > 2)
14340
6.17k
      
for (unsigned I = 0; 5.96k
I < NumInits;
++I204
) {
14341
6.13k
        const auto *Init = ILE->getInit(I);
14342
6.13k
        if (!Init)
14343
0
          break;
14344
6.13k
        const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14345
6.13k
        if (!SL)
14346
5.91k
          break;
14347
14348
223
        unsigned NumConcat = SL->getNumConcatenated();
14349
        // Diagnose missing comma in string array initialization.
14350
        // Do not warn when all the elements in the initializer are concatenated
14351
        // together. Do not warn for macros too.
14352
223
        if (NumConcat == 2 && 
!SL->getBeginLoc().isMacroID()27
) {
14353
19
          bool OnlyOneMissingComma = true;
14354
36
          for (unsigned J = I + 1; J < NumInits; 
++J17
) {
14355
19
            const auto *Init = ILE->getInit(J);
14356
19
            if (!Init)
14357
0
              break;
14358
19
            const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14359
19
            if (!SLJ || SLJ->getNumConcatenated() > 1) {
14360
2
              OnlyOneMissingComma = false;
14361
2
              break;
14362
2
            }
14363
19
          }
14364
14365
19
          if (OnlyOneMissingComma) {
14366
17
            SmallVector<FixItHint, 1> Hints;
14367
34
            for (unsigned i = 0; i < NumConcat - 1; 
++i17
)
14368
17
              Hints.push_back(FixItHint::CreateInsertion(
14369
17
                  PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14370
14371
17
            Diag(SL->getStrTokenLoc(1),
14372
17
                 diag::warn_concatenated_literal_array_init)
14373
17
                << Hints;
14374
17
            Diag(SL->getBeginLoc(),
14375
17
                 diag::note_concatenated_string_literal_silence);
14376
17
          }
14377
          // In any case, stop now.
14378
19
          break;
14379
19
        }
14380
223
      }
14381
25.9k
  }
14382
14383
14384
3.35M
  QualType type = var->getType();
14385
14386
3.35M
  if (var->hasAttr<BlocksAttr>())
14387
503
    getCurFunction()->addByrefBlockVar(var);
14388
14389
3.35M
  Expr *Init = var->getInit();
14390
3.35M
  bool GlobalStorage = var->hasGlobalStorage();
14391
3.35M
  bool IsGlobal = GlobalStorage && 
!var->isStaticLocal()585k
;
14392
3.35M
  QualType baseType = Context.getBaseElementType(type);
14393
3.35M
  bool HasConstInit = true;
14394
14395
  // Check whether the initializer is sufficiently constant.
14396
3.35M
  if (getLangOpts().CPlusPlus && 
!type->isDependentType()2.78M
&&
Init2.26M
&&
14397
3.35M
      
!Init->isValueDependent()2.07M
&&
14398
3.35M
      
(1.88M
GlobalStorage1.88M
||
var->isConstexpr()1.45M
||
14399
1.88M
       
var->mightBeUsableInConstantExpressions(Context)1.45M
)) {
14400
    // If this variable might have a constant initializer or might be usable in
14401
    // constant expressions, check whether or not it actually is now.  We can't
14402
    // do this lazily, because the result might depend on things that change
14403
    // later, such as which constexpr functions happen to be defined.
14404
494k
    SmallVector<PartialDiagnosticAt, 8> Notes;
14405
494k
    if (!getLangOpts().CPlusPlus11) {
14406
      // Prior to C++11, in contexts where a constant initializer is required,
14407
      // the set of valid constant initializers is described by syntactic rules
14408
      // in [expr.const]p2-6.
14409
      // FIXME: Stricter checking for these rules would be useful for constinit /
14410
      // -Wglobal-constructors.
14411
6.91k
      HasConstInit = checkConstInit();
14412
14413
      // Compute and cache the constant value, and remember that we have a
14414
      // constant initializer.
14415
6.91k
      if (HasConstInit) {
14416
3.44k
        (void)var->checkForConstantInitialization(Notes);
14417
3.44k
        Notes.clear();
14418
3.46k
      } else if (CacheCulprit) {
14419
3.46k
        Notes.emplace_back(CacheCulprit->getExprLoc(),
14420
3.46k
                           PDiag(diag::note_invalid_subexpr_in_const_expr));
14421
3.46k
        Notes.back().second << CacheCulprit->getSourceRange();
14422
3.46k
      }
14423
487k
    } else {
14424
      // Evaluate the initializer to see if it's a constant initializer.
14425
487k
      HasConstInit = var->checkForConstantInitialization(Notes);
14426
487k
    }
14427
14428
494k
    if (HasConstInit) {
14429
      // FIXME: Consider replacing the initializer with a ConstantExpr.
14430
418k
    } else 
if (75.5k
var->isConstexpr()75.5k
) {
14431
1.33k
      SourceLocation DiagLoc = var->getLocation();
14432
      // If the note doesn't add any useful information other than a source
14433
      // location, fold it into the primary diagnostic.
14434
1.33k
      if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14435
794
                                   diag::note_invalid_subexpr_in_const_expr) {
14436
28
        DiagLoc = Notes[0].first;
14437
28
        Notes.clear();
14438
28
      }
14439
1.33k
      Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14440
1.33k
          << var << Init->getSourceRange();
14441
3.17k
      for (unsigned I = 0, N = Notes.size(); I != N; 
++I1.84k
)
14442
1.84k
        Diag(Notes[I].first, Notes[I].second);
14443
74.2k
    } else if (GlobalStorage && 
var->hasAttr<ConstInitAttr>()31.8k
) {
14444
67
      auto *Attr = var->getAttr<ConstInitAttr>();
14445
67
      Diag(var->getLocation(), diag::err_require_constant_init_failed)
14446
67
          << Init->getSourceRange();
14447
67
      Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14448
67
          << Attr->getRange() << Attr->isConstinit();
14449
67
      for (auto &it : Notes)
14450
112
        Diag(it.first, it.second);
14451
74.1k
    } else if (IsGlobal &&
14452
74.1k
               !getDiagnostics().isIgnored(diag::warn_global_constructor,
14453
24.7k
                                           var->getLocation())) {
14454
      // Warn about globals which don't have a constant initializer.  Don't
14455
      // warn about globals with a non-trivial destructor because we already
14456
      // warned about them.
14457
33
      CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14458
33
      if (!(RD && 
!RD->hasTrivialDestructor()21
)) {
14459
        // checkConstInit() here permits trivial default initialization even in
14460
        // C++11 onwards, where such an initializer is not a constant initializer
14461
        // but nonetheless doesn't require a global constructor.
14462
31
        if (!checkConstInit())
14463
27
          Diag(var->getLocation(), diag::warn_global_constructor)
14464
27
              << Init->getSourceRange();
14465
31
      }
14466
33
    }
14467
494k
  }
14468
14469
  // Apply section attributes and pragmas to global variables.
14470
3.35M
  if (GlobalStorage && 
var->isThisDeclarationADefinition()585k
&&
14471
3.35M
      
!inTemplateInstantiation()142k
) {
14472
132k
    PragmaStack<StringLiteral *> *Stack = nullptr;
14473
132k
    int SectionFlags = ASTContext::PSF_Read;
14474
132k
    bool MSVCEnv =
14475
132k
        Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14476
132k
    std::optional<QualType::NonConstantStorageReason> Reason;
14477
132k
    if (HasConstInit &&
14478
132k
        
!(Reason = var->getType().isNonConstantStorage(Context, true, false))99.4k
) {
14479
38.9k
      Stack = &ConstSegStack;
14480
93.1k
    } else {
14481
93.1k
      SectionFlags |= ASTContext::PSF_Write;
14482
93.1k
      Stack = var->hasInit() && 
HasConstInit61.8k
?
&DataSegStack29.1k
:
&BSSSegStack63.9k
;
14483
93.1k
    }
14484
132k
    if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14485
846
      if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14486
9
        SectionFlags |= ASTContext::PSF_Implicit;
14487
846
      UnifySection(SA->getName(), SectionFlags, var);
14488
131k
    } else if (Stack->CurrentValue) {
14489
20
      if (Stack != &ConstSegStack && 
MSVCEnv16
&&
14490
20
          
ConstSegStack.CurrentValue != ConstSegStack.DefaultValue15
&&
14491
20
          
var->getType().isConstQualified()13
) {
14492
3
        assert((!Reason || Reason != QualType::NonConstantStorageReason::
14493
3
                                         NonConstNonReferenceType) &&
14494
3
               "This case should've already been handled elsewhere");
14495
3
        Diag(var->getLocation(), diag::warn_section_msvc_compat)
14496
3
                << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14497
3
            ? 
QualType::NonConstantStorageReason::NonTrivialCtor1
14498
3
            : 
*Reason2
);
14499
3
      }
14500
20
      SectionFlags |= ASTContext::PSF_Implicit;
14501
20
      auto SectionName = Stack->CurrentValue->getString();
14502
20
      var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14503
20
                                               Stack->CurrentPragmaLocation,
14504
20
                                               SectionAttr::Declspec_allocate));
14505
20
      if (UnifySection(SectionName, SectionFlags, var))
14506
1
        var->dropAttr<SectionAttr>();
14507
20
    }
14508
14509
    // Apply the init_seg attribute if this has an initializer.  If the
14510
    // initializer turns out to not be dynamic, we'll end up ignoring this
14511
    // attribute.
14512
132k
    if (CurInitSeg && 
var->getInit()38
)
14513
10
      var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14514
10
                                               CurInitSegLoc));
14515
132k
  }
14516
14517
  // All the following checks are C++ only.
14518
3.35M
  if (!getLangOpts().CPlusPlus) {
14519
    // If this variable must be emitted, add it as an initializer for the
14520
    // current module.
14521
576k
    if (Context.DeclMustBeEmitted(var) && 
!ModuleScopes.empty()15.6k
)
14522
20
      Context.addModuleInitializer(ModuleScopes.back().Module, var);
14523
576k
    return;
14524
576k
  }
14525
14526
  // Require the destructor.
14527
2.78M
  if (!type->isDependentType())
14528
2.26M
    if (const RecordType *recordType = baseType->getAs<RecordType>())
14529
175k
      FinalizeVarWithDestructor(var, recordType);
14530
14531
  // If this variable must be emitted, add it as an initializer for the current
14532
  // module.
14533
2.78M
  if (Context.DeclMustBeEmitted(var) && 
!ModuleScopes.empty()59.1k
)
14534
405
    Context.addModuleInitializer(ModuleScopes.back().Module, var);
14535
14536
  // Build the bindings if this is a structured binding declaration.
14537
2.78M
  if (auto *DD = dyn_cast<DecompositionDecl>(var))
14538
683
    CheckCompleteDecompositionDeclaration(DD);
14539
2.78M
}
14540
14541
/// Check if VD needs to be dllexport/dllimport due to being in a
14542
/// dllexport/import function.
14543
10.3k
void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14544
10.3k
  assert(VD->isStaticLocal());
14545
14546
10.3k
  auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14547
14548
  // Find outermost function when VD is in lambda function.
14549
20.4k
  while (FD && 
!getDLLAttr(FD)10.1k
&&
14550
20.4k
         
!FD->hasAttr<DLLExportStaticLocalAttr>()10.0k
&&
14551
20.4k
         
!FD->hasAttr<DLLImportStaticLocalAttr>()10.0k
) {
14552
10.0k
    FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14553
10.0k
  }
14554
14555
10.3k
  if (!FD)
14556
10.2k
    return;
14557
14558
  // Static locals inherit dll attributes from their function.
14559
113
  if (Attr *A = getDLLAttr(FD)) {
14560
108
    auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14561
108
    NewAttr->setInherited(true);
14562
108
    VD->addAttr(NewAttr);
14563
108
  } else 
if (Attr *5
A5
= FD->getAttr<DLLExportStaticLocalAttr>()) {
14564
4
    auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14565
4
    NewAttr->setInherited(true);
14566
4
    VD->addAttr(NewAttr);
14567
14568
    // Export this function to enforce exporting this static variable even
14569
    // if it is not used in this compilation unit.
14570
4
    if (!FD->hasAttr<DLLExportAttr>())
14571
4
      FD->addAttr(NewAttr);
14572
14573
4
  } else 
if (Attr *1
A1
= FD->getAttr<DLLImportStaticLocalAttr>()) {
14574
1
    auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14575
1
    NewAttr->setInherited(true);
14576
1
    VD->addAttr(NewAttr);
14577
1
  }
14578
113
}
14579
14580
1.24k
void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14581
1.24k
  assert(VD->getTLSKind());
14582
14583
  // Perform TLS alignment check here after attributes attached to the variable
14584
  // which may affect the alignment have been processed. Only perform the check
14585
  // if the target has a maximum TLS alignment (zero means no constraints).
14586
1.24k
  if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14587
    // Protect the check so that it's not performed on dependent types and
14588
    // dependent alignments (we can't determine the alignment in that case).
14589
179
    if (!VD->hasDependentAlignment()) {
14590
172
      CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14591
172
      if (Context.getDeclAlign(VD) > MaxAlignChars) {
14592
7
        Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14593
7
            << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14594
7
            << (unsigned)MaxAlignChars.getQuantity();
14595
7
      }
14596
172
    }
14597
179
  }
14598
1.24k
}
14599
14600
/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14601
/// any semantic actions necessary after any initializer has been attached.
14602
37.2M
void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14603
  // Note that we are no longer parsing the initializer for this declaration.
14604
37.2M
  ParsingInitForAutoVars.erase(ThisDecl);
14605
14606
37.2M
  VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14607
37.2M
  if (!VD)
14608
34.1M
    return;
14609
14610
  // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14611
3.09M
  if (VD->hasGlobalStorage() && 
VD->isThisDeclarationADefinition()1.36M
&&
14612
3.09M
      
!inTemplateInstantiation()178k
&&
!VD->hasAttr<SectionAttr>()178k
) {
14613
178k
    if (PragmaClangBSSSection.Valid)
14614
48
      VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14615
48
          Context, PragmaClangBSSSection.SectionName,
14616
48
          PragmaClangBSSSection.PragmaLocation));
14617
178k
    if (PragmaClangDataSection.Valid)
14618
32
      VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14619
32
          Context, PragmaClangDataSection.SectionName,
14620
32
          PragmaClangDataSection.PragmaLocation));
14621
178k
    if (PragmaClangRodataSection.Valid)
14622
44
      VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14623
44
          Context, PragmaClangRodataSection.SectionName,
14624
44
          PragmaClangRodataSection.PragmaLocation));
14625
178k
    if (PragmaClangRelroSection.Valid)
14626
12
      VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14627
12
          Context, PragmaClangRelroSection.SectionName,
14628
12
          PragmaClangRelroSection.PragmaLocation));
14629
178k
  }
14630
14631
3.09M
  if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14632
1.34k
    for (auto *BD : DD->bindings()) {
14633
1.34k
      FinalizeDeclaration(BD);
14634
1.34k
    }
14635
694
  }
14636
14637
3.09M
  checkAttributesAfterMerging(*this, *VD);
14638
14639
3.09M
  if (VD->isStaticLocal())
14640
9.38k
    CheckStaticLocalForDllExport(VD);
14641
14642
3.09M
  if (VD->getTLSKind())
14643
1.01k
    CheckThreadLocalForLargeAlignment(VD);
14644
14645
  // Perform check for initializers of device-side global variables.
14646
  // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14647
  // 7.5). We must also apply the same checks to all __shared__
14648
  // variables whether they are local or not. CUDA also allows
14649
  // constant initializers for __constant__ and __device__ variables.
14650
3.09M
  if (getLangOpts().CUDA)
14651
2.89k
    checkAllowedCUDAInitializer(VD);
14652
14653
  // Grab the dllimport or dllexport attribute off of the VarDecl.
14654
3.09M
  const InheritableAttr *DLLAttr = getDLLAttr(VD);
14655
14656
  // Imported static data members cannot be defined out-of-line.
14657
3.09M
  if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14658
1.92k
    if (VD->isStaticDataMember() && 
VD->isOutOfLine()591
&&
14659
1.92k
        
VD->isThisDeclarationADefinition()238
) {
14660
      // We allow definitions of dllimport class template static data members
14661
      // with a warning.
14662
194
      CXXRecordDecl *Context =
14663
194
        cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14664
194
      bool IsClassTemplateMember =
14665
194
          isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14666
194
          
Context->getDescribedClassTemplate()190
;
14667
14668
194
      Diag(VD->getLocation(),
14669
194
           IsClassTemplateMember
14670
194
               ? 
diag::warn_attribute_dllimport_static_field_definition76
14671
194
               : 
diag::err_attribute_dllimport_static_field_definition118
);
14672
194
      Diag(IA->getLocation(), diag::note_attribute);
14673
194
      if (!IsClassTemplateMember)
14674
118
        VD->setInvalidDecl();
14675
194
    }
14676
1.92k
  }
14677
14678
  // dllimport/dllexport variables cannot be thread local, their TLS index
14679
  // isn't exported with the variable.
14680
3.09M
  if (DLLAttr && 
VD->getTLSKind()3.52k
) {
14681
54
    auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14682
54
    if (F && 
getDLLAttr(F)22
) {
14683
22
      assert(VD->isStaticLocal());
14684
      // But if this is a static local in a dlimport/dllexport function, the
14685
      // function will never be inlined, which means the var would never be
14686
      // imported, so having it marked import/export is safe.
14687
32
    } else {
14688
32
      Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14689
32
                                                                    << DLLAttr;
14690
32
      VD->setInvalidDecl();
14691
32
    }
14692
54
  }
14693
14694
3.09M
  if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14695
115
    if (!Attr->isInherited() && 
!VD->isThisDeclarationADefinition()110
) {
14696
4
      Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14697
4
          << Attr;
14698
4
      VD->dropAttr<UsedAttr>();
14699
4
    }
14700
115
  }
14701
3.09M
  if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14702
14
    if (!Attr->isInherited() && 
!VD->isThisDeclarationADefinition()12
) {
14703
2
      Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14704
2
          << Attr;
14705
2
      VD->dropAttr<RetainAttr>();
14706
2
    }
14707
14
  }
14708
14709
3.09M
  const DeclContext *DC = VD->getDeclContext();
14710
  // If there's a #pragma GCC visibility in scope, and this isn't a class
14711
  // member, set the visibility of this variable.
14712
3.09M
  if (DC->getRedeclContext()->isFileContext() && 
VD->isExternallyVisible()1.06M
)
14713
1.03M
    AddPushedVisibilityAttribute(VD);
14714
14715
  // FIXME: Warn on unused var template partial specializations.
14716
3.09M
  if (VD->isFileVarDecl() && 
!isa<VarTemplatePartialSpecializationDecl>(VD)1.35M
)
14717
1.35M
    MarkUnusedFileScopedDecl(VD);
14718
14719
  // Now we have parsed the initializer and can update the table of magic
14720
  // tag values.
14721
3.09M
  if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14722
3.09M
      
!VD->getType()->isIntegralOrEnumerationType()166
)
14723
3.09M
    return;
14724
14725
102
  for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14726
102
    const Expr *MagicValueExpr = VD->getInit();
14727
102
    if (!MagicValueExpr) {
14728
51
      continue;
14729
51
    }
14730
51
    std::optional<llvm::APSInt> MagicValueInt;
14731
51
    if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14732
1
      Diag(I->getRange().getBegin(),
14733
1
           diag::err_type_tag_for_datatype_not_ice)
14734
1
        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14735
1
      continue;
14736
1
    }
14737
50
    if (MagicValueInt->getActiveBits() > 64) {
14738
0
      Diag(I->getRange().getBegin(),
14739
0
           diag::err_type_tag_for_datatype_too_large)
14740
0
        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14741
0
      continue;
14742
0
    }
14743
50
    uint64_t MagicValue = MagicValueInt->getZExtValue();
14744
50
    RegisterTypeTagForDatatype(I->getArgumentKind(),
14745
50
                               MagicValue,
14746
50
                               I->getMatchingCType(),
14747
50
                               I->getLayoutCompatible(),
14748
50
                               I->getMustBeNull());
14749
50
  }
14750
102
}
14751
14752
74.8k
static bool hasDeducedAuto(DeclaratorDecl *DD) {
14753
74.8k
  auto *VD = dyn_cast<VarDecl>(DD);
14754
74.8k
  return VD && 
!VD->getType()->hasAutoForTrailingReturnType()74.3k
;
14755
74.8k
}
14756
14757
Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14758
36.8M
                                                   ArrayRef<Decl *> Group) {
14759
36.8M
  SmallVector<Decl*, 8> Decls;
14760
14761
36.8M
  if (DS.isTypeSpecOwned())
14762
399k
    Decls.push_back(DS.getRepAsDecl());
14763
14764
36.8M
  DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14765
36.8M
  DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14766
36.8M
  bool DiagnosedMultipleDecomps = false;
14767
36.8M
  DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14768
36.8M
  bool DiagnosedNonDeducedAuto = false;
14769
14770
73.9M
  for (unsigned i = 0, e = Group.size(); i != e; 
++i37.0M
) {
14771
37.0M
    if (Decl *D = Group[i]) {
14772
      // Check if the Decl has been declared in '#pragma omp declare target'
14773
      // directive and has static storage duration.
14774
37.0M
      if (auto *VD = dyn_cast<VarDecl>(D);
14775
37.0M
          LangOpts.OpenMP && 
VD331k
&&
VD->hasAttr<OMPDeclareTargetDeclAttr>()276k
&&
14776
37.0M
          
VD->hasGlobalStorage()795
)
14777
795
        ActOnOpenMPDeclareTargetInitializer(D);
14778
      // For declarators, there are some additional syntactic-ish checks we need
14779
      // to perform.
14780
37.0M
      if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14781
34.8M
        if (!FirstDeclaratorInGroup)
14782
34.6M
          FirstDeclaratorInGroup = DD;
14783
34.8M
        if (!FirstDecompDeclaratorInGroup)
14784
34.8M
          FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14785
34.8M
        if (!FirstNonDeducedAutoInGroup && 
DS.hasAutoTypeSpec()34.8M
&&
14786
34.8M
            
!hasDeducedAuto(DD)74.8k
)
14787
589
          FirstNonDeducedAutoInGroup = DD;
14788
14789
34.8M
        if (FirstDeclaratorInGroup != DD) {
14790
          // A decomposition declaration cannot be combined with any other
14791
          // declaration in the same group.
14792
173k
          if (FirstDecompDeclaratorInGroup && 
!DiagnosedMultipleDecomps12
) {
14793
12
            Diag(FirstDecompDeclaratorInGroup->getLocation(),
14794
12
                 diag::err_decomp_decl_not_alone)
14795
12
                << FirstDeclaratorInGroup->getSourceRange()
14796
12
                << DD->getSourceRange();
14797
12
            DiagnosedMultipleDecomps = true;
14798
12
          }
14799
14800
          // A declarator that uses 'auto' in any way other than to declare a
14801
          // variable with a deduced type cannot be combined with any other
14802
          // declarator in the same group.
14803
173k
          if (FirstNonDeducedAutoInGroup && 
!DiagnosedNonDeducedAuto46
) {
14804
41
            Diag(FirstNonDeducedAutoInGroup->getLocation(),
14805
41
                 diag::err_auto_non_deduced_not_alone)
14806
41
                << FirstNonDeducedAutoInGroup->getType()
14807
41
                       ->hasAutoForTrailingReturnType()
14808
41
                << FirstDeclaratorInGroup->getSourceRange()
14809
41
                << DD->getSourceRange();
14810
41
            DiagnosedNonDeducedAuto = true;
14811
41
          }
14812
173k
        }
14813
34.8M
      }
14814
14815
37.0M
      Decls.push_back(D);
14816
37.0M
    }
14817
37.0M
  }
14818
14819
36.8M
  if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14820
817k
    if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14821
817k
      handleTagNumbering(Tag, S);
14822
817k
      if (FirstDeclaratorInGroup && 
!Tag->hasNameForLinkage()251k
&&
14823
817k
          
getLangOpts().CPlusPlus12.1k
)
14824
11.0k
        Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14825
817k
    }
14826
817k
  }
14827
14828
36.8M
  return BuildDeclaratorGroup(Decls);
14829
36.8M
}
14830
14831
/// BuildDeclaratorGroup - convert a list of declarations into a declaration
14832
/// group, performing any necessary semantic checking.
14833
Sema::DeclGroupPtrTy
14834
37.4M
Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14835
  // C++14 [dcl.spec.auto]p7: (DR1347)
14836
  //   If the type that replaces the placeholder type is not the same in each
14837
  //   deduction, the program is ill-formed.
14838
37.4M
  if (Group.size() > 1) {
14839
465k
    QualType Deduced;
14840
465k
    VarDecl *DeducedDecl = nullptr;
14841
639k
    for (unsigned i = 0, e = Group.size(); i != e; 
++i174k
) {
14842
614k
      VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14843
614k
      if (!D || 
D->isInvalidDecl()174k
)
14844
439k
        break;
14845
174k
      DeducedType *DT = D->getType()->getContainedDeducedType();
14846
174k
      if (!DT || 
DT->getDeducedType().isNull()1.67k
)
14847
172k
        continue;
14848
1.66k
      if (Deduced.isNull()) {
14849
628
        Deduced = DT->getDeducedType();
14850
628
        DeducedDecl = D;
14851
1.03k
      } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14852
24
        auto *AT = dyn_cast<AutoType>(DT);
14853
24
        auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14854
24
                        diag::err_auto_different_deductions)
14855
24
                   << (AT ? 
(unsigned)AT->getKeyword()23
:
31
) << Deduced
14856
24
                   << DeducedDecl->getDeclName() << DT->getDeducedType()
14857
24
                   << D->getDeclName();
14858
24
        if (DeducedDecl->hasInit())
14859
24
          Dia << DeducedDecl->getInit()->getSourceRange();
14860
24
        if (D->getInit())
14861
23
          Dia << D->getInit()->getSourceRange();
14862
24
        D->setInvalidDecl();
14863
24
        break;
14864
24
      }
14865
1.66k
    }
14866
465k
  }
14867
14868
37.4M
  ActOnDocumentableDecls(Group);
14869
14870
37.4M
  return DeclGroupPtrTy::make(
14871
37.4M
      DeclGroupRef::Create(Context, Group.data(), Group.size()));
14872
37.4M
}
14873
14874
15.6M
void Sema::ActOnDocumentableDecl(Decl *D) {
14875
15.6M
  ActOnDocumentableDecls(D);
14876
15.6M
}
14877
14878
53.0M
void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14879
  // Don't parse the comment if Doxygen diagnostics are ignored.
14880
53.0M
  if (Group.empty() || 
!Group[0]53.0M
)
14881
897
    return;
14882
14883
53.0M
  if (Diags.isIgnored(diag::warn_doc_param_not_found,
14884
53.0M
                      Group[0]->getLocation()) &&
14885
53.0M
      Diags.isIgnored(diag::warn_unknown_comment_command_name,
14886
53.0M
                      Group[0]->getLocation()))
14887
53.0M
    return;
14888
14889
11.6k
  if (Group.size() >= 2) {
14890
    // This is a decl group.  Normally it will contain only declarations
14891
    // produced from declarator list.  But in case we have any definitions or
14892
    // additional declaration references:
14893
    //   'typedef struct S {} S;'
14894
    //   'typedef struct S *S;'
14895
    //   'struct S *pS;'
14896
    // FinalizeDeclaratorGroup adds these as separate declarations.
14897
55
    Decl *MaybeTagDecl = Group[0];
14898
55
    if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14899
32
      Group = Group.slice(1);
14900
32
    }
14901
55
  }
14902
14903
  // FIMXE: We assume every Decl in the group is in the same file.
14904
  // This is false when preprocessor constructs the group from decls in
14905
  // different files (e. g. macros or #include).
14906
11.6k
  Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14907
11.6k
}
14908
14909
/// Common checks for a parameter-declaration that should apply to both function
14910
/// parameters and non-type template parameters.
14911
95.1M
void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14912
  // Check that there are no default arguments inside the type of this
14913
  // parameter.
14914
95.1M
  if (getLangOpts().CPlusPlus)
14915
40.4M
    CheckExtraCXXDefaultArguments(D);
14916
14917
  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14918
95.1M
  if (D.getCXXScopeSpec().isSet()) {
14919
5
    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14920
5
      << D.getCXXScopeSpec().getRange();
14921
5
  }
14922
14923
  // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14924
  // simple identifier except [...irrelevant cases...].
14925
95.1M
  switch (D.getName().getKind()) {
14926
95.1M
  case UnqualifiedIdKind::IK_Identifier:
14927
95.1M
    break;
14928
14929
4
  case UnqualifiedIdKind::IK_OperatorFunctionId:
14930
4
  case UnqualifiedIdKind::IK_ConversionFunctionId:
14931
4
  case UnqualifiedIdKind::IK_LiteralOperatorId:
14932
4
  case UnqualifiedIdKind::IK_ConstructorName:
14933
4
  case UnqualifiedIdKind::IK_DestructorName:
14934
4
  case UnqualifiedIdKind::IK_ImplicitSelfParam:
14935
4
  case UnqualifiedIdKind::IK_DeductionGuideName:
14936
4
    Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14937
4
      << GetNameForDeclarator(D).getName();
14938
4
    break;
14939
14940
3
  case UnqualifiedIdKind::IK_TemplateId:
14941
3
  case UnqualifiedIdKind::IK_ConstructorTemplateId:
14942
    // GetNameForDeclarator would not produce a useful name in this case.
14943
3
    Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14944
3
    break;
14945
95.1M
  }
14946
95.1M
}
14947
14948
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
14949
94.6M
                                         SourceLocation ExplicitThisLoc) {
14950
94.6M
  if (!ExplicitThisLoc.isValid())
14951
94.6M
    return;
14952
216
  assert(S.getLangOpts().CPlusPlus &&
14953
216
         "explicit parameter in non-cplusplus mode");
14954
216
  if (!S.getLangOpts().CPlusPlus23)
14955
2
    S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
14956
2
        << P->getSourceRange();
14957
14958
  // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
14959
  // parameter pack.
14960
216
  if (P->isParameterPack()) {
14961
2
    S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
14962
2
        << P->getSourceRange();
14963
2
    return;
14964
2
  }
14965
214
  P->setExplicitObjectParameterLoc(ExplicitThisLoc);
14966
214
  if (LambdaScopeInfo *LSI = S.getCurLambda())
14967
26
    LSI->ExplicitObjectParameter = P;
14968
214
}
14969
14970
/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14971
/// to introduce parameters into function prototype scope.
14972
Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
14973
94.6M
                                 SourceLocation ExplicitThisLoc) {
14974
94.6M
  const DeclSpec &DS = D.getDeclSpec();
14975
14976
  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14977
14978
  // C++03 [dcl.stc]p2 also permits 'auto'.
14979
94.6M
  StorageClass SC = SC_None;
14980
94.6M
  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14981
25
    SC = SC_Register;
14982
    // In C++11, the 'register' storage class specifier is deprecated.
14983
    // In C++17, it is not allowed, but we tolerate it as an extension.
14984
25
    if (getLangOpts().CPlusPlus11) {
14985
13
      Diag(DS.getStorageClassSpecLoc(),
14986
13
           getLangOpts().CPlusPlus17 ? 
diag::ext_register_storage_class5
14987
13
                                     : 
diag::warn_deprecated_register8
)
14988
13
        << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14989
13
    }
14990
94.6M
  } else if (getLangOpts().CPlusPlus &&
14991
94.6M
             
DS.getStorageClassSpec() == DeclSpec::SCS_auto40.0M
) {
14992
3
    SC = SC_Auto;
14993
94.6M
  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14994
10
    Diag(DS.getStorageClassSpecLoc(),
14995
10
         diag::err_invalid_storage_class_in_func_decl);
14996
10
    D.getMutableDeclSpec().ClearStorageClassSpecs();
14997
10
  }
14998
14999
94.6M
  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15000
7
    Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15001
7
      << DeclSpec::getSpecifierName(TSCS);
15002
94.6M
  if (DS.isInlineSpecified())
15003
1
    Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15004
1
        << getLangOpts().CPlusPlus17;
15005
94.6M
  if (DS.hasConstexprSpecifier())
15006
11
    Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15007
11
        << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15008
15009
94.6M
  DiagnoseFunctionSpecifiers(DS);
15010
15011
94.6M
  CheckFunctionOrTemplateParamDeclarator(S, D);
15012
15013
94.6M
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15014
94.6M
  QualType parmDeclType = TInfo->getType();
15015
15016
  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15017
94.6M
  IdentifierInfo *II = D.getIdentifier();
15018
94.6M
  if (II) {
15019
13.8M
    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15020
13.8M
                   ForVisibleRedeclaration);
15021
13.8M
    LookupName(R, S);
15022
13.8M
    if (!R.empty()) {
15023
35.0k
      NamedDecl *PrevDecl = *R.begin();
15024
35.0k
      if (R.isSingleResult() && 
PrevDecl->isTemplateParameter()31.8k
) {
15025
        // Maybe we will complain about the shadowed template parameter.
15026
7
        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15027
        // Just pretend that we didn't see the previous declaration.
15028
7
        PrevDecl = nullptr;
15029
7
      }
15030
35.0k
      if (PrevDecl && 
S->isDeclScope(PrevDecl)35.0k
) {
15031
8
        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15032
8
        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15033
        // Recover by removing the name
15034
8
        II = nullptr;
15035
8
        D.SetIdentifier(nullptr, D.getIdentifierLoc());
15036
8
        D.setInvalidType(true);
15037
8
      }
15038
35.0k
    }
15039
13.8M
  }
15040
15041
  // Temporarily put parameter variables in the translation unit, not
15042
  // the enclosing context.  This prevents them from accidentally
15043
  // looking like class members in C++.
15044
94.6M
  ParmVarDecl *New =
15045
94.6M
      CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15046
94.6M
                     D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15047
15048
94.6M
  if (D.isInvalidType())
15049
505
    New->setInvalidDecl();
15050
15051
94.6M
  CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15052
15053
94.6M
  assert(S->isFunctionPrototypeScope());
15054
94.6M
  assert(S->getFunctionPrototypeDepth() >= 1);
15055
94.6M
  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15056
94.6M
                    S->getNextFunctionPrototypeIndex());
15057
15058
  // Add the parameter declaration into this scope.
15059
94.6M
  S->AddDecl(New);
15060
94.6M
  if (II)
15061
13.8M
    IdResolver.AddDecl(New);
15062
15063
94.6M
  ProcessDeclAttributes(S, New, D);
15064
15065
94.6M
  if (D.getDeclSpec().isModulePrivateSpecified())
15066
2
    Diag(New->getLocation(), diag::err_module_private_local)
15067
2
        << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15068
2
        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15069
15070
94.6M
  if (New->hasAttr<BlocksAttr>()) {
15071
1
    Diag(New->getLocation(), diag::err_block_on_nonlocal);
15072
1
  }
15073
15074
94.6M
  if (getLangOpts().OpenCL)
15075
469k
    deduceOpenCLAddressSpace(New);
15076
15077
94.6M
  return New;
15078
94.6M
}
15079
15080
/// Synthesizes a variable for a parameter arising from a
15081
/// typedef.
15082
ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15083
                                              SourceLocation Loc,
15084
151
                                              QualType T) {
15085
  /* FIXME: setting StartLoc == Loc.
15086
     Would it be worth to modify callers so as to provide proper source
15087
     location for the unnamed parameters, embedding the parameter's type? */
15088
151
  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15089
151
                                T, Context.getTrivialTypeSourceInfo(T, Loc),
15090
151
                                           SC_None, nullptr);
15091
151
  Param->setImplicit();
15092
151
  return Param;
15093
151
}
15094
15095
5.90M
void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15096
  // Don't diagnose unused-parameter errors in template instantiations; we
15097
  // will already have done so in the template itself.
15098
5.90M
  if (inTemplateInstantiation())
15099
268k
    return;
15100
15101
9.45M
  
for (const ParmVarDecl *Parameter : Parameters)5.63M
{
15102
9.45M
    if (!Parameter->isReferenced() && 
Parameter->getDeclName()221k
&&
15103
9.45M
        
!Parameter->hasAttr<UnusedAttr>()41.1k
&&
15104
9.45M
        
!Parameter->getIdentifier()->isPlaceholder()40.8k
) {
15105
40.8k
      Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15106
40.8k
        << Parameter->getDeclName();
15107
40.8k
    }
15108
9.45M
  }
15109
5.63M
}
15110
15111
void Sema::DiagnoseSizeOfParametersAndReturnValue(
15112
5.91M
    ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15113
5.91M
  if (LangOpts.NumLargeByValueCopy == 0) // No check.
15114
5.91M
    return;
15115
15116
  // Warn if the return value is pass-by-value and larger than the specified
15117
  // threshold.
15118
10
  if (!ReturnTy->isDependentType() && 
ReturnTy.isPODType(Context)9
) {
15119
3
    unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15120
3
    if (Size > LangOpts.NumLargeByValueCopy)
15121
2
      Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15122
3
  }
15123
15124
  // Warn if any parameter is pass-by-value and larger than the specified
15125
  // threshold.
15126
10
  for (const ParmVarDecl *Parameter : Parameters) {
15127
8
    QualType T = Parameter->getType();
15128
8
    if (T->isDependentType() || 
!T.isPODType(Context)7
)
15129
2
      continue;
15130
6
    unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15131
6
    if (Size > LangOpts.NumLargeByValueCopy)
15132
4
      Diag(Parameter->getLocation(), diag::warn_parameter_size)
15133
4
          << Parameter << Size;
15134
6
  }
15135
10
}
15136
15137
ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15138
                                  SourceLocation NameLoc, IdentifierInfo *Name,
15139
                                  QualType T, TypeSourceInfo *TSInfo,
15140
98.1M
                                  StorageClass SC) {
15141
  // In ARC, infer a lifetime qualifier for appropriate parameter types.
15142
98.1M
  if (getLangOpts().ObjCAutoRefCount &&
15143
98.1M
      
T.getObjCLifetime() == Qualifiers::OCL_None154k
&&
15144
98.1M
      
T->isObjCLifetimeType()153k
) {
15145
15146
18.5k
    Qualifiers::ObjCLifetime lifetime;
15147
15148
    // Special cases for arrays:
15149
    //   - if it's const, use __unsafe_unretained
15150
    //   - otherwise, it's an error
15151
18.5k
    if (T->isArrayType()) {
15152
205
      if (!T.isConstQualified()) {
15153
10
        if (DelayedDiagnostics.shouldDelayDiagnostics())
15154
8
          DelayedDiagnostics.add(
15155
8
              sema::DelayedDiagnostic::makeForbiddenType(
15156
8
              NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15157
2
        else
15158
2
          Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15159
2
              << TSInfo->getTypeLoc().getSourceRange();
15160
10
      }
15161
205
      lifetime = Qualifiers::OCL_ExplicitNone;
15162
18.3k
    } else {
15163
18.3k
      lifetime = T->getObjCARCImplicitLifetime();
15164
18.3k
    }
15165
18.5k
    T = Context.getLifetimeQualifiedType(T, lifetime);
15166
18.5k
  }
15167
15168
98.1M
  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15169
98.1M
                                         Context.getAdjustedParameterType(T),
15170
98.1M
                                         TSInfo, SC, nullptr);
15171
15172
  // Make a note if we created a new pack in the scope of a lambda, so that
15173
  // we know that references to that pack must also be expanded within the
15174
  // lambda scope.
15175
98.1M
  if (New->isParameterPack())
15176
115k
    if (auto *LSI = getEnclosingLambda())
15177
805
      LSI->LocalPacks.push_back(New);
15178
15179
98.1M
  if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15180
98.1M
      
New->getType().hasNonTrivialToPrimitiveCopyCUnion()98.1M
)
15181
7
    checkNonTrivialCUnion(New->getType(), New->getLocation(),
15182
7
                          NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
15183
15184
  // Parameter declarators cannot be interface types. All ObjC objects are
15185
  // passed by reference.
15186
98.1M
  if (T->isObjCObjectType()) {
15187
13
    SourceLocation TypeEndLoc =
15188
13
        getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
15189
13
    Diag(NameLoc,
15190
13
         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15191
13
      << FixItHint::CreateInsertion(TypeEndLoc, "*");
15192
13
    T = Context.getObjCObjectPointerType(T);
15193
13
    New->setType(T);
15194
13
  }
15195
15196
  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15197
  // duration shall not be qualified by an address-space qualifier."
15198
  // Since all parameters have automatic store duration, they can not have
15199
  // an address space.
15200
98.1M
  if (T.getAddressSpace() != LangAS::Default &&
15201
      // OpenCL allows function arguments declared to be an array of a type
15202
      // to be qualified with an address space.
15203
98.1M
      
!(34
getLangOpts().OpenCL34
&&
15204
34
        
(23
T->isArrayType()23
||
T.getAddressSpace() == LangAS::opencl_private13
)) &&
15205
      // WebAssembly allows reference types as parameters. Funcref in particular
15206
      // lives in a different address space.
15207
98.1M
      
!(20
T->isFunctionPointerType()20
&&
15208
20
        
T.getAddressSpace() == LangAS::wasm_funcref0
)) {
15209
20
    Diag(NameLoc, diag::err_arg_with_address_space);
15210
20
    New->setInvalidDecl();
15211
20
  }
15212
15213
  // PPC MMA non-pointer types are not allowed as function argument types.
15214
98.1M
  if (Context.getTargetInfo().getTriple().isPPC64() &&
15215
98.1M
      
CheckPPCMMAType(New->getOriginalType(), New->getLocation())68.8k
) {
15216
41
    New->setInvalidDecl();
15217
41
  }
15218
15219
98.1M
  return New;
15220
98.1M
}
15221
15222
void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15223
143
                                           SourceLocation LocAfterDecls) {
15224
143
  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15225
15226
  // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15227
  // in the declaration list shall have at least one declarator, those
15228
  // declarators shall only declare identifiers from the identifier list, and
15229
  // every identifier in the identifier list shall be declared.
15230
  //
15231
  // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15232
  // identifiers it names shall be declared in the declaration list."
15233
  //
15234
  // This is why we only diagnose in C99 and later. Note, the other conditions
15235
  // listed are checked elsewhere.
15236
143
  if (!FTI.hasPrototype) {
15237
337
    for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15238
194
      --i;
15239
194
      if (FTI.Params[i].Param == nullptr) {
15240
13
        if (getLangOpts().C99) {
15241
10
          SmallString<256> Code;
15242
10
          llvm::raw_svector_ostream(Code)
15243
10
              << "  int " << FTI.Params[i].Ident->getName() << ";\n";
15244
10
          Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15245
10
              << FTI.Params[i].Ident
15246
10
              << FixItHint::CreateInsertion(LocAfterDecls, Code);
15247
10
        }
15248
15249
        // Implicitly declare the argument as type 'int' for lack of a better
15250
        // type.
15251
13
        AttributeFactory attrs;
15252
13
        DeclSpec DS(attrs);
15253
13
        const char* PrevSpec; // unused
15254
13
        unsigned DiagID; // unused
15255
13
        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15256
13
                           DiagID, Context.getPrintingPolicy());
15257
        // Use the identifier location for the type source range.
15258
13
        DS.SetRangeStart(FTI.Params[i].IdentLoc);
15259
13
        DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15260
13
        Declarator ParamD(DS, ParsedAttributesView::none(),
15261
13
                          DeclaratorContext::KNRTypeList);
15262
13
        ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15263
13
        FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15264
13
      }
15265
194
    }
15266
143
  }
15267
143
}
15268
15269
Decl *
15270
Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15271
                              MultiTemplateParamsArg TemplateParameterLists,
15272
4.59M
                              SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15273
4.59M
  assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15274
4.59M
  assert(D.isFunctionDeclarator() && "Not a function declarator!");
15275
4.59M
  Scope *ParentScope = FnBodyScope->getParent();
15276
15277
  // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15278
  // we define a non-templated function definition, we will create a declaration
15279
  // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15280
  // The base function declaration will have the equivalent of an `omp declare
15281
  // variant` annotation which specifies the mangled definition as a
15282
  // specialization function under the OpenMP context defined as part of the
15283
  // `omp begin declare variant`.
15284
4.59M
  SmallVector<FunctionDecl *, 4> Bases;
15285
4.59M
  if (LangOpts.OpenMP && 
isInOpenMPDeclareVariantScope()46.8k
)
15286
8.77k
    ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15287
8.77k
        ParentScope, D, TemplateParameterLists, Bases);
15288
15289
4.59M
  D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15290
4.59M
  Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15291
4.59M
  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15292
15293
4.59M
  if (!Bases.empty())
15294
8.67k
    ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
15295
15296
4.59M
  return Dcl;
15297
4.59M
}
15298
15299
876k
void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15300
876k
  Consumer.HandleInlineFunctionDefinition(D);
15301
876k
}
15302
15303
static bool FindPossiblePrototype(const FunctionDecl *FD,
15304
6.15M
                                  const FunctionDecl *&PossiblePrototype) {
15305
6.15M
  for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15306
6.15M
       
Prev = Prev->getPreviousDecl()36
) {
15307
    // Ignore any declarations that occur in function or method
15308
    // scope, because they aren't visible from the header.
15309
320k
    if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15310
36
      continue;
15311
15312
320k
    PossiblePrototype = Prev;
15313
320k
    return Prev->getType()->isFunctionProtoType();
15314
320k
  }
15315
5.83M
  return false;
15316
6.15M
}
15317
15318
static bool
15319
ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15320
5.91M
                                const FunctionDecl *&PossiblePrototype) {
15321
  // Don't warn about invalid declarations.
15322
5.91M
  if (FD->isInvalidDecl())
15323
7.25k
    return false;
15324
15325
  // Or declarations that aren't global.
15326
5.90M
  if (!FD->isGlobal())
15327
4.61M
    return false;
15328
15329
  // Don't warn about C++ member functions.
15330
1.29M
  if (isa<CXXMethodDecl>(FD))
15331
223k
    return false;
15332
15333
  // Don't warn about 'main'.
15334
1.07M
  if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15335
357k
    if (IdentifierInfo *II = FD->getIdentifier())
15336
350k
      if (II->isStr("main") || 
II->isStr("efi_main")340k
)
15337
10.3k
        return false;
15338
15339
  // Don't warn about inline functions.
15340
1.06M
  if (FD->isInlined())
15341
586k
    return false;
15342
15343
  // Don't warn about function templates.
15344
475k
  if (FD->getDescribedFunctionTemplate())
15345
199k
    return false;
15346
15347
  // Don't warn about function template specializations.
15348
275k
  if (FD->isFunctionTemplateSpecialization())
15349
32.6k
    return false;
15350
15351
  // Don't warn for OpenCL kernels.
15352
243k
  if (FD->hasAttr<OpenCLKernelAttr>())
15353
1.11k
    return false;
15354
15355
  // Don't warn on explicitly deleted functions.
15356
242k
  if (FD->isDeleted())
15357
0
    return false;
15358
15359
  // Don't warn on implicitly local functions (such as having local-typed
15360
  // parameters).
15361
242k
  if (!FD->isExternallyVisible())
15362
200
    return false;
15363
15364
  // If we were able to find a potential prototype, don't warn.
15365
241k
  if (FindPossiblePrototype(FD, PossiblePrototype))
15366
2.58k
    return false;
15367
15368
239k
  return true;
15369
241k
}
15370
15371
void
15372
Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15373
                                   const FunctionDecl *EffectiveDefinition,
15374
5.90M
                                   SkipBodyInfo *SkipBody) {
15375
5.90M
  const FunctionDecl *Definition = EffectiveDefinition;
15376
5.90M
  if (!Definition &&
15377
5.90M
      
!FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)5.90M
)
15378
5.90M
    return;
15379
15380
347
  if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15381
39
    if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15382
21
      if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15383
        // A merged copy of the same function, instantiated as a member of
15384
        // the same class, is OK.
15385
19
        if (declaresSameEntity(OrigFD, OrigDef) &&
15386
19
            declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15387
16
                               cast<Decl>(FD->getLexicalDeclContext())))
15388
0
          return;
15389
19
      }
15390
21
    }
15391
39
  }
15392
15393
347
  if (canRedefineFunction(Definition, getLangOpts()))
15394
14
    return;
15395
15396
  // Don't emit an error when this is redefinition of a typo-corrected
15397
  // definition.
15398
333
  if (TypoCorrectedFunctionDefinitions.count(Definition))
15399
4
    return;
15400
15401
  // If we don't have a visible definition of the function, and it's inline or
15402
  // a template, skip the new definition.
15403
329
  if (SkipBody && 
!hasVisibleDefinition(Definition)282
&&
15404
329
      
(128
Definition->getFormalLinkage() == Linkage::Internal128
||
15405
128
       Definition->isInlined() || 
Definition->getDescribedFunctionTemplate()64
||
15406
128
       
Definition->getNumTemplateParameterLists()24
)) {
15407
128
    SkipBody->ShouldSkip = true;
15408
128
    SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15409
128
    if (auto *TD = Definition->getDescribedFunctionTemplate())
15410
42
      makeMergedDefinitionVisible(TD);
15411
128
    makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15412
128
    return;
15413
128
  }
15414
15415
201
  if (getLangOpts().GNUMode && 
Definition->isInlineSpecified()63
&&
15416
201
      
Definition->getStorageClass() == SC_Extern2
)
15417
1
    Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15418
1
        << FD << getLangOpts().CPlusPlus;
15419
200
  else
15420
200
    Diag(FD->getLocation(), diag::err_redefinition) << FD;
15421
15422
201
  Diag(Definition->getLocation(), diag::note_previous_definition);
15423
201
  FD->setInvalidDecl();
15424
201
}
15425
15426
5.44k
LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15427
5.44k
  CXXRecordDecl *LambdaClass = CallOperator->getParent();
15428
15429
5.44k
  LambdaScopeInfo *LSI = PushLambdaScope();
15430
5.44k
  LSI->CallOperator = CallOperator;
15431
5.44k
  LSI->Lambda = LambdaClass;
15432
5.44k
  LSI->ReturnType = CallOperator->getReturnType();
15433
  // This function in calls in situation where the context of the call operator
15434
  // is not entered, so we set AfterParameterList to false, so that
15435
  // `tryCaptureVariable` finds explicit captures in the appropriate context.
15436
5.44k
  LSI->AfterParameterList = false;
15437
5.44k
  const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15438
15439
5.44k
  if (LCD == LCD_None)
15440
4.25k
    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15441
1.19k
  else if (LCD == LCD_ByCopy)
15442
1.02k
    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15443
162
  else if (LCD == LCD_ByRef)
15444
162
    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15445
5.44k
  DeclarationNameInfo DNI = CallOperator->getNameInfo();
15446
15447
5.44k
  LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15448
5.44k
  LSI->Mutable = !CallOperator->isConst();
15449
5.44k
  if (CallOperator->isExplicitObjectMemberFunction())
15450
20
    LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15451
15452
  // Add the captures to the LSI so they can be noted as already
15453
  // captured within tryCaptureVar.
15454
5.44k
  auto I = LambdaClass->field_begin();
15455
5.44k
  for (const auto &C : LambdaClass->captures()) {
15456
1.31k
    if (C.capturesVariable()) {
15457
984
      ValueDecl *VD = C.getCapturedVar();
15458
984
      if (VD->isInitCapture())
15459
107
        CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15460
984
      const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15461
984
      LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15462
984
          /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15463
984
          /*EllipsisLoc*/C.isPackExpansion()
15464
984
                         ? 
C.getEllipsisLoc()0
: SourceLocation(),
15465
984
          I->getType(), /*Invalid*/false);
15466
15467
984
    } else 
if (326
C.capturesThis()326
) {
15468
326
      LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15469
326
                          C.getCaptureKind() == LCK_StarThis);
15470
326
    } else {
15471
0
      LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15472
0
                             I->getType());
15473
0
    }
15474
1.31k
    ++I;
15475
1.31k
  }
15476
5.44k
  return LSI;
15477
5.44k
}
15478
15479
Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15480
                                    SkipBodyInfo *SkipBody,
15481
5.90M
                                    FnBodyKind BodyKind) {
15482
5.90M
  if (!D) {
15483
    // Parsing the function declaration failed in some way. Push on a fake scope
15484
    // anyway so we can try to parse the function body.
15485
36
    PushFunctionScope();
15486
36
    PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15487
36
    return D;
15488
36
  }
15489
15490
5.90M
  FunctionDecl *FD = nullptr;
15491
15492
5.90M
  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15493
693k
    FD = FunTmpl->getTemplatedDecl();
15494
5.20M
  else
15495
5.20M
    FD = cast<FunctionDecl>(D);
15496
15497
  // Do not push if it is a lambda because one is already pushed when building
15498
  // the lambda in ActOnStartOfLambdaDefinition().
15499
5.90M
  if (!isLambdaCallOperator(FD))
15500
    // [expr.const]/p14.1
15501
    // An expression or conversion is in an immediate function context if it is
15502
    // potentially evaluated and either: its innermost enclosing non-block scope
15503
    // is a function parameter scope of an immediate function.
15504
5.90M
    PushExpressionEvaluationContext(
15505
5.90M
        FD->isConsteval() ? 
ExpressionEvaluationContext::ImmediateFunctionContext382
15506
5.90M
                          : 
ExprEvalContexts.back().Context5.89M
);
15507
15508
  // Each ExpressionEvaluationContextRecord also keeps track of whether the
15509
  // context is nested in an immediate function context, so smaller contexts
15510
  // that appear inside immediate functions (like variable initializers) are
15511
  // considered to be inside an immediate function context even though by
15512
  // themselves they are not immediate function contexts. But when a new
15513
  // function is entered, we need to reset this tracking, since the entered
15514
  // function might be not an immediate function.
15515
5.90M
  ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15516
5.90M
  ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15517
5.90M
      getLangOpts().CPlusPlus20 && 
FD->isImmediateEscalating()76.7k
;
15518
15519
  // Check for defining attributes before the check for redefinition.
15520
5.90M
  if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15521
1
    Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15522
1
    FD->dropAttr<AliasAttr>();
15523
1
    FD->setInvalidDecl();
15524
1
  }
15525
5.90M
  if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15526
1
    Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15527
1
    FD->dropAttr<IFuncAttr>();
15528
1
    FD->setInvalidDecl();
15529
1
  }
15530
5.90M
  if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15531
120
    if (!Context.getTargetInfo().hasFeature("fmv") &&
15532
120
        
!Attr->isDefaultVersion()29
) {
15533
      // If function multi versioning disabled skip parsing function body
15534
      // defined with non-default target_version attribute
15535
29
      if (SkipBody)
15536
29
        SkipBody->ShouldSkip = true;
15537
29
      return nullptr;
15538
29
    }
15539
120
  }
15540
15541
5.90M
  if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15542
299k
    if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15543
299k
        
Ctor->isDefaultConstructor()44
&&
15544
299k
        
Context.getTargetInfo().getCXXABI().isMicrosoft()20
) {
15545
      // If this is an MS ABI dllexport default constructor, instantiate any
15546
      // default arguments.
15547
3
      InstantiateDefaultCtorDefaultArgs(Ctor);
15548
3
    }
15549
299k
  }
15550
15551
  // See if this is a redefinition. If 'will have body' (or similar) is already
15552
  // set, then these checks were already performed when it was set.
15553
5.90M
  if (!FD->willHaveBody() && 
!FD->isLateTemplateParsed()4.86M
&&
15554
5.90M
      
!FD->isThisDeclarationInstantiatedFromAFriendDefinition()4.86M
) {
15555
4.86M
    CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15556
15557
    // If we're skipping the body, we're done. Don't enter the scope.
15558
4.86M
    if (SkipBody && 
SkipBody->ShouldSkip4.59M
)
15559
128
      return D;
15560
4.86M
  }
15561
15562
  // Mark this function as "will have a body eventually".  This lets users to
15563
  // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15564
  // this function.
15565
5.90M
  FD->setWillHaveBody();
15566
15567
  // If we are instantiating a generic lambda call operator, push
15568
  // a LambdaScopeInfo onto the function stack.  But use the information
15569
  // that's already been calculated (ActOnLambdaExpr) to prime the current
15570
  // LambdaScopeInfo.
15571
  // When the template operator is being specialized, the LambdaScopeInfo,
15572
  // has to be properly restored so that tryCaptureVariable doesn't try
15573
  // and capture any new variables. In addition when calculating potential
15574
  // captures during transformation of nested lambdas, it is necessary to
15575
  // have the LSI properly restored.
15576
5.90M
  if (isGenericLambdaCallOperatorSpecialization(FD)) {
15577
2.62k
    assert(inTemplateInstantiation() &&
15578
2.62k
           "There should be an active template instantiation on the stack "
15579
2.62k
           "when instantiating a generic lambda!");
15580
2.62k
    RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15581
5.89M
  } else {
15582
    // Enter a new function scope
15583
5.89M
    PushFunctionScope();
15584
5.89M
  }
15585
15586
  // Builtin functions cannot be defined.
15587
5.90M
  if (unsigned BuiltinID = FD->getBuiltinID()) {
15588
6.25k
    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15589
6.25k
        
!Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)3
) {
15590
0
      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15591
0
      FD->setInvalidDecl();
15592
0
    }
15593
6.25k
  }
15594
15595
  // The return type of a function definition must be complete (C99 6.9.1p3).
15596
  // C++23 [dcl.fct.def.general]/p2
15597
  // The type of [...] the return for a function definition
15598
  // shall not be a (possibly cv-qualified) class type that is incomplete
15599
  // or abstract within the function body unless the function is deleted.
15600
5.90M
  QualType ResultType = FD->getReturnType();
15601
5.90M
  if (!ResultType->isDependentType() && 
!ResultType->isVoidType()5.13M
&&
15602
5.90M
      
!FD->isInvalidDecl()4.27M
&&
BodyKind != FnBodyKind::Delete4.27M
&&
15603
5.90M
      
(4.27M
RequireCompleteType(FD->getLocation(), ResultType,
15604
4.27M
                           diag::err_func_def_incomplete_result) ||
15605
4.27M
       RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15606
4.27M
                              diag::err_abstract_type_in_decl,
15607
4.27M
                              AbstractReturnType)))
15608
38
    FD->setInvalidDecl();
15609
15610
5.90M
  if (FnBodyScope)
15611
5.63M
    PushDeclContext(FnBodyScope, FD);
15612
15613
  // Check the validity of our function parameters
15614
5.90M
  if (BodyKind != FnBodyKind::Delete)
15615
5.89M
    CheckParmsForFunctionDef(FD->parameters(),
15616
5.89M
                             /*CheckParameterNames=*/true);
15617
15618
  // Add non-parameter declarations already in the function to the current
15619
  // scope.
15620
5.90M
  if (FnBodyScope) {
15621
5.63M
    for (Decl *NPD : FD->decls()) {
15622
54
      auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15623
54
      if (!NonParmDecl)
15624
0
        continue;
15625
54
      assert(!isa<ParmVarDecl>(NonParmDecl) &&
15626
54
             "parameters should not be in newly created FD yet");
15627
15628
      // If the decl has a name, make it accessible in the current scope.
15629
54
      if (NonParmDecl->getDeclName())
15630
41
        PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15631
15632
      // Similarly, dive into enums and fish their constants out, making them
15633
      // accessible in this scope.
15634
54
      if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15635
23
        for (auto *EI : ED->enumerators())
15636
31
          PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15637
23
      }
15638
54
    }
15639
5.63M
  }
15640
15641
  // Introduce our parameters into the function scope
15642
9.74M
  
for (auto *Param : FD->parameters())5.90M
{
15643
9.74M
    Param->setOwningFunction(FD);
15644
15645
    // If this has an identifier, add it to the scope stack.
15646
9.74M
    if (Param->getIdentifier() && 
FnBodyScope9.55M
) {
15647
9.27M
      CheckShadow(FnBodyScope, Param);
15648
15649
9.27M
      PushOnScopeChains(Param, FnBodyScope);
15650
9.27M
    }
15651
9.74M
  }
15652
15653
  // C++ [module.import/6] external definitions are not permitted in header
15654
  // units.  Deleted and Defaulted functions are implicitly inline (but the
15655
  // inline state is not set at this point, so check the BodyKind explicitly).
15656
  // FIXME: Consider an alternate location for the test where the inlined()
15657
  // state is complete.
15658
5.90M
  if (getLangOpts().CPlusPlusModules && 
currentModuleIsHeaderUnit()76.7k
&&
15659
5.90M
      
!FD->isInvalidDecl()14
&&
!FD->isInlined()14
&&
15660
5.90M
      
BodyKind != FnBodyKind::Delete7
&&
BodyKind != FnBodyKind::Default6
&&
15661
5.90M
      
FD->getFormalLinkage() == Linkage::External5
&&
!FD->isTemplated()5
&&
15662
5.90M
      
!FD->isTemplateInstantiation()2
) {
15663
1
    assert(FD->isThisDeclarationADefinition());
15664
1
    Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15665
1
    FD->setInvalidDecl();
15666
1
  }
15667
15668
  // Ensure that the function's exception specification is instantiated.
15669
5.90M
  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15670
5.89M
    ResolveExceptionSpec(D->getLocation(), FPT);
15671
15672
  // dllimport cannot be applied to non-inline function definitions.
15673
5.90M
  if (FD->hasAttr<DLLImportAttr>() && 
!FD->isInlined()1.51k
&&
15674
5.90M
      
!FD->isTemplateInstantiation()283
) {
15675
253
    assert(!FD->hasAttr<DLLExportAttr>());
15676
253
    Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15677
253
    FD->setInvalidDecl();
15678
253
    return D;
15679
253
  }
15680
  // We want to attach documentation to original Decl (which might be
15681
  // a function template).
15682
5.90M
  ActOnDocumentableDecl(D);
15683
5.90M
  if (getCurLexicalContext()->isObjCContainer() &&
15684
5.90M
      
getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl10
&&
15685
5.90M
      
getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation10
)
15686
8
    Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15687
15688
5.90M
  return D;
15689
5.90M
}
15690
15691
/// Given the set of return statements within a function body,
15692
/// compute the variables that are subject to the named return value
15693
/// optimization.
15694
///
15695
/// Each of the variables that is subject to the named return value
15696
/// optimization will be marked as NRVO variables in the AST, and any
15697
/// return statement that has a marked NRVO variable as its NRVO candidate can
15698
/// use the named return value optimization.
15699
///
15700
/// This function applies a very simplistic algorithm for NRVO: if every return
15701
/// statement in the scope of a variable has the same NRVO candidate, that
15702
/// candidate is an NRVO variable.
15703
79.7k
void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15704
79.7k
  ReturnStmt **Returns = Scope->Returns.data();
15705
15706
98.1k
  for (unsigned I = 0, E = Scope->Returns.size(); I != E; 
++I18.3k
) {
15707
18.3k
    if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15708
18.1k
      if (!NRVOCandidate->isNRVOVariable())
15709
187
        Returns[I]->setNRVOCandidate(nullptr);
15710
18.1k
    }
15711
18.3k
  }
15712
79.7k
}
15713
15714
458
bool Sema::canDelayFunctionBody(const Declarator &D) {
15715
  // We can't delay parsing the body of a constexpr function template (yet).
15716
458
  if (D.getDeclSpec().hasConstexprSpecifier())
15717
8
    return false;
15718
15719
  // We can't delay parsing the body of a function template with a deduced
15720
  // return type (yet).
15721
450
  if (D.getDeclSpec().hasAutoTypeSpec()) {
15722
    // If the placeholder introduces a non-deduced trailing return type,
15723
    // we can still delay parsing it.
15724
93
    if (D.getNumTypeObjects()) {
15725
93
      const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15726
93
      if (Outer.Kind == DeclaratorChunk::Function &&
15727
93
          
Outer.Fun.hasTrailingReturnType()90
) {
15728
16
        QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15729
16
        return Ty.isNull() || 
!Ty->isUndeducedType()15
;
15730
16
      }
15731
93
    }
15732
77
    return false;
15733
93
  }
15734
15735
357
  return true;
15736
450
}
15737
15738
2.66k
bool Sema::canSkipFunctionBody(Decl *D) {
15739
  // We cannot skip the body of a function (or function template) which is
15740
  // constexpr, since we may need to evaluate its body in order to parse the
15741
  // rest of the file.
15742
  // We cannot skip the body of a function with an undeduced return type,
15743
  // because any callers of that function need to know the type.
15744
2.66k
  if (const FunctionDecl *FD = D->getAsFunction()) {
15745
2.07k
    if (FD->isConstexpr())
15746
1
      return false;
15747
    // We can't simply call Type::isUndeducedType here, because inside template
15748
    // auto can be deduced to a dependent type, which is not considered
15749
    // "undeduced".
15750
2.07k
    if (FD->getReturnType()->getContainedDeducedType())
15751
5
      return false;
15752
2.07k
  }
15753
2.66k
  return Consumer.shouldSkipFunctionBody(D);
15754
2.66k
}
15755
15756
1.71k
Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15757
1.71k
  if (!Decl)
15758
0
    return nullptr;
15759
1.71k
  if (FunctionDecl *FD = Decl->getAsFunction())
15760
1.20k
    FD->setHasSkippedBody();
15761
505
  else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15762
505
    MD->setHasSkippedBody();
15763
1.71k
  return Decl;
15764
1.71k
}
15765
15766
5.64M
Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15767
5.64M
  return ActOnFinishFunctionBody(D, BodyArg, false);
15768
5.64M
}
15769
15770
/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15771
/// body.
15772
class ExitFunctionBodyRAII {
15773
public:
15774
5.92M
  ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15775
5.92M
  ~ExitFunctionBodyRAII() {
15776
5.92M
    if (!IsLambda)
15777
5.90M
      S.PopExpressionEvaluationContext();
15778
5.92M
  }
15779
15780
private:
15781
  Sema &S;
15782
  bool IsLambda = false;
15783
};
15784
15785
7.06k
static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15786
7.06k
  llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15787
15788
7.06k
  auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15789
24
    if (EscapeInfo.count(BD))
15790
4
      return EscapeInfo[BD];
15791
15792
20
    bool R = false;
15793
20
    const BlockDecl *CurBD = BD;
15794
15795
21
    do {
15796
21
      R = !CurBD->doesNotEscape();
15797
21
      if (R)
15798
18
        break;
15799
3
      CurBD = CurBD->getParent()->getInnermostBlockDecl();
15800
3
    } while (CurBD);
15801
15802
0
    return EscapeInfo[BD] = R;
15803
24
  };
15804
15805
  // If the location where 'self' is implicitly retained is inside a escaping
15806
  // block, emit a diagnostic.
15807
7.06k
  for (const std::pair<SourceLocation, const BlockDecl *> &P :
15808
7.06k
       S.ImplicitlyRetainedSelfLocs)
15809
24
    if (IsOrNestedInEscapingBlock(P.second))
15810
21
      S.Diag(P.first, diag::warn_implicitly_retains_self)
15811
21
          << FixItHint::CreateInsertion(P.first, "self->");
15812
7.06k
}
15813
15814
Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15815
5.92M
                                    bool IsInstantiation) {
15816
5.92M
  FunctionScopeInfo *FSI = getCurFunction();
15817
5.92M
  FunctionDecl *FD = dcl ? 
dcl->getAsFunction()5.92M
:
nullptr36
;
15818
15819
5.92M
  if (FSI->UsesFPIntrin && 
FD124k
&&
!FD->hasAttr<StrictFPAttr>()124k
)
15820
124k
    FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15821
15822
5.92M
  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15823
5.92M
  sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15824
15825
5.92M
  if (getLangOpts().Coroutines && 
FSI->isCoroutine()79.5k
)
15826
608
    CheckCompletedCoroutineBody(FD, Body);
15827
15828
5.92M
  {
15829
    // Do not call PopExpressionEvaluationContext() if it is a lambda because
15830
    // one is already popped when finishing the lambda in BuildLambdaExpr().
15831
    // This is meant to pop the context added in ActOnStartOfFunctionDef().
15832
5.92M
    ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15833
5.92M
    if (FD) {
15834
5.91M
      FD->setBody(Body);
15835
5.91M
      FD->setWillHaveBody(false);
15836
5.91M
      CheckImmediateEscalatingFunctionDefinition(FD, FSI);
15837
15838
5.91M
      if (getLangOpts().CPlusPlus14) {
15839
985k
        if (!FD->isInvalidDecl() && 
Body982k
&&
!FD->isDependentContext()981k
&&
15840
985k
            
FD->getReturnType()->isUndeducedType()837k
) {
15841
          // For a function with a deduced result type to return void,
15842
          // the result type as written must be 'auto' or 'decltype(auto)',
15843
          // possibly cv-qualified or constrained, but not ref-qualified.
15844
2.65k
          if (!FD->getReturnType()->getAs<AutoType>()) {
15845
21
            Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15846
21
                << FD->getReturnType();
15847
21
            FD->setInvalidDecl();
15848
2.63k
          } else {
15849
            // Falling off the end of the function is the same as 'return;'.
15850
2.63k
            Expr *Dummy = nullptr;
15851
2.63k
            if (DeduceFunctionTypeFromReturnExpr(
15852
2.63k
                    FD, dcl->getLocation(), Dummy,
15853
2.63k
                    FD->getReturnType()->getAs<AutoType>()))
15854
2
              FD->setInvalidDecl();
15855
2.63k
          }
15856
2.65k
        }
15857
4.92M
      } else if (getLangOpts().CPlusPlus11 && 
isLambdaCallOperator(FD)2.16M
) {
15858
        // In C++11, we don't use 'auto' deduction rules for lambda call
15859
        // operators because we don't support return type deduction.
15860
2.97k
        auto *LSI = getCurLambda();
15861
2.97k
        if (LSI->HasImplicitReturnType) {
15862
2.82k
          deduceClosureReturnType(*LSI);
15863
15864
          // C++11 [expr.prim.lambda]p4:
15865
          //   [...] if there are no return statements in the compound-statement
15866
          //   [the deduced type is] the type void
15867
2.82k
          QualType RetType =
15868
2.82k
              LSI->ReturnType.isNull() ? 
Context.VoidTy0
: LSI->ReturnType;
15869
15870
          // Update the return type to the deduced type.
15871
2.82k
          const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15872
2.82k
          FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15873
2.82k
                                              Proto->getExtProtoInfo()));
15874
2.82k
        }
15875
2.97k
      }
15876
15877
      // If the function implicitly returns zero (like 'main') or is naked,
15878
      // don't complain about missing return statements.
15879
5.91M
      if (FD->hasImplicitReturnZero() || 
FD->hasAttr<NakedAttr>()5.90M
)
15880
10.3k
        WP.disableCheckFallThrough();
15881
15882
      // MSVC permits the use of pure specifier (=0) on function definition,
15883
      // defined at class scope, warn about this non-standard construct.
15884
5.91M
      if (getLangOpts().MicrosoftExt && 
FD->isPure()105k
&&
!FD->isOutOfLine()9
)
15885
6
        Diag(FD->getLocation(), diag::ext_pure_function_definition);
15886
15887
5.91M
      if (!FD->isInvalidDecl()) {
15888
        // Don't diagnose unused parameters of defaulted, deleted or naked
15889
        // functions.
15890
5.90M
        if (!FD->isDeleted() && 
!FD->isDefaulted()5.90M
&&
!FD->hasSkippedBody()5.90M
&&
15891
5.90M
            
!FD->hasAttr<NakedAttr>()5.90M
)
15892
5.90M
          DiagnoseUnusedParameters(FD->parameters());
15893
5.90M
        DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15894
5.90M
                                               FD->getReturnType(), FD);
15895
15896
        // If this is a structor, we need a vtable.
15897
5.90M
        if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15898
299k
          MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15899
5.60M
        else if (CXXDestructorDecl *Destructor =
15900
5.60M
                     dyn_cast<CXXDestructorDecl>(FD))
15901
34.3k
          MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15902
15903
        // Try to apply the named return value optimization. We have to check
15904
        // if we can do this here because lambdas keep return statements around
15905
        // to deduce an implicit return type.
15906
5.90M
        if (FD->getReturnType()->isRecordType() &&
15907
5.90M
            
(83.4k
!getLangOpts().CPlusPlus83.4k
||
!FD->isDependentContext()63.4k
))
15908
72.7k
          computeNRVO(Body, FSI);
15909
5.90M
      }
15910
15911
      // GNU warning -Wmissing-prototypes:
15912
      //   Warn if a global function is defined without a previous
15913
      //   prototype declaration. This warning is issued even if the
15914
      //   definition itself provides a prototype. The aim is to detect
15915
      //   global functions that fail to be declared in header files.
15916
5.91M
      const FunctionDecl *PossiblePrototype = nullptr;
15917
5.91M
      if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15918
239k
        Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15919
15920
239k
        if (PossiblePrototype) {
15921
          // We found a declaration that is not a prototype,
15922
          // but that could be a zero-parameter prototype
15923
78
          if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15924
78
            TypeLoc TL = TI->getTypeLoc();
15925
78
            if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15926
75
              Diag(PossiblePrototype->getLocation(),
15927
75
                   diag::note_declaration_not_a_prototype)
15928
75
                  << (FD->getNumParams() != 0)
15929
75
                  << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15930
52
                                                    FTL.getRParenLoc(), "void")
15931
75
                                              : 
FixItHint{}23
);
15932
78
          }
15933
239k
        } else {
15934
          // Returns true if the token beginning at this Loc is `const`.
15935
239k
          auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15936
239k
                                  const LangOptions &LangOpts) {
15937
448
            std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15938
448
            if (LocInfo.first.isInvalid())
15939
0
              return false;
15940
15941
448
            bool Invalid = false;
15942
448
            StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15943
448
            if (Invalid)
15944
12
              return false;
15945
15946
436
            if (LocInfo.second > Buffer.size())
15947
0
              return false;
15948
15949
436
            const char *LexStart = Buffer.data() + LocInfo.second;
15950
436
            StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15951
15952
436
            return StartTok.consume_front("const") &&
15953
436
                   
(304
StartTok.empty()304
||
isWhitespace(StartTok[0])304
||
15954
304
                    
StartTok.startswith("/*")2
||
StartTok.startswith("//")0
);
15955
436
          };
15956
15957
239k
          auto findBeginLoc = [&]() {
15958
            // If the return type has `const` qualifier, we want to insert
15959
            // `static` before `const` (and not before the typename).
15960
239k
            if ((FD->getReturnType()->isAnyPointerType() &&
15961
239k
                 
FD->getReturnType()->getPointeeType().isConstQualified()4.28k
) ||
15962
239k
                
FD->getReturnType().isConstQualified()238k
) {
15963
              // But only do this if we can determine where the `const` is.
15964
15965
448
              if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15966
448
                               getLangOpts()))
15967
15968
304
                return FD->getBeginLoc();
15969
448
            }
15970
238k
            return FD->getTypeSpecStartLoc();
15971
239k
          };
15972
239k
          Diag(FD->getTypeSpecStartLoc(),
15973
239k
               diag::note_static_for_internal_linkage)
15974
239k
              << /* function */ 1
15975
239k
              << (FD->getStorageClass() == SC_None
15976
239k
                      ? 
FixItHint::CreateInsertion(findBeginLoc(), "static ")239k
15977
239k
                      : 
FixItHint{}55
);
15978
239k
        }
15979
239k
      }
15980
15981
      // We might not have found a prototype because we didn't wish to warn on
15982
      // the lack of a missing prototype. Try again without the checks for
15983
      // whether we want to warn on the missing prototype.
15984
5.91M
      if (!PossiblePrototype)
15985
5.91M
        (void)FindPossiblePrototype(FD, PossiblePrototype);
15986
15987
      // If the function being defined does not have a prototype, then we may
15988
      // need to diagnose it as changing behavior in C23 because we now know
15989
      // whether the function accepts arguments or not. This only handles the
15990
      // case where the definition has no prototype but does have parameters
15991
      // and either there is no previous potential prototype, or the previous
15992
      // potential prototype also has no actual prototype. This handles cases
15993
      // like:
15994
      //   void f(); void f(a) int a; {}
15995
      //   void g(a) int a; {}
15996
      // See MergeFunctionDecl() for other cases of the behavior change
15997
      // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15998
      // type without a prototype.
15999
5.91M
      if (!FD->hasWrittenPrototype() && 
FD->getNumParams() != 04.77k
&&
16000
5.91M
          
(142
!PossiblePrototype142
||
(35
!PossiblePrototype->hasWrittenPrototype()35
&&
16001
118
                                  
!PossiblePrototype->isImplicit()11
))) {
16002
        // The function definition has parameters, so this will change behavior
16003
        // in C23. If there is a possible prototype, it comes before the
16004
        // function definition.
16005
        // FIXME: The declaration may have already been diagnosed as being
16006
        // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16007
        // there's no way to test for the "changes behavior" condition in
16008
        // SemaType.cpp when forming the declaration's function type. So, we do
16009
        // this awkward dance instead.
16010
        //
16011
        // If we have a possible prototype and it declares a function with a
16012
        // prototype, we don't want to diagnose it; if we have a possible
16013
        // prototype and it has no prototype, it may have already been
16014
        // diagnosed in SemaType.cpp as deprecated depending on whether
16015
        // -Wstrict-prototypes is enabled. If we already warned about it being
16016
        // deprecated, add a note that it also changes behavior. If we didn't
16017
        // warn about it being deprecated (because the diagnostic is not
16018
        // enabled), warn now that it is deprecated and changes behavior.
16019
16020
        // This K&R C function definition definitely changes behavior in C23,
16021
        // so diagnose it.
16022
118
        Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16023
118
            << /*definition*/ 1 << /* not supported in C23 */ 0;
16024
16025
        // If we have a possible prototype for the function which is a user-
16026
        // visible declaration, we already tested that it has no prototype.
16027
        // This will change behavior in C23. This gets a warning rather than a
16028
        // note because it's the same behavior-changing problem as with the
16029
        // definition.
16030
118
        if (PossiblePrototype)
16031
11
          Diag(PossiblePrototype->getLocation(),
16032
11
               diag::warn_non_prototype_changes_behavior)
16033
11
              << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16034
11
              << /*definition*/ 1;
16035
118
      }
16036
16037
      // Warn on CPUDispatch with an actual body.
16038
5.91M
      if (FD->isMultiVersion() && 
FD->hasAttr<CPUDispatchAttr>()582
&&
Body30
)
16039
30
        if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16040
30
          if (!CmpndBody->body_empty())
16041
1
            Diag(CmpndBody->body_front()->getBeginLoc(),
16042
1
                 diag::warn_dispatch_body_ignored);
16043
16044
5.91M
      if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16045
1.47M
        const CXXMethodDecl *KeyFunction;
16046
1.47M
        if (MD->isOutOfLine() && 
(MD = MD->getCanonicalDecl())278k
&&
16047
1.47M
            
MD->isVirtual()278k
&&
16048
1.47M
            
(KeyFunction = Context.getCurrentKeyFunction(MD->getParent()))26.0k
&&
16049
1.47M
            
MD == KeyFunction->getCanonicalDecl()25.3k
) {
16050
          // Update the key-function state if necessary for this ABI.
16051
6.79k
          if (FD->isInlined() &&
16052
6.79k
              
!Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()64
) {
16053
14
            Context.setNonKeyFunction(MD);
16054
16055
            // If the newly-chosen key function is already defined, then we
16056
            // need to mark the vtable as used retroactively.
16057
14
            KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16058
14
            const FunctionDecl *Definition;
16059
14
            if (KeyFunction && 
KeyFunction->isDefined(Definition)8
)
16060
6
              MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16061
6.78k
          } else {
16062
            // We just defined they key function; mark the vtable as used.
16063
6.78k
            MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16064
6.78k
          }
16065
6.79k
        }
16066
1.47M
      }
16067
16068
5.91M
      assert(
16069
5.91M
          (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
16070
5.91M
          "Function parsing confused");
16071
5.91M
    } else 
if (ObjCMethodDecl *7.09k
MD7.09k
= dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16072
7.06k
      assert(MD == getCurMethodDecl() && "Method parsing confused");
16073
7.06k
      MD->setBody(Body);
16074
7.06k
      if (!MD->isInvalidDecl()) {
16075
7.02k
        DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16076
7.02k
                                               MD->getReturnType(), MD);
16077
16078
7.02k
        if (Body)
16079
7.02k
          computeNRVO(Body, FSI);
16080
7.02k
      }
16081
7.06k
      if (FSI->ObjCShouldCallSuper) {
16082
52
        Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16083
52
            << MD->getSelector().getAsString();
16084
52
        FSI->ObjCShouldCallSuper = false;
16085
52
      }
16086
7.06k
      if (FSI->ObjCWarnForNoDesignatedInitChain) {
16087
14
        const ObjCMethodDecl *InitMethod = nullptr;
16088
14
        bool isDesignated =
16089
14
            MD->isDesignatedInitializerForTheInterface(&InitMethod);
16090
14
        assert(isDesignated && InitMethod);
16091
14
        (void)isDesignated;
16092
16093
14
        auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16094
14
          auto IFace = MD->getClassInterface();
16095
14
          if (!IFace)
16096
0
            return false;
16097
14
          auto SuperD = IFace->getSuperClass();
16098
14
          if (!SuperD)
16099
0
            return false;
16100
14
          return SuperD->getIdentifier() ==
16101
14
                 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16102
14
        };
16103
        // Don't issue this warning for unavailable inits or direct subclasses
16104
        // of NSObject.
16105
14
        if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16106
11
          Diag(MD->getLocation(),
16107
11
               diag::warn_objc_designated_init_missing_super_call);
16108
11
          Diag(InitMethod->getLocation(),
16109
11
               diag::note_objc_designated_init_marked_here);
16110
11
        }
16111
14
        FSI->ObjCWarnForNoDesignatedInitChain = false;
16112
14
      }
16113
7.06k
      if (FSI->ObjCWarnForNoInitDelegation) {
16114
        // Don't issue this warning for unavaialable inits.
16115
5
        if (!MD->isUnavailable())
16116
4
          Diag(MD->getLocation(),
16117
4
               diag::warn_objc_secondary_init_missing_init_call);
16118
5
        FSI->ObjCWarnForNoInitDelegation = false;
16119
5
      }
16120
16121
7.06k
      diagnoseImplicitlyRetainedSelf(*this);
16122
7.06k
    } else {
16123
      // Parsing the function declaration failed in some way. Pop the fake scope
16124
      // we pushed on.
16125
36
      PopFunctionScopeInfo(ActivePolicy, dcl);
16126
36
      return nullptr;
16127
36
    }
16128
16129
5.92M
    if (Body && 
FSI->HasPotentialAvailabilityViolations5.91M
)
16130
978
      DiagnoseUnguardedAvailabilityViolations(dcl);
16131
16132
5.92M
    assert(!FSI->ObjCShouldCallSuper &&
16133
5.92M
           "This should only be set for ObjC methods, which should have been "
16134
5.92M
           "handled in the block above.");
16135
16136
    // Verify and clean out per-function state.
16137
5.92M
    if (Body && 
(5.91M
!FD5.91M
||
!FD->isDefaulted()5.90M
)) {
16138
      // C++ constructors that have function-try-blocks can't have return
16139
      // statements in the handlers of that block. (C++ [except.handle]p14)
16140
      // Verify this.
16141
5.91M
      if (FD && 
isa<CXXConstructorDecl>(FD)5.90M
&&
isa<CXXTryStmt>(Body)299k
)
16142
42
        DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16143
16144
      // Verify that gotos and switch cases don't jump into scopes illegally.
16145
5.91M
      if (FSI->NeedsScopeChecking() && 
!PP.isCodeCompletionEnabled()8.91k
)
16146
8.91k
        DiagnoseInvalidJumps(Body);
16147
16148
5.91M
      if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16149
34.2k
        if (!Destructor->getParent()->isDependentType())
16150
11.0k
          CheckDestructor(Destructor);
16151
16152
34.2k
        MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
16153
34.2k
                                               Destructor->getParent());
16154
34.2k
      }
16155
16156
      // If any errors have occurred, clear out any temporaries that may have
16157
      // been leftover. This ensures that these temporaries won't be picked up
16158
      // for deletion in some later function.
16159
5.91M
      if (hasUncompilableErrorOccurred() ||
16160
5.91M
          
hasAnyUnrecoverableErrorsInThisFunction()5.81M
||
16161
5.91M
          
getDiagnostics().getSuppressAllDiagnostics()5.81M
) {
16162
97.9k
        DiscardCleanupsInEvaluationContext();
16163
97.9k
      }
16164
5.91M
      if (!hasUncompilableErrorOccurred() && 
!isa<FunctionTemplateDecl>(dcl)5.81M
) {
16165
        // Since the body is valid, issue any analysis-based warnings that are
16166
        // enabled.
16167
5.13M
        ActivePolicy = &WP;
16168
5.13M
      }
16169
16170
5.91M
      if (!IsInstantiation && 
FD5.64M
&&
FD->isConstexpr()5.63M
&&
!FD->isInvalidDecl()230k
&&
16171
5.91M
          
!CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)230k
)
16172
123
        FD->setInvalidDecl();
16173
16174
5.91M
      if (FD && 
FD->hasAttr<NakedAttr>()5.90M
) {
16175
40
        for (const Stmt *S : Body->children()) {
16176
          // Allow local register variables without initializer as they don't
16177
          // require prologue.
16178
28
          bool RegisterVariables = false;
16179
28
          if (auto *DS = dyn_cast<DeclStmt>(S)) {
16180
7
            for (const auto *Decl : DS->decls()) {
16181
7
              if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16182
7
                RegisterVariables =
16183
7
                    Var->hasAttr<AsmLabelAttr>() && 
!Var->hasInit()6
;
16184
7
                if (!RegisterVariables)
16185
3
                  break;
16186
7
              }
16187
7
            }
16188
5
          }
16189
28
          if (RegisterVariables)
16190
2
            continue;
16191
26
          if (!isa<AsmStmt>(S) && 
!isa<NullStmt>(S)8
) {
16192
4
            Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16193
4
            Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16194
4
            FD->setInvalidDecl();
16195
4
            break;
16196
4
          }
16197
26
        }
16198
40
      }
16199
16200
5.91M
      assert(ExprCleanupObjects.size() ==
16201
5.91M
                 ExprEvalContexts.back().NumCleanupObjects &&
16202
5.91M
             "Leftover temporaries in function");
16203
5.91M
      assert(!Cleanup.exprNeedsCleanups() &&
16204
5.91M
             "Unaccounted cleanups in function");
16205
5.91M
      assert(MaybeODRUseExprs.empty() &&
16206
5.91M
             "Leftover expressions for odr-use checking");
16207
5.91M
    }
16208
5.92M
  } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16209
    // the declaration context below. Otherwise, we're unable to transform
16210
    // 'this' expressions when transforming immediate context functions.
16211
16212
5.92M
  if (!IsInstantiation)
16213
5.64M
    PopDeclContext();
16214
16215
5.92M
  PopFunctionScopeInfo(ActivePolicy, dcl);
16216
  // If any errors have occurred, clear out any temporaries that may have
16217
  // been leftover. This ensures that these temporaries won't be picked up for
16218
  // deletion in some later function.
16219
5.92M
  if (hasUncompilableErrorOccurred()) {
16220
102k
    DiscardCleanupsInEvaluationContext();
16221
102k
  }
16222
16223
5.92M
  if (FD && 
(5.91M
(5.91M
LangOpts.OpenMP5.91M
&&
(107k
LangOpts.OpenMPIsTargetDevice107k
||
16224
107k
                                  
!LangOpts.OMPTargetTriples.empty()93.6k
)) ||
16225
5.91M
             
LangOpts.CUDA5.87M
||
LangOpts.SYCLIsDevice5.86M
)) {
16226
52.4k
    auto ES = getEmissionStatus(FD);
16227
52.4k
    if (ES == Sema::FunctionEmissionStatus::Emitted ||
16228
52.4k
        
ES == Sema::FunctionEmissionStatus::Unknown49.7k
)
16229
42.5k
      DeclsToCheckForDeferredDiags.insert(FD);
16230
52.4k
  }
16231
16232
5.92M
  if (FD && 
!FD->isDeleted()5.91M
)
16233
5.91M
    checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16234
16235
5.92M
  return dcl;
16236
5.92M
}
16237
16238
/// When we finish delayed parsing of an attribute, we must attach it to the
16239
/// relevant Decl.
16240
void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16241
11.7k
                                       ParsedAttributes &Attrs) {
16242
  // Always attach attributes to the underlying decl.
16243
11.7k
  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16244
4.87k
    D = TD->getTemplatedDecl();
16245
11.7k
  ProcessDeclAttributeList(S, D, Attrs);
16246
16247
11.7k
  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16248
5.32k
    if (Method->isStatic())
16249
37
      checkThisInStaticMemberFunctionAttributes(Method);
16250
11.7k
}
16251
16252
/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16253
/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16254
NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16255
492
                                          IdentifierInfo &II, Scope *S) {
16256
  // It is not valid to implicitly define a function in C23.
16257
492
  assert(LangOpts.implicitFunctionsAllowed() &&
16258
492
         "Implicit function declarations aren't allowed in this language mode");
16259
16260
  // Find the scope in which the identifier is injected and the corresponding
16261
  // DeclContext.
16262
  // FIXME: C89 does not say what happens if there is no enclosing block scope.
16263
  // In that case, we inject the declaration into the translation unit scope
16264
  // instead.
16265
492
  Scope *BlockScope = S;
16266
516
  while (!BlockScope->isCompoundStmtScope() && 
BlockScope->getParent()33
)
16267
24
    BlockScope = BlockScope->getParent();
16268
16269
  // Loop until we find a DeclContext that is either a function/method or the
16270
  // translation unit, which are the only two valid places to implicitly define
16271
  // a function. This avoids accidentally defining the function within a tag
16272
  // declaration, for example.
16273
492
  Scope *ContextScope = BlockScope;
16274
562
  while (!ContextScope->getEntity() ||
16275
562
         
(498
!ContextScope->getEntity()->isFunctionOrMethod()498
&&
16276
498
          
!ContextScope->getEntity()->isTranslationUnit()15
))
16277
70
    ContextScope = ContextScope->getParent();
16278
492
  ContextRAII SavedContext(*this, ContextScope->getEntity());
16279
16280
  // Before we produce a declaration for an implicitly defined
16281
  // function, see whether there was a locally-scoped declaration of
16282
  // this name as a function or variable. If so, use that
16283
  // (non-visible) declaration, and complain about it.
16284
492
  NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16285
492
  if (ExternCPrev) {
16286
    // We still need to inject the function into the enclosing block scope so
16287
    // that later (non-call) uses can see it.
16288
51
    PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16289
16290
    // C89 footnote 38:
16291
    //   If in fact it is not defined as having type "function returning int",
16292
    //   the behavior is undefined.
16293
51
    if (!isa<FunctionDecl>(ExternCPrev) ||
16294
51
        !Context.typesAreCompatible(
16295
50
            cast<FunctionDecl>(ExternCPrev)->getType(),
16296
50
            Context.getFunctionNoProtoType(Context.IntTy))) {
16297
2
      Diag(Loc, diag::ext_use_out_of_scope_declaration)
16298
2
          << ExternCPrev << !getLangOpts().C99;
16299
2
      Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16300
2
      return ExternCPrev;
16301
2
    }
16302
51
  }
16303
16304
  // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16305
490
  unsigned diag_id;
16306
490
  if (II.getName().startswith("__builtin_"))
16307
173
    diag_id = diag::warn_builtin_unknown;
16308
  // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16309
317
  else if (getLangOpts().C99)
16310
256
    diag_id = diag::ext_implicit_function_decl_c99;
16311
61
  else
16312
61
    diag_id = diag::warn_implicit_function_decl;
16313
16314
490
  TypoCorrection Corrected;
16315
  // Because typo correction is expensive, only do it if the implicit
16316
  // function declaration is going to be treated as an error.
16317
  //
16318
  // Perform the correction before issuing the main diagnostic, as some
16319
  // consumers use typo-correction callbacks to enhance the main diagnostic.
16320
490
  if (S && !ExternCPrev &&
16321
490
      
(Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)441
) {
16322
202
    DeclFilterCCC<FunctionDecl> CCC{};
16323
202
    Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16324
202
                            S, nullptr, CCC, CTK_NonError);
16325
202
  }
16326
16327
490
  Diag(Loc, diag_id) << &II;
16328
490
  if (Corrected) {
16329
    // If the correction is going to suggest an implicitly defined function,
16330
    // skip the correction as not being a particularly good idea.
16331
34
    bool Diagnose = true;
16332
34
    if (const auto *D = Corrected.getCorrectionDecl())
16333
34
      Diagnose = !D->isImplicit();
16334
34
    if (Diagnose)
16335
27
      diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16336
27
                   /*ErrorRecovery*/ false);
16337
34
  }
16338
16339
  // If we found a prior declaration of this function, don't bother building
16340
  // another one. We've already pushed that one into scope, so there's nothing
16341
  // more to do.
16342
490
  if (ExternCPrev)
16343
49
    return ExternCPrev;
16344
16345
  // Set a Declarator for the implicit definition: int foo();
16346
441
  const char *Dummy;
16347
441
  AttributeFactory attrFactory;
16348
441
  DeclSpec DS(attrFactory);
16349
441
  unsigned DiagID;
16350
441
  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16351
441
                                  Context.getPrintingPolicy());
16352
441
  (void)Error; // Silence warning.
16353
441
  assert(!Error && "Error setting up implicit decl!");
16354
441
  SourceLocation NoLoc;
16355
441
  Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16356
441
  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16357
441
                                             /*IsAmbiguous=*/false,
16358
441
                                             /*LParenLoc=*/NoLoc,
16359
441
                                             /*Params=*/nullptr,
16360
441
                                             /*NumParams=*/0,
16361
441
                                             /*EllipsisLoc=*/NoLoc,
16362
441
                                             /*RParenLoc=*/NoLoc,
16363
441
                                             /*RefQualifierIsLvalueRef=*/true,
16364
441
                                             /*RefQualifierLoc=*/NoLoc,
16365
441
                                             /*MutableLoc=*/NoLoc, EST_None,
16366
441
                                             /*ESpecRange=*/SourceRange(),
16367
441
                                             /*Exceptions=*/nullptr,
16368
441
                                             /*ExceptionRanges=*/nullptr,
16369
441
                                             /*NumExceptions=*/0,
16370
441
                                             /*NoexceptExpr=*/nullptr,
16371
441
                                             /*ExceptionSpecTokens=*/nullptr,
16372
441
                                             /*DeclsInPrototype=*/std::nullopt,
16373
441
                                             Loc, Loc, D),
16374
441
                std::move(DS.getAttributes()), SourceLocation());
16375
441
  D.SetIdentifier(&II, Loc);
16376
16377
  // Insert this function into the enclosing block scope.
16378
441
  FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16379
441
  FD->setImplicit();
16380
16381
441
  AddKnownFunctionAttributes(FD);
16382
16383
441
  return FD;
16384
441
}
16385
16386
/// If this function is a C++ replaceable global allocation function
16387
/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16388
/// adds any function attributes that we know a priori based on the standard.
16389
///
16390
/// We need to check for duplicate attributes both here and where user-written
16391
/// attributes are applied to declarations.
16392
void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16393
38.6M
    FunctionDecl *FD) {
16394
38.6M
  if (FD->isInvalidDecl())
16395
0
    return;
16396
16397
38.6M
  if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16398
38.6M
      
FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New38.6M
)
16399
38.6M
    return;
16400
16401
15.4k
  std::optional<unsigned> AlignmentParam;
16402
15.4k
  bool IsNothrow = false;
16403
15.4k
  if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16404
4.69k
    return;
16405
16406
  // C++2a [basic.stc.dynamic.allocation]p4:
16407
  //   An allocation function that has a non-throwing exception specification
16408
  //   indicates failure by returning a null pointer value. Any other allocation
16409
  //   function never returns a null pointer value and indicates failure only by
16410
  //   throwing an exception [...]
16411
  //
16412
  // However, -fcheck-new invalidates this possible assumption, so don't add
16413
  // NonNull when that is enabled.
16414
10.8k
  if (!IsNothrow && 
!FD->hasAttr<ReturnsNonNullAttr>()9.31k
&&
16415
10.8k
      
!getLangOpts().CheckNew7.73k
)
16416
7.72k
    FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16417
16418
  // C++2a [basic.stc.dynamic.allocation]p2:
16419
  //   An allocation function attempts to allocate the requested amount of
16420
  //   storage. [...] If the request succeeds, the value returned by a
16421
  //   replaceable allocation function is a [...] pointer value p0 different
16422
  //   from any previously returned value p1 [...]
16423
  //
16424
  // However, this particular information is being added in codegen,
16425
  // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16426
16427
  // C++2a [basic.stc.dynamic.allocation]p2:
16428
  //   An allocation function attempts to allocate the requested amount of
16429
  //   storage. If it is successful, it returns the address of the start of a
16430
  //   block of storage whose length in bytes is at least as large as the
16431
  //   requested size.
16432
10.8k
  if (!FD->hasAttr<AllocSizeAttr>()) {
16433
9.22k
    FD->addAttr(AllocSizeAttr::CreateImplicit(
16434
9.22k
        Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16435
9.22k
        /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16436
9.22k
  }
16437
16438
  // C++2a [basic.stc.dynamic.allocation]p3:
16439
  //   For an allocation function [...], the pointer returned on a successful
16440
  //   call shall represent the address of storage that is aligned as follows:
16441
  //   (3.1) If the allocation function takes an argument of type
16442
  //         std​::​align_­val_­t, the storage will have the alignment
16443
  //         specified by the value of this argument.
16444
10.8k
  if (AlignmentParam && 
!FD->hasAttr<AllocAlignAttr>()2.67k
) {
16445
2.52k
    FD->addAttr(AllocAlignAttr::CreateImplicit(
16446
2.52k
        Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16447
2.52k
  }
16448
16449
  // FIXME:
16450
  // C++2a [basic.stc.dynamic.allocation]p3:
16451
  //   For an allocation function [...], the pointer returned on a successful
16452
  //   call shall represent the address of storage that is aligned as follows:
16453
  //   (3.2) Otherwise, if the allocation function is named operator new[],
16454
  //         the storage is aligned for any object that does not have
16455
  //         new-extended alignment ([basic.align]) and is no larger than the
16456
  //         requested size.
16457
  //   (3.3) Otherwise, the storage is aligned for any object that does not
16458
  //         have new-extended alignment and is of the requested size.
16459
10.8k
}
16460
16461
/// Adds any function attributes that we know a priori based on
16462
/// the declaration of this function.
16463
///
16464
/// These attributes can apply both to implicitly-declared builtins
16465
/// (like __builtin___printf_chk) or to library-declared functions
16466
/// like NSLog or printf.
16467
///
16468
/// We need to check for duplicate attributes both here and where user-written
16469
/// attributes are applied to declarations.
16470
38.6M
void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16471
38.6M
  if (FD->isInvalidDecl())
16472
2.66k
    return;
16473
16474
  // If this is a built-in function, map its builtin attributes to
16475
  // actual attributes.
16476
38.6M
  if (unsigned BuiltinID = FD->getBuiltinID()) {
16477
    // Handle printf-formatting attributes.
16478
30.1M
    unsigned FormatIdx;
16479
30.1M
    bool HasVAListArg;
16480
30.1M
    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16481
19.5k
      if (!FD->hasAttr<FormatAttr>()) {
16482
6.26k
        const char *fmt = "printf";
16483
6.26k
        unsigned int NumParams = FD->getNumParams();
16484
6.26k
        if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16485
6.26k
            FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16486
465
          fmt = "NSString";
16487
6.26k
        FD->addAttr(FormatAttr::CreateImplicit(Context,
16488
6.26k
                                               &Context.Idents.get(fmt),
16489
6.26k
                                               FormatIdx+1,
16490
6.26k
                                               HasVAListArg ? 
02.80k
:
FormatIdx+23.45k
,
16491
6.26k
                                               FD->getLocation()));
16492
6.26k
      }
16493
19.5k
    }
16494
30.1M
    if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16495
30.1M
                                             HasVAListArg)) {
16496
13.4k
     if (!FD->hasAttr<FormatAttr>())
16497
3.94k
       FD->addAttr(FormatAttr::CreateImplicit(Context,
16498
3.94k
                                              &Context.Idents.get("scanf"),
16499
3.94k
                                              FormatIdx+1,
16500
3.94k
                                              HasVAListArg ? 
01.90k
:
FormatIdx+22.04k
,
16501
3.94k
                                              FD->getLocation()));
16502
13.4k
    }
16503
16504
    // Handle automatically recognized callbacks.
16505
30.1M
    SmallVector<int, 4> Encoding;
16506
30.1M
    if (!FD->hasAttr<CallbackAttr>() &&
16507
30.1M
        Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16508
0
      FD->addAttr(CallbackAttr::CreateImplicit(
16509
0
          Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16510
16511
    // Mark const if we don't care about errno and/or floating point exceptions
16512
    // that are the only thing preventing the function from being const. This
16513
    // allows IRgen to use LLVM intrinsics for such functions.
16514
30.1M
    bool NoExceptions =
16515
30.1M
        getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16516
30.1M
    bool ConstWithoutErrnoAndExceptions =
16517
30.1M
        Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16518
30.1M
    bool ConstWithoutExceptions =
16519
30.1M
        Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16520
30.1M
    if (!FD->hasAttr<ConstAttr>() &&
16521
30.1M
        
(30.0M
ConstWithoutErrnoAndExceptions30.0M
||
ConstWithoutExceptions29.9M
) &&
16522
30.1M
        
(161k
!ConstWithoutErrnoAndExceptions161k
||
16523
161k
         
(159k
!getLangOpts().MathErrno159k
&&
NoExceptions157k
)) &&
16524
30.1M
        
(159k
!ConstWithoutExceptions159k
||
NoExceptions2.16k
))
16525
159k
      FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16526
16527
    // We make "fma" on GNU or Windows const because we know it does not set
16528
    // errno in those environments even though it could set errno based on the
16529
    // C standard.
16530
30.1M
    const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16531
30.1M
    if ((Trip.isGNUEnvironment() || 
Trip.isOSMSVCRT()2.49M
) &&
16532
30.1M
        
!FD->hasAttr<ConstAttr>()27.6M
) {
16533
27.6M
      switch (BuiltinID) {
16534
2
      case Builtin::BI__builtin_fma:
16535
4
      case Builtin::BI__builtin_fmaf:
16536
6
      case Builtin::BI__builtin_fmal:
16537
10
      case Builtin::BIfma:
16538
14
      case Builtin::BIfmaf:
16539
18
      case Builtin::BIfmal:
16540
18
        FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16541
18
        break;
16542
27.6M
      default:
16543
27.6M
        break;
16544
27.6M
      }
16545
27.6M
    }
16546
16547
30.1M
    if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16548
30.1M
        
!FD->hasAttr<ReturnsTwiceAttr>()2.35k
)
16549
1.44k
      FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16550
1.44k
                                         FD->getLocation()));
16551
30.1M
    if (Context.BuiltinInfo.isNoThrow(BuiltinID) && 
!FD->hasAttr<NoThrowAttr>()30.0M
)
16552
29.9M
      FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16553
30.1M
    if (Context.BuiltinInfo.isPure(BuiltinID) && 
!FD->hasAttr<PureAttr>()13.6k
)
16554
10.0k
      FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16555
30.1M
    if (Context.BuiltinInfo.isConst(BuiltinID) && 
!FD->hasAttr<ConstAttr>()505k
)
16556
497k
      FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16557
30.1M
    if (getLangOpts().CUDA && 
Context.BuiltinInfo.isTSBuiltin(BuiltinID)1.61k
&&
16558
30.1M
        
!FD->hasAttr<CUDADeviceAttr>()600
&&
!FD->hasAttr<CUDAHostAttr>()600
) {
16559
      // Add the appropriate attribute, depending on the CUDA compilation mode
16560
      // and which target the builtin belongs to. For example, during host
16561
      // compilation, aux builtins are __device__, while the rest are __host__.
16562
600
      if (getLangOpts().CUDAIsDevice !=
16563
600
          Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16564
599
        FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16565
1
      else
16566
1
        FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16567
600
    }
16568
16569
    // Add known guaranteed alignment for allocation functions.
16570
30.1M
    switch (BuiltinID) {
16571
4
    case Builtin::BImemalign:
16572
1.23k
    case Builtin::BIaligned_alloc:
16573
1.23k
      if (!FD->hasAttr<AllocAlignAttr>())
16574
971
        FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16575
971
                                                   FD->getLocation()));
16576
1.23k
      break;
16577
30.1M
    default:
16578
30.1M
      break;
16579
30.1M
    }
16580
16581
    // Add allocsize attribute for allocation functions.
16582
30.1M
    switch (BuiltinID) {
16583
1.26k
    case Builtin::BIcalloc:
16584
1.26k
      FD->addAttr(AllocSizeAttr::CreateImplicit(
16585
1.26k
          Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16586
1.26k
      break;
16587
4
    case Builtin::BImemalign:
16588
1.23k
    case Builtin::BIaligned_alloc:
16589
2.48k
    case Builtin::BIrealloc:
16590
2.48k
      FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16591
2.48k
                                                ParamIdx(), FD->getLocation()));
16592
2.48k
      break;
16593
1.46k
    case Builtin::BImalloc:
16594
1.46k
      FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16595
1.46k
                                                ParamIdx(), FD->getLocation()));
16596
1.46k
      break;
16597
30.1M
    default:
16598
30.1M
      break;
16599
30.1M
    }
16600
16601
    // Add lifetime attribute to std::move, std::fowrard et al.
16602
30.1M
    switch (BuiltinID) {
16603
1.04k
    case Builtin::BIaddressof:
16604
1.04k
    case Builtin::BI__addressof:
16605
1.58k
    case Builtin::BI__builtin_addressof:
16606
1.62k
    case Builtin::BIas_const:
16607
2.73k
    case Builtin::BIforward:
16608
2.74k
    case Builtin::BIforward_like:
16609
3.81k
    case Builtin::BImove:
16610
4.31k
    case Builtin::BImove_if_noexcept:
16611
4.31k
      if (ParmVarDecl *P = FD->getParamDecl(0u);
16612
4.31k
          !P->hasAttr<LifetimeBoundAttr>())
16613
2.28k
        P->addAttr(
16614
2.28k
            LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16615
4.31k
      break;
16616
30.1M
    default:
16617
30.1M
      break;
16618
30.1M
    }
16619
30.1M
  }
16620
16621
38.6M
  AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16622
16623
  // If C++ exceptions are enabled but we are told extern "C" functions cannot
16624
  // throw, add an implicit nothrow attribute to any extern "C" function we come
16625
  // across.
16626
38.6M
  if (getLangOpts().CXXExceptions && 
getLangOpts().ExternCNoUnwind3.51M
&&
16627
38.6M
      
FD->isExternC()8
&&
!FD->hasAttr<NoThrowAttr>()2
) {
16628
2
    const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16629
2
    if (!FPT || FPT->getExceptionSpecType() == EST_None)
16630
1
      FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16631
2
  }
16632
16633
38.6M
  IdentifierInfo *Name = FD->getIdentifier();
16634
38.6M
  if (!Name)
16635
992k
    return;
16636
37.6M
  if ((!getLangOpts().CPlusPlus && 
FD->getDeclContext()->isTranslationUnit()21.7M
) ||
16637
37.6M
      
(15.8M
isa<LinkageSpecDecl>(FD->getDeclContext())15.8M
&&
16638
15.8M
       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16639
35.4M
           LinkageSpecLanguageIDs::C)) {
16640
    // Okay: this could be a libc/libm/Objective-C function we know
16641
    // about.
16642
35.4M
  } else
16643
2.19M
    return;
16644
16645
35.4M
  if (Name->isStr("asprintf") || 
Name->isStr("vasprintf")35.4M
) {
16646
    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16647
    // target-specific builtins, perhaps?
16648
3.11k
    if (!FD->hasAttr<FormatAttr>())
16649
8
      FD->addAttr(FormatAttr::CreateImplicit(Context,
16650
8
                                             &Context.Idents.get("printf"), 2,
16651
8
                                             Name->isStr("vasprintf") ? 
04
:
34
,
16652
8
                                             FD->getLocation()));
16653
3.11k
  }
16654
16655
35.4M
  if (Name->isStr("__CFStringMakeConstantString")) {
16656
    // We already have a __builtin___CFStringMakeConstantString,
16657
    // but builds that use -fno-constant-cfstrings don't go through that.
16658
222
    if (!FD->hasAttr<FormatArgAttr>())
16659
1
      FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16660
1
                                                FD->getLocation()));
16661
222
  }
16662
35.4M
}
16663
16664
TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16665
2.12M
                                    TypeSourceInfo *TInfo) {
16666
2.12M
  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16667
2.12M
  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16668
16669
2.12M
  if (!TInfo) {
16670
0
    assert(D.isInvalidType() && "no declarator info for valid type");
16671
0
    TInfo = Context.getTrivialTypeSourceInfo(T);
16672
0
  }
16673
16674
  // Scope manipulation handled by caller.
16675
2.12M
  TypedefDecl *NewTD =
16676
2.12M
      TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16677
2.12M
                          D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16678
16679
  // Bail out immediately if we have an invalid declaration.
16680
2.12M
  if (D.isInvalidType()) {
16681
183
    NewTD->setInvalidDecl();
16682
183
    return NewTD;
16683
183
  }
16684
16685
2.12M
  if (D.getDeclSpec().isModulePrivateSpecified()) {
16686
8
    if (CurContext->isFunctionOrMethod())
16687
1
      Diag(NewTD->getLocation(), diag::err_module_private_local)
16688
1
          << 2 << NewTD
16689
1
          << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16690
1
          << FixItHint::CreateRemoval(
16691
1
                 D.getDeclSpec().getModulePrivateSpecLoc());
16692
7
    else
16693
7
      NewTD->setModulePrivate();
16694
8
  }
16695
16696
  // C++ [dcl.typedef]p8:
16697
  //   If the typedef declaration defines an unnamed class (or
16698
  //   enum), the first typedef-name declared by the declaration
16699
  //   to be that class type (or enum type) is used to denote the
16700
  //   class type (or enum type) for linkage purposes only.
16701
  // We need to check whether the type was declared in the declaration.
16702
2.12M
  switch (D.getDeclSpec().getTypeSpecType()) {
16703
83.0k
  case TST_enum:
16704
588k
  case TST_struct:
16705
588k
  case TST_interface:
16706
597k
  case TST_union:
16707
597k
  case TST_class: {
16708
597k
    TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16709
597k
    setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16710
597k
    break;
16711
597k
  }
16712
16713
1.52M
  default:
16714
1.52M
    break;
16715
2.12M
  }
16716
16717
2.12M
  return NewTD;
16718
2.12M
}
16719
16720
/// Check that this is a valid underlying type for an enum declaration.
16721
173k
bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16722
173k
  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16723
173k
  QualType T = TI->getType();
16724
16725
173k
  if (T->isDependentType())
16726
38
    return false;
16727
16728
  // This doesn't use 'isIntegralType' despite the error message mentioning
16729
  // integral type because isIntegralType would also allow enum types in C.
16730
172k
  if (const BuiltinType *BT = T->getAs<BuiltinType>())
16731
172k
    if (BT->isInteger())
16732
172k
      return false;
16733
16734
10
  return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16735
10
         << T << T->isBitIntType();
16736
172k
}
16737
16738
/// Check whether this is a valid redeclaration of a previous enumeration.
16739
/// \return true if the redeclaration was invalid.
16740
bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16741
                                  QualType EnumUnderlyingTy, bool IsFixed,
16742
70.3k
                                  const EnumDecl *Prev) {
16743
70.3k
  if (IsScoped != Prev->isScoped()) {
16744
6
    Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16745
6
      << Prev->isScoped();
16746
6
    Diag(Prev->getLocation(), diag::note_previous_declaration);
16747
6
    return true;
16748
6
  }
16749
16750
70.3k
  if (IsFixed && 
Prev->isFixed()70.2k
) {
16751
70.2k
    if (!EnumUnderlyingTy->isDependentType() &&
16752
70.2k
        
!Prev->getIntegerType()->isDependentType()70.2k
&&
16753
70.2k
        !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16754
70.2k
                                        Prev->getIntegerType())) {
16755
      // TODO: Highlight the underlying type of the redeclaration.
16756
47
      Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16757
47
        << EnumUnderlyingTy << Prev->getIntegerType();
16758
47
      Diag(Prev->getLocation(), diag::note_previous_declaration)
16759
47
          << Prev->getIntegerTypeRange();
16760
47
      return true;
16761
47
    }
16762
70.2k
  } else 
if (68
IsFixed != Prev->isFixed()68
) {
16763
6
    Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16764
6
      << Prev->isFixed();
16765
6
    Diag(Prev->getLocation(), diag::note_previous_declaration);
16766
6
    return true;
16767
6
  }
16768
16769
70.2k
  return false;
16770
70.3k
}
16771
16772
/// Get diagnostic %select index for tag kind for
16773
/// redeclaration diagnostic message.
16774
/// WARNING: Indexes apply to particular diagnostics only!
16775
///
16776
/// \returns diagnostic %select index.
16777
84
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16778
84
  switch (Tag) {
16779
44
  case TagTypeKind::Struct:
16780
44
    return 0;
16781
0
  case TagTypeKind::Interface:
16782
0
    return 1;
16783
40
  case TagTypeKind::Class:
16784
40
    return 2;
16785
0
  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16786
84
  }
16787
84
}
16788
16789
/// Determine if tag kind is a class-key compatible with
16790
/// class for redeclaration (class, struct, or __interface).
16791
///
16792
/// \returns true iff the tag kind is compatible.
16793
static bool isClassCompatTagKind(TagTypeKind Tag)
16794
1.38M
{
16795
1.38M
  return Tag == TagTypeKind::Struct || 
Tag == TagTypeKind::Class553k
||
16796
1.38M
         
Tag == TagTypeKind::Interface448k
;
16797
1.38M
}
16798
16799
Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16800
33
                                             TagTypeKind TTK) {
16801
33
  if (isa<TypedefDecl>(PrevDecl))
16802
26
    return NTK_Typedef;
16803
7
  else if (isa<TypeAliasDecl>(PrevDecl))
16804
0
    return NTK_TypeAlias;
16805
7
  else if (isa<ClassTemplateDecl>(PrevDecl))
16806
6
    return NTK_Template;
16807
1
  else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16808
1
    return NTK_TypeAliasTemplate;
16809
0
  else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16810
0
    return NTK_TemplateTemplateArgument;
16811
0
  switch (TTK) {
16812
0
  case TagTypeKind::Struct:
16813
0
  case TagTypeKind::Interface:
16814
0
  case TagTypeKind::Class:
16815
0
    return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16816
0
  case TagTypeKind::Union:
16817
0
    return NTK_NonUnion;
16818
0
  case TagTypeKind::Enum:
16819
0
    return NTK_NonEnum;
16820
0
  }
16821
0
  llvm_unreachable("invalid TTK");
16822
0
}
16823
16824
/// Determine whether a tag with a given kind is acceptable
16825
/// as a redeclaration of the given tag declaration.
16826
///
16827
/// \returns true if the new tag kind is acceptable, false otherwise.
16828
bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16829
                                        TagTypeKind NewTag, bool isDefinition,
16830
                                        SourceLocation NewTagLoc,
16831
1.38M
                                        const IdentifierInfo *Name) {
16832
  // C++ [dcl.type.elab]p3:
16833
  //   The class-key or enum keyword present in the
16834
  //   elaborated-type-specifier shall agree in kind with the
16835
  //   declaration to which the name in the elaborated-type-specifier
16836
  //   refers. This rule also applies to the form of
16837
  //   elaborated-type-specifier that declares a class-name or
16838
  //   friend class since it can be construed as referring to the
16839
  //   definition of the class. Thus, in any
16840
  //   elaborated-type-specifier, the enum keyword shall be used to
16841
  //   refer to an enumeration (7.2), the union class-key shall be
16842
  //   used to refer to a union (clause 9), and either the class or
16843
  //   struct class-key shall be used to refer to a class (clause 9)
16844
  //   declared using the class or struct class-key.
16845
1.38M
  TagTypeKind OldTag = Previous->getTagKind();
16846
1.38M
  if (OldTag != NewTag &&
16847
1.38M
      
!(631
isClassCompatTagKind(OldTag)631
&&
isClassCompatTagKind(NewTag)598
))
16848
78
    return false;
16849
16850
  // Tags are compatible, but we might still want to warn on mismatched tags.
16851
  // Non-class tags can't be mismatched at this point.
16852
1.38M
  if (!isClassCompatTagKind(NewTag))
16853
448k
    return true;
16854
16855
  // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16856
  // by our warning analysis. We don't want to warn about mismatches with (eg)
16857
  // declarations in system headers that are designed to be specialized, but if
16858
  // a user asks us to warn, we should warn if their code contains mismatched
16859
  // declarations.
16860
932k
  
auto IsIgnoredLoc = [&](SourceLocation Loc) 932k
{
16861
932k
    return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16862
932k
                                      Loc);
16863
932k
  };
16864
932k
  if (IsIgnoredLoc(NewTagLoc))
16865
932k
    return true;
16866
16867
271
  
auto IsIgnored = [&](const TagDecl *Tag) 167
{
16868
271
    return IsIgnoredLoc(Tag->getLocation());
16869
271
  };
16870
175
  while (IsIgnored(Previous)) {
16871
12
    Previous = Previous->getPreviousDecl();
16872
12
    if (!Previous)
16873
4
      return true;
16874
8
    OldTag = Previous->getTagKind();
16875
8
  }
16876
16877
163
  bool isTemplate = false;
16878
163
  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16879
101
    isTemplate = Record->getDescribedClassTemplate();
16880
16881
163
  if (inTemplateInstantiation()) {
16882
0
    if (OldTag != NewTag) {
16883
      // In a template instantiation, do not offer fix-its for tag mismatches
16884
      // since they usually mess up the template instead of fixing the problem.
16885
0
      Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16886
0
        << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16887
0
        << getRedeclDiagFromTagKind(OldTag);
16888
      // FIXME: Note previous location?
16889
0
    }
16890
0
    return true;
16891
0
  }
16892
16893
163
  if (isDefinition) {
16894
    // On definitions, check all previous tags and issue a fix-it for each
16895
    // one that doesn't match the current tag.
16896
49
    if (Previous->getDefinition()) {
16897
      // Don't suggest fix-its for redefinitions.
16898
28
      return true;
16899
28
    }
16900
16901
21
    bool previousMismatch = false;
16902
37
    for (const TagDecl *I : Previous->redecls()) {
16903
37
      if (I->getTagKind() != NewTag) {
16904
        // Ignore previous declarations for which the warning was disabled.
16905
12
        if (IsIgnored(I))
16906
0
          continue;
16907
16908
12
        if (!previousMismatch) {
16909
8
          previousMismatch = true;
16910
8
          Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16911
8
            << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16912
8
            << getRedeclDiagFromTagKind(I->getTagKind());
16913
8
        }
16914
12
        Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16915
12
          << getRedeclDiagFromTagKind(NewTag)
16916
12
          << FixItHint::CreateReplacement(I->getInnerLocStart(),
16917
12
               TypeWithKeyword::getTagTypeKindName(NewTag));
16918
12
      }
16919
37
    }
16920
21
    return true;
16921
49
  }
16922
16923
  // Identify the prevailing tag kind: this is the kind of the definition (if
16924
  // there is a non-ignored definition), or otherwise the kind of the prior
16925
  // (non-ignored) declaration.
16926
114
  const TagDecl *PrevDef = Previous->getDefinition();
16927
114
  if (PrevDef && 
IsIgnored(PrevDef)84
)
16928
4
    PrevDef = nullptr;
16929
114
  const TagDecl *Redecl = PrevDef ? 
PrevDef80
:
Previous34
;
16930
114
  if (Redecl->getTagKind() != NewTag) {
16931
26
    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16932
26
      << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16933
26
      << getRedeclDiagFromTagKind(OldTag);
16934
26
    Diag(Redecl->getLocation(), diag::note_previous_use);
16935
16936
    // If there is a previous definition, suggest a fix-it.
16937
26
    if (PrevDef) {
16938
4
      Diag(NewTagLoc, diag::note_struct_class_suggestion)
16939
4
        << getRedeclDiagFromTagKind(Redecl->getTagKind())
16940
4
        << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
16941
4
             TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16942
4
    }
16943
26
  }
16944
16945
114
  return true;
16946
163
}
16947
16948
/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16949
/// from an outer enclosing namespace or file scope inside a friend declaration.
16950
/// This should provide the commented out code in the following snippet:
16951
///   namespace N {
16952
///     struct X;
16953
///     namespace M {
16954
///       struct Y { friend struct /*N::*/ X; };
16955
///     }
16956
///   }
16957
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16958
6
                                         SourceLocation NameLoc) {
16959
  // While the decl is in a namespace, do repeated lookup of that name and see
16960
  // if we get the same namespace back.  If we do not, continue until
16961
  // translation unit scope, at which point we have a fully qualified NNS.
16962
6
  SmallVector<IdentifierInfo *, 4> Namespaces;
16963
6
  DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16964
8
  for (; !DC->isTranslationUnit(); 
DC = DC->getParent()2
) {
16965
    // This tag should be declared in a namespace, which can only be enclosed by
16966
    // other namespaces.  Bail if there's an anonymous namespace in the chain.
16967
6
    NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16968
6
    if (!Namespace || Namespace->isAnonymousNamespace())
16969
0
      return FixItHint();
16970
6
    IdentifierInfo *II = Namespace->getIdentifier();
16971
6
    Namespaces.push_back(II);
16972
6
    NamedDecl *Lookup = SemaRef.LookupSingleName(
16973
6
        S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16974
6
    if (Lookup == Namespace)
16975
4
      break;
16976
6
  }
16977
16978
  // Once we have all the namespaces, reverse them to go outermost first, and
16979
  // build an NNS.
16980
6
  SmallString<64> Insertion;
16981
6
  llvm::raw_svector_ostream OS(Insertion);
16982
6
  if (DC->isTranslationUnit())
16983
2
    OS << "::";
16984
6
  std::reverse(Namespaces.begin(), Namespaces.end());
16985
6
  for (auto *II : Namespaces)
16986
6
    OS << II->getName() << "::";
16987
6
  return FixItHint::CreateInsertion(NameLoc, Insertion);
16988
6
}
16989
16990
/// Determine whether a tag originally declared in context \p OldDC can
16991
/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16992
/// found a declaration in \p OldDC as a previous decl, perhaps through a
16993
/// using-declaration).
16994
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16995
19
                                         DeclContext *NewDC) {
16996
19
  OldDC = OldDC->getRedeclContext();
16997
19
  NewDC = NewDC->getRedeclContext();
16998
16999
19
  if (OldDC->Equals(NewDC))
17000
2
    return true;
17001
17002
  // In MSVC mode, we allow a redeclaration if the contexts are related (either
17003
  // encloses the other).
17004
17
  if (S.getLangOpts().MSVCCompat &&
17005
17
      
(10
OldDC->Encloses(NewDC)10
||
NewDC->Encloses(OldDC)0
))
17006
10
    return true;
17007
17008
7
  return false;
17009
17
}
17010
17011
/// This is invoked when we see 'struct foo' or 'struct {'.  In the
17012
/// former case, Name will be non-null.  In the later case, Name will be null.
17013
/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
17014
/// reference/declaration/definition of a tag.
17015
///
17016
/// \param IsTypeSpecifier \c true if this is a type-specifier (or
17017
/// trailing-type-specifier) other than one in an alias-declaration.
17018
///
17019
/// \param SkipBody If non-null, will be set to indicate if the caller should
17020
/// skip the definition of this tag and treat it as if it were a declaration.
17021
DeclResult
17022
Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17023
               CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17024
               const ParsedAttributesView &Attrs, AccessSpecifier AS,
17025
               SourceLocation ModulePrivateLoc,
17026
               MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17027
               bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17028
               bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17029
               bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17030
2.65M
               OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17031
  // If this is not a definition, it must have a name.
17032
2.65M
  IdentifierInfo *OrigName = Name;
17033
2.65M
  assert((Name != nullptr || TUK == TUK_Definition) &&
17034
2.65M
         "Nameless record must be a definition!");
17035
2.65M
  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
17036
17037
2.65M
  OwnedDecl = false;
17038
2.65M
  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17039
2.65M
  bool ScopedEnum = ScopedEnumKWLoc.isValid();
17040
17041
  // FIXME: Check member specializations more carefully.
17042
2.65M
  bool isMemberSpecialization = false;
17043
2.65M
  bool Invalid = false;
17044
17045
  // We only need to do this matching if we have template parameters
17046
  // or a scope specifier, which also conveniently avoids this work
17047
  // for non-C++ cases.
17048
2.65M
  if (TemplateParameterLists.size() > 0 ||
17049
2.65M
      
(2.30M
SS.isNotEmpty()2.30M
&&
TUK != TUK_Reference3.45k
)) {
17050
352k
    if (TemplateParameterList *TemplateParams =
17051
352k
            MatchTemplateParametersToScopeSpecifier(
17052
352k
                KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17053
352k
                TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
17054
348k
      if (Kind == TagTypeKind::Enum) {
17055
2
        Diag(KWLoc, diag::err_enum_template);
17056
2
        return true;
17057
2
      }
17058
17059
348k
      if (TemplateParams->size() > 0) {
17060
        // This is a declaration or definition of a class template (which may
17061
        // be a member of another template).
17062
17063
348k
        if (Invalid)
17064
1
          return true;
17065
17066
348k
        OwnedDecl = false;
17067
348k
        DeclResult Result = CheckClassTemplate(
17068
348k
            S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17069
348k
            AS, ModulePrivateLoc,
17070
348k
            /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17071
348k
            TemplateParameterLists.data(), SkipBody);
17072
348k
        return Result.get();
17073
348k
      } else {
17074
        // The "template<>" header is extraneous.
17075
9
        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17076
9
          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17077
9
        isMemberSpecialization = true;
17078
9
      }
17079
348k
    }
17080
17081
3.99k
    if (!TemplateParameterLists.empty() && 
isMemberSpecialization803
&&
17082
3.99k
        
CheckTemplateDeclScope(S, TemplateParameterLists.back())167
)
17083
2
      return true;
17084
3.99k
  }
17085
17086
  // Figure out the underlying type if this a enum declaration. We need to do
17087
  // this early, because it's needed to detect if this is an incompatible
17088
  // redeclaration.
17089
2.30M
  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17090
2.30M
  bool IsFixed = !UnderlyingType.isUnset() || 
ScopedEnum2.13M
;
17091
17092
2.30M
  if (Kind == TagTypeKind::Enum) {
17093
909k
    if (UnderlyingType.isInvalid() || 
(909k
!UnderlyingType.get()909k
&&
ScopedEnum736k
)) {
17094
      // No underlying type explicitly specified, or we failed to parse the
17095
      // type, default to int.
17096
2.29k
      EnumUnderlying = Context.IntTy.getTypePtr();
17097
907k
    } else if (UnderlyingType.get()) {
17098
      // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17099
      // integral type; any cv-qualification is ignored.
17100
172k
      TypeSourceInfo *TI = nullptr;
17101
172k
      GetTypeFromParser(UnderlyingType.get(), &TI);
17102
172k
      EnumUnderlying = TI;
17103
17104
172k
      if (CheckEnumUnderlyingType(TI))
17105
        // Recover by falling back to int.
17106
8
        EnumUnderlying = Context.IntTy.getTypePtr();
17107
17108
172k
      if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
17109
172k
                                          UPPC_FixedUnderlyingType))
17110
2
        EnumUnderlying = Context.IntTy.getTypePtr();
17111
17112
734k
    } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17113
      // For MSVC ABI compatibility, unfixed enums must use an underlying type
17114
      // of 'int'. However, if this is an unfixed forward declaration, don't set
17115
      // the underlying type unless the user enables -fms-compatibility. This
17116
      // makes unfixed forward declared enums incomplete and is more conforming.
17117
432
      if (TUK == TUK_Definition || 
getLangOpts().MSVCCompat90
)
17118
386
        EnumUnderlying = Context.IntTy.getTypePtr();
17119
432
    }
17120
909k
  }
17121
17122
2.30M
  DeclContext *SearchDC = CurContext;
17123
2.30M
  DeclContext *DC = CurContext;
17124
2.30M
  bool isStdBadAlloc = false;
17125
2.30M
  bool isStdAlignValT = false;
17126
17127
2.30M
  RedeclarationKind Redecl = forRedeclarationInCurContext();
17128
2.30M
  if (TUK == TUK_Friend || 
TUK == TUK_Reference2.29M
)
17129
1.09M
    Redecl = NotForRedeclaration;
17130
17131
  /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17132
  /// implemented asks for structural equivalence checking, the returned decl
17133
  /// here is passed back to the parser, allowing the tag body to be parsed.
17134
2.30M
  auto createTagFromNewDecl = [&]() -> TagDecl * {
17135
14
    assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17136
    // If there is an identifier, use the location of the identifier as the
17137
    // location of the decl, otherwise use the location of the struct/union
17138
    // keyword.
17139
14
    SourceLocation Loc = NameLoc.isValid() ? NameLoc : 
KWLoc0
;
17140
14
    TagDecl *New = nullptr;
17141
17142
14
    if (Kind == TagTypeKind::Enum) {
17143
4
      New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17144
4
                             ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17145
      // If this is an undefined enum, bail.
17146
4
      if (TUK != TUK_Definition && 
!Invalid0
)
17147
0
        return nullptr;
17148
4
      if (EnumUnderlying) {
17149
2
        EnumDecl *ED = cast<EnumDecl>(New);
17150
2
        if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17151
2
          ED->setIntegerTypeSourceInfo(TI);
17152
0
        else
17153
0
          ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17154
2
        QualType EnumTy = ED->getIntegerType();
17155
2
        ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17156
2
                                 ? 
Context.getPromotedIntegerType(EnumTy)0
17157
2
                                 : EnumTy);
17158
2
      }
17159
10
    } else { // struct/union
17160
10
      New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17161
10
                               nullptr);
17162
10
    }
17163
17164
14
    if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17165
      // Add alignment attributes if necessary; these attributes are checked
17166
      // when the ASTContext lays out the structure.
17167
      //
17168
      // It is important for implementing the correct semantics that this
17169
      // happen here (in ActOnTag). The #pragma pack stack is
17170
      // maintained as a result of parser callbacks which can occur at
17171
      // many points during the parsing of a struct declaration (because
17172
      // the #pragma tokens are effectively skipped over during the
17173
      // parsing of the struct).
17174
10
      if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17175
10
        AddAlignmentAttributesForRecord(RD);
17176
10
        AddMsStructLayoutForRecord(RD);
17177
10
      }
17178
10
    }
17179
14
    New->setLexicalDeclContext(CurContext);
17180
14
    return New;
17181
14
  };
17182
17183
2.30M
  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17184
2.30M
  if (Name && 
SS.isNotEmpty()1.75M
) {
17185
    // We have a nested-name tag ('struct foo::bar').
17186
17187
    // Check for invalid 'foo::'.
17188
4.25k
    if (SS.isInvalid()) {
17189
7
      Name = nullptr;
17190
7
      goto CreateNewDecl;
17191
7
    }
17192
17193
    // If this is a friend or a reference to a class in a dependent
17194
    // context, don't try to make a decl for it.
17195
4.24k
    if (TUK == TUK_Friend || 
TUK == TUK_Reference3.03k
) {
17196
1.45k
      DC = computeDeclContext(SS, false);
17197
1.45k
      if (!DC) {
17198
49
        IsDependent = true;
17199
49
        return true;
17200
49
      }
17201
2.78k
    } else {
17202
2.78k
      DC = computeDeclContext(SS, true);
17203
2.78k
      if (!DC) {
17204
5
        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17205
5
          << SS.getRange();
17206
5
        return true;
17207
5
      }
17208
2.78k
    }
17209
17210
4.18k
    if (RequireCompleteDeclContext(SS, DC))
17211
11
      return true;
17212
17213
4.17k
    SearchDC = DC;
17214
    // Look-up name inside 'foo::'.
17215
4.17k
    LookupQualifiedName(Previous, DC);
17216
17217
4.17k
    if (Previous.isAmbiguous())
17218
1
      return true;
17219
17220
4.17k
    if (Previous.empty()) {
17221
      // Name lookup did not find anything. However, if the
17222
      // nested-name-specifier refers to the current instantiation,
17223
      // and that current instantiation has any dependent base
17224
      // classes, we might find something at instantiation time: treat
17225
      // this as a dependent elaborated-type-specifier.
17226
      // But this only makes any sense for reference-like lookups.
17227
55
      if (Previous.wasNotFoundInCurrentInstantiation() &&
17228
55
          
(2
TUK == TUK_Reference2
||
TUK == TUK_Friend1
)) {
17229
2
        IsDependent = true;
17230
2
        return true;
17231
2
      }
17232
17233
      // A tag 'foo::bar' must already exist.
17234
53
      Diag(NameLoc, diag::err_not_tag_in_scope)
17235
53
          << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17236
53
      Name = nullptr;
17237
53
      Invalid = true;
17238
53
      goto CreateNewDecl;
17239
55
    }
17240
2.30M
  } else if (Name) {
17241
    // C++14 [class.mem]p14:
17242
    //   If T is the name of a class, then each of the following shall have a
17243
    //   name different from T:
17244
    //    -- every member of class T that is itself a type
17245
1.74M
    if (TUK != TUK_Reference && 
TUK != TUK_Friend669k
&&
17246
1.74M
        
DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))660k
)
17247
4
      return true;
17248
17249
    // If this is a named struct, check to see if there was a previous forward
17250
    // declaration or definition.
17251
    // FIXME: We're looking into outer scopes here, even when we
17252
    // shouldn't be. Doing so can result in ambiguities that we
17253
    // shouldn't be diagnosing.
17254
1.74M
    LookupName(Previous, S);
17255
17256
    // When declaring or defining a tag, ignore ambiguities introduced
17257
    // by types using'ed into this scope.
17258
1.74M
    if (Previous.isAmbiguous() &&
17259
1.74M
        
(18
TUK == TUK_Definition18
||
TUK == TUK_Declaration17
)) {
17260
5
      LookupResult::Filter F = Previous.makeFilter();
17261
15
      while (F.hasNext()) {
17262
10
        NamedDecl *ND = F.next();
17263
10
        if (!ND->getDeclContext()->getRedeclContext()->Equals(
17264
10
                SearchDC->getRedeclContext()))
17265
8
          F.erase();
17266
10
      }
17267
5
      F.done();
17268
5
    }
17269
17270
    // C++11 [namespace.memdef]p3:
17271
    //   If the name in a friend declaration is neither qualified nor
17272
    //   a template-id and the declaration is a function or an
17273
    //   elaborated-type-specifier, the lookup to determine whether
17274
    //   the entity has been previously declared shall not consider
17275
    //   any scopes outside the innermost enclosing namespace.
17276
    //
17277
    // MSVC doesn't implement the above rule for types, so a friend tag
17278
    // declaration may be a redeclaration of a type declared in an enclosing
17279
    // scope.  They do implement this rule for friend functions.
17280
    //
17281
    // Does it matter that this should be by scope instead of by
17282
    // semantic context?
17283
1.74M
    if (!Previous.empty() && 
TUK == TUK_Friend1.04M
) {
17284
7.58k
      DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17285
7.58k
      LookupResult::Filter F = Previous.makeFilter();
17286
7.58k
      bool FriendSawTagOutsideEnclosingNamespace = false;
17287
15.1k
      while (F.hasNext()) {
17288
7.58k
        NamedDecl *ND = F.next();
17289
7.58k
        DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17290
7.58k
        if (DC->isFileContext() &&
17291
7.58k
            
!EnclosingNS->Encloses(ND->getDeclContext())6.51k
) {
17292
33
          if (getLangOpts().MSVCCompat)
17293
6
            FriendSawTagOutsideEnclosingNamespace = true;
17294
27
          else
17295
27
            F.erase();
17296
33
        }
17297
7.58k
      }
17298
7.58k
      F.done();
17299
17300
      // Diagnose this MSVC extension in the easy case where lookup would have
17301
      // unambiguously found something outside the enclosing namespace.
17302
7.58k
      if (Previous.isSingleResult() && 
FriendSawTagOutsideEnclosingNamespace7.55k
) {
17303
6
        NamedDecl *ND = Previous.getFoundDecl();
17304
6
        Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17305
6
            << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17306
6
      }
17307
7.58k
    }
17308
17309
    // Note:  there used to be some attempt at recovery here.
17310
1.74M
    if (Previous.isAmbiguous())
17311
13
      return true;
17312
17313
1.74M
    if (!getLangOpts().CPlusPlus && 
TUK != TUK_Reference969k
) {
17314
      // FIXME: This makes sure that we ignore the contexts associated
17315
      // with C structs, unions, and enums when looking for a matching
17316
      // tag declaration or definition. See the similar lookup tweak
17317
      // in Sema::LookupName; is there a better way to deal with this?
17318
350k
      while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17319
1.44k
        SearchDC = SearchDC->getParent();
17320
1.40M
    } else if (getLangOpts().CPlusPlus) {
17321
      // Inside ObjCContainer want to keep it as a lexical decl context but go
17322
      // past it (most often to TranslationUnit) to find the semantic decl
17323
      // context.
17324
780k
      while (isa<ObjCContainerDecl>(SearchDC))
17325
147
        SearchDC = SearchDC->getParent();
17326
780k
    }
17327
1.74M
  } else 
if (553k
getLangOpts().CPlusPlus553k
) {
17328
    // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17329
    // TagDecl the same way as we skip it for named TagDecl.
17330
100k
    while (isa<ObjCContainerDecl>(SearchDC))
17331
117
      SearchDC = SearchDC->getParent();
17332
100k
  }
17333
17334
2.30M
  if (Previous.isSingleResult() &&
17335
2.30M
      
Previous.getFoundDecl()->isTemplateParameter()1.04M
) {
17336
    // Maybe we will complain about the shadowed template parameter.
17337
18
    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17338
    // Just pretend that we didn't see the previous declaration.
17339
18
    Previous.clear();
17340
18
  }
17341
17342
2.30M
  if (getLangOpts().CPlusPlus && 
Name885k
&&
DC784k
&&
StdNamespace784k
&&
17343
2.30M
      
DC->Equals(getStdNamespace())506k
) {
17344
15.9k
    if (Name->isStr("bad_alloc")) {
17345
      // This is a declaration of or a reference to "std::bad_alloc".
17346
645
      isStdBadAlloc = true;
17347
17348
      // If std::bad_alloc has been implicitly declared (but made invisible to
17349
      // name lookup), fill in this implicit declaration as the previous
17350
      // declaration, so that the declarations get chained appropriately.
17351
645
      if (Previous.empty() && StdBadAlloc)
17352
0
        Previous.addDecl(getStdBadAlloc());
17353
15.2k
    } else if (Name->isStr("align_val_t")) {
17354
703
      isStdAlignValT = true;
17355
703
      if (Previous.empty() && StdAlignValT)
17356
60
        Previous.addDecl(getStdAlignValT());
17357
703
    }
17358
15.9k
  }
17359
17360
  // If we didn't find a previous declaration, and this is a reference
17361
  // (or friend reference), move to the correct scope.  In C++, we
17362
  // also need to do a redeclaration lookup there, just in case
17363
  // there's a shadow friend decl.
17364
2.30M
  if (Name && 
Previous.empty()1.75M
&&
17365
2.30M
      
(706k
TUK == TUK_Reference706k
||
TUK == TUK_Friend578k
||
IsTemplateParamOrArg577k
)) {
17366
129k
    if (Invalid) 
goto CreateNewDecl0
;
17367
129k
    assert(SS.isEmpty());
17368
17369
129k
    if (TUK == TUK_Reference || 
IsTemplateParamOrArg894
) {
17370
      // C++ [basic.scope.pdecl]p5:
17371
      //   -- for an elaborated-type-specifier of the form
17372
      //
17373
      //          class-key identifier
17374
      //
17375
      //      if the elaborated-type-specifier is used in the
17376
      //      decl-specifier-seq or parameter-declaration-clause of a
17377
      //      function defined in namespace scope, the identifier is
17378
      //      declared as a class-name in the namespace that contains
17379
      //      the declaration; otherwise, except as a friend
17380
      //      declaration, the identifier is declared in the smallest
17381
      //      non-class, non-function-prototype scope that contains the
17382
      //      declaration.
17383
      //
17384
      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17385
      // C structs and unions.
17386
      //
17387
      // It is an error in C++ to declare (rather than define) an enum
17388
      // type, including via an elaborated type specifier.  We'll
17389
      // diagnose that later; for now, declare the enum in the same
17390
      // scope as we would have picked for any other tag type.
17391
      //
17392
      // GNU C also supports this behavior as part of its incomplete
17393
      // enum types extension, while GNU C++ does not.
17394
      //
17395
      // Find the context where we'll be declaring the tag.
17396
      // FIXME: We would like to maintain the current DeclContext as the
17397
      // lexical context,
17398
128k
      SearchDC = getTagInjectionContext(SearchDC);
17399
17400
      // Find the scope where we'll be declaring the tag.
17401
128k
      S = getTagInjectionScope(S, getLangOpts());
17402
128k
    } else {
17403
888
      assert(TUK == TUK_Friend);
17404
888
      CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17405
17406
      // C++ [namespace.memdef]p3:
17407
      //   If a friend declaration in a non-local class first declares a
17408
      //   class or function, the friend class or function is a member of
17409
      //   the innermost enclosing namespace.
17410
888
      SearchDC = RD->isLocalClass() ? 
RD->isLocalClass()5
17411
888
                                    : 
SearchDC->getEnclosingNamespaceContext()883
;
17412
888
    }
17413
17414
    // In C++, we need to do a redeclaration lookup to properly
17415
    // diagnose some problems.
17416
    // FIXME: redeclaration lookup is also used (with and without C++) to find a
17417
    // hidden declaration so that we don't get ambiguity errors when using a
17418
    // type declared by an elaborated-type-specifier.  In C that is not correct
17419
    // and we should instead merge compatible types found by lookup.
17420
129k
    if (getLangOpts().CPlusPlus) {
17421
      // FIXME: This can perform qualified lookups into function contexts,
17422
      // which are meaningless.
17423
16.2k
      Previous.setRedeclarationKind(forRedeclarationInCurContext());
17424
16.2k
      LookupQualifiedName(Previous, SearchDC);
17425
113k
    } else {
17426
113k
      Previous.setRedeclarationKind(forRedeclarationInCurContext());
17427
113k
      LookupName(Previous, S);
17428
113k
    }
17429
129k
  }
17430
17431
  // If we have a known previous declaration to use, then use it.
17432
2.30M
  if (Previous.empty() && 
SkipBody1.25M
&&
SkipBody->Previous1.25M
)
17433
5
    Previous.addDecl(SkipBody->Previous);
17434
17435
2.30M
  if (!Previous.empty()) {
17436
1.04M
    NamedDecl *PrevDecl = Previous.getFoundDecl();
17437
1.04M
    NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17438
17439
    // It's okay to have a tag decl in the same scope as a typedef
17440
    // which hides a tag decl in the same scope.  Finding this
17441
    // with a redeclaration lookup can only actually happen in C++.
17442
    //
17443
    // This is also okay for elaborated-type-specifiers, which is
17444
    // technically forbidden by the current standard but which is
17445
    // okay according to the likely resolution of an open issue;
17446
    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17447
1.04M
    if (getLangOpts().CPlusPlus) {
17448
473k
      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17449
57
        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17450
55
          TagDecl *Tag = TT->getDecl();
17451
55
          if (Tag->getDeclName() == Name &&
17452
55
              Tag->getDeclContext()->getRedeclContext()
17453
6
                          ->Equals(TD->getDeclContext()->getRedeclContext())) {
17454
0
            PrevDecl = Tag;
17455
0
            Previous.clear();
17456
0
            Previous.addDecl(Tag);
17457
0
            Previous.resolveKind();
17458
0
          }
17459
55
        }
17460
57
      }
17461
473k
    }
17462
17463
    // If this is a redeclaration of a using shadow declaration, it must
17464
    // declare a tag in the same context. In MSVC mode, we allow a
17465
    // redefinition if either context is within the other.
17466
1.04M
    if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17467
162
      auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17468
162
      if (SS.isEmpty() && 
TUK != TUK_Reference114
&&
TUK != TUK_Friend23
&&
17469
162
          
isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization)19
&&
17470
162
          
!(19
OldTag19
&& isAcceptableTagRedeclContext(
17471
19
                          *this, OldTag->getDeclContext(), SearchDC))) {
17472
7
        Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17473
7
        Diag(Shadow->getTargetDecl()->getLocation(),
17474
7
             diag::note_using_decl_target);
17475
7
        Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17476
7
            << 0;
17477
        // Recover by ignoring the old declaration.
17478
7
        Previous.clear();
17479
7
        goto CreateNewDecl;
17480
7
      }
17481
162
    }
17482
17483
1.04M
    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17484
      // If this is a use of a previous tag, or if the tag is already declared
17485
      // in the same scope (so that the definition/declaration completes or
17486
      // rementions the tag), reuse the decl.
17487
1.04M
      if (TUK == TUK_Reference || 
TUK == TUK_Friend94.6k
||
17488
1.04M
          isDeclInScope(DirectPrevDecl, SearchDC, S,
17489
1.04M
                        
SS.isNotEmpty()85.8k
||
isMemberSpecialization83.1k
)) {
17490
        // Make sure that this wasn't declared as an enum and now used as a
17491
        // struct or something similar.
17492
1.04M
        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17493
1.04M
                                          TUK == TUK_Definition, KWLoc,
17494
1.04M
                                          Name)) {
17495
65
          bool SafeToContinue =
17496
65
              (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17497
65
               
Kind != TagTypeKind::Enum51
);
17498
65
          if (SafeToContinue)
17499
37
            Diag(KWLoc, diag::err_use_with_wrong_tag)
17500
37
              << Name
17501
37
              << FixItHint::CreateReplacement(SourceRange(KWLoc),
17502
37
                                              PrevTagDecl->getKindName());
17503
28
          else
17504
28
            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17505
65
          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17506
17507
65
          if (SafeToContinue)
17508
37
            Kind = PrevTagDecl->getTagKind();
17509
28
          else {
17510
            // Recover by making this an anonymous redefinition.
17511
28
            Name = nullptr;
17512
28
            Previous.clear();
17513
28
            Invalid = true;
17514
28
          }
17515
65
        }
17516
17517
1.04M
        if (Kind == TagTypeKind::Enum &&
17518
1.04M
            
PrevTagDecl->getTagKind() == TagTypeKind::Enum436k
) {
17519
436k
          const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17520
436k
          if (TUK == TUK_Reference || 
TUK == TUK_Friend70.3k
)
17521
365k
            return PrevTagDecl;
17522
17523
70.3k
          QualType EnumUnderlyingTy;
17524
70.3k
          if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17525
70.1k
            EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17526
151
          else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17527
89
            EnumUnderlyingTy = QualType(T, 0);
17528
17529
          // All conflicts with previous declarations are recovered by
17530
          // returning the previous declaration, unless this is a definition,
17531
          // in which case we want the caller to bail out.
17532
70.3k
          if (CheckEnumRedeclaration(NameLoc.isValid() ? 
NameLoc70.3k
:
KWLoc5
,
17533
70.3k
                                     ScopedEnum, EnumUnderlyingTy,
17534
70.3k
                                     IsFixed, PrevEnum))
17535
51
            return TUK == TUK_Declaration ? 
PrevTagDecl28
:
nullptr23
;
17536
70.3k
        }
17537
17538
        // C++11 [class.mem]p1:
17539
        //   A member shall not be declared twice in the member-specification,
17540
        //   except that a nested class or member class template can be declared
17541
        //   and then later defined.
17542
679k
        if (TUK == TUK_Declaration && 
PrevDecl->isCXXClassMember()1.62k
&&
17543
679k
            
S->isDeclScope(PrevDecl)89
) {
17544
41
          Diag(NameLoc, diag::ext_member_redeclared);
17545
41
          Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17546
41
        }
17547
17548
679k
        if (!Invalid) {
17549
          // If this is a use, just return the declaration we found, unless
17550
          // we have attributes.
17551
679k
          if (TUK == TUK_Reference || 
TUK == TUK_Friend92.7k
) {
17552
595k
            if (!Attrs.empty()) {
17553
              // FIXME: Diagnose these attributes. For now, we create a new
17554
              // declaration to hold them.
17555
590k
            } else if (TUK == TUK_Reference &&
17556
590k
                       
(581k
PrevTagDecl->getFriendObjectKind() ==
17557
581k
                            Decl::FOK_Undeclared ||
17558
581k
                        
PrevDecl->getOwningModule() != getCurrentModule()581k
) &&
17559
590k
                       
SS.isEmpty()1.67k
) {
17560
              // This declaration is a reference to an existing entity, but
17561
              // has different visibility from that entity: it either makes
17562
              // a friend visible or it makes a type visible in a new module.
17563
              // In either case, create a new declaration. We only do this if
17564
              // the declaration would have meant the same thing if no prior
17565
              // declaration were found, that is, if it was found in the same
17566
              // scope where we would have injected a declaration.
17567
1.67k
              if (!getTagInjectionContext(CurContext)->getRedeclContext()
17568
1.67k
                       ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17569
10
                return PrevTagDecl;
17570
              // This is in the injected scope, create a new declaration in
17571
              // that scope.
17572
1.66k
              S = getTagInjectionScope(S, getLangOpts());
17573
588k
            } else {
17574
588k
              return PrevTagDecl;
17575
588k
            }
17576
595k
          }
17577
17578
          // Diagnose attempts to redefine a tag.
17579
90.7k
          if (TUK == TUK_Definition) {
17580
82.2k
            if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17581
              // If we're defining a specialization and the previous definition
17582
              // is from an implicit instantiation, don't emit an error
17583
              // here; we'll catch this in the general case below.
17584
213
              bool IsExplicitSpecializationAfterInstantiation = false;
17585
213
              if (isMemberSpecialization) {
17586
4
                if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17587
2
                  IsExplicitSpecializationAfterInstantiation =
17588
2
                    RD->getTemplateSpecializationKind() !=
17589
2
                    TSK_ExplicitSpecialization;
17590
2
                else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17591
2
                  IsExplicitSpecializationAfterInstantiation =
17592
2
                    ED->getTemplateSpecializationKind() !=
17593
2
                    TSK_ExplicitSpecialization;
17594
4
              }
17595
17596
              // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17597
              // not keep more that one definition around (merge them). However,
17598
              // ensure the decl passes the structural compatibility check in
17599
              // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17600
213
              NamedDecl *Hidden = nullptr;
17601
213
              if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17602
                // There is a definition of this tag, but it is not visible. We
17603
                // explicitly make use of C++'s one definition rule here, and
17604
                // assume that this definition is identical to the hidden one
17605
                // we already have. Make the existing definition visible and
17606
                // use it in place of this one.
17607
134
                if (!getLangOpts().CPlusPlus) {
17608
                  // Postpone making the old definition visible until after we
17609
                  // complete parsing the new one and do the structural
17610
                  // comparison.
17611
14
                  SkipBody->CheckSameAsPrevious = true;
17612
14
                  SkipBody->New = createTagFromNewDecl();
17613
14
                  SkipBody->Previous = Def;
17614
14
                  return Def;
17615
120
                } else {
17616
120
                  SkipBody->ShouldSkip = true;
17617
120
                  SkipBody->Previous = Def;
17618
120
                  makeMergedDefinitionVisible(Hidden);
17619
                  // Carry on and handle it like a normal definition. We'll
17620
                  // skip starting the definitiion later.
17621
120
                }
17622
134
              } else 
if (79
!IsExplicitSpecializationAfterInstantiation79
) {
17623
                // A redeclaration in function prototype scope in C isn't
17624
                // visible elsewhere, so merely issue a warning.
17625
75
                if (!getLangOpts().CPlusPlus && 
S->containedInPrototypeScope()34
)
17626
3
                  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17627
72
                else
17628
72
                  Diag(NameLoc, diag::err_redefinition) << Name;
17629
75
                notePreviousDefinition(Def,
17630
75
                                       NameLoc.isValid() ? NameLoc : 
KWLoc0
);
17631
                // If this is a redefinition, recover by making this
17632
                // struct be anonymous, which will make any later
17633
                // references get the previous definition.
17634
75
                Name = nullptr;
17635
75
                Previous.clear();
17636
75
                Invalid = true;
17637
75
              }
17638
82.0k
            } else {
17639
              // If the type is currently being defined, complain
17640
              // about a nested redefinition.
17641
82.0k
              auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17642
82.0k
              if (TD->isBeingDefined()) {
17643
6
                Diag(NameLoc, diag::err_nested_redefinition) << Name;
17644
6
                Diag(PrevTagDecl->getLocation(),
17645
6
                     diag::note_previous_definition);
17646
6
                Name = nullptr;
17647
6
                Previous.clear();
17648
6
                Invalid = true;
17649
6
              }
17650
82.0k
            }
17651
17652
            // Okay, this is definition of a previously declared or referenced
17653
            // tag. We're going to create a new Decl for it.
17654
82.2k
          }
17655
17656
          // Okay, we're going to make a redeclaration.  If this is some kind
17657
          // of reference, make sure we build the redeclaration in the same DC
17658
          // as the original, and ignore the current access specifier.
17659
90.6k
          if (TUK == TUK_Friend || 
TUK == TUK_Reference90.2k
) {
17660
6.81k
            SearchDC = PrevTagDecl->getDeclContext();
17661
6.81k
            AS = AS_none;
17662
6.81k
          }
17663
90.6k
        }
17664
        // If we get here we have (another) forward declaration or we
17665
        // have a definition.  Just create a new decl.
17666
17667
679k
      } else {
17668
        // If we get here, this is a definition of a new tag type in a nested
17669
        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17670
        // new decl/type.  We set PrevDecl to NULL so that the entities
17671
        // have distinct types.
17672
1.88k
        Previous.clear();
17673
1.88k
      }
17674
      // If we get here, we're going to create a new Decl. If PrevDecl
17675
      // is non-NULL, it's a definition of the tag declared by
17676
      // PrevDecl. If it's NULL, we have a new definition.
17677
17678
    // Otherwise, PrevDecl is not a tag, but was found with tag
17679
    // lookup.  This is only actually possible in C++, where a few
17680
    // things like templates still live in the tag namespace.
17681
1.04M
    } else {
17682
      // Use a better diagnostic if an elaborated-type-specifier
17683
      // found the wrong kind of type on the first
17684
      // (non-redeclaration) lookup.
17685
106
      if ((TUK == TUK_Reference || 
TUK == TUK_Friend82
) &&
17686
106
          
!Previous.isForRedeclaration()25
) {
17687
24
        NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17688
24
        Diag(NameLoc, diag::err_tag_reference_non_tag)
17689
24
            << PrevDecl << NTK << llvm::to_underlying(Kind);
17690
24
        Diag(PrevDecl->getLocation(), diag::note_declared_at);
17691
24
        Invalid = true;
17692
17693
      // Otherwise, only diagnose if the declaration is in scope.
17694
82
      } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17695
82
                                SS.isNotEmpty() || 
isMemberSpecialization70
)) {
17696
        // do nothing
17697
17698
      // Diagnose implicit declarations introduced by elaborated types.
17699
47
      } else 
if (35
TUK == TUK_Reference35
||
TUK == TUK_Friend34
) {
17700
1
        NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17701
1
        Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17702
1
        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17703
1
        Invalid = true;
17704
17705
      // Otherwise it's a declaration.  Call out a particularly common
17706
      // case here.
17707
34
      } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17708
19
        unsigned Kind = 0;
17709
19
        if (isa<TypeAliasDecl>(PrevDecl)) 
Kind = 10
;
17710
19
        Diag(NameLoc, diag::err_tag_definition_of_typedef)
17711
19
          << Name << Kind << TND->getUnderlyingType();
17712
19
        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17713
19
        Invalid = true;
17714
17715
      // Otherwise, diagnose.
17716
19
      } else {
17717
        // The tag name clashes with something else in the target scope,
17718
        // issue an error and recover by making this tag be anonymous.
17719
15
        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17720
15
        notePreviousDefinition(PrevDecl, NameLoc);
17721
15
        Name = nullptr;
17722
15
        Invalid = true;
17723
15
      }
17724
17725
      // The existing declaration isn't relevant to us; we're in a
17726
      // new scope, so clear out the previous declaration.
17727
106
      Previous.clear();
17728
106
    }
17729
1.04M
  }
17730
17731
1.35M
CreateNewDecl:
17732
17733
1.35M
  TagDecl *PrevDecl = nullptr;
17734
1.35M
  if (Previous.isSingleResult())
17735
90.6k
    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17736
17737
  // If there is an identifier, use the location of the identifier as the
17738
  // location of the decl, otherwise use the location of the struct/union
17739
  // keyword.
17740
1.35M
  SourceLocation Loc = NameLoc.isValid() ? 
NameLoc799k
:
KWLoc553k
;
17741
17742
  // Otherwise, create a new declaration. If there is a previous
17743
  // declaration of the same entity, the two will be linked via
17744
  // PrevDecl.
17745
1.35M
  TagDecl *New;
17746
17747
1.35M
  if (Kind == TagTypeKind::Enum) {
17748
    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17749
    // enum X { A, B, C } D;    D should chain to X.
17750
543k
    New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17751
543k
                           cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17752
543k
                           ScopedEnumUsesClassTag, IsFixed);
17753
17754
543k
    if (isStdAlignValT && 
(703
!StdAlignValT703
||
getStdAlignValT()->isImplicit()60
))
17755
703
      StdAlignValT = cast<EnumDecl>(New);
17756
17757
    // If this is an undefined enum, warn.
17758
543k
    if (TUK != TUK_Definition && 
!Invalid70.5k
) {
17759
70.4k
      TagDecl *Def;
17760
70.4k
      if (IsFixed && 
cast<EnumDecl>(New)->isFixed()70.3k
) {
17761
        // C++0x: 7.2p2: opaque-enum-declaration.
17762
        // Conflicts are diagnosed above. Do nothing.
17763
70.3k
      }
17764
158
      else if (PrevDecl && 
(Def = cast<EnumDecl>(PrevDecl)->getDefinition())17
) {
17765
13
        Diag(Loc, diag::ext_forward_ref_enum_def)
17766
13
          << New;
17767
13
        Diag(Def->getLocation(), diag::note_previous_definition);
17768
145
      } else {
17769
145
        unsigned DiagID = diag::ext_forward_ref_enum;
17770
145
        if (getLangOpts().MSVCCompat)
17771
20
          DiagID = diag::ext_ms_forward_ref_enum;
17772
125
        else if (getLangOpts().CPlusPlus)
17773
37
          DiagID = diag::err_forward_ref_enum;
17774
145
        Diag(Loc, DiagID);
17775
145
      }
17776
70.4k
    }
17777
17778
543k
    if (EnumUnderlying) {
17779
175k
      EnumDecl *ED = cast<EnumDecl>(New);
17780
175k
      if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17781
172k
        ED->setIntegerTypeSourceInfo(TI);
17782
2.63k
      else
17783
2.63k
        ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17784
175k
      QualType EnumTy = ED->getIntegerType();
17785
175k
      ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17786
175k
                               ? 
Context.getPromotedIntegerType(EnumTy)5.65k
17787
175k
                               : 
EnumTy169k
);
17788
175k
      assert(ED->isComplete() && "enum with type should be complete");
17789
175k
    }
17790
809k
  } else {
17791
    // struct/union/class
17792
17793
    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17794
    // struct X { int A; } D;    D should chain to X.
17795
809k
    if (getLangOpts().CPlusPlus) {
17796
      // FIXME: Look for a way to use RecordDecl for simple structs.
17797
345k
      New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17798
345k
                                  cast_or_null<CXXRecordDecl>(PrevDecl));
17799
17800
345k
      if (isStdBadAlloc && 
(645
!StdBadAlloc645
||
getStdBadAlloc()->isImplicit()0
))
17801
645
        StdBadAlloc = cast<CXXRecordDecl>(New);
17802
345k
    } else
17803
463k
      New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17804
463k
                               cast_or_null<RecordDecl>(PrevDecl));
17805
809k
  }
17806
17807
1.35M
  if (OOK != OOK_Outside && 
TUK == TUK_Definition46
&&
!getLangOpts().CPlusPlus46
)
17808
41
    Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17809
41
        << (OOK == OOK_Macro) << New->getSourceRange();
17810
17811
  // C++11 [dcl.type]p3:
17812
  //   A type-specifier-seq shall not define a class or enumeration [...].
17813
1.35M
  if (!Invalid && 
getLangOpts().CPlusPlus1.35M
&&
17814
1.35M
      
(432k
IsTypeSpecifier432k
||
IsTemplateParamOrArg432k
) &&
TUK == TUK_Definition153
) {
17815
83
    Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17816
83
      << Context.getTagDeclType(New);
17817
83
    Invalid = true;
17818
83
  }
17819
17820
1.35M
  if (!Invalid && 
getLangOpts().CPlusPlus1.35M
&&
TUK == TUK_Definition432k
&&
17821
1.35M
      
DC->getDeclKind() == Decl::Enum389k
) {
17822
2
    Diag(New->getLocation(), diag::err_type_defined_in_enum)
17823
2
      << Context.getTagDeclType(New);
17824
2
    Invalid = true;
17825
2
  }
17826
17827
  // Maybe add qualifier info.
17828
1.35M
  if (SS.isNotEmpty()) {
17829
2.77k
    if (SS.isSet()) {
17830
      // If this is either a declaration or a definition, check the
17831
      // nested-name-specifier against the current context.
17832
2.76k
      if ((TUK == TUK_Definition || 
TUK == TUK_Declaration79
) &&
17833
2.76k
          diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17834
2.74k
                                       isMemberSpecialization))
17835
23
        Invalid = true;
17836
17837
2.76k
      New->setQualifierInfo(SS.getWithLocInContext(Context));
17838
2.76k
      if (TemplateParameterLists.size() > 0) {
17839
764
        New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17840
764
      }
17841
2.76k
    }
17842
7
    else
17843
7
      Invalid = true;
17844
2.77k
  }
17845
17846
1.35M
  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17847
    // Add alignment attributes if necessary; these attributes are checked when
17848
    // the ASTContext lays out the structure.
17849
    //
17850
    // It is important for implementing the correct semantics that this
17851
    // happen here (in ActOnTag). The #pragma pack stack is
17852
    // maintained as a result of parser callbacks which can occur at
17853
    // many points during the parsing of a struct declaration (because
17854
    // the #pragma tokens are effectively skipped over during the
17855
    // parsing of the struct).
17856
809k
    if (TUK == TUK_Definition && 
(714k
!SkipBody714k
||
!SkipBody->ShouldSkip714k
)) {
17857
714k
      AddAlignmentAttributesForRecord(RD);
17858
714k
      AddMsStructLayoutForRecord(RD);
17859
714k
    }
17860
809k
  }
17861
17862
1.35M
  if (ModulePrivateLoc.isValid()) {
17863
15
    if (isMemberSpecialization)
17864
1
      Diag(New->getLocation(), diag::err_module_private_specialization)
17865
1
        << 2
17866
1
        << FixItHint::CreateRemoval(ModulePrivateLoc);
17867
    // __module_private__ does not apply to local classes. However, we only
17868
    // diagnose this as an error when the declaration specifiers are
17869
    // freestanding. Here, we just ignore the __module_private__.
17870
14
    else if (!SearchDC->isFunctionOrMethod())
17871
12
      New->setModulePrivate();
17872
15
  }
17873
17874
  // If this is a specialization of a member class (of a class template),
17875
  // check the specialization.
17876
1.35M
  if (isMemberSpecialization && 
CheckMemberSpecialization(New, Previous)151
)
17877
10
    Invalid = true;
17878
17879
  // If we're declaring or defining a tag in function prototype scope in C,
17880
  // note that this type can only be used within the function and add it to
17881
  // the list of decls to inject into the function definition scope.
17882
1.35M
  if ((Name || 
Kind == TagTypeKind::Enum553k
) &&
17883
1.35M
      
getNonFieldDeclScope(S)->isFunctionPrototypeScope()1.17M
) {
17884
508
    if (getLangOpts().CPlusPlus) {
17885
      // C++ [dcl.fct]p6:
17886
      //   Types shall not be defined in return or parameter types.
17887
42
      if (TUK == TUK_Definition && 
!IsTypeSpecifier28
) {
17888
24
        Diag(Loc, diag::err_type_defined_in_param_type)
17889
24
            << Name;
17890
24
        Invalid = true;
17891
24
      }
17892
466
    } else if (!PrevDecl) {
17893
183
      Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17894
183
    }
17895
508
  }
17896
17897
1.35M
  if (Invalid)
17898
370
    New->setInvalidDecl();
17899
17900
  // Set the lexical context. If the tag has a C++ scope specifier, the
17901
  // lexical context will be different from the semantic context.
17902
1.35M
  New->setLexicalDeclContext(CurContext);
17903
17904
  // Mark this as a friend decl if applicable.
17905
  // In Microsoft mode, a friend declaration also acts as a forward
17906
  // declaration so we always pass true to setObjectOfFriendDecl to make
17907
  // the tag name visible.
17908
1.35M
  if (TUK == TUK_Friend)
17909
1.21k
    New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17910
17911
  // Set the access specifier.
17912
1.35M
  if (!Invalid && 
SearchDC->isRecord()1.35M
)
17913
66.8k
    SetMemberAccessSpecifier(New, PrevDecl, AS);
17914
17915
1.35M
  if (PrevDecl)
17916
90.6k
    CheckRedeclarationInModule(New, PrevDecl);
17917
17918
1.35M
  if (TUK == TUK_Definition && 
(1.18M
!SkipBody1.18M
||
!SkipBody->ShouldSkip1.18M
))
17919
1.18M
    New->startDefinition();
17920
17921
1.35M
  ProcessDeclAttributeList(S, New, Attrs);
17922
1.35M
  AddPragmaAttributes(S, New);
17923
17924
  // If this has an identifier, add it to the scope stack.
17925
1.35M
  if (TUK == TUK_Friend) {
17926
    // We might be replacing an existing declaration in the lookup tables;
17927
    // if so, borrow its access specifier.
17928
1.21k
    if (PrevDecl)
17929
413
      New->setAccess(PrevDecl->getAccess());
17930
17931
1.21k
    DeclContext *DC = New->getDeclContext()->getRedeclContext();
17932
1.21k
    DC->makeDeclVisibleInContext(New);
17933
1.21k
    if (Name) // can be null along some error paths
17934
1.20k
      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17935
1.20k
        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17936
1.35M
  } else if (Name) {
17937
798k
    S = getNonFieldDeclScope(S);
17938
798k
    PushOnScopeChains(New, S, true);
17939
798k
  } else {
17940
553k
    CurContext->addDecl(New);
17941
553k
  }
17942
17943
  // If this is the C FILE type, notify the AST context.
17944
1.35M
  if (IdentifierInfo *II = New->getIdentifier())
17945
799k
    if (!New->isInvalidDecl() &&
17946
799k
        
New->getDeclContext()->getRedeclContext()->isTranslationUnit()799k
&&
17947
799k
        
II->isStr("FILE")615k
)
17948
36
      Context.setFILEDecl(New);
17949
17950
1.35M
  if (PrevDecl)
17951
90.6k
    mergeDeclAttributes(New, PrevDecl);
17952
17953
1.35M
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
17954
345k
    inferGslOwnerPointerAttribute(CXXRD);
17955
17956
  // If there's a #pragma GCC visibility in scope, set the visibility of this
17957
  // record.
17958
1.35M
  AddPushedVisibilityAttribute(New);
17959
17960
1.35M
  if (isMemberSpecialization && 
!New->isInvalidDecl()151
)
17961
135
    CompleteMemberSpecialization(New, Previous);
17962
17963
1.35M
  OwnedDecl = true;
17964
  // In C++, don't return an invalid declaration. We can't recover well from
17965
  // the cases where we make the type anonymous.
17966
1.35M
  if (Invalid && 
getLangOpts().CPlusPlus370
) {
17967
323
    if (New->isBeingDefined())
17968
237
      if (auto RD = dyn_cast<RecordDecl>(New))
17969
205
        RD->completeDefinition();
17970
323
    return true;
17971
1.35M
  } else if (SkipBody && 
SkipBody->ShouldSkip1.35M
) {
17972
120
    return SkipBody->Previous;
17973
1.35M
  } else {
17974
1.35M
    return New;
17975
1.35M
  }
17976
1.35M
}
17977
17978
1.73M
void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17979
1.73M
  AdjustDeclIfTemplate(TagD);
17980
1.73M
  TagDecl *Tag = cast<TagDecl>(TagD);
17981
17982
  // Enter the tag context.
17983
1.73M
  PushDeclContext(S, Tag);
17984
17985
1.73M
  ActOnDocumentableDecl(TagD);
17986
17987
  // If there's a #pragma GCC visibility in scope, set the visibility of this
17988
  // record.
17989
1.73M
  AddPushedVisibilityAttribute(Tag);
17990
1.73M
}
17991
17992
14
bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17993
14
  if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17994
5
    return false;
17995
17996
  // Make the previous decl visible.
17997
9
  makeMergedDefinitionVisible(SkipBody.Previous);
17998
9
  return true;
17999
14
}
18000
18001
1.82M
void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
18002
1.82M
  assert(IDecl->getLexicalParent() == CurContext &&
18003
1.82M
      "The next DeclContext should be lexically contained in the current one.");
18004
1.82M
  CurContext = IDecl;
18005
1.82M
}
18006
18007
void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18008
                                           SourceLocation FinalLoc,
18009
                                           bool IsFinalSpelledSealed,
18010
                                           bool IsAbstract,
18011
851k
                                           SourceLocation LBraceLoc) {
18012
851k
  AdjustDeclIfTemplate(TagD);
18013
851k
  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18014
18015
851k
  FieldCollector->StartClass();
18016
18017
851k
  if (!Record->getIdentifier())
18018
40.0k
    return;
18019
18020
811k
  if (IsAbstract)
18021
12
    Record->markAbstract();
18022
18023
811k
  if (FinalLoc.isValid()) {
18024
231
    Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18025
231
                                      IsFinalSpelledSealed
18026
231
                                          ? 
FinalAttr::Keyword_sealed18
18027
231
                                          : 
FinalAttr::Keyword_final213
));
18028
231
  }
18029
  // C++ [class]p2:
18030
  //   [...] The class-name is also inserted into the scope of the
18031
  //   class itself; this is known as the injected-class-name. For
18032
  //   purposes of access checking, the injected-class-name is treated
18033
  //   as if it were a public member name.
18034
811k
  CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18035
811k
      Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18036
811k
      Record->getLocation(), Record->getIdentifier(),
18037
811k
      /*PrevDecl=*/nullptr,
18038
811k
      /*DelayTypeCreation=*/true);
18039
811k
  Context.getTypeDeclType(InjectedClassName, Record);
18040
811k
  InjectedClassName->setImplicit();
18041
811k
  InjectedClassName->setAccess(AS_public);
18042
811k
  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18043
284k
      InjectedClassName->setDescribedClassTemplate(Template);
18044
811k
  PushOnScopeChains(InjectedClassName, S);
18045
811k
  assert(InjectedClassName->isInjectedClassName() &&
18046
811k
         "Broken injected-class-name");
18047
811k
}
18048
18049
void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18050
1.73M
                                    SourceRange BraceRange) {
18051
1.73M
  AdjustDeclIfTemplate(TagD);
18052
1.73M
  TagDecl *Tag = cast<TagDecl>(TagD);
18053
1.73M
  Tag->setBraceRange(BraceRange);
18054
18055
  // Make sure we "complete" the definition even it is invalid.
18056
1.73M
  if (Tag->isBeingDefined()) {
18057
0
    assert(Tag->isInvalidDecl() && "We should already have completed it");
18058
0
    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18059
0
      RD->completeDefinition();
18060
0
  }
18061
18062
1.73M
  if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18063
851k
    FieldCollector->FinishClass();
18064
851k
    if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18065
18
      auto *Def = RD->getDefinition();
18066
18
      assert(Def && "The record is expected to have a completed definition");
18067
18
      unsigned NumInitMethods = 0;
18068
26
      for (auto *Method : Def->methods()) {
18069
26
        if (!Method->getIdentifier())
18070
9
            continue;
18071
17
        if (Method->getName() == "__init")
18072
16
          NumInitMethods++;
18073
17
      }
18074
18
      if (NumInitMethods > 1 || 
!Def->hasInitMethod()17
)
18075
9
        Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18076
18
    }
18077
851k
  }
18078
18079
  // Exit this scope of this tag's definition.
18080
1.73M
  PopDeclContext();
18081
18082
1.73M
  if (getCurLexicalContext()->isObjCContainer() &&
18083
1.73M
      
Tag->getDeclContext()->isFileContext()4.81k
)
18084
4.15k
    Tag->setTopLevelDeclInObjCContainer();
18085
18086
  // Notify the consumer that we've defined a tag.
18087
1.73M
  if (!Tag->isInvalidDecl())
18088
1.73M
    Consumer.HandleTagDeclDefinition(Tag);
18089
18090
  // Clangs implementation of #pragma align(packed) differs in bitfield layout
18091
  // from XLs and instead matches the XL #pragma pack(1) behavior.
18092
1.73M
  if (Context.getTargetInfo().getTriple().isOSAIX() &&
18093
1.73M
      
AlignPackStack.hasValue()642
) {
18094
80
    AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18095
    // Only diagnose #pragma align(packed).
18096
80
    if (!APInfo.IsAlignAttr() || 
APInfo.getAlignMode() != AlignPackInfo::Packed42
)
18097
60
      return;
18098
20
    const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18099
20
    if (!RD)
18100
0
      return;
18101
    // Only warn if there is at least 1 bitfield member.
18102
20
    if (llvm::any_of(RD->fields(),
18103
32
                     [](const FieldDecl *FD) { return FD->isBitField(); }))
18104
16
      Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18105
20
  }
18106
1.73M
}
18107
18108
1.82M
void Sema::ActOnObjCContainerFinishDefinition() {
18109
  // Exit this scope of this interface definition.
18110
1.82M
  PopDeclContext();
18111
1.82M
}
18112
18113
1.68M
void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
18114
1.68M
  assert(ObjCCtx == CurContext && "Mismatch of container contexts");
18115
1.68M
  OriginalLexicalContext = ObjCCtx;
18116
1.68M
  ActOnObjCContainerFinishDefinition();
18117
1.68M
}
18118
18119
1.68M
void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
18120
1.68M
  ActOnObjCContainerStartDefinition(ObjCCtx);
18121
1.68M
  OriginalLexicalContext = nullptr;
18122
1.68M
}
18123
18124
13
void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18125
13
  AdjustDeclIfTemplate(TagD);
18126
13
  TagDecl *Tag = cast<TagDecl>(TagD);
18127
13
  Tag->setInvalidDecl();
18128
18129
  // Make sure we "complete" the definition even it is invalid.
18130
13
  if (Tag->isBeingDefined()) {
18131
13
    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18132
13
      RD->completeDefinition();
18133
13
  }
18134
18135
  // We're undoing ActOnTagStartDefinition here, not
18136
  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18137
  // the FieldCollector.
18138
18139
13
  PopDeclContext();
18140
13
}
18141
18142
// Note that FieldName may be null for anonymous bitfields.
18143
ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18144
                                IdentifierInfo *FieldName, QualType FieldTy,
18145
77.3k
                                bool IsMsStruct, Expr *BitWidth) {
18146
77.3k
  assert(BitWidth);
18147
77.3k
  if (BitWidth->containsErrors())
18148
4
    return ExprError();
18149
18150
  // C99 6.7.2.1p4 - verify the field type.
18151
  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18152
77.3k
  if (!FieldTy->isDependentType() && 
!FieldTy->isIntegralOrEnumerationType()76.4k
) {
18153
    // Handle incomplete and sizeless types with a specific error.
18154
6
    if (RequireCompleteSizedType(FieldLoc, FieldTy,
18155
6
                                 diag::err_field_incomplete_or_sizeless))
18156
0
      return ExprError();
18157
6
    if (FieldName)
18158
4
      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18159
4
        << FieldName << FieldTy << BitWidth->getSourceRange();
18160
2
    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18161
2
      << FieldTy << BitWidth->getSourceRange();
18162
77.3k
  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18163
77.3k
                                             UPPC_BitFieldWidth))
18164
2
    return ExprError();
18165
18166
  // If the bit-width is type- or value-dependent, don't try to check
18167
  // it now.
18168
77.3k
  if (BitWidth->isValueDependent() || 
BitWidth->isTypeDependent()76.8k
)
18169
490
    return BitWidth;
18170
18171
76.8k
  llvm::APSInt Value;
18172
76.8k
  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
18173
76.8k
  if (ICE.isInvalid())
18174
93
    return ICE;
18175
76.8k
  BitWidth = ICE.get();
18176
18177
  // Zero-width bitfield is ok for anonymous field.
18178
76.8k
  if (Value == 0 && 
FieldName798
)
18179
6
    return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18180
6
           << FieldName << BitWidth->getSourceRange();
18181
18182
76.7k
  if (Value.isSigned() && 
Value.isNegative()75.7k
) {
18183
6
    if (FieldName)
18184
5
      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18185
5
               << FieldName << toString(Value, 10);
18186
1
    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18187
1
      << toString(Value, 10);
18188
6
  }
18189
18190
  // The size of the bit-field must not exceed our maximum permitted object
18191
  // size.
18192
76.7k
  if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18193
1
    return Diag(FieldLoc, diag::err_bitfield_too_wide)
18194
1
           << !FieldName << FieldName << toString(Value, 10);
18195
1
  }
18196
18197
76.7k
  if (!FieldTy->isDependentType()) {
18198
76.3k
    uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18199
76.3k
    uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18200
76.3k
    bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18201
18202
    // Over-wide bitfields are an error in C or when using the MSVC bitfield
18203
    // ABI.
18204
76.3k
    bool CStdConstraintViolation =
18205
76.3k
        BitfieldIsOverwide && 
!getLangOpts().CPlusPlus87
;
18206
76.3k
    bool MSBitfieldViolation =
18207
76.3k
        Value.ugt(TypeStorageSize) &&
18208
76.3k
        
(61
IsMsStruct61
||
Context.getTargetInfo().getCXXABI().isMicrosoft()58
);
18209
76.3k
    if (CStdConstraintViolation || 
MSBitfieldViolation76.3k
) {
18210
20
      unsigned DiagWidth =
18211
20
          CStdConstraintViolation ? 
TypeWidth17
:
TypeStorageSize3
;
18212
20
      return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18213
20
             << (bool)FieldName << FieldName << toString(Value, 10)
18214
20
             << !CStdConstraintViolation << DiagWidth;
18215
20
    }
18216
18217
    // Warn on types where the user might conceivably expect to get all
18218
    // specified bits as value bits: that's all integral types other than
18219
    // 'bool'.
18220
76.3k
    if (BitfieldIsOverwide && 
!FieldTy->isBooleanType()67
&&
FieldName42
) {
18221
41
      Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18222
41
          << FieldName << toString(Value, 10)
18223
41
          << (unsigned)TypeWidth;
18224
41
    }
18225
76.3k
  }
18226
18227
76.7k
  return BitWidth;
18228
76.7k
}
18229
18230
/// ActOnField - Each field of a C struct/union is passed into this in order
18231
/// to create a FieldDecl object for it.
18232
Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18233
1.82M
                       Declarator &D, Expr *BitfieldWidth) {
18234
1.82M
  FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18235
1.82M
                               D, BitfieldWidth,
18236
1.82M
                               /*InitStyle=*/ICIS_NoInit, AS_public);
18237
1.82M
  return Res;
18238
1.82M
}
18239
18240
/// HandleField - Analyze a field of a C struct or a C++ data member.
18241
///
18242
FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18243
                             SourceLocation DeclStart,
18244
                             Declarator &D, Expr *BitWidth,
18245
                             InClassInitStyle InitStyle,
18246
2.95M
                             AccessSpecifier AS) {
18247
2.95M
  if (D.isDecompositionDeclarator()) {
18248
12
    const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18249
12
    Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18250
12
      << Decomp.getSourceRange();
18251
12
    return nullptr;
18252
12
  }
18253
18254
2.95M
  IdentifierInfo *II = D.getIdentifier();
18255
2.95M
  SourceLocation Loc = DeclStart;
18256
2.95M
  if (II) 
Loc = D.getIdentifierLoc()2.95M
;
18257
18258
2.95M
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18259
2.95M
  QualType T = TInfo->getType();
18260
2.95M
  if (getLangOpts().CPlusPlus) {
18261
1.13M
    CheckExtraCXXDefaultArguments(D);
18262
18263
1.13M
    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18264
1.13M
                                        UPPC_DataMemberType)) {
18265
4
      D.setInvalidType();
18266
4
      T = Context.IntTy;
18267
4
      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18268
4
    }
18269
1.13M
  }
18270
18271
2.95M
  DiagnoseFunctionSpecifiers(D.getDeclSpec());
18272
18273
2.95M
  if (D.getDeclSpec().isInlineSpecified())
18274
3
    Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18275
3
        << getLangOpts().CPlusPlus17;
18276
2.95M
  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18277
5
    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18278
5
         diag::err_invalid_thread)
18279
5
      << DeclSpec::getSpecifierName(TSCS);
18280
18281
  // Check to see if this name was declared as a member previously
18282
2.95M
  NamedDecl *PrevDecl = nullptr;
18283
2.95M
  LookupResult Previous(*this, II, Loc, LookupMemberName,
18284
2.95M
                        ForVisibleRedeclaration);
18285
2.95M
  LookupName(Previous, S);
18286
2.95M
  switch (Previous.getResultKind()) {
18287
2.28k
    case LookupResult::Found:
18288
2.29k
    case LookupResult::FoundUnresolvedValue:
18289
2.29k
      PrevDecl = Previous.getAsSingle<NamedDecl>();
18290
2.29k
      break;
18291
18292
1
    case LookupResult::FoundOverloaded:
18293
1
      PrevDecl = Previous.getRepresentativeDecl();
18294
1
      break;
18295
18296
2.95M
    case LookupResult::NotFound:
18297
2.95M
    case LookupResult::NotFoundInCurrentInstantiation:
18298
2.95M
    case LookupResult::Ambiguous:
18299
2.95M
      break;
18300
2.95M
  }
18301
2.95M
  Previous.suppressDiagnostics();
18302
18303
2.95M
  if (PrevDecl && 
PrevDecl->isTemplateParameter()2.29k
) {
18304
    // Maybe we will complain about the shadowed template parameter.
18305
5
    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18306
    // Just pretend that we didn't see the previous declaration.
18307
5
    PrevDecl = nullptr;
18308
5
  }
18309
18310
2.95M
  if (PrevDecl && 
!isDeclInScope(PrevDecl, Record, S)2.28k
)
18311
2.16k
    PrevDecl = nullptr;
18312
18313
2.95M
  bool Mutable
18314
2.95M
    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18315
2.95M
  SourceLocation TSSL = D.getBeginLoc();
18316
2.95M
  FieldDecl *NewFD
18317
2.95M
    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18318
2.95M
                     TSSL, AS, PrevDecl, &D);
18319
18320
2.95M
  if (NewFD->isInvalidDecl())
18321
648
    Record->setInvalidDecl();
18322
18323
2.95M
  if (D.getDeclSpec().isModulePrivateSpecified())
18324
5
    NewFD->setModulePrivate();
18325
18326
2.95M
  if (NewFD->isInvalidDecl() && 
PrevDecl648
) {
18327
    // Don't introduce NewFD into scope; there's already something
18328
    // with the same name in the same scope.
18329
2.95M
  } else if (II) {
18330
2.95M
    PushOnScopeChains(NewFD, S);
18331
2.95M
  } else
18332
4.38k
    Record->addDecl(NewFD);
18333
18334
2.95M
  return NewFD;
18335
2.95M
}
18336
18337
/// Build a new FieldDecl and check its well-formedness.
18338
///
18339
/// This routine builds a new FieldDecl given the fields name, type,
18340
/// record, etc. \p PrevDecl should refer to any previous declaration
18341
/// with the same name and in the same scope as the field to be
18342
/// created.
18343
///
18344
/// \returns a new FieldDecl.
18345
///
18346
/// \todo The Declarator argument is a hack. It will be removed once
18347
FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18348
                                TypeSourceInfo *TInfo,
18349
                                RecordDecl *Record, SourceLocation Loc,
18350
                                bool Mutable, Expr *BitWidth,
18351
                                InClassInitStyle InitStyle,
18352
                                SourceLocation TSSL,
18353
                                AccessSpecifier AS, NamedDecl *PrevDecl,
18354
3.07M
                                Declarator *D) {
18355
3.07M
  IdentifierInfo *II = Name.getAsIdentifierInfo();
18356
3.07M
  bool InvalidDecl = false;
18357
3.07M
  if (D) 
InvalidDecl = D->isInvalidType()2.95M
;
18358
18359
  // If we receive a broken type, recover by assuming 'int' and
18360
  // marking this declaration as invalid.
18361
3.07M
  if (T.isNull() || T->containsErrors()) {
18362
5
    InvalidDecl = true;
18363
5
    T = Context.IntTy;
18364
5
  }
18365
18366
3.07M
  QualType EltTy = Context.getBaseElementType(T);
18367
3.07M
  if (!EltTy->isDependentType() && 
!EltTy->containsErrors()2.97M
) {
18368
2.97M
    if (RequireCompleteSizedType(Loc, EltTy,
18369
2.97M
                                 diag::err_field_incomplete_or_sizeless)) {
18370
      // Fields of incomplete type force their record to be invalid.
18371
232
      Record->setInvalidDecl();
18372
232
      InvalidDecl = true;
18373
2.97M
    } else {
18374
2.97M
      NamedDecl *Def;
18375
2.97M
      EltTy->isIncompleteType(&Def);
18376
2.97M
      if (Def && 
Def->isInvalidDecl()855k
) {
18377
16
        Record->setInvalidDecl();
18378
16
        InvalidDecl = true;
18379
16
      }
18380
2.97M
    }
18381
2.97M
  }
18382
18383
  // TR 18037 does not allow fields to be declared with address space
18384
3.07M
  if (T.hasAddressSpace() || 
T->isDependentAddressSpaceType()3.07M
||
18385
3.07M
      
T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()3.07M
) {
18386
8
    Diag(Loc, diag::err_field_with_address_space);
18387
8
    Record->setInvalidDecl();
18388
8
    InvalidDecl = true;
18389
8
  }
18390
18391
3.07M
  if (LangOpts.OpenCL) {
18392
    // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18393
    // used as structure or union field: image, sampler, event or block types.
18394
848
    if (T->isEventT() || 
T->isImageType()847
||
T->isSamplerT()845
||
18395
848
        
T->isBlockPointerType()839
) {
18396
11
      Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18397
11
      Record->setInvalidDecl();
18398
11
      InvalidDecl = true;
18399
11
    }
18400
    // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18401
    // is enabled.
18402
848
    if (BitWidth && !getOpenCLOptions().isAvailableOption(
18403
2
                        "__cl_clang_bitfields", LangOpts)) {
18404
1
      Diag(Loc, diag::err_opencl_bitfields);
18405
1
      InvalidDecl = true;
18406
1
    }
18407
848
  }
18408
18409
  // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18410
3.07M
  if (!InvalidDecl && 
getLangOpts().CPlusPlus3.07M
&&
!II1.25M
&&
BitWidth5.80k
&&
18411
3.07M
      
T.hasQualifiers()2.59k
) {
18412
13
    InvalidDecl = true;
18413
13
    Diag(Loc, diag::err_anon_bitfield_qualifiers);
18414
13
  }
18415
18416
  // C99 6.7.2.1p8: A member of a structure or union may have any type other
18417
  // than a variably modified type.
18418
3.07M
  if (!InvalidDecl && 
T->isVariablyModifiedType()3.07M
) {
18419
254
    if (!tryToFixVariablyModifiedVarType(
18420
254
            TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18421
49
      InvalidDecl = true;
18422
254
  }
18423
18424
  // Fields can not have abstract class types
18425
3.07M
  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18426
3.07M
                                             diag::err_abstract_type_in_decl,
18427
3.07M
                                             AbstractFieldType))
18428
2
    InvalidDecl = true;
18429
18430
3.07M
  if (InvalidDecl)
18431
533
    BitWidth = nullptr;
18432
  // If this is declared as a bit-field, check the bit-field.
18433
3.07M
  if (BitWidth) {
18434
71.9k
    BitWidth =
18435
71.9k
        VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18436
71.9k
    if (!BitWidth) {
18437
133
      InvalidDecl = true;
18438
133
      BitWidth = nullptr;
18439
133
    }
18440
71.9k
  }
18441
18442
  // Check that 'mutable' is consistent with the type of the declaration.
18443
3.07M
  if (!InvalidDecl && 
Mutable3.07M
) {
18444
5.54k
    unsigned DiagID = 0;
18445
5.54k
    if (T->isReferenceType())
18446
5
      DiagID = getLangOpts().MSVCCompat ? 
diag::ext_mutable_reference1
18447
5
                                        : 
diag::err_mutable_reference4
;
18448
5.54k
    else if (T.isConstQualified())
18449
9
      DiagID = diag::err_mutable_const;
18450
18451
5.54k
    if (DiagID) {
18452
14
      SourceLocation ErrLoc = Loc;
18453
14
      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18454
14
        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18455
14
      Diag(ErrLoc, DiagID);
18456
14
      if (DiagID != diag::ext_mutable_reference) {
18457
13
        Mutable = false;
18458
13
        InvalidDecl = true;
18459
13
      }
18460
14
    }
18461
5.54k
  }
18462
18463
  // C++11 [class.union]p8 (DR1460):
18464
  //   At most one variant member of a union may have a
18465
  //   brace-or-equal-initializer.
18466
3.07M
  if (InitStyle != ICIS_NoInit)
18467
8.14k
    checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18468
18469
3.07M
  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18470
3.07M
                                       BitWidth, Mutable, InitStyle);
18471
3.07M
  if (InvalidDecl)
18472
679
    NewFD->setInvalidDecl();
18473
18474
3.07M
  if (PrevDecl && 
!isa<TagDecl>(PrevDecl)121
&&
18475
3.07M
      
!PrevDecl->isPlaceholderVar(getLangOpts())22
) {
18476
10
    Diag(Loc, diag::err_duplicate_member) << II;
18477
10
    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18478
10
    NewFD->setInvalidDecl();
18479
10
  }
18480
18481
3.07M
  if (!InvalidDecl && 
getLangOpts().CPlusPlus3.07M
) {
18482
1.25M
    if (Record->isUnion()) {
18483
56.7k
      if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18484
32.6k
        CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18485
32.6k
        if (RDecl->getDefinition()) {
18486
          // C++ [class.union]p1: An object of a class with a non-trivial
18487
          // constructor, a non-trivial copy constructor, a non-trivial
18488
          // destructor, or a non-trivial copy assignment operator
18489
          // cannot be a member of a union, nor can an array of such
18490
          // objects.
18491
32.6k
          if (CheckNontrivialField(NewFD))
18492
31
            NewFD->setInvalidDecl();
18493
32.6k
        }
18494
32.6k
      }
18495
18496
      // C++ [class.union]p1: If a union contains a member of reference type,
18497
      // the program is ill-formed, except when compiling with MSVC extensions
18498
      // enabled.
18499
56.7k
      if (EltTy->isReferenceType()) {
18500
6
        Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18501
4
                                    diag::ext_union_member_of_reference_type :
18502
6
                                    
diag::err_union_member_of_reference_type2
)
18503
6
          << NewFD->getDeclName() << EltTy;
18504
6
        if (!getLangOpts().MicrosoftExt)
18505
2
          NewFD->setInvalidDecl();
18506
6
      }
18507
56.7k
    }
18508
1.25M
  }
18509
18510
  // FIXME: We need to pass in the attributes given an AST
18511
  // representation, not a parser representation.
18512
3.07M
  if (D) {
18513
    // FIXME: The current scope is almost... but not entirely... correct here.
18514
2.95M
    ProcessDeclAttributes(getCurScope(), NewFD, *D);
18515
18516
2.95M
    if (NewFD->hasAttrs())
18517
4.40k
      CheckAlignasUnderalignment(NewFD);
18518
2.95M
  }
18519
18520
  // In auto-retain/release, infer strong retension for fields of
18521
  // retainable type.
18522
3.07M
  if (getLangOpts().ObjCAutoRefCount && 
inferObjCARCLifetime(NewFD)42.4k
)
18523
0
    NewFD->setInvalidDecl();
18524
18525
3.07M
  if (T.isObjCGCWeak())
18526
8
    Diag(Loc, diag::warn_attribute_weak_on_field);
18527
18528
  // PPC MMA non-pointer types are not allowed as field types.
18529
3.07M
  if (Context.getTargetInfo().getTriple().isPPC64() &&
18530
3.07M
      
CheckPPCMMAType(T, NewFD->getLocation())7.41k
)
18531
16
    NewFD->setInvalidDecl();
18532
18533
3.07M
  NewFD->setAccess(AS);
18534
3.07M
  return NewFD;
18535
3.07M
}
18536
18537
38.3k
bool Sema::CheckNontrivialField(FieldDecl *FD) {
18538
38.3k
  assert(FD);
18539
38.3k
  assert(getLangOpts().CPlusPlus && "valid check only for C++");
18540
18541
38.3k
  if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18542
6.97k
    return false;
18543
18544
31.3k
  QualType EltTy = Context.getBaseElementType(FD->getType());
18545
31.3k
  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18546
29.1k
    CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18547
29.1k
    if (RDecl->getDefinition()) {
18548
      // We check for copy constructors before constructors
18549
      // because otherwise we'll never get complaints about
18550
      // copy constructors.
18551
18552
29.1k
      CXXSpecialMember member = CXXInvalid;
18553
      // We're required to check for any non-trivial constructors. Since the
18554
      // implicit default constructor is suppressed if there are any
18555
      // user-declared constructors, we just need to check that there is a
18556
      // trivial default constructor and a trivial copy constructor. (We don't
18557
      // worry about move constructors here, since this is a C++98 check.)
18558
29.1k
      if (RDecl->hasNonTrivialCopyConstructor())
18559
89
        member = CXXCopyConstructor;
18560
29.1k
      else if (!RDecl->hasTrivialDefaultConstructor())
18561
1.36k
        member = CXXDefaultConstructor;
18562
27.7k
      else if (RDecl->hasNonTrivialCopyAssignment())
18563
12
        member = CXXCopyAssignment;
18564
27.7k
      else if (RDecl->hasNonTrivialDestructor())
18565
25
        member = CXXDestructor;
18566
18567
29.1k
      if (member != CXXInvalid) {
18568
1.48k
        if (!getLangOpts().CPlusPlus11 &&
18569
1.48k
            
getLangOpts().ObjCAutoRefCount33
&&
RDecl->hasObjectMember()1
) {
18570
          // Objective-C++ ARC: it is an error to have a non-trivial field of
18571
          // a union. However, system headers in Objective-C programs
18572
          // occasionally have Objective-C lifetime objects within unions,
18573
          // and rather than cause the program to fail, we make those
18574
          // members unavailable.
18575
1
          SourceLocation Loc = FD->getLocation();
18576
1
          if (getSourceManager().isInSystemHeader(Loc)) {
18577
1
            if (!FD->hasAttr<UnavailableAttr>())
18578
1
              FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18579
1
                            UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18580
1
            return false;
18581
1
          }
18582
1
        }
18583
18584
1.48k
        Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
18585
1.45k
               diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18586
1.48k
               
diag::err_illegal_union_or_anon_struct_member32
)
18587
1.48k
          << FD->getParent()->isUnion() << FD->getDeclName() << member;
18588
1.48k
        DiagnoseNontrivial(RDecl, member);
18589
1.48k
        return !getLangOpts().CPlusPlus11;
18590
1.48k
      }
18591
29.1k
    }
18592
29.1k
  }
18593
18594
29.8k
  return false;
18595
31.3k
}
18596
18597
/// TranslateIvarVisibility - Translate visibility from a token ID to an
18598
///  AST enum value.
18599
static ObjCIvarDecl::AccessControl
18600
120k
TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
18601
120k
  switch (ivarVisibility) {
18602
0
  default: llvm_unreachable("Unknown visitibility kind");
18603
101k
  case tok::objc_private: return ObjCIvarDecl::Private;
18604
514
  case tok::objc_public: return ObjCIvarDecl::Public;
18605
16.2k
  case tok::objc_protected: return ObjCIvarDecl::Protected;
18606
2.43k
  case tok::objc_package: return ObjCIvarDecl::Package;
18607
120k
  }
18608
120k
}
18609
18610
/// ActOnIvar - Each ivar field of an objective-c class is passed into this
18611
/// in order to create an IvarDecl object for it.
18612
Decl *Sema::ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D,
18613
120k
                      Expr *BitWidth, tok::ObjCKeywordKind Visibility) {
18614
18615
120k
  IdentifierInfo *II = D.getIdentifier();
18616
120k
  SourceLocation Loc = DeclStart;
18617
120k
  if (II) 
Loc = D.getIdentifierLoc()120k
;
18618
18619
  // FIXME: Unnamed fields can be handled in various different ways, for
18620
  // example, unnamed unions inject all members into the struct namespace!
18621
18622
120k
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18623
120k
  QualType T = TInfo->getType();
18624
18625
120k
  if (BitWidth) {
18626
    // 6.7.2.1p3, 6.7.2.1p4
18627
5.47k
    BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18628
5.47k
    if (!BitWidth)
18629
5
      D.setInvalidType();
18630
115k
  } else {
18631
    // Not a bitfield.
18632
18633
    // validate II.
18634
18635
115k
  }
18636
120k
  if (T->isReferenceType()) {
18637
1
    Diag(Loc, diag::err_ivar_reference_type);
18638
1
    D.setInvalidType();
18639
1
  }
18640
  // C99 6.7.2.1p8: A member of a structure or union may have any type other
18641
  // than a variably modified type.
18642
120k
  else if (T->isVariablyModifiedType()) {
18643
3
    if (!tryToFixVariablyModifiedVarType(
18644
3
            TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18645
2
      D.setInvalidType();
18646
3
  }
18647
18648
  // Get the visibility (access control) for this ivar.
18649
120k
  ObjCIvarDecl::AccessControl ac =
18650
120k
    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18651
120k
                                        : 
ObjCIvarDecl::None0
;
18652
  // Must set ivar's DeclContext to its enclosing interface.
18653
120k
  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
18654
120k
  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18655
1
    return nullptr;
18656
120k
  ObjCContainerDecl *EnclosingContext;
18657
120k
  if (ObjCImplementationDecl *IMPDecl =
18658
120k
      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18659
301
    if (LangOpts.ObjCRuntime.isFragile()) {
18660
    // Case of ivar declared in an implementation. Context is that of its class.
18661
18
      EnclosingContext = IMPDecl->getClassInterface();
18662
18
      assert(EnclosingContext && "Implementation has no class interface!");
18663
18
    }
18664
283
    else
18665
283
      EnclosingContext = EnclosingDecl;
18666
120k
  } else {
18667
120k
    if (ObjCCategoryDecl *CDecl =
18668
120k
        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18669
227
      if (LangOpts.ObjCRuntime.isFragile() || 
!CDecl->IsClassExtension()225
) {
18670
4
        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18671
4
        return nullptr;
18672
4
      }
18673
227
    }
18674
120k
    EnclosingContext = EnclosingDecl;
18675
120k
  }
18676
18677
  // Construct the decl.
18678
120k
  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(
18679
120k
      Context, EnclosingContext, DeclStart, Loc, II, T, TInfo, ac, BitWidth);
18680
18681
120k
  if (T->containsErrors())
18682
1
    NewID->setInvalidDecl();
18683
18684
120k
  if (II) {
18685
120k
    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18686
120k
                                           ForVisibleRedeclaration);
18687
120k
    if (PrevDecl && 
isDeclInScope(PrevDecl, EnclosingContext, S)2
18688
120k
        && 
!isa<TagDecl>(PrevDecl)2
) {
18689
2
      Diag(Loc, diag::err_duplicate_member) << II;
18690
2
      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18691
2
      NewID->setInvalidDecl();
18692
2
    }
18693
120k
  }
18694
18695
  // Process attributes attached to the ivar.
18696
120k
  ProcessDeclAttributes(S, NewID, D);
18697
18698
120k
  if (D.isInvalidType())
18699
11
    NewID->setInvalidDecl();
18700
18701
  // In ARC, infer 'retaining' for ivars of retainable type.
18702
120k
  if (getLangOpts().ObjCAutoRefCount && 
inferObjCARCLifetime(NewID)2.63k
)
18703
0
    NewID->setInvalidDecl();
18704
18705
120k
  if (D.getDeclSpec().isModulePrivateSpecified())
18706
0
    NewID->setModulePrivate();
18707
18708
120k
  if (II) {
18709
    // FIXME: When interfaces are DeclContexts, we'll need to add
18710
    // these to the interface.
18711
120k
    S->AddDecl(NewID);
18712
120k
    IdResolver.AddDecl(NewID);
18713
120k
  }
18714
18715
120k
  if (LangOpts.ObjCRuntime.isNonFragile() &&
18716
120k
      
!NewID->isInvalidDecl()120k
&&
isa<ObjCInterfaceDecl>(EnclosingDecl)120k
)
18717
120k
    Diag(Loc, diag::warn_ivars_in_interface);
18718
18719
120k
  return NewID;
18720
120k
}
18721
18722
/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18723
/// class and class extensions. For every class \@interface and class
18724
/// extension \@interface, if the last ivar is a bitfield of any type,
18725
/// then add an implicit `char :0` ivar to the end of that interface.
18726
void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18727
34.8k
                             SmallVectorImpl<Decl *> &AllIvarDecls) {
18728
34.8k
  if (LangOpts.ObjCRuntime.isFragile() || 
AllIvarDecls.empty()34.6k
)
18729
3.60k
    return;
18730
18731
31.2k
  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18732
31.2k
  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18733
18734
31.2k
  if (!Ivar->isBitField() || 
Ivar->isZeroLengthBitField(Context)63
)
18735
31.1k
    return;
18736
59
  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18737
59
  if (!ID) {
18738
22
    if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18739
17
      if (!CD->IsClassExtension())
18740
0
        return;
18741
17
    }
18742
    // No need to add this to end of @implementation.
18743
5
    else
18744
5
      return;
18745
22
  }
18746
  // All conditions are met. Add a new bitfield to the tail end of ivars.
18747
54
  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18748
54
  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18749
18750
54
  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18751
54
                              DeclLoc, DeclLoc, nullptr,
18752
54
                              Context.CharTy,
18753
54
                              Context.getTrivialTypeSourceInfo(Context.CharTy,
18754
54
                                                               DeclLoc),
18755
54
                              ObjCIvarDecl::Private, BW,
18756
54
                              true);
18757
54
  AllIvarDecls.push_back(Ivar);
18758
54
}
18759
18760
/// [class.dtor]p4:
18761
///   At the end of the definition of a class, overload resolution is
18762
///   performed among the prospective destructors declared in that class with
18763
///   an empty argument list to select the destructor for the class, also
18764
///   known as the selected destructor.
18765
///
18766
/// We do the overload resolution here, then mark the selected constructor in the AST.
18767
/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18768
961k
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18769
961k
  if (!Record->hasUserDeclaredDestructor()) {
18770
895k
    return;
18771
895k
  }
18772
18773
66.2k
  SourceLocation Loc = Record->getLocation();
18774
66.2k
  OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18775
18776
1.50M
  for (auto *Decl : Record->decls()) {
18777
1.50M
    if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18778
66.3k
      if (DD->isInvalidDecl())
18779
32
        continue;
18780
66.3k
      S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18781
66.3k
                             OCS);
18782
66.3k
      assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18783
66.3k
    }
18784
1.50M
  }
18785
18786
66.2k
  if (OCS.empty()) {
18787
18
    return;
18788
18
  }
18789
66.2k
  OverloadCandidateSet::iterator Best;
18790
66.2k
  unsigned Msg = 0;
18791
66.2k
  OverloadCandidateDisplayKind DisplayKind;
18792
18793
66.2k
  switch (OCS.BestViableFunction(S, Loc, Best)) {
18794
65.5k
  case OR_Success:
18795
66.2k
  case OR_Deleted:
18796
66.2k
    Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18797
66.2k
    break;
18798
18799
3
  case OR_Ambiguous:
18800
3
    Msg = diag::err_ambiguous_destructor;
18801
3
    DisplayKind = OCD_AmbiguousCandidates;
18802
3
    break;
18803
18804
1
  case OR_No_Viable_Function:
18805
1
    Msg = diag::err_no_viable_destructor;
18806
1
    DisplayKind = OCD_AllCandidates;
18807
1
    break;
18808
66.2k
  }
18809
18810
66.2k
  if (Msg) {
18811
    // OpenCL have got their own thing going with destructors. It's slightly broken,
18812
    // but we allow it.
18813
4
    if (!S.LangOpts.OpenCL) {
18814
2
      PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18815
2
      OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18816
2
      Record->setInvalidDecl();
18817
2
    }
18818
    // It's a bit hacky: At this point we've raised an error but we want the
18819
    // rest of the compiler to continue somehow working. However almost
18820
    // everything we'll try to do with the class will depend on there being a
18821
    // destructor. So let's pretend the first one is selected and hope for the
18822
    // best.
18823
4
    Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18824
4
  }
18825
66.2k
}
18826
18827
/// [class.mem.special]p5
18828
/// Two special member functions are of the same kind if:
18829
/// - they are both default constructors,
18830
/// - they are both copy or move constructors with the same first parameter
18831
///   type, or
18832
/// - they are both copy or move assignment operators with the same first
18833
///   parameter type and the same cv-qualifiers and ref-qualifier, if any.
18834
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
18835
                                              CXXMethodDecl *M1,
18836
                                              CXXMethodDecl *M2,
18837
11.5k
                                              Sema::CXXSpecialMember CSM) {
18838
  // We don't want to compare templates to non-templates: See
18839
  // https://github.com/llvm/llvm-project/issues/59206
18840
11.5k
  if (CSM == Sema::CXXDefaultConstructor)
18841
9.48k
    return bool(M1->getDescribedFunctionTemplate()) ==
18842
9.48k
           bool(M2->getDescribedFunctionTemplate());
18843
  // FIXME: better resolve CWG
18844
  // https://cplusplus.github.io/CWG/issues/2787.html
18845
2.08k
  if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18846
2.08k
                           M2->getNonObjectParameter(0)->getType()))
18847
404
    return false;
18848
1.68k
  if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
18849
1.68k
                           M2->getFunctionObjectParameterReferenceType()))
18850
1.57k
    return false;
18851
18852
110
  return true;
18853
1.68k
}
18854
18855
/// [class.mem.special]p6:
18856
/// An eligible special member function is a special member function for which:
18857
/// - the function is not deleted,
18858
/// - the associated constraints, if any, are satisfied, and
18859
/// - no special member function of the same kind whose associated constraints
18860
///   [CWG2595], if any, are satisfied is more constrained.
18861
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18862
                               ArrayRef<CXXMethodDecl *> Methods,
18863
4.80M
                               Sema::CXXSpecialMember CSM) {
18864
4.80M
  SmallVector<bool, 4> SatisfactionStatus;
18865
18866
4.80M
  for (CXXMethodDecl *Method : Methods) {
18867
318k
    const Expr *Constraints = Method->getTrailingRequiresClause();
18868
318k
    if (!Constraints)
18869
318k
      SatisfactionStatus.push_back(true);
18870
221
    else {
18871
221
      ConstraintSatisfaction Satisfaction;
18872
221
      if (S.CheckFunctionConstraints(Method, Satisfaction))
18873
0
        SatisfactionStatus.push_back(false);
18874
221
      else
18875
221
        SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18876
221
    }
18877
318k
  }
18878
18879
5.12M
  for (size_t i = 0; i < Methods.size(); 
i++318k
) {
18880
318k
    if (!SatisfactionStatus[i])
18881
146
      continue;
18882
318k
    CXXMethodDecl *Method = Methods[i];
18883
318k
    CXXMethodDecl *OrigMethod = Method;
18884
318k
    if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18885
102k
      OrigMethod = cast<CXXMethodDecl>(MF);
18886
18887
318k
    const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18888
318k
    bool AnotherMethodIsMoreConstrained = false;
18889
647k
    for (size_t j = 0; j < Methods.size(); 
j++329k
) {
18890
329k
      if (i == j || 
!SatisfactionStatus[j]11.7k
)
18891
318k
        continue;
18892
11.5k
      CXXMethodDecl *OtherMethod = Methods[j];
18893
11.5k
      if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18894
440
        OtherMethod = cast<CXXMethodDecl>(MF);
18895
18896
11.5k
      if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18897
11.5k
                                             CSM))
18898
2.02k
        continue;
18899
18900
9.54k
      const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18901
9.54k
      if (!OtherConstraints)
18902
9.48k
        continue;
18903
60
      if (!Constraints) {
18904
50
        AnotherMethodIsMoreConstrained = true;
18905
50
        break;
18906
50
      }
18907
10
      if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18908
10
                                   {Constraints},
18909
10
                                   AnotherMethodIsMoreConstrained)) {
18910
        // There was an error with the constraints comparison. Exit the loop
18911
        // and don't consider this function eligible.
18912
0
        AnotherMethodIsMoreConstrained = true;
18913
0
      }
18914
10
      if (AnotherMethodIsMoreConstrained)
18915
5
        break;
18916
10
    }
18917
    // FIXME: Do not consider deleted methods as eligible after implementing
18918
    // DR1734 and DR1496.
18919
318k
    if (!AnotherMethodIsMoreConstrained) {
18920
318k
      Method->setIneligibleOrNotSelected(false);
18921
318k
      Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
18922
318k
    }
18923
318k
  }
18924
4.80M
}
18925
18926
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
18927
961k
                                                    CXXRecordDecl *Record) {
18928
961k
  SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18929
961k
  SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18930
961k
  SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18931
961k
  SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18932
961k
  SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18933
18934
5.27M
  for (auto *Decl : Record->decls()) {
18935
5.27M
    auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18936
5.27M
    if (!MD) {
18937
3.67M
      auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18938
3.67M
      if (FTD)
18939
395k
        MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18940
3.67M
    }
18941
5.27M
    if (!MD)
18942
3.27M
      continue;
18943
1.99M
    if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18944
492k
      if (CD->isInvalidDecl())
18945
100
        continue;
18946
492k
      if (CD->isDefaultConstructor())
18947
107k
        DefaultConstructors.push_back(MD);
18948
384k
      else if (CD->isCopyConstructor())
18949
80.1k
        CopyConstructors.push_back(MD);
18950
304k
      else if (CD->isMoveConstructor())
18951
21.3k
        MoveConstructors.push_back(MD);
18952
1.50M
    } else if (MD->isCopyAssignmentOperator()) {
18953
81.8k
      CopyAssignmentOperators.push_back(MD);
18954
1.41M
    } else if (MD->isMoveAssignmentOperator()) {
18955
26.9k
      MoveAssignmentOperators.push_back(MD);
18956
26.9k
    }
18957
1.99M
  }
18958
18959
961k
  SetEligibleMethods(S, Record, DefaultConstructors,
18960
961k
                     Sema::CXXDefaultConstructor);
18961
961k
  SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
18962
961k
  SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
18963
961k
  SetEligibleMethods(S, Record, CopyAssignmentOperators,
18964
961k
                     Sema::CXXCopyAssignment);
18965
961k
  SetEligibleMethods(S, Record, MoveAssignmentOperators,
18966
961k
                     Sema::CXXMoveAssignment);
18967
961k
}
18968
18969
void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18970
                       ArrayRef<Decl *> Fields, SourceLocation LBrac,
18971
                       SourceLocation RBrac,
18972
1.90M
                       const ParsedAttributesView &Attrs) {
18973
1.90M
  assert(EnclosingDecl && "missing record or interface decl");
18974
18975
  // If this is an Objective-C @implementation or category and we have
18976
  // new fields here we should reset the layout of the interface since
18977
  // it will now change.
18978
1.90M
  if (!Fields.empty() && 
isa<ObjCContainerDecl>(EnclosingDecl)776k
) {
18979
31.4k
    ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18980
31.4k
    switch (DC->getKind()) {
18981
31.0k
    default: break;
18982
31.0k
    case Decl::ObjCCategory:
18983
166
      Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18984
166
      break;
18985
221
    case Decl::ObjCImplementation:
18986
221
      Context.
18987
221
        ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18988
221
      break;
18989
31.4k
    }
18990
31.4k
  }
18991
18992
1.90M
  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18993
1.90M
  CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18994
18995
  // Start counting up the number of named members; make sure to include
18996
  // members of anonymous structs and unions in the total.
18997
1.90M
  unsigned NumNamedMembers = 0;
18998
1.90M
  if (Record) {
18999
9.68M
    for (const auto *I : Record->decls()) {
19000
9.68M
      if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19001
13.9k
        if (IFD->getDeclName())
19002
13.9k
          ++NumNamedMembers;
19003
9.68M
    }
19004
1.87M
  }
19005
19006
  // Verify that all the fields are okay.
19007
1.90M
  SmallVector<FieldDecl*, 32> RecFields;
19008
19009
1.90M
  for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19010
5.11M
       i != end; 
++i3.20M
) {
19011
3.20M
    FieldDecl *FD = cast<FieldDecl>(*i);
19012
19013
    // Get the type for the field.
19014
3.20M
    const Type *FDTy = FD->getType().getTypePtr();
19015
19016
3.20M
    if (!FD->isAnonymousStructOrUnion()) {
19017
      // Remember all fields written by the user.
19018
3.20M
      RecFields.push_back(FD);
19019
3.20M
    }
19020
19021
    // If the field is already invalid for some reason, don't emit more
19022
    // diagnostics about it.
19023
3.20M
    if (FD->isInvalidDecl()) {
19024
858
      EnclosingDecl->setInvalidDecl();
19025
858
      continue;
19026
858
    }
19027
19028
    // C99 6.7.2.1p2:
19029
    //   A structure or union shall not contain a member with
19030
    //   incomplete or function type (hence, a structure shall not
19031
    //   contain an instance of itself, but may contain a pointer to
19032
    //   an instance of itself), except that the last member of a
19033
    //   structure with more than one named member may have incomplete
19034
    //   array type; such a structure (and any union containing,
19035
    //   possibly recursively, a member that is such a structure)
19036
    //   shall not be a member of a structure or an element of an
19037
    //   array.
19038
3.20M
    bool IsLastField = (i + 1 == Fields.end());
19039
3.20M
    if (FDTy->isFunctionType()) {
19040
      // Field declared as a function.
19041
11
      Diag(FD->getLocation(), diag::err_field_declared_as_function)
19042
11
        << FD->getDeclName();
19043
11
      FD->setInvalidDecl();
19044
11
      EnclosingDecl->setInvalidDecl();
19045
11
      continue;
19046
3.20M
    } else if (FDTy->isIncompleteArrayType() &&
19047
3.20M
               
(1.17k
Record1.17k
||
isa<ObjCContainerDecl>(EnclosingDecl)31
)) {
19048
1.17k
      if (Record) {
19049
        // Flexible array member.
19050
        // Microsoft and g++ is more permissive regarding flexible array.
19051
        // It will accept flexible array in union and also
19052
        // as the sole element of a struct/class.
19053
1.14k
        unsigned DiagID = 0;
19054
1.14k
        if (!Record->isUnion() && 
!IsLastField1.11k
) {
19055
1
          Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19056
1
              << FD->getDeclName() << FD->getType()
19057
1
              << llvm::to_underlying(Record->getTagKind());
19058
1
          Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19059
1
          FD->setInvalidDecl();
19060
1
          EnclosingDecl->setInvalidDecl();
19061
1
          continue;
19062
1.14k
        } else if (Record->isUnion())
19063
30
          DiagID = getLangOpts().MicrosoftExt
19064
30
                       ? 
diag::ext_flexible_array_union_ms4
19065
30
                       : 
getLangOpts().CPlusPlus26
19066
26
                             ? 
diag::ext_flexible_array_union_gnu22
19067
26
                             : 
diag::err_flexible_array_union4
;
19068
1.11k
        else if (NumNamedMembers < 1)
19069
49
          DiagID = getLangOpts().MicrosoftExt
19070
49
                       ? 
diag::ext_flexible_array_empty_aggregate_ms2
19071
49
                       : 
getLangOpts().CPlusPlus47
19072
47
                             ? 
diag::ext_flexible_array_empty_aggregate_gnu42
19073
47
                             : 
diag::err_flexible_array_empty_aggregate5
;
19074
19075
1.14k
        if (DiagID)
19076
79
          Diag(FD->getLocation(), DiagID)
19077
79
              << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19078
        // While the layout of types that contain virtual bases is not specified
19079
        // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19080
        // virtual bases after the derived members.  This would make a flexible
19081
        // array member declared at the end of an object not adjacent to the end
19082
        // of the type.
19083
1.14k
        if (CXXRecord && 
CXXRecord->getNumVBases() != 0171
)
19084
1
          Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19085
1
              << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19086
1.14k
        if (!getLangOpts().C99)
19087
177
          Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19088
177
              << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19089
19090
        // If the element type has a non-trivial destructor, we would not
19091
        // implicitly destroy the elements, so disallow it for now.
19092
        //
19093
        // FIXME: GCC allows this. We should probably either implicitly delete
19094
        // the destructor of the containing class, or just allow this.
19095
1.14k
        QualType BaseElem = Context.getBaseElementType(FD->getType());
19096
1.14k
        if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19097
2
          Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19098
2
            << FD->getDeclName() << FD->getType();
19099
2
          FD->setInvalidDecl();
19100
2
          EnclosingDecl->setInvalidDecl();
19101
2
          continue;
19102
2
        }
19103
        // Okay, we have a legal flexible array member at the end of the struct.
19104
1.14k
        Record->setHasFlexibleArrayMember(true);
19105
1.14k
      } else {
19106
        // In ObjCContainerDecl ivars with incomplete array type are accepted,
19107
        // unless they are followed by another ivar. That check is done
19108
        // elsewhere, after synthesized ivars are known.
19109
31
      }
19110
3.20M
    } else if (!FDTy->isDependentType() &&
19111
3.20M
               RequireCompleteSizedType(
19112
3.09M
                   FD->getLocation(), FD->getType(),
19113
3.09M
                   diag::err_field_incomplete_or_sizeless)) {
19114
      // Incomplete type
19115
3
      FD->setInvalidDecl();
19116
3
      EnclosingDecl->setInvalidDecl();
19117
3
      continue;
19118
3.20M
    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19119
837k
      if (Record && 
FDTTy->getDecl()->hasFlexibleArrayMember()835k
) {
19120
        // A type which contains a flexible array member is considered to be a
19121
        // flexible array member.
19122
73
        Record->setHasFlexibleArrayMember(true);
19123
73
        if (!Record->isUnion()) {
19124
          // If this is a struct/class and this is not the last element, reject
19125
          // it.  Note that GCC supports variable sized arrays in the middle of
19126
          // structures.
19127
61
          if (!IsLastField)
19128
13
            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19129
13
              << FD->getDeclName() << FD->getType();
19130
48
          else {
19131
            // We support flexible arrays at the end of structs in
19132
            // other structs as an extension.
19133
48
            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19134
48
              << FD->getDeclName();
19135
48
          }
19136
61
        }
19137
73
      }
19138
837k
      if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19139
837k
          RequireNonAbstractType(FD->getLocation(), FD->getType(),
19140
2.00k
                                 diag::err_abstract_type_in_decl,
19141
2.00k
                                 AbstractIvarType)) {
19142
        // Ivars can not have abstract class types
19143
1
        FD->setInvalidDecl();
19144
1
      }
19145
837k
      if (Record && 
FDTTy->getDecl()->hasObjectMember()835k
)
19146
34
        Record->setHasObjectMember(true);
19147
837k
      if (Record && 
FDTTy->getDecl()->hasVolatileMember()835k
)
19148
9
        Record->setHasVolatileMember(true);
19149
2.36M
    } else if (FDTy->isObjCObjectType()) {
19150
      /// A field cannot be an Objective-c object
19151
6
      Diag(FD->getLocation(), diag::err_statically_allocated_object)
19152
6
        << FixItHint::CreateInsertion(FD->getLocation(), "*");
19153
6
      QualType T = Context.getObjCObjectPointerType(FD->getType());
19154
6
      FD->setType(T);
19155
2.36M
    } else if (Record && 
Record->isUnion()2.25M
&&
19156
2.36M
               
FD->getType().hasNonTrivialObjCLifetime()47.8k
&&
19157
2.36M
               
getSourceManager().isInSystemHeader(FD->getLocation())21
&&
19158
2.36M
               
!getLangOpts().CPlusPlus8
&&
!FD->hasAttr<UnavailableAttr>()6
&&
19159
2.36M
               
(6
FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong6
||
19160
6
                
!Context.hasDirectOwnershipQualifier(FD->getType())5
)) {
19161
      // For backward compatibility, fields of C unions declared in system
19162
      // headers that have non-trivial ObjC ownership qualifications are marked
19163
      // as unavailable unless the qualifier is explicit and __strong. This can
19164
      // break ABI compatibility between programs compiled with ARC and MRR, but
19165
      // is a better option than rejecting programs using those unions under
19166
      // ARC.
19167
5
      FD->addAttr(UnavailableAttr::CreateImplicit(
19168
5
          Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19169
5
          FD->getLocation()));
19170
2.36M
    } else if (getLangOpts().ObjC &&
19171
2.36M
               
getLangOpts().getGC() != LangOptions::NonGC1.55M
&&
Record343
&&
19172
2.36M
               
!Record->hasObjectMember()211
) {
19173
115
      if (FD->getType()->isObjCObjectPointerType() ||
19174
115
          
FD->getType().isObjCGCStrong()92
)
19175
23
        Record->setHasObjectMember(true);
19176
92
      else if (Context.getAsArrayType(FD->getType())) {
19177
9
        QualType BaseType = Context.getBaseElementType(FD->getType());
19178
9
        if (BaseType->isRecordType() &&
19179
9
            
BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()2
)
19180
1
          Record->setHasObjectMember(true);
19181
8
        else if (BaseType->isObjCObjectPointerType() ||
19182
8
                 
BaseType.isObjCGCStrong()5
)
19183
3
               Record->setHasObjectMember(true);
19184
9
      }
19185
115
    }
19186
19187
3.20M
    if (Record && 
!getLangOpts().CPlusPlus3.08M
&&
19188
3.20M
        
!shouldIgnoreForRecordTriviality(FD)1.82M
) {
19189
1.82M
      QualType FT = FD->getType();
19190
1.82M
      if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19191
89
        Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19192
89
        if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19193
89
            
Record->isUnion()88
)
19194
6
          Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19195
89
      }
19196
1.82M
      QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19197
1.82M
      if (PCK != QualType::PCK_Trivial && 
PCK != QualType::PCK_VolatileTrivial2.47k
) {
19198
89
        Record->setNonTrivialToPrimitiveCopy(true);
19199
89
        if (FT.hasNonTrivialToPrimitiveCopyCUnion() || 
Record->isUnion()88
)
19200
6
          Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19201
89
      }
19202
1.82M
      if (FT.isDestructedType()) {
19203
89
        Record->setNonTrivialToPrimitiveDestroy(true);
19204
89
        Record->setParamDestroyedInCallee(true);
19205
89
        if (FT.hasNonTrivialToPrimitiveDestructCUnion() || 
Record->isUnion()88
)
19206
6
          Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19207
89
      }
19208
19209
1.82M
      if (const auto *RT = FT->getAs<RecordType>()) {
19210
504k
        if (RT->getDecl()->getArgPassingRestrictions() ==
19211
504k
            RecordArgPassingKind::CanNeverPassInRegs)
19212
2
          Record->setArgPassingRestrictions(
19213
2
              RecordArgPassingKind::CanNeverPassInRegs);
19214
1.31M
      } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
19215
10
        Record->setArgPassingRestrictions(
19216
10
            RecordArgPassingKind::CanNeverPassInRegs);
19217
1.82M
    }
19218
19219
3.20M
    if (Record && 
FD->getType().isVolatileQualified()3.08M
)
19220
2.87k
      Record->setHasVolatileMember(true);
19221
    // Keep track of the number of named members.
19222
3.20M
    if (FD->getIdentifier())
19223
3.19M
      ++NumNamedMembers;
19224
3.20M
  }
19225
19226
  // Okay, we successfully defined 'Record'.
19227
1.90M
  if (Record) {
19228
1.87M
    bool Completed = false;
19229
1.87M
    if (CXXRecord) {
19230
1.46M
      if (!CXXRecord->isInvalidDecl()) {
19231
        // Set access bits correctly on the directly-declared conversions.
19232
1.43M
        for (CXXRecordDecl::conversion_iterator
19233
1.43M
               I = CXXRecord->conversion_begin(),
19234
1.47M
               E = CXXRecord->conversion_end(); I != E; 
++I40.5k
)
19235
40.5k
          I.setAccess((*I)->getAccess());
19236
1.43M
      }
19237
19238
      // Add any implicitly-declared members to this class.
19239
1.46M
      AddImplicitlyDeclaredMembersToClass(CXXRecord);
19240
19241
1.46M
      if (!CXXRecord->isDependentType()) {
19242
961k
        if (!CXXRecord->isInvalidDecl()) {
19243
          // If we have virtual base classes, we may end up finding multiple
19244
          // final overriders for a given virtual function. Check for this
19245
          // problem now.
19246
932k
          if (CXXRecord->getNumVBases()) {
19247
4.78k
            CXXFinalOverriderMap FinalOverriders;
19248
4.78k
            CXXRecord->getFinalOverriders(FinalOverriders);
19249
19250
4.78k
            for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19251
4.78k
                                             MEnd = FinalOverriders.end();
19252
16.3k
                 M != MEnd; 
++M11.5k
) {
19253
11.5k
              for (OverridingMethods::iterator SO = M->second.begin(),
19254
11.5k
                                            SOEnd = M->second.end();
19255
23.2k
                   SO != SOEnd; 
++SO11.6k
) {
19256
11.6k
                assert(SO->second.size() > 0 &&
19257
11.6k
                       "Virtual function without overriding functions?");
19258
11.6k
                if (SO->second.size() == 1)
19259
11.6k
                  continue;
19260
19261
                // C++ [class.virtual]p2:
19262
                //   In a derived class, if a virtual member function of a base
19263
                //   class subobject has more than one final overrider the
19264
                //   program is ill-formed.
19265
2
                Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19266
2
                  << (const NamedDecl *)M->first << Record;
19267
2
                Diag(M->first->getLocation(),
19268
2
                     diag::note_overridden_virtual_function);
19269
2
                for (OverridingMethods::overriding_iterator
19270
2
                          OM = SO->second.begin(),
19271
2
                       OMEnd = SO->second.end();
19272
6
                     OM != OMEnd; 
++OM4
)
19273
4
                  Diag(OM->Method->getLocation(), diag::note_final_overrider)
19274
4
                    << (const NamedDecl *)M->first << OM->Method->getParent();
19275
19276
2
                Record->setInvalidDecl();
19277
2
              }
19278
11.5k
            }
19279
4.78k
            CXXRecord->completeDefinition(&FinalOverriders);
19280
4.78k
            Completed = true;
19281
4.78k
          }
19282
932k
        }
19283
961k
        ComputeSelectedDestructor(*this, CXXRecord);
19284
961k
        ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
19285
961k
      }
19286
1.46M
    }
19287
19288
1.87M
    if (!Completed)
19289
1.86M
      Record->completeDefinition();
19290
19291
    // Handle attributes before checking the layout.
19292
1.87M
    ProcessDeclAttributeList(S, Record, Attrs);
19293
19294
    // Check to see if a FieldDecl is a pointer to a function.
19295
1.87M
    auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19296
450k
      const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19297
450k
      if (!FD) {
19298
        // Check whether this is a forward declaration that was inserted by
19299
        // Clang. This happens when a non-forward declared / defined type is
19300
        // used, e.g.:
19301
        //
19302
        //   struct foo {
19303
        //     struct bar *(*f)();
19304
        //     struct bar *(*g)();
19305
        //   };
19306
        //
19307
        // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19308
        // incomplete definition.
19309
2.38k
        if (const auto *TD = dyn_cast<TagDecl>(D))
19310
2.38k
          return !TD->isCompleteDefinition();
19311
1
        return false;
19312
2.38k
      }
19313
448k
      QualType FieldType = FD->getType().getDesugaredType(Context);
19314
448k
      if (isa<PointerType>(FieldType)) {
19315
64.7k
        QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19316
64.7k
        return PointeeType.getDesugaredType(Context)->isFunctionType();
19317
64.7k
      }
19318
383k
      return false;
19319
448k
    };
19320
19321
    // Maybe randomize the record's decls. We automatically randomize a record
19322
    // of function pointers, unless it has the "no_randomize_layout" attribute.
19323
1.87M
    if (!getLangOpts().CPlusPlus &&
19324
1.87M
        
(407k
Record->hasAttr<RandomizeLayoutAttr>()407k
||
19325
407k
         
(407k
!Record->hasAttr<NoRandomizeLayoutAttr>()407k
&&
19326
407k
          
llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl)407k
)) &&
19327
1.87M
        
!Record->isUnion()4.92k
&&
!getLangOpts().RandstructSeed.empty()4.56k
&&
19328
1.87M
        
!Record->isRandomized()22
) {
19329
22
      SmallVector<Decl *, 32> NewDeclOrdering;
19330
22
      if (randstruct::randomizeStructureLayout(Context, Record,
19331
22
                                               NewDeclOrdering))
19332
21
        Record->reorderDecls(NewDeclOrdering);
19333
22
    }
19334
19335
    // We may have deferred checking for a deleted destructor. Check now.
19336
1.87M
    if (CXXRecord) {
19337
1.46M
      auto *Dtor = CXXRecord->getDestructor();
19338
1.46M
      if (Dtor && 
Dtor->isImplicit()78.4k
&&
19339
1.46M
          
ShouldDeleteSpecialMember(Dtor, CXXDestructor)12.1k
) {
19340
840
        CXXRecord->setImplicitDestructorIsDeleted();
19341
840
        SetDeclDeleted(Dtor, CXXRecord->getLocation());
19342
840
      }
19343
1.46M
    }
19344
19345
1.87M
    if (Record->hasAttrs()) {
19346
437k
      CheckAlignasUnderalignment(Record);
19347
19348
437k
      if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19349
78
        checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19350
78
                                           IA->getRange(), IA->getBestCase(),
19351
78
                                           IA->getInheritanceModel());
19352
437k
    }
19353
19354
    // Check if the structure/union declaration is a type that can have zero
19355
    // size in C. For C this is a language extension, for C++ it may cause
19356
    // compatibility problems.
19357
1.87M
    bool CheckForZeroSize;
19358
1.87M
    if (!getLangOpts().CPlusPlus) {
19359
407k
      CheckForZeroSize = true;
19360
1.46M
    } else {
19361
      // For C++ filter out types that cannot be referenced in C code.
19362
1.46M
      CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19363
1.46M
      CheckForZeroSize =
19364
1.46M
          CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19365
1.46M
          
!CXXRecord->isDependentType()48.9k
&&
!inTemplateInstantiation()48.9k
&&
19366
1.46M
          
CXXRecord->isCLike()48.9k
;
19367
1.46M
    }
19368
1.87M
    if (CheckForZeroSize) {
19369
456k
      bool ZeroSize = true;
19370
456k
      bool IsEmpty = true;
19371
456k
      unsigned NonBitFields = 0;
19372
456k
      for (RecordDecl::field_iterator I = Record->field_begin(),
19373
456k
                                      E = Record->field_end();
19374
910k
           (NonBitFields == 0 || 
ZeroSize454k
) &&
I != E456k
;
++I454k
) {
19375
454k
        IsEmpty = false;
19376
454k
        if (I->isUnnamedBitfield()) {
19377
410
          if (!I->isZeroLengthBitField(Context))
19378
263
            ZeroSize = false;
19379
454k
        } else {
19380
454k
          ++NonBitFields;
19381
454k
          QualType FieldType = I->getType();
19382
454k
          if (FieldType->isIncompleteType() ||
19383
454k
              
!Context.getTypeSizeInChars(FieldType).isZero()454k
)
19384
454k
            ZeroSize = false;
19385
454k
        }
19386
454k
      }
19387
19388
      // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19389
      // allowed in C++, but warn if its declaration is inside
19390
      // extern "C" block.
19391
456k
      if (ZeroSize) {
19392
2.03k
        Diag(RecLoc, getLangOpts().CPlusPlus ?
19393
29
                         diag::warn_zero_size_struct_union_in_extern_c :
19394
2.03k
                         
diag::warn_zero_size_struct_union_compat2.00k
)
19395
2.03k
          << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19396
2.03k
      }
19397
19398
      // Structs without named members are extension in C (C99 6.7.2.1p7),
19399
      // but are accepted by GCC.
19400
456k
      if (NonBitFields == 0 && 
!getLangOpts().CPlusPlus1.90k
) {
19401
1.87k
        Diag(RecLoc, IsEmpty ? 
diag::ext_empty_struct_union1.81k
:
19402
1.87k
                               
diag::ext_no_named_members_in_struct_union52
)
19403
1.87k
          << Record->isUnion();
19404
1.87k
      }
19405
456k
    }
19406
1.87M
  } else {
19407
34.8k
    ObjCIvarDecl **ClsFields =
19408
34.8k
      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19409
34.8k
    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19410
34.4k
      ID->setEndOfDefinitionLoc(RBrac);
19411
      // Add ivar's to class's DeclContext.
19412
154k
      for (unsigned i = 0, e = RecFields.size(); i != e; 
++i120k
) {
19413
120k
        ClsFields[i]->setLexicalDeclContext(ID);
19414
120k
        ID->addDecl(ClsFields[i]);
19415
120k
      }
19416
      // Must enforce the rule that ivars in the base classes may not be
19417
      // duplicates.
19418
34.4k
      if (ID->getSuperClass())
19419
32.2k
        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19420
34.4k
    } else 
if (ObjCImplementationDecl *407
IMPDecl407
=
19421
407
                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19422
231
      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19423
532
      
for (unsigned I = 0, N = RecFields.size(); 231
I != N;
++I301
)
19424
        // Ivar declared in @implementation never belongs to the implementation.
19425
        // Only it is in implementation's lexical context.
19426
301
        ClsFields[I]->setLexicalDeclContext(IMPDecl);
19427
231
      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19428
231
      IMPDecl->setIvarLBraceLoc(LBrac);
19429
231
      IMPDecl->setIvarRBraceLoc(RBrac);
19430
231
    } else 
if (ObjCCategoryDecl *176
CDecl176
=
19431
176
                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19432
      // case of ivars in class extension; all other cases have been
19433
      // reported as errors elsewhere.
19434
      // FIXME. Class extension does not have a LocEnd field.
19435
      // CDecl->setLocEnd(RBrac);
19436
      // Add ivar's to class extension's DeclContext.
19437
      // Diagnose redeclaration of private ivars.
19438
176
      ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19439
416
      for (unsigned i = 0, e = RecFields.size(); i != e; 
++i240
) {
19440
240
        if (IDecl) {
19441
240
          if (const ObjCIvarDecl *ClsIvar =
19442
240
              IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19443
3
            Diag(ClsFields[i]->getLocation(),
19444
3
                 diag::err_duplicate_ivar_declaration);
19445
3
            Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19446
3
            continue;
19447
3
          }
19448
288
          
for (const auto *Ext : IDecl->known_extensions())237
{
19449
288
            if (const ObjCIvarDecl *ClsExtIvar
19450
288
                  = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19451
7
              Diag(ClsFields[i]->getLocation(),
19452
7
                   diag::err_duplicate_ivar_declaration);
19453
7
              Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19454
7
              continue;
19455
7
            }
19456
288
          }
19457
237
        }
19458
237
        ClsFields[i]->setLexicalDeclContext(CDecl);
19459
237
        CDecl->addDecl(ClsFields[i]);
19460
237
      }
19461
176
      CDecl->setIvarLBraceLoc(LBrac);
19462
176
      CDecl->setIvarRBraceLoc(RBrac);
19463
176
    }
19464
34.8k
  }
19465
19466
  // Check the "counted_by" attribute to ensure that the count field exists in
19467
  // the struct. Make sure we're performing this check on the outer-most
19468
  // record.  This is a C-only feature.
19469
1.90M
  if (!getLangOpts().CPlusPlus && 
Record438k
&&
19470
1.90M
      
!isa<RecordDecl>(Record->getParent())407k
) {
19471
1.82M
    auto Pred = [](const Decl *D) {
19472
1.82M
      if (const auto *FD = dyn_cast_if_present<FieldDecl>(D))
19473
1.82M
        return FD->hasAttr<CountedByAttr>();
19474
0
      return false;
19475
1.82M
    };
19476
396k
    if (const FieldDecl *FD = Record->findFieldIf(Pred))
19477
14
      CheckCountedByAttr(S, FD);
19478
396k
  }
19479
1.90M
}
19480
19481
/// Determine whether the given integral value is representable within
19482
/// the given type T.
19483
static bool isRepresentableIntegerValue(ASTContext &Context,
19484
                                        llvm::APSInt &Value,
19485
5.65M
                                        QualType T) {
19486
5.65M
  assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19487
5.65M
         "Integral type required!");
19488
5.65M
  unsigned BitWidth = Context.getIntWidth(T);
19489
19490
5.65M
  if (Value.isUnsigned() || 
Value.isNonNegative()5.46M
) {
19491
4.36M
    if (T->isSignedIntegerOrEnumerationType())
19492
3.82M
      --BitWidth;
19493
4.36M
    return Value.getActiveBits() <= BitWidth;
19494
4.36M
  }
19495
1.28M
  return Value.getSignificantBits() <= BitWidth;
19496
5.65M
}
19497
19498
// Given an integral type, return the next larger integral type
19499
// (or a NULL type of no such type exists).
19500
9
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19501
  // FIXME: Int128/UInt128 support, which also needs to be introduced into
19502
  // enum checking below.
19503
9
  assert((T->isIntegralType(Context) ||
19504
9
         T->isEnumeralType()) && "Integral type required!");
19505
9
  const unsigned NumTypes = 4;
19506
9
  QualType SignedIntegralTypes[NumTypes] = {
19507
9
    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19508
9
  };
19509
9
  QualType UnsignedIntegralTypes[NumTypes] = {
19510
9
    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19511
9
    Context.UnsignedLongLongTy
19512
9
  };
19513
19514
9
  unsigned BitWidth = Context.getTypeSize(T);
19515
9
  QualType *Types = T->isSignedIntegerOrEnumerationType()? 
SignedIntegralTypes2
19516
9
                                                        : 
UnsignedIntegralTypes7
;
19517
17
  for (unsigned I = 0; I != NumTypes; 
++I8
)
19518
16
    if (Context.getTypeSize(Types[I]) > BitWidth)
19519
8
      return Types[I];
19520
19521
1
  return QualType();
19522
9
}
19523
19524
EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19525
                                          EnumConstantDecl *LastEnumConst,
19526
                                          SourceLocation IdLoc,
19527
                                          IdentifierInfo *Id,
19528
3.85M
                                          Expr *Val) {
19529
3.85M
  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19530
3.85M
  llvm::APSInt EnumVal(IntWidth);
19531
3.85M
  QualType EltTy;
19532
19533
3.85M
  if (Val && 
DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)3.66M
)
19534
2
    Val = nullptr;
19535
19536
3.85M
  if (Val)
19537
3.66M
    Val = DefaultLvalueConversion(Val).get();
19538
19539
3.85M
  if (Val) {
19540
3.66M
    if (Enum->isDependentType() || 
Val->isTypeDependent()3.66M
||
19541
3.66M
        
Val->containsErrors()3.66M
)
19542
5.39k
      EltTy = Context.DependentTy;
19543
3.66M
    else {
19544
      // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19545
      // underlying type, but do allow it in all other contexts.
19546
3.66M
      if (getLangOpts().CPlusPlus11 && 
Enum->isFixed()523k
) {
19547
        // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19548
        // constant-expression in the enumerator-definition shall be a converted
19549
        // constant expression of the underlying type.
19550
151k
        EltTy = Enum->getIntegerType();
19551
151k
        ExprResult Converted =
19552
151k
          CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19553
151k
                                           CCEK_Enumerator);
19554
151k
        if (Converted.isInvalid())
19555
22
          Val = nullptr;
19556
151k
        else
19557
151k
          Val = Converted.get();
19558
3.50M
      } else if (!Val->isValueDependent() &&
19559
3.50M
                 !(Val =
19560
3.50M
                       VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19561
3.50M
                           .get())) {
19562
        // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19563
3.50M
      } else {
19564
3.50M
        if (Enum->isComplete()) {
19565
795k
          EltTy = Enum->getIntegerType();
19566
19567
          // In Obj-C and Microsoft mode, require the enumeration value to be
19568
          // representable in the underlying type of the enumeration. In C++11,
19569
          // we perform a non-narrowing conversion as part of converted constant
19570
          // expression checking.
19571
795k
          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19572
16
            if (Context.getTargetInfo()
19573
16
                    .getTriple()
19574
16
                    .isWindowsMSVCEnvironment()) {
19575
16
              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19576
16
            } else {
19577
0
              Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19578
0
            }
19579
16
          }
19580
19581
          // Cast to the underlying type.
19582
795k
          Val = ImpCastExprToType(Val, EltTy,
19583
795k
                                  EltTy->isBooleanType() ? 
CK_IntegralToBoolean2
19584
795k
                                                         : 
CK_IntegralCast795k
)
19585
795k
                    .get();
19586
2.71M
        } else if (getLangOpts().CPlusPlus) {
19587
          // C++11 [dcl.enum]p5:
19588
          //   If the underlying type is not fixed, the type of each enumerator
19589
          //   is the type of its initializing value:
19590
          //     - If an initializer is specified for an enumerator, the
19591
          //       initializing value has the same type as the expression.
19592
371k
          EltTy = Val->getType();
19593
2.34M
        } else {
19594
          // C99 6.7.2.2p2:
19595
          //   The expression that defines the value of an enumeration constant
19596
          //   shall be an integer constant expression that has a value
19597
          //   representable as an int.
19598
19599
          // Complain if the value is not representable in an int.
19600
2.34M
          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19601
17.0k
            Diag(IdLoc, diag::ext_enum_value_not_int)
19602
17.0k
              << toString(EnumVal, 10) << Val->getSourceRange()
19603
17.0k
              << (EnumVal.isUnsigned() || 
EnumVal.isNonNegative()5
);
19604
2.32M
          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19605
            // Force the type of the expression to 'int'.
19606
45.5k
            Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19607
45.5k
          }
19608
2.34M
          EltTy = Val->getType();
19609
2.34M
        }
19610
3.50M
      }
19611
3.66M
    }
19612
3.66M
  }
19613
19614
3.85M
  if (!Val) {
19615
185k
    if (Enum->isDependentType())
19616
319
      EltTy = Context.DependentTy;
19617
185k
    else if (!LastEnumConst) {
19618
      // C++0x [dcl.enum]p5:
19619
      //   If the underlying type is not fixed, the type of each enumerator
19620
      //   is the type of its initializing value:
19621
      //     - If no initializer is specified for the first enumerator, the
19622
      //       initializing value has an unspecified integral type.
19623
      //
19624
      // GCC uses 'int' for its unspecified integral type, as does
19625
      // C99 6.7.2.2p3.
19626
20.9k
      if (Enum->isFixed()) {
19627
10.7k
        EltTy = Enum->getIntegerType();
19628
10.7k
      }
19629
10.1k
      else {
19630
10.1k
        EltTy = Context.IntTy;
19631
10.1k
      }
19632
164k
    } else {
19633
      // Assign the last value + 1.
19634
164k
      EnumVal = LastEnumConst->getInitVal();
19635
164k
      ++EnumVal;
19636
164k
      EltTy = LastEnumConst->getType();
19637
19638
      // Check for overflow on increment.
19639
164k
      if (EnumVal < LastEnumConst->getInitVal()) {
19640
        // C++0x [dcl.enum]p5:
19641
        //   If the underlying type is not fixed, the type of each enumerator
19642
        //   is the type of its initializing value:
19643
        //
19644
        //     - Otherwise the type of the initializing value is the same as
19645
        //       the type of the initializing value of the preceding enumerator
19646
        //       unless the incremented value is not representable in that type,
19647
        //       in which case the type is an unspecified integral type
19648
        //       sufficient to contain the incremented value. If no such type
19649
        //       exists, the program is ill-formed.
19650
9
        QualType T = getNextLargerIntegralType(Context, EltTy);
19651
9
        if (T.isNull() || 
Enum->isFixed()8
) {
19652
          // There is no integral type larger enough to represent this
19653
          // value. Complain, then allow the value to wrap around.
19654
9
          EnumVal = LastEnumConst->getInitVal();
19655
9
          EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19656
9
          ++EnumVal;
19657
9
          if (Enum->isFixed())
19658
            // When the underlying type is fixed, this is ill-formed.
19659
8
            Diag(IdLoc, diag::err_enumerator_wrapped)
19660
8
              << toString(EnumVal, 10)
19661
8
              << EltTy;
19662
1
          else
19663
1
            Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19664
1
              << toString(EnumVal, 10);
19665
9
        } else {
19666
0
          EltTy = T;
19667
0
        }
19668
19669
        // Retrieve the last enumerator's value, extent that type to the
19670
        // type that is supposed to be large enough to represent the incremented
19671
        // value, then increment.
19672
9
        EnumVal = LastEnumConst->getInitVal();
19673
9
        EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19674
9
        EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19675
9
        ++EnumVal;
19676
19677
        // If we're not in C++, diagnose the overflow of enumerator values,
19678
        // which in C99 means that the enumerator value is not representable in
19679
        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19680
        // permits enumerator values that are representable in some larger
19681
        // integral type.
19682
9
        if (!getLangOpts().CPlusPlus && 
!T.isNull()0
)
19683
0
          Diag(IdLoc, diag::warn_enum_value_overflow);
19684
164k
      } else if (!getLangOpts().CPlusPlus &&
19685
164k
                 
!EltTy->isDependentType()126k
&&
19686
164k
                 
!isRepresentableIntegerValue(Context, EnumVal, EltTy)126k
) {
19687
        // Enforce C99 6.7.2.2p2 even when we compute the next value.
19688
0
        Diag(IdLoc, diag::ext_enum_value_not_int)
19689
0
          << toString(EnumVal, 10) << 1;
19690
0
      }
19691
164k
    }
19692
185k
  }
19693
19694
3.85M
  if (!EltTy->isDependentType()) {
19695
    // Make the enumerator value match the signedness and size of the
19696
    // enumerator's type.
19697
3.84M
    EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19698
3.84M
    EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19699
3.84M
  }
19700
19701
3.85M
  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19702
3.85M
                                  Val, EnumVal);
19703
3.85M
}
19704
19705
Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19706
379k
                                                SourceLocation IILoc) {
19707
379k
  if (!(getLangOpts().Modules || 
getLangOpts().ModulesLocalVisibility372k
) ||
19708
379k
      
!getLangOpts().CPlusPlus7.00k
)
19709
374k
    return SkipBodyInfo();
19710
19711
  // We have an anonymous enum definition. Look up the first enumerator to
19712
  // determine if we should merge the definition with an existing one and
19713
  // skip the body.
19714
4.87k
  NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19715
4.87k
                                         forRedeclarationInCurContext());
19716
4.87k
  auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19717
4.87k
  if (!PrevECD)
19718
4.86k
    return SkipBodyInfo();
19719
19720
12
  EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19721
12
  NamedDecl *Hidden;
19722
12
  if (!PrevED->getDeclName() && 
!hasVisibleDefinition(PrevED, &Hidden)11
) {
19723
5
    SkipBodyInfo Skip;
19724
5
    Skip.Previous = Hidden;
19725
5
    return Skip;
19726
5
  }
19727
19728
7
  return SkipBodyInfo();
19729
12
}
19730
19731
Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19732
                              SourceLocation IdLoc, IdentifierInfo *Id,
19733
                              const ParsedAttributesView &Attrs,
19734
3.84M
                              SourceLocation EqualLoc, Expr *Val) {
19735
3.84M
  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19736
3.84M
  EnumConstantDecl *LastEnumConst =
19737
3.84M
    cast_or_null<EnumConstantDecl>(lastEnumConst);
19738
19739
  // The scope passed in may not be a decl scope.  Zip up the scope tree until
19740
  // we find one that is.
19741
3.84M
  S = getNonFieldDeclScope(S);
19742
19743
  // Verify that there isn't already something declared with this name in this
19744
  // scope.
19745
3.84M
  LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
19746
3.84M
  LookupName(R, S);
19747
3.84M
  NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19748
19749
3.84M
  if (PrevDecl && 
PrevDecl->isTemplateParameter()159
) {
19750
    // Maybe we will complain about the shadowed template parameter.
19751
2
    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19752
    // Just pretend that we didn't see the previous declaration.
19753
2
    PrevDecl = nullptr;
19754
2
  }
19755
19756
  // C++ [class.mem]p15:
19757
  // If T is the name of a class, then each of the following shall have a name
19758
  // different from T:
19759
  // - every enumerator of every member of class T that is an unscoped
19760
  // enumerated type
19761
3.84M
  if (getLangOpts().CPlusPlus && 
!TheEnumDecl->isScoped()571k
)
19762
534k
    DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19763
534k
                            DeclarationNameInfo(Id, IdLoc));
19764
19765
3.84M
  EnumConstantDecl *New =
19766
3.84M
    CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19767
3.84M
  if (!New)
19768
0
    return nullptr;
19769
19770
3.84M
  if (PrevDecl) {
19771
157
    if (!TheEnumDecl->isScoped() && 
isa<ValueDecl>(PrevDecl)82
) {
19772
      // Check for other kinds of shadowing not already handled.
19773
62
      CheckShadow(New, PrevDecl, R);
19774
62
    }
19775
19776
    // When in C++, we may get a TagDecl with the same name; in this case the
19777
    // enum constant will 'hide' the tag.
19778
157
    assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19779
157
           "Received TagDecl when not in C++!");
19780
157
    if (!isa<TagDecl>(PrevDecl) && 
isDeclInScope(PrevDecl, CurContext, S)131
) {
19781
11
      if (isa<EnumConstantDecl>(PrevDecl))
19782
9
        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19783
2
      else
19784
2
        Diag(IdLoc, diag::err_redefinition) << Id;
19785
11
      notePreviousDefinition(PrevDecl, IdLoc);
19786
11
      return nullptr;
19787
11
    }
19788
157
  }
19789
19790
  // Process attributes.
19791
3.84M
  ProcessDeclAttributeList(S, New, Attrs);
19792
3.84M
  AddPragmaAttributes(S, New);
19793
19794
  // Register this decl in the current scope stack.
19795
3.84M
  New->setAccess(TheEnumDecl->getAccess());
19796
3.84M
  PushOnScopeChains(New, S);
19797
19798
3.84M
  ActOnDocumentableDecl(New);
19799
19800
3.84M
  return New;
19801
3.84M
}
19802
19803
// Returns true when the enum initial expression does not trigger the
19804
// duplicate enum warning.  A few common cases are exempted as follows:
19805
// Element2 = Element1
19806
// Element2 = Element1 + 1
19807
// Element2 = Element1 - 1
19808
// Where Element2 and Element1 are from the same enum.
19809
78
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
19810
78
  Expr *InitExpr = ECD->getInitExpr();
19811
78
  if (!InitExpr)
19812
53
    return true;
19813
25
  InitExpr = InitExpr->IgnoreImpCasts();
19814
19815
25
  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19816
4
    if (!BO->isAdditiveOp())
19817
0
      return true;
19818
4
    IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19819
4
    if (!IL)
19820
0
      return true;
19821
4
    if (IL->getValue() != 1)
19822
0
      return true;
19823
19824
4
    InitExpr = BO->getLHS();
19825
4
  }
19826
19827
  // This checks if the elements are from the same enum.
19828
25
  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19829
25
  if (!DRE)
19830
13
    return true;
19831
19832
12
  EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19833
12
  if (!EnumConstant)
19834
0
    return true;
19835
19836
12
  if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19837
12
      Enum)
19838
0
    return true;
19839
19840
12
  return false;
19841
12
}
19842
19843
// Emits a warning when an element is implicitly set a value that
19844
// a previous element has already been set to.
19845
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
19846
473k
                                        EnumDecl *Enum, QualType EnumType) {
19847
  // Avoid anonymous enums
19848
473k
  if (!Enum->getIdentifier())
19849
380k
    return;
19850
19851
  // Only check for small enums.
19852
93.3k
  if (Enum->getNumPositiveBits() > 63 || 
Enum->getNumNegativeBits() > 6493.0k
)
19853
355
    return;
19854
19855
93.0k
  if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19856
92.9k
    return;
19857
19858
37
  typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19859
37
  typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19860
19861
37
  typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19862
19863
  // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19864
37
  typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19865
19866
  // Use int64_t as a key to avoid needing special handling for map keys.
19867
119
  auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19868
119
    llvm::APSInt Val = D->getInitVal();
19869
119
    return Val.isSigned() ? 
Val.getSExtValue()98
:
Val.getZExtValue()21
;
19870
119
  };
19871
19872
37
  DuplicatesVector DupVector;
19873
37
  ValueToVectorMap EnumMap;
19874
19875
  // Populate the EnumMap with all values represented by enum constants without
19876
  // an initializer.
19877
80
  for (auto *Element : Elements) {
19878
80
    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19879
19880
    // Null EnumConstantDecl means a previous diagnostic has been emitted for
19881
    // this constant.  Skip this enum since it may be ill-formed.
19882
80
    if (!ECD) {
19883
2
      return;
19884
2
    }
19885
19886
    // Constants with initializers are handled in the next loop.
19887
78
    if (ECD->getInitExpr())
19888
25
      continue;
19889
19890
    // Duplicate values are handled in the next loop.
19891
53
    EnumMap.insert({EnumConstantToKey(ECD), ECD});
19892
53
  }
19893
19894
35
  if (EnumMap.size() == 0)
19895
2
    return;
19896
19897
  // Create vectors for any values that has duplicates.
19898
78
  
for (auto *Element : Elements)33
{
19899
    // The last loop returned if any constant was null.
19900
78
    EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19901
78
    if (!ValidDuplicateEnum(ECD, Enum))
19902
12
      continue;
19903
19904
66
    auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19905
66
    if (Iter == EnumMap.end())
19906
7
      continue;
19907
19908
59
    DeclOrVector& Entry = Iter->second;
19909
59
    if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19910
      // Ensure constants are different.
19911
55
      if (D == ECD)
19912
45
        continue;
19913
19914
      // Create new vector and push values onto it.
19915
10
      auto Vec = std::make_unique<ECDVector>();
19916
10
      Vec->push_back(D);
19917
10
      Vec->push_back(ECD);
19918
19919
      // Update entry to point to the duplicates vector.
19920
10
      Entry = Vec.get();
19921
19922
      // Store the vector somewhere we can consult later for quick emission of
19923
      // diagnostics.
19924
10
      DupVector.emplace_back(std::move(Vec));
19925
10
      continue;
19926
55
    }
19927
19928
4
    ECDVector *Vec = Entry.get<ECDVector*>();
19929
    // Make sure constants are not added more than once.
19930
4
    if (*Vec->begin() == ECD)
19931
4
      continue;
19932
19933
0
    Vec->push_back(ECD);
19934
0
  }
19935
19936
  // Emit diagnostics.
19937
33
  for (const auto &Vec : DupVector) {
19938
10
    assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19939
19940
    // Emit warning for one enum constant.
19941
10
    auto *FirstECD = Vec->front();
19942
10
    S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19943
10
      << FirstECD << toString(FirstECD->getInitVal(), 10)
19944
10
      << FirstECD->getSourceRange();
19945
19946
    // Emit one note for each of the remaining enum constants with
19947
    // the same value.
19948
10
    for (auto *ECD : llvm::drop_begin(*Vec))
19949
10
      S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19950
10
        << ECD << toString(ECD->getInitVal(), 10)
19951
10
        << ECD->getSourceRange();
19952
10
  }
19953
33
}
19954
19955
bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19956
61
                             bool AllowMask) const {
19957
61
  assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19958
61
  assert(ED->isCompleteDefinition() && "expected enum definition");
19959
19960
61
  auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19961
61
  llvm::APInt &FlagBits = R.first->second;
19962
19963
61
  if (R.second) {
19964
27
    for (auto *E : ED->enumerators()) {
19965
27
      const auto &EVal = E->getInitVal();
19966
      // Only single-bit enumerators introduce new flag values.
19967
27
      if (EVal.isPowerOf2())
19968
16
        FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19969
27
    }
19970
9
  }
19971
19972
  // A value is in a flag enum if either its bits are a subset of the enum's
19973
  // flag bits (the first condition) or we are allowing masks and the same is
19974
  // true of its complement (the second condition). When masks are allowed, we
19975
  // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19976
  //
19977
  // While it's true that any value could be used as a mask, the assumption is
19978
  // that a mask will have all of the insignificant bits set. Anything else is
19979
  // likely a logic error.
19980
61
  llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19981
61
  return !(FlagMask & Val) || 
(34
AllowMask34
&&
!(FlagMask & ~Val)23
);
19982
61
}
19983
19984
void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
19985
                         Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19986
476k
                         const ParsedAttributesView &Attrs) {
19987
476k
  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19988
476k
  QualType EnumType = Context.getTypeDeclType(Enum);
19989
19990
476k
  ProcessDeclAttributeList(S, Enum, Attrs);
19991
19992
476k
  if (Enum->isDependentType()) {
19993
9.11k
    for (unsigned i = 0, e = Elements.size(); i != e; 
++i5.70k
) {
19994
5.70k
      EnumConstantDecl *ECD =
19995
5.70k
        cast_or_null<EnumConstantDecl>(Elements[i]);
19996
5.70k
      if (!ECD) 
continue0
;
19997
19998
5.70k
      ECD->setType(EnumType);
19999
5.70k
    }
20000
20001
3.41k
    Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20002
3.41k
    return;
20003
3.41k
  }
20004
20005
  // TODO: If the result value doesn't fit in an int, it must be a long or long
20006
  // long value.  ISO C does not support this, but GCC does as an extension,
20007
  // emit a warning.
20008
473k
  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20009
473k
  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20010
473k
  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20011
20012
  // Verify that all the values are okay, compute the size of the values, and
20013
  // reverse the list.
20014
473k
  unsigned NumNegativeBits = 0;
20015
473k
  unsigned NumPositiveBits = 0;
20016
20017
4.31M
  for (unsigned i = 0, e = Elements.size(); i != e; 
++i3.84M
) {
20018
3.84M
    EnumConstantDecl *ECD =
20019
3.84M
      cast_or_null<EnumConstantDecl>(Elements[i]);
20020
3.84M
    if (!ECD) 
continue11
; // Already issued a diagnostic.
20021
20022
3.84M
    const llvm::APSInt &InitVal = ECD->getInitVal();
20023
20024
    // Keep track of the size of positive and negative values.
20025
3.84M
    if (InitVal.isUnsigned() || 
InitVal.isNonNegative()3.18M
) {
20026
      // If the enumerator is zero that should still be counted as a positive
20027
      // bit since we need a bit to store the value zero.
20028
3.02M
      unsigned ActiveBits = InitVal.getActiveBits();
20029
3.02M
      NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20030
3.02M
    } else {
20031
818k
      NumNegativeBits =
20032
818k
          std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20033
818k
    }
20034
3.84M
  }
20035
20036
  // If we have an empty set of enumerators we still need one bit.
20037
  // From [dcl.enum]p8
20038
  // If the enumerator-list is empty, the values of the enumeration are as if
20039
  // the enumeration had a single enumerator with value 0
20040
473k
  if (!NumPositiveBits && 
!NumNegativeBits48.0k
)
20041
2.35k
    NumPositiveBits = 1;
20042
20043
  // Figure out the type that should be used for this enum.
20044
473k
  QualType BestType;
20045
473k
  unsigned BestWidth;
20046
20047
  // C++0x N3000 [conv.prom]p3:
20048
  //   An rvalue of an unscoped enumeration type whose underlying
20049
  //   type is not fixed can be converted to an rvalue of the first
20050
  //   of the following types that can represent all the values of
20051
  //   the enumeration: int, unsigned int, long int, unsigned long
20052
  //   int, long long int, or unsigned long long int.
20053
  // C99 6.4.4.3p2:
20054
  //   An identifier declared as an enumeration constant has type int.
20055
  // The C99 rule is modified by a gcc extension
20056
473k
  QualType BestPromotionType;
20057
20058
473k
  bool Packed = Enum->hasAttr<PackedAttr>();
20059
  // -fshort-enums is the equivalent to specifying the packed attribute on all
20060
  // enum definitions.
20061
473k
  if (LangOpts.ShortEnums)
20062
2
    Packed = true;
20063
20064
  // If the enum already has a type because it is fixed or dictated by the
20065
  // target, promote that type instead of analyzing the enumerators.
20066
473k
  if (Enum->isComplete()) {
20067
105k
    BestType = Enum->getIntegerType();
20068
105k
    if (Context.isPromotableIntegerType(BestType))
20069
3.23k
      BestPromotionType = Context.getPromotedIntegerType(BestType);
20070
101k
    else
20071
101k
      BestPromotionType = BestType;
20072
20073
105k
    BestWidth = Context.getIntWidth(BestType);
20074
105k
  }
20075
368k
  else if (NumNegativeBits) {
20076
    // If there is a negative value, figure out the smallest integer type (of
20077
    // int/long/longlong) that fits.
20078
    // If it's packed, check also if it fits a char or a short.
20079
56.5k
    if (Packed && 
NumNegativeBits <= CharWidth0
&&
NumPositiveBits < CharWidth0
) {
20080
0
      BestType = Context.SignedCharTy;
20081
0
      BestWidth = CharWidth;
20082
56.5k
    } else if (Packed && 
NumNegativeBits <= ShortWidth0
&&
20083
56.5k
               
NumPositiveBits < ShortWidth0
) {
20084
0
      BestType = Context.ShortTy;
20085
0
      BestWidth = ShortWidth;
20086
56.5k
    } else if (NumNegativeBits <= IntWidth && 
NumPositiveBits < IntWidth56.5k
) {
20087
56.5k
      BestType = Context.IntTy;
20088
56.5k
      BestWidth = IntWidth;
20089
56.5k
    } else {
20090
35
      BestWidth = Context.getTargetInfo().getLongWidth();
20091
20092
35
      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20093
22
        BestType = Context.LongTy;
20094
22
      } else {
20095
13
        BestWidth = Context.getTargetInfo().getLongLongWidth();
20096
20097
13
        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20098
9
          Diag(Enum->getLocation(), diag::ext_enum_too_large);
20099
13
        BestType = Context.LongLongTy;
20100
13
      }
20101
35
    }
20102
56.5k
    BestPromotionType = (BestWidth <= IntWidth ? 
Context.IntTy56.5k
:
BestType35
);
20103
311k
  } else {
20104
    // If there is no negative value, figure out the smallest type that fits
20105
    // all of the enumerator values.
20106
    // If it's packed, check also if it fits a char or a short.
20107
311k
    if (Packed && 
NumPositiveBits <= CharWidth6
) {
20108
6
      BestType = Context.UnsignedCharTy;
20109
6
      BestPromotionType = Context.IntTy;
20110
6
      BestWidth = CharWidth;
20111
311k
    } else if (Packed && 
NumPositiveBits <= ShortWidth0
) {
20112
0
      BestType = Context.UnsignedShortTy;
20113
0
      BestPromotionType = Context.IntTy;
20114
0
      BestWidth = ShortWidth;
20115
311k
    } else if (NumPositiveBits <= IntWidth) {
20116
311k
      BestType = Context.UnsignedIntTy;
20117
311k
      BestWidth = IntWidth;
20118
311k
      BestPromotionType
20119
311k
        = (NumPositiveBits == BestWidth || 
!getLangOpts().CPlusPlus300k
)
20120
311k
                           ? 
Context.UnsignedIntTy256k
:
Context.IntTy54.9k
;
20121
311k
    } else 
if (668
NumPositiveBits <=
20122
668
               (BestWidth = Context.getTargetInfo().getLongWidth())) {
20123
656
      BestType = Context.UnsignedLongTy;
20124
656
      BestPromotionType
20125
656
        = (NumPositiveBits == BestWidth || 
!getLangOpts().CPlusPlus14
)
20126
656
                           ? 
Context.UnsignedLongTy642
:
Context.LongTy14
;
20127
656
    } else {
20128
12
      BestWidth = Context.getTargetInfo().getLongLongWidth();
20129
12
      assert(NumPositiveBits <= BestWidth &&
20130
12
             "How could an initializer get larger than ULL?");
20131
12
      BestType = Context.UnsignedLongLongTy;
20132
12
      BestPromotionType
20133
12
        = (NumPositiveBits == BestWidth || 
!getLangOpts().CPlusPlus2
)
20134
12
                           ? 
Context.UnsignedLongLongTy10
:
Context.LongLongTy2
;
20135
12
    }
20136
311k
  }
20137
20138
  // Loop over all of the enumerator constants, changing their types to match
20139
  // the type of the enum if needed.
20140
3.84M
  
for (auto *D : Elements)473k
{
20141
3.84M
    auto *ECD = cast_or_null<EnumConstantDecl>(D);
20142
3.84M
    if (!ECD) 
continue11
; // Already issued a diagnostic.
20143
20144
    // Standard C says the enumerators have int type, but we allow, as an
20145
    // extension, the enumerators to be larger than int size.  If each
20146
    // enumerator value fits in an int, type it as an int, otherwise type it the
20147
    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
20148
    // that X has type 'int', not 'unsigned'.
20149
20150
    // Determine whether the value fits into an int.
20151
3.84M
    llvm::APSInt InitVal = ECD->getInitVal();
20152
20153
    // If it fits into an integer type, force it.  Otherwise force it to match
20154
    // the enum decl type.
20155
3.84M
    QualType NewTy;
20156
3.84M
    unsigned NewWidth;
20157
3.84M
    bool NewSign;
20158
3.84M
    if (!getLangOpts().CPlusPlus &&
20159
3.84M
        
!Enum->isFixed()3.27M
&&
20160
3.84M
        
isRepresentableIntegerValue(Context, InitVal, Context.IntTy)2.38M
) {
20161
2.36M
      NewTy = Context.IntTy;
20162
2.36M
      NewWidth = IntWidth;
20163
2.36M
      NewSign = true;
20164
2.36M
    } else 
if (1.48M
ECD->getType() == BestType1.48M
) {
20165
      // Already the right type!
20166
1.17M
      if (getLangOpts().CPlusPlus)
20167
        // C++ [dcl.enum]p4: Following the closing brace of an
20168
        // enum-specifier, each enumerator has the type of its
20169
        // enumeration.
20170
268k
        ECD->setType(EnumType);
20171
1.17M
      continue;
20172
1.17M
    } else {
20173
305k
      NewTy = BestType;
20174
305k
      NewWidth = BestWidth;
20175
305k
      NewSign = BestType->isSignedIntegerOrEnumerationType();
20176
305k
    }
20177
20178
    // Adjust the APSInt value.
20179
2.66M
    InitVal = InitVal.extOrTrunc(NewWidth);
20180
2.66M
    InitVal.setIsSigned(NewSign);
20181
2.66M
    ECD->setInitVal(InitVal);
20182
20183
    // Adjust the Expr initializer and type.
20184
2.66M
    if (ECD->getInitExpr() &&
20185
2.66M
        
!Context.hasSameType(NewTy, ECD->getInitExpr()->getType())2.60M
)
20186
272k
      ECD->setInitExpr(ImplicitCastExpr::Create(
20187
272k
          Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20188
272k
          /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20189
2.66M
    if (getLangOpts().CPlusPlus)
20190
      // C++ [dcl.enum]p4: Following the closing brace of an
20191
      // enum-specifier, each enumerator has the type of its
20192
      // enumeration.
20193
301k
      ECD->setType(EnumType);
20194
2.36M
    else
20195
2.36M
      ECD->setType(NewTy);
20196
2.66M
  }
20197
20198
473k
  Enum->completeDefinition(BestType, BestPromotionType,
20199
473k
                           NumPositiveBits, NumNegativeBits);
20200
20201
473k
  CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20202
20203
473k
  if (Enum->isClosedFlag()) {
20204
30
    for (Decl *D : Elements) {
20205
30
      EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20206
30
      if (!ECD) 
continue0
; // Already issued a diagnostic.
20207
20208
30
      llvm::APSInt InitVal = ECD->getInitVal();
20209
30
      if (InitVal != 0 && 
!InitVal.isPowerOf2()29
&&
20210
30
          
!IsValueInFlagEnum(Enum, InitVal, true)11
)
20211
5
        Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20212
5
          << ECD << Enum;
20213
30
    }
20214
11
  }
20215
20216
  // Now that the enum type is defined, ensure it's not been underaligned.
20217
473k
  if (Enum->hasAttrs())
20218
100k
    CheckAlignasUnderalignment(Enum);
20219
473k
}
20220
20221
Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
20222
                                  SourceLocation StartLoc,
20223
102
                                  SourceLocation EndLoc) {
20224
102
  StringLiteral *AsmString = cast<StringLiteral>(expr);
20225
20226
102
  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
20227
102
                                                   AsmString, StartLoc,
20228
102
                                                   EndLoc);
20229
102
  CurContext->addDecl(New);
20230
102
  return New;
20231
102
}
20232
20233
58
Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) {
20234
58
  auto *New = TopLevelStmtDecl::Create(Context, Statement);
20235
58
  Context.getTranslationUnitDecl()->addDecl(New);
20236
58
  return New;
20237
58
}
20238
20239
void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20240
                                      IdentifierInfo* AliasName,
20241
                                      SourceLocation PragmaLoc,
20242
                                      SourceLocation NameLoc,
20243
11
                                      SourceLocation AliasNameLoc) {
20244
11
  NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20245
11
                                         LookupOrdinaryName);
20246
11
  AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20247
11
                           AttributeCommonInfo::Form::Pragma());
20248
11
  AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20249
11
      Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20250
20251
  // If a declaration that:
20252
  // 1) declares a function or a variable
20253
  // 2) has external linkage
20254
  // already exists, add a label attribute to it.
20255
11
  if (PrevDecl && 
(2
isa<FunctionDecl>(PrevDecl)2
||
isa<VarDecl>(PrevDecl)1
)) {
20256
1
    if (isDeclExternC(PrevDecl))
20257
1
      PrevDecl->addAttr(Attr);
20258
0
    else
20259
0
      Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20260
0
          << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20261
    // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20262
1
  } else
20263
10
    (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20264
11
}
20265
20266
void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20267
                             SourceLocation PragmaLoc,
20268
91
                             SourceLocation NameLoc) {
20269
91
  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20270
20271
91
  if (PrevDecl) {
20272
19
    PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20273
72
  } else {
20274
72
    (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20275
72
  }
20276
91
}
20277
20278
void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20279
                                IdentifierInfo* AliasName,
20280
                                SourceLocation PragmaLoc,
20281
                                SourceLocation NameLoc,
20282
35
                                SourceLocation AliasNameLoc) {
20283
35
  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20284
35
                                    LookupOrdinaryName);
20285
35
  WeakInfo W = WeakInfo(Name, NameLoc);
20286
20287
35
  if (PrevDecl && 
(12
isa<FunctionDecl>(PrevDecl)12
||
isa<VarDecl>(PrevDecl)2
)) {
20288
11
    if (!PrevDecl->hasAttr<AliasAttr>())
20289
11
      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20290
11
        DeclApplyPragmaWeak(TUScope, ND, W);
20291
24
  } else {
20292
24
    (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20293
24
  }
20294
35
}
20295
20296
46.5M
ObjCContainerDecl *Sema::getObjCDeclContext() const {
20297
46.5M
  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
20298
46.5M
}
20299
20300
Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20301
113k
                                                     bool Final) {
20302
113k
  assert(FD && "Expected non-null FunctionDecl");
20303
20304
  // SYCL functions can be template, so we check if they have appropriate
20305
  // attribute prior to checking if it is a template.
20306
113k
  if (LangOpts.SYCLIsDevice && 
FD->hasAttr<SYCLKernelAttr>()648
)
20307
149
    return FunctionEmissionStatus::Emitted;
20308
20309
  // Templates are emitted when they're instantiated.
20310
113k
  if (FD->isDependentContext())
20311
10.5k
    return FunctionEmissionStatus::TemplateDiscarded;
20312
20313
  // Check whether this function is an externally visible definition.
20314
102k
  auto IsEmittedForExternalSymbol = [this, FD]() {
20315
    // We have to check the GVA linkage of the function's *definition* -- if we
20316
    // only have a declaration, we don't know whether or not the function will
20317
    // be emitted, because (say) the definition could include "inline".
20318
29.8k
    const FunctionDecl *Def = FD->getDefinition();
20319
20320
29.8k
    return Def && !isDiscardableGVALinkage(
20321
29.5k
                      getASTContext().GetGVALinkageForFunction(Def));
20322
29.8k
  };
20323
20324
102k
  if (LangOpts.OpenMPIsTargetDevice) {
20325
    // In OpenMP device mode we will not emit host only functions, or functions
20326
    // we don't need due to their linkage.
20327
27.2k
    std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20328
27.2k
        OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20329
    // DevTy may be changed later by
20330
    //  #pragma omp declare target to(*) device_type(*).
20331
    // Therefore DevTy having no value does not imply host. The emission status
20332
    // will be checked again at the end of compilation unit with Final = true.
20333
27.2k
    if (DevTy)
20334
2.11k
      if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20335
2
        return FunctionEmissionStatus::OMPDiscarded;
20336
    // If we have an explicit value for the device type, or we are in a target
20337
    // declare context, we need to emit all extern and used symbols.
20338
27.2k
    if (isInOpenMPDeclareTargetContext() || 
DevTy26.0k
)
20339
2.12k
      if (IsEmittedForExternalSymbol())
20340
1.34k
        return FunctionEmissionStatus::Emitted;
20341
    // Device mode only emits what it must, if it wasn't tagged yet and needed,
20342
    // we'll omit it.
20343
25.8k
    if (Final)
20344
12.7k
      return FunctionEmissionStatus::OMPDiscarded;
20345
75.3k
  } else if (LangOpts.OpenMP > 45) {
20346
    // In OpenMP host compilation prior to 5.0 everything was an emitted host
20347
    // function. In 5.0, no_host was introduced which might cause a function to
20348
    // be ommitted.
20349
31.6k
    std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20350
31.6k
        OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20351
31.6k
    if (DevTy)
20352
871
      if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20353
26
        return FunctionEmissionStatus::OMPDiscarded;
20354
31.6k
  }
20355
20356
88.4k
  if (Final && 
LangOpts.OpenMP21.7k
&&
!LangOpts.CUDA21.2k
)
20357
21.1k
    return FunctionEmissionStatus::Emitted;
20358
20359
67.3k
  if (LangOpts.CUDA) {
20360
    // When compiling for device, host functions are never emitted.  Similarly,
20361
    // when compiling for host, device and global functions are never emitted.
20362
    // (Technically, we do emit a host-side stub for global functions, but this
20363
    // doesn't count for our purposes here.)
20364
32.6k
    Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
20365
32.6k
    if (LangOpts.CUDAIsDevice && 
T == Sema::CFT_Host25.5k
)
20366
2.35k
      return FunctionEmissionStatus::CUDADiscarded;
20367
30.2k
    if (!LangOpts.CUDAIsDevice &&
20368
30.2k
        
(7.06k
T == Sema::CFT_Device7.06k
||
T == Sema::CFT_Global4.87k
))
20369
2.52k
      return FunctionEmissionStatus::CUDADiscarded;
20370
20371
27.7k
    if (IsEmittedForExternalSymbol())
20372
10.6k
      return FunctionEmissionStatus::Emitted;
20373
27.7k
  }
20374
20375
  // Otherwise, the function is known-emitted if it's in our set of
20376
  // known-emitted functions.
20377
51.7k
  return FunctionEmissionStatus::Unknown;
20378
67.3k
}
20379
20380
71.2k
bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20381
  // Host-side references to a __global__ function refer to the stub, so the
20382
  // function itself is never emitted and therefore should not be marked.
20383
  // If we have host fn calls kernel fn calls host+device, the HD function
20384
  // does not get instantiated on the host. We model this by omitting at the
20385
  // call to the kernel from the callgraph. This ensures that, when compiling
20386
  // for host, only HD functions actually called from the host get marked as
20387
  // known-emitted.
20388
71.2k
  return LangOpts.CUDA && 
!LangOpts.CUDAIsDevice679
&&
20389
71.2k
         
IdentifyCUDATarget(Callee) == CFT_Global296
;
20390
71.2k
}