Coverage Report

Created: 2022-05-17 06:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/Sema.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
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 the actions class which performs semantic analysis and
10
// builds an AST out of a parse stream.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "UsedDeclVisitor.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/ASTDiagnostic.h"
17
#include "clang/AST/Decl.h"
18
#include "clang/AST/DeclCXX.h"
19
#include "clang/AST/DeclFriend.h"
20
#include "clang/AST/DeclObjC.h"
21
#include "clang/AST/Expr.h"
22
#include "clang/AST/ExprCXX.h"
23
#include "clang/AST/PrettyDeclStackTrace.h"
24
#include "clang/AST/StmtCXX.h"
25
#include "clang/Basic/DarwinSDKInfo.h"
26
#include "clang/Basic/DiagnosticOptions.h"
27
#include "clang/Basic/PartialDiagnostic.h"
28
#include "clang/Basic/SourceManager.h"
29
#include "clang/Basic/Stack.h"
30
#include "clang/Basic/TargetInfo.h"
31
#include "clang/Lex/HeaderSearch.h"
32
#include "clang/Lex/HeaderSearchOptions.h"
33
#include "clang/Lex/Preprocessor.h"
34
#include "clang/Sema/CXXFieldCollector.h"
35
#include "clang/Sema/DelayedDiagnostic.h"
36
#include "clang/Sema/ExternalSemaSource.h"
37
#include "clang/Sema/Initialization.h"
38
#include "clang/Sema/MultiplexExternalSemaSource.h"
39
#include "clang/Sema/ObjCMethodList.h"
40
#include "clang/Sema/Scope.h"
41
#include "clang/Sema/ScopeInfo.h"
42
#include "clang/Sema/SemaConsumer.h"
43
#include "clang/Sema/SemaInternal.h"
44
#include "clang/Sema/TemplateDeduction.h"
45
#include "clang/Sema/TemplateInstCallback.h"
46
#include "clang/Sema/TypoCorrection.h"
47
#include "llvm/ADT/DenseMap.h"
48
#include "llvm/ADT/SmallPtrSet.h"
49
#include "llvm/Support/TimeProfiler.h"
50
51
using namespace clang;
52
using namespace sema;
53
54
100k
SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
55
100k
  return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
56
100k
}
57
58
123k
ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
59
60
DarwinSDKInfo *
61
Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
62
46
                                              StringRef Platform) {
63
46
  auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking();
64
46
  if (!SDKInfo && 
!WarnedDarwinSDKInfoMissing2
) {
65
1
    Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
66
1
        << Platform;
67
1
    WarnedDarwinSDKInfoMissing = true;
68
1
  }
69
46
  return SDKInfo;
70
46
}
71
72
112
DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() {
73
112
  if (CachedDarwinSDKInfo)
74
100
    return CachedDarwinSDKInfo->get();
75
12
  auto SDKInfo = parseDarwinSDKInfo(
76
12
      PP.getFileManager().getVirtualFileSystem(),
77
12
      PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
78
12
  if (SDKInfo && *SDKInfo) {
79
4
    CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
80
4
    return CachedDarwinSDKInfo->get();
81
4
  }
82
8
  if (!SDKInfo)
83
0
    llvm::consumeError(SDKInfo.takeError());
84
8
  CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
85
8
  return nullptr;
86
12
}
87
88
IdentifierInfo *
89
Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
90
2.31k
                                                 unsigned int Index) {
91
2.31k
  std::string InventedName;
92
2.31k
  llvm::raw_string_ostream OS(InventedName);
93
94
2.31k
  if (!ParamName)
95
88
    OS << "auto:" << Index + 1;
96
2.22k
  else
97
2.22k
    OS << ParamName->getName() << ":auto";
98
99
2.31k
  OS.flush();
100
2.31k
  return &Context.Idents.get(OS.str());
101
2.31k
}
102
103
PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
104
111M
                                       const Preprocessor &PP) {
105
111M
  PrintingPolicy Policy = Context.getPrintingPolicy();
106
  // In diagnostics, we print _Bool as bool if the latter is defined as the
107
  // former.
108
111M
  Policy.Bool = Context.getLangOpts().Bool;
109
111M
  if (!Policy.Bool) {
110
62.5M
    if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
111
46.7M
      Policy.Bool = BoolMacro->isObjectLike() &&
112
46.7M
                    BoolMacro->getNumTokens() == 1 &&
113
46.7M
                    BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
114
46.7M
    }
115
62.5M
  }
116
117
  // Shorten the data output if needed
118
111M
  Policy.EntireContentsOfLargeArray = false;
119
120
111M
  return Policy;
121
111M
}
122
123
86.6k
void Sema::ActOnTranslationUnitScope(Scope *S) {
124
86.6k
  TUScope = S;
125
86.6k
  PushDeclContext(S, Context.getTranslationUnitDecl());
126
86.6k
}
127
128
namespace clang {
129
namespace sema {
130
131
class SemaPPCallbacks : public PPCallbacks {
132
  Sema *S = nullptr;
133
  llvm::SmallVector<SourceLocation, 8> IncludeStack;
134
135
public:
136
86.7k
  void set(Sema &S) { this->S = &S; }
137
138
81.9k
  void reset() { S = nullptr; }
139
140
  virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
141
                           SrcMgr::CharacteristicKind FileType,
142
1.80M
                           FileID PrevFID) override {
143
1.80M
    if (!S)
144
0
      return;
145
1.80M
    switch (Reason) {
146
834k
    case EnterFile: {
147
834k
      SourceManager &SM = S->getSourceManager();
148
834k
      SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
149
834k
      if (IncludeLoc.isValid()) {
150
578k
        if (llvm::timeTraceProfilerEnabled()) {
151
0
          const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
152
0
          llvm::timeTraceProfilerBegin(
153
0
              "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
154
0
        }
155
156
578k
        IncludeStack.push_back(IncludeLoc);
157
578k
        S->DiagnoseNonDefaultPragmaAlignPack(
158
578k
            Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude,
159
578k
            IncludeLoc);
160
578k
      }
161
834k
      break;
162
0
    }
163
748k
    case ExitFile:
164
748k
      if (!IncludeStack.empty()) {
165
578k
        if (llvm::timeTraceProfilerEnabled())
166
0
          llvm::timeTraceProfilerEnd();
167
168
578k
        S->DiagnoseNonDefaultPragmaAlignPack(
169
578k
            Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit,
170
578k
            IncludeStack.pop_back_val());
171
578k
      }
172
748k
      break;
173
224k
    default:
174
224k
      break;
175
1.80M
    }
176
1.80M
  }
177
};
178
179
} // end namespace sema
180
} // end namespace clang
181
182
const unsigned Sema::MaxAlignmentExponent;
183
const uint64_t Sema::MaximumAlignment;
184
185
Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
186
           TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
187
    : ExternalSource(nullptr), isMultiplexExternalSource(false),
188
      CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
189
      Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
190
      SourceMgr(PP.getSourceManager()), CollectStats(false),
191
      CodeCompleter(CodeCompleter), CurContext(nullptr),
192
      OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
193
      MSPointerToMemberRepresentationMethod(
194
          LangOpts.getMSPointerToMemberRepresentationMethod()),
195
      VtorDispStack(LangOpts.getVtorDispMode()),
196
      AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
197
      DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
198
      CodeSegStack(nullptr), FpPragmaStack(FPOptionsOverride()),
199
      CurInitSeg(nullptr), VisContext(nullptr),
200
      PragmaAttributeCurrentTargetDecl(nullptr),
201
      IsBuildingRecoveryCallExpr(false), LateTemplateParser(nullptr),
202
      LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
203
      StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
204
      StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
205
      MSVCGuidDecl(nullptr), StdSourceLocationImplDecl(nullptr),
206
      NSNumberDecl(nullptr), NSValueDecl(nullptr), NSStringDecl(nullptr),
207
      StringWithUTF8StringMethod(nullptr),
208
      ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
209
      ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
210
      DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
211
      TUKind(TUKind), NumSFINAEErrors(0),
212
      FullyCheckedComparisonCategories(
213
          static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
214
      SatisfactionCache(Context), AccessCheckingSFINAE(false),
215
      InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
216
      ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
217
      DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
218
      ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
219
86.7k
      CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
220
86.7k
  assert(pp.TUKind == TUKind);
221
0
  TUScope = nullptr;
222
86.7k
  isConstantEvaluatedOverride = false;
223
224
86.7k
  LoadedExternalKnownNamespaces = false;
225
1.38M
  for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; 
++I1.30M
)
226
1.30M
    NSNumberLiteralMethods[I] = nullptr;
227
228
86.7k
  if (getLangOpts().ObjC)
229
22.7k
    NSAPIObj.reset(new NSAPI(Context));
230
231
86.7k
  if (getLangOpts().CPlusPlus)
232
67.9k
    FieldCollector.reset(new CXXFieldCollector());
233
234
  // Tell diagnostics how to render things from the AST library.
235
86.7k
  Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
236
237
  // This evaluation context exists to ensure that there's always at least one
238
  // valid evaluation context available. It is never removed from the
239
  // evaluation stack.
240
86.7k
  ExprEvalContexts.emplace_back(
241
86.7k
      ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
242
86.7k
      nullptr, ExpressionEvaluationContextRecord::EK_Other);
243
244
  // Initialization of data sharing attributes stack for OpenMP
245
86.7k
  InitDataSharingAttributesStack();
246
247
86.7k
  std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
248
86.7k
      std::make_unique<sema::SemaPPCallbacks>();
249
86.7k
  SemaPPCallbackHandler = Callbacks.get();
250
86.7k
  PP.addPPCallbacks(std::move(Callbacks));
251
86.7k
  SemaPPCallbackHandler->set(*this);
252
86.7k
  if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine)
253
    // Use setting from TargetInfo.
254
86.6k
    PP.setCurrentFPEvalMethod(SourceLocation(),
255
86.6k
                              ctxt.getTargetInfo().getFPEvalMethod());
256
22
  else
257
    // Set initial value of __FLT_EVAL_METHOD__ from the command line.
258
22
    PP.setCurrentFPEvalMethod(SourceLocation(),
259
22
                              getLangOpts().getFPEvalMethod());
260
86.7k
  CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
261
  // When `-ffast-math` option is enabled, it triggers several driver math
262
  // options to be enabled. Among those, only one the following two modes
263
  // affect the eval-method:  reciprocal or reassociate.
264
86.7k
  if (getLangOpts().AllowFPReassoc || 
getLangOpts().AllowRecip86.6k
)
265
58
    PP.setCurrentFPEvalMethod(SourceLocation(),
266
58
                              LangOptions::FEM_Indeterminable);
267
86.7k
}
268
269
// Anchor Sema's type info to this TU.
270
0
void Sema::anchor() {}
271
272
175k
void Sema::addImplicitTypedef(StringRef Name, QualType T) {
273
175k
  DeclarationName DN = &Context.Idents.get(Name);
274
175k
  if (IdResolver.begin(DN) == IdResolver.end())
275
170k
    PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
276
175k
}
277
278
86.7k
void Sema::Initialize() {
279
86.7k
  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
280
21.2k
    SC->InitializeSema(*this);
281
282
  // Tell the external Sema source about this Sema object.
283
86.7k
  if (ExternalSemaSource *ExternalSema
284
86.7k
      = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
285
13.8k
    ExternalSema->InitializeSema(*this);
286
287
  // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
288
  // will not be able to merge any duplicate __va_list_tag decls correctly.
289
86.7k
  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
290
291
86.7k
  if (!TUScope)
292
149
    return;
293
294
  // Initialize predefined 128-bit integer types, if needed.
295
86.5k
  if (Context.getTargetInfo().hasInt128Type() ||
296
86.5k
      
(16.2k
Context.getAuxTargetInfo()16.2k
&&
297
70.3k
       
Context.getAuxTargetInfo()->hasInt128Type()9
)) {
298
    // If either of the 128-bit integer types are unavailable to name lookup,
299
    // define them now.
300
70.3k
    DeclarationName Int128 = &Context.Idents.get("__int128_t");
301
70.3k
    if (IdResolver.begin(Int128) == IdResolver.end())
302
67.5k
      PushOnScopeChains(Context.getInt128Decl(), TUScope);
303
304
70.3k
    DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
305
70.3k
    if (IdResolver.begin(UInt128) == IdResolver.end())
306
67.5k
      PushOnScopeChains(Context.getUInt128Decl(), TUScope);
307
70.3k
  }
308
309
310
  // Initialize predefined Objective-C types:
311
86.5k
  if (getLangOpts().ObjC) {
312
    // If 'SEL' does not yet refer to any declarations, make it refer to the
313
    // predefined 'SEL'.
314
22.7k
    DeclarationName SEL = &Context.Idents.get("SEL");
315
22.7k
    if (IdResolver.begin(SEL) == IdResolver.end())
316
22.5k
      PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
317
318
    // If 'id' does not yet refer to any declarations, make it refer to the
319
    // predefined 'id'.
320
22.7k
    DeclarationName Id = &Context.Idents.get("id");
321
22.7k
    if (IdResolver.begin(Id) == IdResolver.end())
322
22.5k
      PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
323
324
    // Create the built-in typedef for 'Class'.
325
22.7k
    DeclarationName Class = &Context.Idents.get("Class");
326
22.7k
    if (IdResolver.begin(Class) == IdResolver.end())
327
22.5k
      PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
328
329
    // Create the built-in forward declaratino for 'Protocol'.
330
22.7k
    DeclarationName Protocol = &Context.Idents.get("Protocol");
331
22.7k
    if (IdResolver.begin(Protocol) == IdResolver.end())
332
22.5k
      PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
333
22.7k
  }
334
335
  // Create the internal type for the *StringMakeConstantString builtins.
336
86.5k
  DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
337
86.5k
  if (IdResolver.begin(ConstantString) == IdResolver.end())
338
82.8k
    PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
339
340
  // Initialize Microsoft "predefined C++ types".
341
86.5k
  if (getLangOpts().MSVCCompat) {
342
10.4k
    if (getLangOpts().CPlusPlus &&
343
10.4k
        
IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end()9.33k
)
344
9.32k
      PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
345
9.32k
                        TUScope);
346
347
10.4k
    addImplicitTypedef("size_t", Context.getSizeType());
348
10.4k
  }
349
350
  // Initialize predefined OpenCL types and supported extensions and (optional)
351
  // core features.
352
86.5k
  if (getLangOpts().OpenCL) {
353
642
    getOpenCLOptions().addSupport(
354
642
        Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
355
642
    addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
356
642
    addImplicitTypedef("event_t", Context.OCLEventTy);
357
642
    auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
358
642
    if (OCLCompatibleVersion >= 200) {
359
375
      if (getLangOpts().OpenCLCPlusPlus || 
getLangOpts().Blocks233
) {
360
338
        addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
361
338
        addImplicitTypedef("queue_t", Context.OCLQueueTy);
362
338
      }
363
375
      if (getLangOpts().OpenCLPipes)
364
326
        addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
365
375
      addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
366
375
      addImplicitTypedef("atomic_uint",
367
375
                         Context.getAtomicType(Context.UnsignedIntTy));
368
375
      addImplicitTypedef("atomic_float",
369
375
                         Context.getAtomicType(Context.FloatTy));
370
      // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
371
      // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
372
375
      addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
373
374
375
      // OpenCL v2.0 s6.13.11.6:
376
      // - The atomic_long and atomic_ulong types are supported if the
377
      //   cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
378
      //   extensions are supported.
379
      // - The atomic_double type is only supported if double precision
380
      //   is supported and the cl_khr_int64_base_atomics and
381
      //   cl_khr_int64_extended_atomics extensions are supported.
382
      // - If the device address space is 64-bits, the data types
383
      //   atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
384
      //   atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
385
      //   cl_khr_int64_extended_atomics extensions are supported.
386
387
375
      auto AddPointerSizeDependentTypes = [&]() {
388
351
        auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
389
351
        auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
390
351
        auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
391
351
        auto AtomicPtrDiffT =
392
351
            Context.getAtomicType(Context.getPointerDiffType());
393
351
        addImplicitTypedef("atomic_size_t", AtomicSizeT);
394
351
        addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
395
351
        addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
396
351
        addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
397
351
      };
398
399
375
      if (Context.getTypeSize(Context.getSizeType()) == 32) {
400
155
        AddPointerSizeDependentTypes();
401
155
      }
402
403
375
      if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
404
334
        auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
405
334
        addImplicitTypedef("atomic_half", AtomicHalfT);
406
334
      }
407
408
375
      std::vector<QualType> Atomic64BitTypes;
409
375
      if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
410
375
                                         getLangOpts()) &&
411
375
          getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
412
332
                                         getLangOpts())) {
413
332
        if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
414
325
          auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
415
325
          addImplicitTypedef("atomic_double", AtomicDoubleT);
416
325
          Atomic64BitTypes.push_back(AtomicDoubleT);
417
325
        }
418
332
        auto AtomicLongT = Context.getAtomicType(Context.LongTy);
419
332
        auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
420
332
        addImplicitTypedef("atomic_long", AtomicLongT);
421
332
        addImplicitTypedef("atomic_ulong", AtomicULongT);
422
423
424
332
        if (Context.getTypeSize(Context.getSizeType()) == 64) {
425
196
          AddPointerSizeDependentTypes();
426
196
        }
427
332
      }
428
375
    }
429
430
642
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext)                                      \
431
7.70k
  if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) {                   \
432
5.76k
    addImplicitTypedef(#ExtType, Context.Id##Ty);                              \
433
5.76k
  }
434
642
#include "clang/Basic/OpenCLExtensionTypes.def"
435
642
  }
436
437
86.5k
  if (Context.getTargetInfo().hasAArch64SVETypes()) {
438
2.76k
#define SVE_TYPE(Name, Id, SingletonId) \
439
135k
    addImplicitTypedef(Name, Context.SingletonId);
440
2.76k
#include "clang/Basic/AArch64SVEACLETypes.def"
441
2.76k
  }
442
443
86.5k
  if (Context.getTargetInfo().getTriple().isPPC64()) {
444
3.75k
#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
445
3.75k
      addImplicitTypedef(#Name, Context.Id##Ty);
446
3.75k
#include "clang/Basic/PPCTypes.def"
447
3.75k
#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
448
3.75k
    addImplicitTypedef(#Name, Context.Id##Ty);
449
3.75k
#include "clang/Basic/PPCTypes.def"
450
3.75k
  }
451
452
86.5k
  if (Context.getTargetInfo().hasRISCVVTypes()) {
453
142
#define RVV_TYPE(Name, Id, SingletonId)                                        \
454
9.37k
  addImplicitTypedef(Name, Context.SingletonId);
455
142
#include "clang/Basic/RISCVVTypes.def"
456
142
  }
457
458
86.5k
  if (Context.getTargetInfo().hasBuiltinMSVaList()) {
459
65.8k
    DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
460
65.8k
    if (IdResolver.begin(MSVaList) == IdResolver.end())
461
64.1k
      PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
462
65.8k
  }
463
464
86.5k
  DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
465
86.5k
  if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
466
82.8k
    PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
467
86.5k
}
468
469
81.9k
Sema::~Sema() {
470
81.9k
  assert(InstantiatingSpecializations.empty() &&
471
81.9k
         "failed to clean up an InstantiatingTemplate?");
472
473
81.9k
  if (VisContext) 
FreeVisContext()4
;
474
475
  // Kill all the active scopes.
476
81.9k
  for (sema::FunctionScopeInfo *FSI : FunctionScopes)
477
0
    delete FSI;
478
479
  // Tell the SemaConsumer to forget about us; we're going out of scope.
480
81.9k
  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
481
21.2k
    SC->ForgetSema();
482
483
  // Detach from the external Sema source.
484
81.9k
  if (ExternalSemaSource *ExternalSema
485
81.9k
        = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
486
12.8k
    ExternalSema->ForgetSema();
487
488
  // If Sema's ExternalSource is the multiplexer - we own it.
489
81.9k
  if (isMultiplexExternalSource)
490
142
    delete ExternalSource;
491
492
  // Delete cached satisfactions.
493
81.9k
  std::vector<ConstraintSatisfaction *> Satisfactions;
494
81.9k
  Satisfactions.reserve(Satisfactions.size());
495
81.9k
  for (auto &Node : SatisfactionCache)
496
878
    Satisfactions.push_back(&Node);
497
81.9k
  for (auto *Node : Satisfactions)
498
878
    delete Node;
499
500
81.9k
  threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
501
502
  // Destroys data sharing attributes stack for OpenMP
503
81.9k
  DestroyDataSharingAttributesStack();
504
505
  // Detach from the PP callback handler which outlives Sema since it's owned
506
  // by the preprocessor.
507
81.9k
  SemaPPCallbackHandler->reset();
508
81.9k
}
509
510
11
void Sema::warnStackExhausted(SourceLocation Loc) {
511
  // Only warn about this once.
512
11
  if (!WarnedStackExhausted) {
513
2
    Diag(Loc, diag::warn_stack_exhausted);
514
2
    WarnedStackExhausted = true;
515
2
  }
516
11
}
517
518
void Sema::runWithSufficientStackSpace(SourceLocation Loc,
519
126M
                                       llvm::function_ref<void()> Fn) {
520
126M
  clang::runWithSufficientStackSpace([&] 
{ warnStackExhausted(Loc); }11
, Fn);
521
126M
}
522
523
/// makeUnavailableInSystemHeader - There is an error in the current
524
/// context.  If we're still in a system header, and we can plausibly
525
/// make the relevant declaration unavailable instead of erroring, do
526
/// so and return true.
527
bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
528
338
                                      UnavailableAttr::ImplicitReason reason) {
529
  // If we're not in a function, it's an error.
530
338
  FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
531
338
  if (!fn) 
return false24
;
532
533
  // If we're in template instantiation, it's an error.
534
314
  if (inTemplateInstantiation())
535
0
    return false;
536
537
  // If that function's not in a system header, it's an error.
538
314
  if (!Context.getSourceManager().isInSystemHeader(loc))
539
310
    return false;
540
541
  // If the function is already unavailable, it's not an error.
542
4
  if (fn->hasAttr<UnavailableAttr>()) 
return true0
;
543
544
4
  fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
545
4
  return true;
546
4
}
547
548
867k
ASTMutationListener *Sema::getASTMutationListener() const {
549
867k
  return getASTConsumer().GetASTMutationListener();
550
867k
}
551
552
///Registers an external source. If an external source already exists,
553
/// creates a multiplex external source and appends to it.
554
///
555
///\param[in] E - A non-null external sema source.
556
///
557
14.0k
void Sema::addExternalSource(ExternalSemaSource *E) {
558
14.0k
  assert(E && "Cannot use with NULL ptr");
559
560
14.0k
  if (!ExternalSource) {
561
13.8k
    ExternalSource = E;
562
13.8k
    return;
563
13.8k
  }
564
565
153
  if (isMultiplexExternalSource)
566
2
    static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
567
151
  else {
568
151
    ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
569
151
    isMultiplexExternalSource = true;
570
151
  }
571
153
}
572
573
/// Print out statistics about the semantic analysis.
574
4
void Sema::PrintStats() const {
575
4
  llvm::errs() << "\n*** Semantic Analysis Stats:\n";
576
4
  llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
577
578
4
  BumpAlloc.PrintStats();
579
4
  AnalysisWarnings.PrintStats();
580
4
}
581
582
void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
583
                                               QualType SrcType,
584
21.4M
                                               SourceLocation Loc) {
585
21.4M
  Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
586
21.4M
  if (!ExprNullability || 
(9.43k
*ExprNullability != NullabilityKind::Nullable9.43k
&&
587
9.43k
                           
*ExprNullability != NullabilityKind::NullableResult4.71k
))
588
21.4M
    return;
589
590
4.73k
  Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
591
4.73k
  if (!TypeNullability || 
*TypeNullability != NullabilityKind::NonNull428
)
592
4.56k
    return;
593
594
171
  Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
595
171
}
596
597
11.1M
void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
598
11.1M
  if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
599
11.1M
                      E->getBeginLoc()))
600
11.1M
    return;
601
  // nullptr only exists from C++11 on, so don't warn on its absence earlier.
602
740
  if (!getLangOpts().CPlusPlus11)
603
307
    return;
604
605
433
  if (Kind != CK_NullToPointer && 
Kind != CK_NullToMemberPointer373
)
606
366
    return;
607
67
  if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
608
16
    return;
609
610
  // Don't diagnose the conversion from a 0 literal to a null pointer argument
611
  // in a synthesized call to operator<=>.
612
51
  if (!CodeSynthesisContexts.empty() &&
613
51
      CodeSynthesisContexts.back().Kind ==
614
10
          CodeSynthesisContext::RewritingOperatorAsSpaceship)
615
2
    return;
616
617
  // If it is a macro from system header, and if the macro name is not "NULL",
618
  // do not warn.
619
49
  SourceLocation MaybeMacroLoc = E->getBeginLoc();
620
49
  if (Diags.getSuppressSystemWarnings() &&
621
49
      
SourceMgr.isInSystemMacro(MaybeMacroLoc)25
&&
622
49
      
!findMacroSpelling(MaybeMacroLoc, "NULL")3
)
623
2
    return;
624
625
47
  Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
626
47
      << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
627
47
}
628
629
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
630
/// If there is already an implicit cast, merge into the existing one.
631
/// The result is of the given category.
632
ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
633
                                   CastKind Kind, ExprValueKind VK,
634
                                   const CXXCastPath *BasePath,
635
11.1M
                                   CheckedConversionKind CCK) {
636
11.1M
#ifndef NDEBUG
637
11.1M
  if (VK == VK_PRValue && 
!E->isPRValue()10.9M
) {
638
1.51M
    switch (Kind) {
639
0
    default:
640
0
      llvm_unreachable(
641
0
          ("can't implicitly cast glvalue to prvalue with this cast "
642
0
           "kind: " +
643
0
           std::string(CastExpr::getCastKindName(Kind)))
644
0
              .c_str());
645
341k
    case CK_Dependent:
646
341k
    case CK_LValueToRValue:
647
588k
    case CK_ArrayToPointerDecay:
648
1.51M
    case CK_FunctionToPointerDecay:
649
1.51M
    case CK_ToVoid:
650
1.51M
    case CK_NonAtomicToAtomic:
651
1.51M
      break;
652
1.51M
    }
653
1.51M
  }
654
11.1M
  assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
655
11.1M
         "can't cast prvalue to glvalue");
656
0
#endif
657
658
0
  diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
659
11.1M
  diagnoseZeroToNullptrConversion(Kind, E);
660
661
11.1M
  QualType ExprTy = Context.getCanonicalType(E->getType());
662
11.1M
  QualType TypeTy = Context.getCanonicalType(Ty);
663
664
11.1M
  if (ExprTy == TypeTy)
665
3.39M
    return E;
666
667
7.71M
  if (Kind == CK_ArrayToPointerDecay) {
668
    // C++1z [conv.array]: The temporary materialization conversion is applied.
669
    // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
670
247k
    if (getLangOpts().CPlusPlus && 
E->isPRValue()188k
) {
671
      // The temporary is an lvalue in C++98 and an xvalue otherwise.
672
56
      ExprResult Materialized = CreateMaterializeTemporaryExpr(
673
56
          E->getType(), E, !getLangOpts().CPlusPlus11);
674
56
      if (Materialized.isInvalid())
675
0
        return ExprError();
676
56
      E = Materialized.get();
677
56
    }
678
    // C17 6.7.1p6 footnote 124: The implementation can treat any register
679
    // declaration simply as an auto declaration. However, whether or not
680
    // addressable storage is actually used, the address of any part of an
681
    // object declared with storage-class specifier register cannot be
682
    // computed, either explicitly(by use of the unary & operator as discussed
683
    // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
684
    // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
685
    // array declared with storage-class specifier register is sizeof.
686
247k
    if (VK == VK_PRValue && !getLangOpts().CPlusPlus && 
!E->isPRValue()59.0k
) {
687
59.0k
      if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
688
9.37k
        if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
689
9.37k
          if (VD->getStorageClass() == SC_Register) {
690
9
            Diag(E->getExprLoc(), diag::err_typecheck_address_of)
691
9
                << /*register variable*/ 3 << E->getSourceRange();
692
9
            return ExprError();
693
9
          }
694
9.37k
        }
695
9.37k
      }
696
59.0k
    }
697
247k
  }
698
699
7.71M
  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
700
713k
    if (ImpCast->getCastKind() == Kind && 
(21.9k
!BasePath21.9k
||
BasePath->empty()483
)) {
701
21.7k
      ImpCast->setType(Ty);
702
21.7k
      ImpCast->setValueKind(VK);
703
21.7k
      return E;
704
21.7k
    }
705
713k
  }
706
707
7.68M
  return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
708
7.68M
                                  CurFPFeatureOverrides());
709
7.71M
}
710
711
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
712
/// to the conversion from scalar type ScalarTy to the Boolean type.
713
344k
CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
714
344k
  switch (ScalarTy->getScalarTypeKind()) {
715
196k
  case Type::STK_Bool: return CK_NoOp;
716
18.6k
  case Type::STK_CPointer: return CK_PointerToBoolean;
717
7
  case Type::STK_BlockPointer: return CK_PointerToBoolean;
718
163
  case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
719
111
  case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
720
128k
  case Type::STK_Integral: return CK_IntegralToBoolean;
721
1.51k
  case Type::STK_Floating: return CK_FloatingToBoolean;
722
15
  case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
723
1
  case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
724
0
  case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
725
344k
  }
726
0
  llvm_unreachable("unknown scalar type kind");
727
0
}
728
729
/// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
730
35.8k
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
731
35.8k
  if (D->getMostRecentDecl()->isUsed())
732
6.61k
    return true;
733
734
29.2k
  if (D->isExternallyVisible())
735
51
    return true;
736
737
29.2k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
738
    // If this is a function template and none of its specializations is used,
739
    // we should warn.
740
22.9k
    if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
741
1.98k
      for (const auto *Spec : Template->specializations())
742
86
        if (ShouldRemoveFromUnused(SemaRef, Spec))
743
56
          return true;
744
745
    // UnusedFileScopedDecls stores the first declaration.
746
    // The declaration may have become definition so check again.
747
22.9k
    const FunctionDecl *DeclToCheck;
748
22.9k
    if (FD->hasBody(DeclToCheck))
749
13.4k
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
750
751
    // Later redecls may add new information resulting in not having to warn,
752
    // so check again.
753
9.51k
    DeclToCheck = FD->getMostRecentDecl();
754
9.51k
    if (DeclToCheck != FD)
755
62
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
756
9.51k
  }
757
758
15.6k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
759
    // If a variable usable in constant expressions is referenced,
760
    // don't warn if it isn't used: if the value of a variable is required
761
    // for the computation of a constant expression, it doesn't make sense to
762
    // warn even if the variable isn't odr-used.  (isReferenced doesn't
763
    // precisely reflect that, but it's a decent approximation.)
764
6.20k
    if (VD->isReferenced() &&
765
6.20k
        
VD->mightBeUsableInConstantExpressions(SemaRef->Context)1.07k
)
766
990
      return true;
767
768
5.21k
    if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
769
      // If this is a variable template and none of its specializations is used,
770
      // we should warn.
771
233
      for (const auto *Spec : Template->specializations())
772
26
        if (ShouldRemoveFromUnused(SemaRef, Spec))
773
10
          return true;
774
775
    // UnusedFileScopedDecls stores the first declaration.
776
    // The declaration may have become definition so check again.
777
5.20k
    const VarDecl *DeclToCheck = VD->getDefinition();
778
5.20k
    if (DeclToCheck)
779
4.50k
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
780
781
    // Later redecls may add new information resulting in not having to warn,
782
    // so check again.
783
700
    DeclToCheck = VD->getMostRecentDecl();
784
700
    if (DeclToCheck != VD)
785
37
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
786
700
  }
787
788
10.1k
  return false;
789
15.6k
}
790
791
50
static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
792
50
  if (auto *FD = dyn_cast<FunctionDecl>(ND))
793
15
    return FD->isExternC();
794
35
  return cast<VarDecl>(ND)->isExternC();
795
50
}
796
797
/// Determine whether ND is an external-linkage function or variable whose
798
/// type has no linkage.
799
1.04M
bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
800
  // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
801
  // because we also want to catch the case where its type has VisibleNoLinkage,
802
  // which does not affect the linkage of VD.
803
1.04M
  return getLangOpts().CPlusPlus && 
VD->hasExternalFormalLinkage()423k
&&
804
1.04M
         
!isExternalFormalLinkage(VD->getType()->getLinkage())422k
&&
805
1.04M
         
!isFunctionOrVarDeclExternC(VD)50
;
806
1.04M
}
807
808
/// Obtains a sorted list of functions and variables that are undefined but
809
/// ODR-used.
810
void Sema::getUndefinedButUsed(
811
11.4k
    SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
812
131k
  for (const auto &UndefinedUse : UndefinedButUsed) {
813
131k
    NamedDecl *ND = UndefinedUse.first;
814
815
    // Ignore attributes that have become invalid.
816
131k
    if (ND->isInvalidDecl()) 
continue0
;
817
818
    // __attribute__((weakref)) is basically a definition.
819
131k
    if (ND->hasAttr<WeakRefAttr>()) 
continue0
;
820
821
131k
    if (isa<CXXDeductionGuideDecl>(ND))
822
5
      continue;
823
824
131k
    if (ND->hasAttr<DLLImportAttr>() || 
ND->hasAttr<DLLExportAttr>()131k
) {
825
      // An exported function will always be emitted when defined, so even if
826
      // the function is inline, it doesn't have to be emitted in this TU. An
827
      // imported function implies that it has been exported somewhere else.
828
244
      continue;
829
244
    }
830
831
130k
    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
832
130k
      if (FD->isDefined())
833
95.8k
        continue;
834
35.0k
      if (FD->isExternallyVisible() &&
835
35.0k
          
!isExternalWithNoLinkageType(FD)3.06k
&&
836
35.0k
          
!FD->getMostRecentDecl()->isInlined()3.06k
&&
837
35.0k
          
!FD->hasAttr<ExcludeFromExplicitInstantiationAttr>()6
)
838
6
        continue;
839
35.0k
      if (FD->getBuiltinID())
840
31.8k
        continue;
841
35.0k
    } else {
842
45
      auto *VD = cast<VarDecl>(ND);
843
45
      if (VD->hasDefinition() != VarDecl::DeclarationOnly)
844
26
        continue;
845
19
      if (VD->isExternallyVisible() &&
846
19
          
!isExternalWithNoLinkageType(VD)2
&&
847
19
          
!VD->getMostRecentDecl()->isInline()2
&&
848
19
          
!VD->hasAttr<ExcludeFromExplicitInstantiationAttr>()0
)
849
0
        continue;
850
851
      // Skip VarDecls that lack formal definitions but which we know are in
852
      // fact defined somewhere.
853
19
      if (VD->isKnownToBeDefined())
854
0
        continue;
855
19
    }
856
857
3.13k
    Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
858
3.13k
  }
859
11.4k
}
860
861
/// checkUndefinedButUsed - Check for undefined objects with internal linkage
862
/// or that are inline.
863
71.7k
static void checkUndefinedButUsed(Sema &S) {
864
71.7k
  if (S.UndefinedButUsed.empty()) 
return65.8k
;
865
866
  // Collect all the still-undefined entities with internal linkage.
867
5.90k
  SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
868
5.90k
  S.getUndefinedButUsed(Undefined);
869
5.90k
  if (Undefined.empty()) 
return5.68k
;
870
871
847
  
for (auto Undef : Undefined)220
{
872
847
    ValueDecl *VD = cast<ValueDecl>(Undef.first);
873
847
    SourceLocation UseLoc = Undef.second;
874
875
847
    if (S.isExternalWithNoLinkageType(VD)) {
876
      // C++ [basic.link]p8:
877
      //   A type without linkage shall not be used as the type of a variable
878
      //   or function with external linkage unless
879
      //    -- the entity has C language linkage
880
      //    -- the entity is not odr-used or is defined in the same TU
881
      //
882
      // As an extension, accept this in cases where the type is externally
883
      // visible, since the function or variable actually can be defined in
884
      // another translation unit in that case.
885
7
      S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
886
7
                                    ? 
diag::ext_undefined_internal_type3
887
7
                                    : 
diag::err_undefined_internal_type4
)
888
7
        << isa<VarDecl>(VD) << VD;
889
840
    } else if (!VD->isExternallyVisible()) {
890
      // FIXME: We can promote this to an error. The function or variable can't
891
      // be defined anywhere else, so the program must necessarily violate the
892
      // one definition rule.
893
616
      bool IsImplicitBase = false;
894
616
      if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
895
599
        auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
896
599
        if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
897
399
                          llvm::omp::TraitProperty::
898
399
                              implementation_extension_disable_implicit_base)) {
899
399
          const auto *Func = cast<FunctionDecl>(
900
399
              cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
901
399
          IsImplicitBase = BaseD->isImplicit() &&
902
399
                           
Func->getIdentifier()->isMangledOpenMPVariantName()398
;
903
399
        }
904
599
      }
905
616
      if (!S.getLangOpts().OpenMP || 
!IsImplicitBase400
)
906
218
        S.Diag(VD->getLocation(), diag::warn_undefined_internal)
907
218
            << isa<VarDecl>(VD) << VD;
908
616
    } else 
if (auto *224
FD224
= dyn_cast<FunctionDecl>(VD)) {
909
222
      (void)FD;
910
222
      assert(FD->getMostRecentDecl()->isInlined() &&
911
222
             "used object requires definition but isn't inline or internal?");
912
      // FIXME: This is ill-formed; we should reject.
913
0
      S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
914
222
    } else {
915
2
      assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
916
2
             "used var requires definition but isn't inline or internal?");
917
0
      S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
918
2
    }
919
847
    if (UseLoc.isValid())
920
846
      S.Diag(UseLoc, diag::note_used_here);
921
847
  }
922
923
220
  S.UndefinedButUsed.clear();
924
220
}
925
926
26.8M
void Sema::LoadExternalWeakUndeclaredIdentifiers() {
927
26.8M
  if (!ExternalSource)
928
26.3M
    return;
929
930
491k
  SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
931
491k
  ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
932
491k
  for (auto &WeakID : WeakIDs)
933
8
    (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
934
491k
}
935
936
937
typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
938
939
/// Returns true, if all methods and nested classes of the given
940
/// CXXRecordDecl are defined in this translation unit.
941
///
942
/// Should only be called from ActOnEndOfTranslationUnit so that all
943
/// definitions are actually read.
944
static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
945
104
                                            RecordCompleteMap &MNCComplete) {
946
104
  RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
947
104
  if (Cache != MNCComplete.end())
948
12
    return Cache->second;
949
92
  if (!RD->isCompleteDefinition())
950
6
    return false;
951
86
  bool Complete = true;
952
86
  for (DeclContext::decl_iterator I = RD->decls_begin(),
953
86
                                  E = RD->decls_end();
954
479
       I != E && 
Complete410
;
++I393
) {
955
393
    if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
956
79
      Complete = M->isDefined() || 
M->isDefaulted()11
||
957
79
                 
(11
M->isPure()11
&&
!isa<CXXDestructorDecl>(M)3
);
958
314
    else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
959
      // If the template function is marked as late template parsed at this
960
      // point, it has not been instantiated and therefore we have not
961
      // performed semantic analysis on it yet, so we cannot know if the type
962
      // can be considered complete.
963
4
      Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
964
4
                  
F->getTemplatedDecl()->isDefined()3
;
965
310
    else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
966
98
      if (R->isInjectedClassName())
967
86
        continue;
968
12
      if (R->hasDefinition())
969
6
        Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
970
6
                                                   MNCComplete);
971
6
      else
972
6
        Complete = false;
973
12
    }
974
393
  }
975
86
  MNCComplete[RD] = Complete;
976
86
  return Complete;
977
92
}
978
979
/// Returns true, if the given CXXRecordDecl is fully defined in this
980
/// translation unit, i.e. all methods are defined or pure virtual and all
981
/// friends, friend functions and nested classes are fully defined in this
982
/// translation unit.
983
///
984
/// Should only be called from ActOnEndOfTranslationUnit so that all
985
/// definitions are actually read.
986
static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
987
                                 RecordCompleteMap &RecordsComplete,
988
110
                                 RecordCompleteMap &MNCComplete) {
989
110
  RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
990
110
  if (Cache != RecordsComplete.end())
991
33
    return Cache->second;
992
77
  bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
993
77
  for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
994
77
                                      E = RD->friend_end();
995
107
       I != E && 
Complete39
;
++I30
) {
996
    // Check if friend classes and methods are complete.
997
30
    if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
998
      // Friend classes are available as the TypeSourceInfo of the FriendDecl.
999
21
      if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
1000
21
        Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
1001
0
      else
1002
0
        Complete = false;
1003
21
    } else {
1004
      // Friend functions are available through the NamedDecl of FriendDecl.
1005
9
      if (const FunctionDecl *FD =
1006
9
          dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
1007
6
        Complete = FD->isDefined();
1008
3
      else
1009
        // This is a template friend, give up.
1010
3
        Complete = false;
1011
9
    }
1012
30
  }
1013
77
  RecordsComplete[RD] = Complete;
1014
77
  return Complete;
1015
110
}
1016
1017
71.8k
void Sema::emitAndClearUnusedLocalTypedefWarnings() {
1018
71.8k
  if (ExternalSource)
1019
11.2k
    ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1020
11.2k
        UnusedLocalTypedefNameCandidates);
1021
71.8k
  for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
1022
254
    if (TD->isReferenced())
1023
16
      continue;
1024
238
    Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1025
238
        << isa<TypeAliasDecl>(TD) << TD->getDeclName();
1026
238
  }
1027
71.8k
  UnusedLocalTypedefNameCandidates.clear();
1028
71.8k
}
1029
1030
/// This is called before the very first declaration in the translation unit
1031
/// is parsed. Note that the ASTContext may have already injected some
1032
/// declarations.
1033
85.2k
void Sema::ActOnStartOfTranslationUnit() {
1034
85.2k
  if (getLangOpts().CPlusPlusModules &&
1035
85.2k
      
getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit3.82k
)
1036
14
    HandleStartOfHeaderUnit();
1037
85.1k
  else if (getLangOpts().ModulesTS &&
1038
85.1k
           
(139
getLangOpts().getCompilingModule() ==
1039
139
                LangOptions::CMK_ModuleInterface ||
1040
139
            
getLangOpts().getCompilingModule() == LangOptions::CMK_None96
)) {
1041
    // We start in an implied global module fragment.
1042
125
    SourceLocation StartOfTU =
1043
125
        SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1044
125
    ActOnGlobalModuleFragmentDecl(StartOfTU);
1045
125
    ModuleScopes.back().ImplicitGlobalModuleFragment = true;
1046
125
  }
1047
85.2k
}
1048
1049
80.4k
void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
1050
  // No explicit actions are required at the end of the global module fragment.
1051
80.4k
  if (Kind == TUFragmentKind::Global)
1052
116
    return;
1053
1054
  // Transfer late parsed template instantiations over to the pending template
1055
  // instantiation list. During normal compilation, the late template parser
1056
  // will be installed and instantiating these templates will succeed.
1057
  //
1058
  // If we are building a TU prefix for serialization, it is also safe to
1059
  // transfer these over, even though they are not parsed. The end of the TU
1060
  // should be outside of any eager template instantiation scope, so when this
1061
  // AST is deserialized, these templates will not be parsed until the end of
1062
  // the combined TU.
1063
80.3k
  PendingInstantiations.insert(PendingInstantiations.end(),
1064
80.3k
                               LateParsedInstantiations.begin(),
1065
80.3k
                               LateParsedInstantiations.end());
1066
80.3k
  LateParsedInstantiations.clear();
1067
1068
  // If DefinedUsedVTables ends up marking any virtual member functions it
1069
  // might lead to more pending template instantiations, which we then need
1070
  // to instantiate.
1071
80.3k
  DefineUsedVTables();
1072
1073
  // C++: Perform implicit template instantiations.
1074
  //
1075
  // FIXME: When we perform these implicit instantiations, we do not
1076
  // carefully keep track of the point of instantiation (C++ [temp.point]).
1077
  // This means that name lookup that occurs within the template
1078
  // instantiation will always happen at the end of the translation unit,
1079
  // so it will find some names that are not required to be found. This is
1080
  // valid, but we could do better by diagnosing if an instantiation uses a
1081
  // name that was not visible at its first point of instantiation.
1082
80.3k
  if (ExternalSource) {
1083
    // Load pending instantiations from the external source.
1084
12.0k
    SmallVector<PendingImplicitInstantiation, 4> Pending;
1085
12.0k
    ExternalSource->ReadPendingInstantiations(Pending);
1086
12.0k
    for (auto PII : Pending)
1087
3.70k
      if (auto Func = dyn_cast<FunctionDecl>(PII.first))
1088
3.64k
        Func->setInstantiationIsPending(true);
1089
12.0k
    PendingInstantiations.insert(PendingInstantiations.begin(),
1090
12.0k
                                 Pending.begin(), Pending.end());
1091
12.0k
  }
1092
1093
80.3k
  {
1094
80.3k
    llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1095
80.3k
    PerformPendingInstantiations();
1096
80.3k
  }
1097
1098
80.3k
  emitDeferredDiags();
1099
1100
80.3k
  assert(LateParsedInstantiations.empty() &&
1101
80.3k
         "end of TU template instantiation should not create more "
1102
80.3k
         "late-parsed templates");
1103
1104
  // Report diagnostics for uncorrected delayed typos. Ideally all of them
1105
  // should have been corrected by that time, but it is very hard to cover all
1106
  // cases in practice.
1107
3
  for (const auto &Typo : DelayedTypos) {
1108
    // We pass an empty TypoCorrection to indicate no correction was performed.
1109
3
    Typo.second.DiagHandler(TypoCorrection());
1110
3
  }
1111
80.3k
  DelayedTypos.clear();
1112
80.3k
}
1113
1114
/// ActOnEndOfTranslationUnit - This is called at the very end of the
1115
/// translation unit when EOF is reached and all but the top-level scope is
1116
/// popped.
1117
85.1k
void Sema::ActOnEndOfTranslationUnit() {
1118
85.1k
  assert(DelayedDiagnostics.getCurrentPool() == nullptr
1119
85.1k
         && "reached end of translation unit with a pool attached?");
1120
1121
  // If code completion is enabled, don't perform any end-of-translation-unit
1122
  // work.
1123
85.1k
  if (PP.isCodeCompletionEnabled())
1124
1.28k
    return;
1125
1126
  // Complete translation units and modules define vtables and perform implicit
1127
  // instantiations. PCH files do not.
1128
83.8k
  if (TUKind != TU_Prefix) {
1129
80.3k
    DiagnoseUseOfUnimplementedSelectors();
1130
1131
80.3k
    ActOnEndOfTranslationUnitFragment(
1132
80.3k
        !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1133
294
                                     Module::PrivateModuleFragment
1134
80.3k
            ? 
TUFragmentKind::Private10
1135
80.3k
            : 
TUFragmentKind::Normal80.3k
);
1136
1137
80.3k
    if (LateTemplateParserCleanup)
1138
0
      LateTemplateParserCleanup(OpaqueParser);
1139
1140
80.3k
    CheckDelayedMemberExceptionSpecs();
1141
80.3k
  } else {
1142
    // If we are building a TU prefix for serialization, it is safe to transfer
1143
    // these over, even though they are not parsed. The end of the TU should be
1144
    // outside of any eager template instantiation scope, so when this AST is
1145
    // deserialized, these templates will not be parsed until the end of the
1146
    // combined TU.
1147
3.50k
    PendingInstantiations.insert(PendingInstantiations.end(),
1148
3.50k
                                 LateParsedInstantiations.begin(),
1149
3.50k
                                 LateParsedInstantiations.end());
1150
3.50k
    LateParsedInstantiations.clear();
1151
1152
3.50k
    if (LangOpts.PCHInstantiateTemplates) {
1153
56
      llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1154
56
      PerformPendingInstantiations();
1155
56
    }
1156
3.50k
  }
1157
1158
83.8k
  DiagnoseUnterminatedPragmaAlignPack();
1159
83.8k
  DiagnoseUnterminatedPragmaAttribute();
1160
1161
  // All delayed member exception specs should be checked or we end up accepting
1162
  // incompatible declarations.
1163
83.8k
  assert(DelayedOverridingExceptionSpecChecks.empty());
1164
0
  assert(DelayedEquivalentExceptionSpecChecks.empty());
1165
1166
  // All dllexport classes should have been processed already.
1167
0
  assert(DelayedDllExportClasses.empty());
1168
0
  assert(DelayedDllExportMemberFunctions.empty());
1169
1170
  // Remove file scoped decls that turned out to be used.
1171
0
  UnusedFileScopedDecls.erase(
1172
83.8k
      std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1173
83.8k
                     UnusedFileScopedDecls.end(),
1174
83.8k
                     [this](const DeclaratorDecl *DD) {
1175
24.5k
                       return ShouldRemoveFromUnused(this, DD);
1176
24.5k
                     }),
1177
83.8k
      UnusedFileScopedDecls.end());
1178
1179
83.8k
  if (TUKind == TU_Prefix) {
1180
    // Translation unit prefixes don't need any of the checking below.
1181
3.50k
    if (!PP.isIncrementalProcessingEnabled())
1182
3.50k
      TUScope = nullptr;
1183
3.50k
    return;
1184
3.50k
  }
1185
1186
  // Check for #pragma weak identifiers that were never declared
1187
80.3k
  LoadExternalWeakUndeclaredIdentifiers();
1188
80.3k
  for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
1189
90
    if (WeakIDs.second.empty())
1190
72
      continue;
1191
1192
18
    Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
1193
18
                                      LookupOrdinaryName);
1194
18
    if (PrevDecl != nullptr &&
1195
18
        
!(6
isa<FunctionDecl>(PrevDecl)6
||
isa<VarDecl>(PrevDecl)4
))
1196
3
      for (const auto &WI : WeakIDs.second)
1197
3
        Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
1198
3
            << "'weak'" << ExpectedVariableOrFunction;
1199
15
    else
1200
15
      for (const auto &WI : WeakIDs.second)
1201
15
        Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
1202
15
            << WeakIDs.first;
1203
18
  }
1204
1205
80.3k
  if (LangOpts.CPlusPlus11 &&
1206
80.3k
      
!Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation())55.7k
)
1207
55.7k
    CheckDelegatingCtorCycles();
1208
1209
80.3k
  if (!Diags.hasErrorOccurred()) {
1210
71.7k
    if (ExternalSource)
1211
11.1k
      ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1212
71.7k
    checkUndefinedButUsed(*this);
1213
71.7k
  }
1214
1215
  // A global-module-fragment is only permitted within a module unit.
1216
80.3k
  bool DiagnosedMissingModuleDeclaration = false;
1217
80.3k
  if (!ModuleScopes.empty() &&
1218
80.3k
      
ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment294
&&
1219
80.3k
      
!ModuleScopes.back().ImplicitGlobalModuleFragment51
) {
1220
3
    Diag(ModuleScopes.back().BeginLoc,
1221
3
         diag::err_module_declaration_missing_after_global_module_introducer);
1222
3
    DiagnosedMissingModuleDeclaration = true;
1223
3
  }
1224
1225
80.3k
  if (TUKind == TU_Module) {
1226
    // If we are building a module interface unit, we need to have seen the
1227
    // module declaration by now.
1228
2.24k
    if (getLangOpts().getCompilingModule() ==
1229
2.24k
            LangOptions::CMK_ModuleInterface &&
1230
2.24k
        
(123
ModuleScopes.empty()123
||
1231
123
         !ModuleScopes.back().Module->isModulePurview()) &&
1232
2.24k
        
!DiagnosedMissingModuleDeclaration1
) {
1233
      // FIXME: Make a better guess as to where to put the module declaration.
1234
1
      Diag(getSourceManager().getLocForStartOfFile(
1235
1
               getSourceManager().getMainFileID()),
1236
1
           diag::err_module_declaration_missing);
1237
1
    }
1238
1239
    // If we are building a module, resolve all of the exported declarations
1240
    // now.
1241
2.24k
    if (Module *CurrentModule = PP.getCurrentModule()) {
1242
2.17k
      ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
1243
1244
2.17k
      SmallVector<Module *, 2> Stack;
1245
2.17k
      Stack.push_back(CurrentModule);
1246
28.5k
      while (!Stack.empty()) {
1247
26.4k
        Module *Mod = Stack.pop_back_val();
1248
1249
        // Resolve the exported declarations and conflicts.
1250
        // FIXME: Actually complain, once we figure out how to teach the
1251
        // diagnostic client to deal with complaints in the module map at this
1252
        // point.
1253
26.4k
        ModMap.resolveExports(Mod, /*Complain=*/false);
1254
26.4k
        ModMap.resolveUses(Mod, /*Complain=*/false);
1255
26.4k
        ModMap.resolveConflicts(Mod, /*Complain=*/false);
1256
1257
        // Queue the submodules, so their exports will also be resolved.
1258
26.4k
        Stack.append(Mod->submodule_begin(), Mod->submodule_end());
1259
26.4k
      }
1260
2.17k
    }
1261
1262
    // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1263
    // modules when they are built, not every time they are used.
1264
2.24k
    emitAndClearUnusedLocalTypedefWarnings();
1265
2.24k
  }
1266
1267
  // C99 6.9.2p2:
1268
  //   A declaration of an identifier for an object that has file
1269
  //   scope without an initializer, and without a storage-class
1270
  //   specifier or with the storage-class specifier static,
1271
  //   constitutes a tentative definition. If a translation unit
1272
  //   contains one or more tentative definitions for an identifier,
1273
  //   and the translation unit contains no external definition for
1274
  //   that identifier, then the behavior is exactly as if the
1275
  //   translation unit contains a file scope declaration of that
1276
  //   identifier, with the composite type as of the end of the
1277
  //   translation unit, with an initializer equal to 0.
1278
80.3k
  llvm::SmallSet<VarDecl *, 32> Seen;
1279
80.3k
  for (TentativeDefinitionsType::iterator
1280
80.3k
            T = TentativeDefinitions.begin(ExternalSource),
1281
80.3k
         TEnd = TentativeDefinitions.end();
1282
90.5k
       T != TEnd; 
++T10.2k
) {
1283
10.2k
    VarDecl *VD = (*T)->getActingDefinition();
1284
1285
    // If the tentative definition was completed, getActingDefinition() returns
1286
    // null. If we've already seen this variable before, insert()'s second
1287
    // return value is false.
1288
10.2k
    if (!VD || 
VD->isInvalidDecl()10.1k
||
!Seen.insert(VD).second10.1k
)
1289
236
      continue;
1290
1291
9.98k
    if (const IncompleteArrayType *ArrayT
1292
9.98k
        = Context.getAsIncompleteArrayType(VD->getType())) {
1293
      // Set the length of the array to 1 (C99 6.9.2p5).
1294
28
      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1295
28
      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1296
28
      QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One,
1297
28
                                                nullptr, ArrayType::Normal, 0);
1298
28
      VD->setType(T);
1299
9.95k
    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1300
9.95k
                                   diag::err_tentative_def_incomplete_type))
1301
15
      VD->setInvalidDecl();
1302
1303
    // No initialization is performed for a tentative definition.
1304
9.98k
    CheckCompleteVariableDeclaration(VD);
1305
1306
    // Notify the consumer that we've completed a tentative definition.
1307
9.98k
    if (!VD->isInvalidDecl())
1308
9.96k
      Consumer.CompleteTentativeDefinition(VD);
1309
9.98k
  }
1310
1311
80.3k
  for (auto D : ExternalDeclarations) {
1312
12
    if (!D || D->isInvalidDecl() || D->getPreviousDecl() || 
!D->isUsed()11
)
1313
5
      continue;
1314
1315
7
    Consumer.CompleteExternalDeclaration(D);
1316
7
  }
1317
1318
  // If there were errors, disable 'unused' warnings since they will mostly be
1319
  // noise. Don't warn for a use from a module: either we should warn on all
1320
  // file-scope declarations in modules or not at all, but whether the
1321
  // declaration is used is immaterial.
1322
80.3k
  if (!Diags.hasErrorOccurred() && 
TUKind != TU_Module71.7k
) {
1323
    // Output warning for unused file scoped decls.
1324
69.6k
    for (UnusedFileScopedDeclsType::iterator
1325
69.6k
           I = UnusedFileScopedDecls.begin(ExternalSource),
1326
80.8k
           E = UnusedFileScopedDecls.end(); I != E; 
++I11.2k
) {
1327
11.2k
      if (ShouldRemoveFromUnused(this, *I))
1328
10
        continue;
1329
1330
11.2k
      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1331
9.62k
        const FunctionDecl *DiagD;
1332
9.62k
        if (!FD->hasBody(DiagD))
1333
4.57k
          DiagD = FD;
1334
9.62k
        if (DiagD->isDeleted())
1335
1
          continue; // Deleted functions are supposed to be unused.
1336
9.62k
        if (DiagD->isReferenced()) {
1337
420
          if (isa<CXXMethodDecl>(DiagD))
1338
5
            Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1339
5
                << DiagD;
1340
415
          else {
1341
415
            if (FD->getStorageClass() == SC_Static &&
1342
415
                
!FD->isInlineSpecified()412
&&
1343
415
                !SourceMgr.isInMainFile(
1344
404
                   SourceMgr.getExpansionLoc(FD->getLocation())))
1345
169
              Diag(DiagD->getLocation(),
1346
169
                   diag::warn_unneeded_static_internal_decl)
1347
169
                  << DiagD;
1348
246
            else
1349
246
              Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1350
246
                  << /*function*/ 0 << DiagD;
1351
415
          }
1352
9.20k
        } else {
1353
9.20k
          if (FD->getDescribedFunctionTemplate())
1354
947
            Diag(DiagD->getLocation(), diag::warn_unused_template)
1355
947
                << /*function*/ 0 << DiagD;
1356
8.25k
          else
1357
8.25k
            Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1358
8.25k
                                           ? 
diag::warn_unused_member_function166
1359
8.25k
                                           : 
diag::warn_unused_function8.09k
)
1360
8.25k
                << DiagD;
1361
9.20k
        }
1362
9.62k
      } else {
1363
1.59k
        const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1364
1.59k
        if (!DiagD)
1365
307
          DiagD = cast<VarDecl>(*I);
1366
1.59k
        if (DiagD->isReferenced()) {
1367
13
          Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1368
13
              << /*variable*/ 1 << DiagD;
1369
1.58k
        } else if (DiagD->getType().isConstQualified()) {
1370
534
          const SourceManager &SM = SourceMgr;
1371
534
          if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1372
534
              !PP.getLangOpts().IsHeaderFile)
1373
532
            Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1374
532
                << DiagD;
1375
1.04k
        } else {
1376
1.04k
          if (DiagD->getDescribedVarTemplate())
1377
103
            Diag(DiagD->getLocation(), diag::warn_unused_template)
1378
103
                << /*variable*/ 1 << DiagD;
1379
946
          else
1380
946
            Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD;
1381
1.04k
        }
1382
1.59k
      }
1383
11.2k
    }
1384
1385
69.6k
    emitAndClearUnusedLocalTypedefWarnings();
1386
69.6k
  }
1387
1388
80.3k
  if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1389
    // FIXME: Load additional unused private field candidates from the external
1390
    // source.
1391
2.21k
    RecordCompleteMap RecordsComplete;
1392
2.21k
    RecordCompleteMap MNCComplete;
1393
2.21k
    for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
1394
2.32k
         E = UnusedPrivateFields.end(); I != E; 
++I116
) {
1395
116
      const NamedDecl *D = *I;
1396
116
      const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1397
116
      if (RD && !RD->isUnion() &&
1398
116
          
IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)110
) {
1399
71
        Diag(D->getLocation(), diag::warn_unused_private_field)
1400
71
              << D->getDeclName();
1401
71
      }
1402
116
    }
1403
2.21k
  }
1404
1405
80.3k
  if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1406
79.8k
    if (ExternalSource)
1407
11.9k
      ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1408
79.8k
    for (const auto &DeletedFieldInfo : DeleteExprs) {
1409
591
      for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1410
591
        AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1411
591
                                  DeleteExprLoc.second);
1412
591
      }
1413
386
    }
1414
79.8k
  }
1415
1416
  // Check we've noticed that we're no longer parsing the initializer for every
1417
  // variable. If we miss cases, then at best we have a performance issue and
1418
  // at worst a rejects-valid bug.
1419
80.3k
  assert(ParsingInitForAutoVars.empty() &&
1420
80.3k
         "Didn't unmark var as having its initializer parsed");
1421
1422
80.3k
  if (!PP.isIncrementalProcessingEnabled())
1423
80.3k
    TUScope = nullptr;
1424
80.3k
}
1425
1426
1427
//===----------------------------------------------------------------------===//
1428
// Helper functions.
1429
//===----------------------------------------------------------------------===//
1430
1431
121M
DeclContext *Sema::getFunctionLevelDeclContext(bool AllowLambda) {
1432
121M
  DeclContext *DC = CurContext;
1433
1434
124M
  while (true) {
1435
124M
    if (isa<BlockDecl>(DC) || 
isa<EnumDecl>(DC)124M
||
isa<CapturedDecl>(DC)124M
||
1436
124M
        
isa<RequiresExprBodyDecl>(DC)121M
) {
1437
3.39M
      DC = DC->getParent();
1438
121M
    } else if (!AllowLambda && 
isa<CXXMethodDecl>(DC)121M
&&
1439
121M
               
cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call10.3M
&&
1440
121M
               
cast<CXXRecordDecl>(DC->getParent())->isLambda()627k
) {
1441
77.5k
      DC = DC->getParent()->getParent();
1442
121M
    } else break;
1443
124M
  }
1444
1445
121M
  return DC;
1446
121M
}
1447
1448
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
1449
/// to the function decl for the function being parsed.  If we're currently
1450
/// in a 'block', this returns the containing context.
1451
85.6M
FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) {
1452
85.6M
  DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
1453
85.6M
  return dyn_cast<FunctionDecl>(DC);
1454
85.6M
}
1455
1456
29.1M
ObjCMethodDecl *Sema::getCurMethodDecl() {
1457
29.1M
  DeclContext *DC = getFunctionLevelDeclContext();
1458
30.4M
  while (isa<RecordDecl>(DC))
1459
1.25M
    DC = DC->getParent();
1460
29.1M
  return dyn_cast<ObjCMethodDecl>(DC);
1461
29.1M
}
1462
1463
1.92M
NamedDecl *Sema::getCurFunctionOrMethodDecl() {
1464
1.92M
  DeclContext *DC = getFunctionLevelDeclContext();
1465
1.92M
  if (isa<ObjCMethodDecl>(DC) || 
isa<FunctionDecl>(DC)1.92M
)
1466
1.86M
    return cast<NamedDecl>(DC);
1467
64.3k
  return nullptr;
1468
1.92M
}
1469
1470
724k
LangAS Sema::getDefaultCXXMethodAddrSpace() const {
1471
724k
  if (getLangOpts().OpenCL)
1472
401
    return getASTContext().getDefaultOpenCLPointeeAddrSpace();
1473
723k
  return LangAS::Default;
1474
724k
}
1475
1476
2.91M
void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1477
  // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1478
  // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1479
  // been made more painfully obvious by the refactor that introduced this
1480
  // function, but it is possible that the incoming argument can be
1481
  // eliminated. If it truly cannot be (for example, there is some reentrancy
1482
  // issue I am not seeing yet), then there should at least be a clarifying
1483
  // comment somewhere.
1484
2.91M
  if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
1485
174k
    switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1486
174k
              Diags.getCurrentDiagID())) {
1487
101
    case DiagnosticIDs::SFINAE_Report:
1488
      // We'll report the diagnostic below.
1489
101
      break;
1490
1491
135k
    case DiagnosticIDs::SFINAE_SubstitutionFailure:
1492
      // Count this failure so that we know that template argument deduction
1493
      // has failed.
1494
135k
      ++NumSFINAEErrors;
1495
1496
      // Make a copy of this suppressed diagnostic and store it with the
1497
      // template-deduction information.
1498
135k
      if (*Info && 
!(*Info)->hasSFINAEDiagnostic()124k
) {
1499
122k
        Diagnostic DiagInfo(&Diags);
1500
122k
        (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1501
122k
                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1502
122k
      }
1503
1504
135k
      Diags.setLastDiagnosticIgnored(true);
1505
135k
      Diags.Clear();
1506
135k
      return;
1507
1508
96
    case DiagnosticIDs::SFINAE_AccessControl: {
1509
      // Per C++ Core Issue 1170, access control is part of SFINAE.
1510
      // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1511
      // make access control a part of SFINAE for the purposes of checking
1512
      // type traits.
1513
96
      if (!AccessCheckingSFINAE && 
!getLangOpts().CPlusPlus1117
)
1514
1
        break;
1515
1516
95
      SourceLocation Loc = Diags.getCurrentDiagLoc();
1517
1518
      // Suppress this diagnostic.
1519
95
      ++NumSFINAEErrors;
1520
1521
      // Make a copy of this suppressed diagnostic and store it with the
1522
      // template-deduction information.
1523
95
      if (*Info && 
!(*Info)->hasSFINAEDiagnostic()15
) {
1524
14
        Diagnostic DiagInfo(&Diags);
1525
14
        (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1526
14
                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1527
14
      }
1528
1529
95
      Diags.setLastDiagnosticIgnored(true);
1530
95
      Diags.Clear();
1531
1532
      // Now the diagnostic state is clear, produce a C++98 compatibility
1533
      // warning.
1534
95
      Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1535
1536
      // The last diagnostic which Sema produced was ignored. Suppress any
1537
      // notes attached to it.
1538
95
      Diags.setLastDiagnosticIgnored(true);
1539
95
      return;
1540
96
    }
1541
1542
39.2k
    case DiagnosticIDs::SFINAE_Suppress:
1543
      // Make a copy of this suppressed diagnostic and store it with the
1544
      // template-deduction information;
1545
39.2k
      if (*Info) {
1546
34.5k
        Diagnostic DiagInfo(&Diags);
1547
34.5k
        (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1548
34.5k
                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1549
34.5k
      }
1550
1551
      // Suppress this diagnostic.
1552
39.2k
      Diags.setLastDiagnosticIgnored(true);
1553
39.2k
      Diags.Clear();
1554
39.2k
      return;
1555
174k
    }
1556
174k
  }
1557
1558
  // Copy the diagnostic printing policy over the ASTContext printing policy.
1559
  // TODO: Stop doing that.  See: https://reviews.llvm.org/D45093#1090292
1560
2.74M
  Context.setPrintingPolicy(getPrintingPolicy());
1561
1562
  // Emit the diagnostic.
1563
2.74M
  if (!Diags.EmitCurrentDiagnostic())
1564
2.46M
    return;
1565
1566
  // If this is not a note, and we're in a template instantiation
1567
  // that is different from the last template instantiation where
1568
  // we emitted an error, print a template instantiation
1569
  // backtrace.
1570
275k
  if (!DiagnosticIDs::isBuiltinNote(DiagID))
1571
183k
    PrintContextStack();
1572
275k
}
1573
1574
Sema::SemaDiagnosticBuilder
1575
92.7k
Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) {
1576
92.7k
  return Diag(Loc, PD.getDiagID(), DeferHint) << PD;
1577
92.7k
}
1578
1579
11.0M
bool Sema::hasUncompilableErrorOccurred() const {
1580
11.0M
  if (getDiagnostics().hasUncompilableErrorOccurred())
1581
221k
    return true;
1582
10.8M
  auto *FD = dyn_cast<FunctionDecl>(CurContext);
1583
10.8M
  if (!FD)
1584
3.61M
    return false;
1585
7.25M
  auto Loc = DeviceDeferredDiags.find(FD);
1586
7.25M
  if (Loc == DeviceDeferredDiags.end())
1587
7.25M
    return false;
1588
185
  for (auto PDAt : Loc->second) {
1589
185
    if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
1590
185
      return true;
1591
185
  }
1592
0
  return false;
1593
185
}
1594
1595
// Print notes showing how we can reach FD starting from an a priori
1596
// known-callable function.
1597
146
static void emitCallStackNotes(Sema &S, FunctionDecl *FD) {
1598
146
  auto FnIt = S.DeviceKnownEmittedFns.find(FD);
1599
264
  while (FnIt != S.DeviceKnownEmittedFns.end()) {
1600
    // Respect error limit.
1601
119
    if (S.Diags.hasFatalErrorOccurred())
1602
1
      return;
1603
118
    DiagnosticBuilder Builder(
1604
118
        S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1605
118
    Builder << FnIt->second.FD;
1606
118
    FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
1607
118
  }
1608
146
}
1609
1610
namespace {
1611
1612
/// Helper class that emits deferred diagnostic messages if an entity directly
1613
/// or indirectly using the function that causes the deferred diagnostic
1614
/// messages is known to be emitted.
1615
///
1616
/// During parsing of AST, certain diagnostic messages are recorded as deferred
1617
/// diagnostics since it is unknown whether the functions containing such
1618
/// diagnostics will be emitted. A list of potentially emitted functions and
1619
/// variables that may potentially trigger emission of functions are also
1620
/// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1621
/// by each function to emit deferred diagnostics.
1622
///
1623
/// During the visit, certain OpenMP directives or initializer of variables
1624
/// with certain OpenMP attributes will cause subsequent visiting of any
1625
/// functions enter a state which is called OpenMP device context in this
1626
/// implementation. The state is exited when the directive or initializer is
1627
/// exited. This state can change the emission states of subsequent uses
1628
/// of functions.
1629
///
1630
/// Conceptually the functions or variables to be visited form a use graph
1631
/// where the parent node uses the child node. At any point of the visit,
1632
/// the tree nodes traversed from the tree root to the current node form a use
1633
/// stack. The emission state of the current node depends on two factors:
1634
///    1. the emission state of the root node
1635
///    2. whether the current node is in OpenMP device context
1636
/// If the function is decided to be emitted, its contained deferred diagnostics
1637
/// are emitted, together with the information about the use stack.
1638
///
1639
class DeferredDiagnosticsEmitter
1640
    : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1641
public:
1642
  typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
1643
1644
  // Whether the function is already in the current use-path.
1645
  llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
1646
1647
  // The current use-path.
1648
  llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
1649
1650
  // Whether the visiting of the function has been done. Done[0] is for the
1651
  // case not in OpenMP device context. Done[1] is for the case in OpenMP
1652
  // device context. We need two sets because diagnostics emission may be
1653
  // different depending on whether it is in OpenMP device context.
1654
  llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
1655
1656
  // Emission state of the root node of the current use graph.
1657
  bool ShouldEmitRootNode;
1658
1659
  // Current OpenMP device context level. It is initialized to 0 and each
1660
  // entering of device context increases it by 1 and each exit decreases
1661
  // it by 1. Non-zero value indicates it is currently in device context.
1662
  unsigned InOMPDeviceContext;
1663
1664
  DeferredDiagnosticsEmitter(Sema &S)
1665
4.64k
      : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1666
1667
557
  bool shouldVisitDiscardedStmt() const { return false; }
1668
1669
8.89k
  void VisitOMPTargetDirective(OMPTargetDirective *Node) {
1670
8.89k
    ++InOMPDeviceContext;
1671
8.89k
    Inherited::VisitOMPTargetDirective(Node);
1672
8.89k
    --InOMPDeviceContext;
1673
8.89k
  }
1674
1675
309k
  void visitUsedDecl(SourceLocation Loc, Decl *D) {
1676
309k
    if (isa<VarDecl>(D))
1677
213k
      return;
1678
96.3k
    if (auto *FD = dyn_cast<FunctionDecl>(D))
1679
35.2k
      checkFunc(Loc, FD);
1680
61.1k
    else
1681
61.1k
      Inherited::visitUsedDecl(Loc, D);
1682
96.3k
  }
1683
1684
1.83k
  void checkVar(VarDecl *VD) {
1685
1.83k
    assert(VD->isFileVarDecl() &&
1686
1.83k
           "Should only check file-scope variables");
1687
1.83k
    if (auto *Init = VD->getInit()) {
1688
1.83k
      auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
1689
1.83k
      bool IsDev = DevTy && 
(169
*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost169
||
1690
169
                             *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
1691
1.83k
      if (IsDev)
1692
169
        ++InOMPDeviceContext;
1693
1.83k
      this->Visit(Init);
1694
1.83k
      if (IsDev)
1695
169
        --InOMPDeviceContext;
1696
1.83k
    }
1697
1.83k
  }
1698
1699
66.8k
  void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
1700
66.8k
    auto &Done = DoneMap[InOMPDeviceContext > 0 ? 
13.87k
:
062.9k
];
1701
66.8k
    FunctionDecl *Caller = UsePath.empty() ? 
nullptr35.6k
:
UsePath.back()31.2k
;
1702
66.8k
    if ((!ShouldEmitRootNode && 
!S.getLangOpts().OpenMP25.1k
&&
!Caller293
) ||
1703
66.8k
        
S.shouldIgnoreInHostDeviceCheck(FD)66.5k
||
InUsePath.count(FD)66.5k
)
1704
441
      return;
1705
    // Finalize analysis of OpenMP-specific constructs.
1706
66.4k
    if (Caller && 
S.LangOpts.OpenMP31.0k
&&
UsePath.size() == 130.7k
&&
1707
66.4k
        
(26.2k
ShouldEmitRootNode26.2k
||
InOMPDeviceContext11.8k
))
1708
14.5k
      S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
1709
66.4k
    if (Caller)
1710
31.0k
      S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
1711
    // Always emit deferred diagnostics for the direct users. This does not
1712
    // lead to explosion of diagnostics since each user is visited at most
1713
    // twice.
1714
66.4k
    if (ShouldEmitRootNode || 
InOMPDeviceContext24.8k
)
1715
43.3k
      emitDeferredDiags(FD, Caller);
1716
    // Do not revisit a function if the function body has been completely
1717
    // visited before.
1718
66.4k
    if (!Done.insert(FD).second)
1719
23.8k
      return;
1720
42.5k
    InUsePath.insert(FD);
1721
42.5k
    UsePath.push_back(FD);
1722
42.5k
    if (auto *S = FD->getBody()) {
1723
35.5k
      this->Visit(S);
1724
35.5k
    }
1725
42.5k
    UsePath.pop_back();
1726
42.5k
    InUsePath.erase(FD);
1727
42.5k
  }
1728
1729
33.4k
  void checkRecordedDecl(Decl *D) {
1730
33.4k
    if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1731
31.6k
      ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
1732
31.6k
                           Sema::FunctionEmissionStatus::Emitted;
1733
31.6k
      checkFunc(SourceLocation(), FD);
1734
31.6k
    } else
1735
1.83k
      checkVar(cast<VarDecl>(D));
1736
33.4k
  }
1737
1738
  // Emit any deferred diagnostics for FD
1739
43.3k
  void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
1740
43.3k
    auto It = S.DeviceDeferredDiags.find(FD);
1741
43.3k
    if (It == S.DeviceDeferredDiags.end())
1742
43.2k
      return;
1743
92
    bool HasWarningOrError = false;
1744
92
    bool FirstDiag = true;
1745
225
    for (PartialDiagnosticAt &PDAt : It->second) {
1746
      // Respect error limit.
1747
225
      if (S.Diags.hasFatalErrorOccurred())
1748
1
        return;
1749
224
      const SourceLocation &Loc = PDAt.first;
1750
224
      const PartialDiagnostic &PD = PDAt.second;
1751
224
      HasWarningOrError |=
1752
224
          S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
1753
224
          DiagnosticsEngine::Warning;
1754
224
      {
1755
224
        DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
1756
224
        PD.Emit(Builder);
1757
224
      }
1758
      // Emit the note on the first diagnostic in case too many diagnostics
1759
      // cause the note not emitted.
1760
224
      if (FirstDiag && 
HasWarningOrError91
&&
ShowCallStack86
) {
1761
83
        emitCallStackNotes(S, FD);
1762
83
        FirstDiag = false;
1763
83
      }
1764
224
    }
1765
92
  }
1766
};
1767
} // namespace
1768
1769
80.3k
void Sema::emitDeferredDiags() {
1770
80.3k
  if (ExternalSource)
1771
12.0k
    ExternalSource->ReadDeclsToCheckForDeferredDiags(
1772
12.0k
        DeclsToCheckForDeferredDiags);
1773
1774
80.3k
  if ((DeviceDeferredDiags.empty() && 
!LangOpts.OpenMP80.2k
) ||
1775
80.3k
      
DeclsToCheckForDeferredDiags.empty()9.33k
)
1776
75.7k
    return;
1777
1778
4.64k
  DeferredDiagnosticsEmitter DDE(*this);
1779
4.64k
  for (auto D : DeclsToCheckForDeferredDiags)
1780
33.4k
    DDE.checkRecordedDecl(D);
1781
4.64k
}
1782
1783
// In CUDA, there are some constructs which may appear in semantically-valid
1784
// code, but trigger errors if we ever generate code for the function in which
1785
// they appear.  Essentially every construct you're not allowed to use on the
1786
// device falls into this category, because you are allowed to use these
1787
// constructs in a __host__ __device__ function, but only if that function is
1788
// never codegen'ed on the device.
1789
//
1790
// To handle semantic checking for these constructs, we keep track of the set of
1791
// functions we know will be emitted, either because we could tell a priori that
1792
// they would be emitted, or because they were transitively called by a
1793
// known-emitted function.
1794
//
1795
// We also keep a partial call graph of which not-known-emitted functions call
1796
// which other not-known-emitted functions.
1797
//
1798
// When we see something which is illegal if the current function is emitted
1799
// (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1800
// CheckCUDACall), we first check if the current function is known-emitted.  If
1801
// so, we immediately output the diagnostic.
1802
//
1803
// Otherwise, we "defer" the diagnostic.  It sits in Sema::DeviceDeferredDiags
1804
// until we discover that the function is known-emitted, at which point we take
1805
// it out of this map and emit the diagnostic.
1806
1807
Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
1808
                                                   unsigned DiagID,
1809
                                                   FunctionDecl *Fn, Sema &S)
1810
    : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
1811
2.92M
      ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
1812
2.92M
  switch (K) {
1813
119
  case K_Nop:
1814
119
    break;
1815
2.91M
  case K_Immediate:
1816
2.91M
  case K_ImmediateWithCallStack:
1817
2.91M
    ImmediateDiag.emplace(
1818
2.91M
        ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
1819
2.91M
    break;
1820
555
  case K_Deferred:
1821
555
    assert(Fn && "Must have a function to attach the deferred diag to.");
1822
0
    auto &Diags = S.DeviceDeferredDiags[Fn];
1823
555
    PartialDiagId.emplace(Diags.size());
1824
555
    Diags.emplace_back(Loc, S.PDiag(DiagID));
1825
555
    break;
1826
2.92M
  }
1827
2.92M
}
1828
1829
Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
1830
    : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
1831
      ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
1832
18
      PartialDiagId(D.PartialDiagId) {
1833
  // Clean the previous diagnostics.
1834
18
  D.ShowCallStack = false;
1835
18
  D.ImmediateDiag.reset();
1836
18
  D.PartialDiagId.reset();
1837
18
}
1838
1839
3.01M
Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
1840
3.01M
  if (ImmediateDiag) {
1841
    // Emit our diagnostic and, if it was a warning or error, output a callstack
1842
    // if Fn isn't a priori known-emitted.
1843
3.01M
    bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
1844
3.01M
                                DiagID, Loc) >= DiagnosticsEngine::Warning;
1845
3.01M
    ImmediateDiag.reset(); // Emit the immediate diag.
1846
3.01M
    if (IsWarningOrError && 
ShowCallStack349k
)
1847
63
      emitCallStackNotes(S, Fn);
1848
3.01M
  } else {
1849
885
    assert((!PartialDiagId || ShowCallStack) &&
1850
885
           "Must always show call stack for deferred diags.");
1851
885
  }
1852
3.01M
}
1853
1854
Sema::SemaDiagnosticBuilder
1855
813
Sema::targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD) {
1856
813
  FD = FD ? 
FD372
:
getCurFunctionDecl()441
;
1857
813
  if (LangOpts.OpenMP)
1858
355
    return LangOpts.OpenMPIsDevice ? 
diagIfOpenMPDeviceCode(Loc, DiagID, FD)348
1859
355
                                   : 
diagIfOpenMPHostCode(Loc, DiagID, FD)7
;
1860
458
  if (getLangOpts().CUDA)
1861
70
    return getLangOpts().CUDAIsDevice ? 
CUDADiagIfDeviceCode(Loc, DiagID)69
1862
70
                                      : 
CUDADiagIfHostCode(Loc, DiagID)1
;
1863
1864
388
  if (getLangOpts().SYCLIsDevice)
1865
122
    return SYCLDiagIfDeviceCode(Loc, DiagID);
1866
1867
266
  return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,
1868
266
                               FD, *this);
1869
388
}
1870
1871
Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID,
1872
2.91M
                                       bool DeferHint) {
1873
2.91M
  bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID);
1874
2.91M
  bool ShouldDefer = getLangOpts().CUDA && 
LangOpts.GPUDeferDiag5.47k
&&
1875
2.91M
                     
DiagnosticIDs::isDeferrable(DiagID)135
&&
1876
2.91M
                     
(60
DeferHint60
||
DeferDiags48
||
!IsError42
);
1877
2.91M
  auto SetIsLastErrorImmediate = [&](bool Flag) {
1878
2.91M
    if (IsError)
1879
660k
      IsLastErrorImmediate = Flag;
1880
2.91M
  };
1881
2.91M
  if (!ShouldDefer) {
1882
2.91M
    SetIsLastErrorImmediate(true);
1883
2.91M
    return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc,
1884
2.91M
                                 DiagID, getCurFunctionDecl(), *this);
1885
2.91M
  }
1886
1887
18
  SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice
1888
18
                                 ? 
CUDADiagIfDeviceCode(Loc, DiagID)6
1889
18
                                 : 
CUDADiagIfHostCode(Loc, DiagID)12
;
1890
18
  SetIsLastErrorImmediate(DB.isImmediate());
1891
18
  return DB;
1892
2.91M
}
1893
1894
34.9M
void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {
1895
34.9M
  if (isUnevaluatedContext() || 
Ty.isNull()34.7M
)
1896
199k
    return;
1897
1898
  // The original idea behind checkTypeSupport function is that unused
1899
  // declarations can be replaced with an array of bytes of the same size during
1900
  // codegen, such replacement doesn't seem to be possible for types without
1901
  // constant byte size like zero length arrays. So, do a deep check for SYCL.
1902
34.7M
  if (D && 
LangOpts.SYCLIsDevice22.3M
) {
1903
1.22k
    llvm::DenseSet<QualType> Visited;
1904
1.22k
    deepTypeCheckForSYCLDevice(Loc, Visited, D);
1905
1.22k
  }
1906
1907
34.7M
  Decl *C = cast<Decl>(getCurLexicalContext());
1908
1909
  // Memcpy operations for structs containing a member with unsupported type
1910
  // are ok, though.
1911
34.7M
  if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
1912
4.96M
    if ((MD->isCopyAssignmentOperator() || 
MD->isMoveAssignmentOperator()4.92M
) &&
1913
4.96M
        
MD->isTrivial()79.0k
)
1914
24.3k
      return;
1915
1916
4.94M
    if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
1917
982k
      if (Ctor->isCopyOrMoveConstructor() && 
Ctor->isTrivial()118k
)
1918
37.5k
        return;
1919
4.94M
  }
1920
1921
  // Try to associate errors with the lexical context, if that is a function, or
1922
  // the value declaration otherwise.
1923
34.6M
  FunctionDecl *FD = isa<FunctionDecl>(C) ? 
cast<FunctionDecl>(C)23.7M
1924
34.6M
                                          : 
dyn_cast_or_null<FunctionDecl>(D)10.9M
;
1925
1926
34.6M
  auto CheckDeviceType = [&](QualType Ty) {
1927
290k
    if (Ty->isDependentType())
1928
3.69k
      return;
1929
1930
287k
    if (Ty->isBitIntType()) {
1931
4
      if (!Context.getTargetInfo().hasBitIntType()) {
1932
0
        PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1933
0
        if (D)
1934
0
          PD << D;
1935
0
        else
1936
0
          PD << "expression";
1937
0
        targetDiag(Loc, PD, FD)
1938
0
            << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
1939
0
            << Ty << Context.getTargetInfo().getTriple().str();
1940
0
      }
1941
4
      return;
1942
4
    }
1943
1944
    // Check if we are dealing with two 'long double' but with different
1945
    // semantics.
1946
287k
    bool LongDoubleMismatched = false;
1947
287k
    if (Ty->isRealFloatingType() && 
Context.getTypeSize(Ty) == 12833.0k
) {
1948
213
      const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
1949
213
      if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
1950
213
           
!Context.getTargetInfo().hasFloat128Type()125
) ||
1951
213
          
(120
&Sem == &llvm::APFloat::PPCDoubleDouble()120
&&
1952
120
           
!Context.getTargetInfo().hasIbm128Type()88
))
1953
178
        LongDoubleMismatched = true;
1954
213
    }
1955
1956
287k
    if ((Ty->isFloat16Type() && 
!Context.getTargetInfo().hasFloat16Type()144
) ||
1957
287k
        (Ty->isFloat128Type() && 
!Context.getTargetInfo().hasFloat128Type()82
) ||
1958
287k
        
(287k
Ty->isIbm128Type()287k
&&
!Context.getTargetInfo().hasIbm128Type()1
) ||
1959
287k
        
(287k
Ty->isIntegerType()287k
&&
Context.getTypeSize(Ty) == 128187k
&&
1960
287k
         
!Context.getTargetInfo().hasInt128Type()115
) ||
1961
287k
        
LongDoubleMismatched287k
) {
1962
217
      PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1963
217
      if (D)
1964
171
        PD << D;
1965
46
      else
1966
46
        PD << "expression";
1967
1968
217
      if (targetDiag(Loc, PD, FD)
1969
217
          << true /*show bit size*/
1970
217
          << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1971
217
          << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
1972
30
        if (D)
1973
30
          D->setInvalidDecl();
1974
30
      }
1975
217
      if (D)
1976
171
        targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
1977
217
    }
1978
287k
  };
1979
1980
55.2M
  auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
1981
55.2M
    if (LangOpts.SYCLIsDevice || 
(55.2M
LangOpts.OpenMP55.2M
&&
LangOpts.OpenMPIsDevice9.76M
) ||
1982
55.2M
        
LangOpts.CUDAIsDevice54.9M
)
1983
290k
      CheckDeviceType(Ty);
1984
1985
55.2M
    QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();
1986
55.2M
    const TargetInfo &TI = Context.getTargetInfo();
1987
55.2M
    if (!TI.hasLongDoubleType() && 
UnqualTy == Context.LongDoubleTy430
) {
1988
28
      PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1989
28
      if (D)
1990
16
        PD << D;
1991
12
      else
1992
12
        PD << "expression";
1993
1994
28
      if (Diag(Loc, PD, FD)
1995
28
          << false /*show bit size*/ << 0 << Ty << false /*return*/
1996
28
          << Context.getTargetInfo().getTriple().str()) {
1997
28
        if (D)
1998
16
          D->setInvalidDecl();
1999
28
      }
2000
28
      if (D)
2001
16
        targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2002
28
    }
2003
2004
55.2M
    bool IsDouble = UnqualTy == Context.DoubleTy;
2005
55.2M
    bool IsFloat = UnqualTy == Context.FloatTy;
2006
55.2M
    if (IsRetTy && 
!TI.hasFPReturn()8.12M
&&
(0
IsDouble0
||
IsFloat0
)) {
2007
0
      PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2008
0
      if (D)
2009
0
        PD << D;
2010
0
      else
2011
0
        PD << "expression";
2012
2013
0
      if (Diag(Loc, PD, FD)
2014
0
          << false /*show bit size*/ << 0 << Ty << true /*return*/
2015
0
          << Context.getTargetInfo().getTriple().str()) {
2016
0
        if (D)
2017
0
          D->setInvalidDecl();
2018
0
      }
2019
0
      if (D)
2020
0
        targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2021
0
    }
2022
55.2M
  };
2023
2024
34.6M
  CheckType(Ty);
2025
34.6M
  if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
2026
7.94M
    for (const auto &ParamTy : FPTy->param_types())
2027
12.4M
      CheckType(ParamTy);
2028
7.94M
    CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
2029
7.94M
  }
2030
34.6M
  if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
2031
177k
    CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
2032
34.6M
}
2033
2034
/// Looks through the macro-expansion chain for the given
2035
/// location, looking for a macro expansion with the given name.
2036
/// If one is found, returns true and sets the location to that
2037
/// expansion loc.
2038
184
bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
2039
184
  SourceLocation loc = locref;
2040
184
  if (!loc.isMacroID()) 
return false5
;
2041
2042
  // There's no good way right now to look at the intermediate
2043
  // expansions, so just jump to the expansion location.
2044
179
  loc = getSourceManager().getExpansionLoc(loc);
2045
2046
  // If that's written with the name, stop here.
2047
179
  SmallString<16> buffer;
2048
179
  if (getPreprocessor().getSpelling(loc, buffer) == name) {
2049
13
    locref = loc;
2050
13
    return true;
2051
13
  }
2052
166
  return false;
2053
179
}
2054
2055
/// Determines the active Scope associated with the given declaration
2056
/// context.
2057
///
2058
/// This routine maps a declaration context to the active Scope object that
2059
/// represents that declaration context in the parser. It is typically used
2060
/// from "scope-less" code (e.g., template instantiation, lazy creation of
2061
/// declarations) that injects a name for name-lookup purposes and, therefore,
2062
/// must update the Scope.
2063
///
2064
/// \returns The scope corresponding to the given declaraion context, or NULL
2065
/// if no such scope is open.
2066
437k
Scope *Sema::getScopeForContext(DeclContext *Ctx) {
2067
2068
437k
  if (!Ctx)
2069
0
    return nullptr;
2070
2071
437k
  Ctx = Ctx->getPrimaryContext();
2072
1.55M
  for (Scope *S = getCurScope(); S; 
S = S->getParent()1.11M
) {
2073
    // Ignore scopes that cannot have declarations. This is important for
2074
    // out-of-line definitions of static class members.
2075
1.17M
    if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
2076
1.17M
      if (DeclContext *Entity = S->getEntity())
2077
1.03M
        if (Ctx == Entity->getPrimaryContext())
2078
61.4k
          return S;
2079
1.17M
  }
2080
2081
375k
  return nullptr;
2082
437k
}
2083
2084
/// Enter a new function scope
2085
3.68M
void Sema::PushFunctionScope() {
2086
3.68M
  if (FunctionScopes.empty() && 
CachedFunctionScope3.54M
) {
2087
    // Use CachedFunctionScope to avoid allocating memory when possible.
2088
3.48M
    CachedFunctionScope->Clear();
2089
3.48M
    FunctionScopes.push_back(CachedFunctionScope.release());
2090
3.48M
  } else {
2091
195k
    FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
2092
195k
  }
2093
3.68M
  if (LangOpts.OpenMP)
2094
90.0k
    pushOpenMPFunctionRegion();
2095
3.68M
}
2096
2097
3.38k
void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
2098
3.38k
  FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
2099
3.38k
                                              BlockScope, Block));
2100
3.38k
}
2101
2102
13.4k
LambdaScopeInfo *Sema::PushLambdaScope() {
2103
13.4k
  LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
2104
13.4k
  FunctionScopes.push_back(LSI);
2105
13.4k
  return LSI;
2106
13.4k
}
2107
2108
3.67k
void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
2109
3.67k
  if (LambdaScopeInfo *const LSI = getCurLambda()) {
2110
3.67k
    LSI->AutoTemplateParameterDepth = Depth;
2111
3.67k
    return;
2112
3.67k
  }
2113
0
  llvm_unreachable(
2114
0
      "Remove assertion if intentionally called in a non-lambda context.");
2115
0
}
2116
2117
// Check that the type of the VarDecl has an accessible copy constructor and
2118
// resolve its destructor's exception specification.
2119
// This also performs initialization of block variables when they are moved
2120
// to the heap. It uses the same rules as applicable for implicit moves
2121
// according to the C++ standard in effect ([class.copy.elision]p3).
2122
102
static void checkEscapingByref(VarDecl *VD, Sema &S) {
2123
102
  QualType T = VD->getType();
2124
102
  EnterExpressionEvaluationContext scope(
2125
102
      S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2126
102
  SourceLocation Loc = VD->getLocation();
2127
102
  Expr *VarRef =
2128
102
      new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2129
102
  ExprResult Result;
2130
102
  auto IE = InitializedEntity::InitializeBlock(Loc, T);
2131
102
  if (S.getLangOpts().CPlusPlus2b) {
2132
9
    auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
2133
9
                                       VK_XValue, FPOptionsOverride());
2134
9
    Result = S.PerformCopyInitialization(IE, SourceLocation(), E);
2135
93
  } else {
2136
93
    Result = S.PerformMoveOrCopyInitialization(
2137
93
        IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible},
2138
93
        VarRef);
2139
93
  }
2140
2141
102
  if (!Result.isInvalid()) {
2142
61
    Result = S.MaybeCreateExprWithCleanups(Result);
2143
61
    Expr *Init = Result.getAs<Expr>();
2144
61
    S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
2145
61
  }
2146
2147
  // The destructor's exception specification is needed when IRGen generates
2148
  // block copy/destroy functions. Resolve it here.
2149
102
  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2150
83
    if (CXXDestructorDecl *DD = RD->getDestructor()) {
2151
15
      auto *FPT = DD->getType()->getAs<FunctionProtoType>();
2152
15
      S.ResolveExceptionSpec(Loc, FPT);
2153
15
    }
2154
102
}
2155
2156
4.27M
static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
2157
  // Set the EscapingByref flag of __block variables captured by
2158
  // escaping blocks.
2159
4.27M
  for (const BlockDecl *BD : FSI.Blocks) {
2160
3.21k
    for (const BlockDecl::Capture &BC : BD->captures()) {
2161
3.21k
      VarDecl *VD = BC.getVariable();
2162
3.21k
      if (VD->hasAttr<BlocksAttr>()) {
2163
        // Nothing to do if this is a __block variable captured by a
2164
        // non-escaping block.
2165
550
        if (BD->doesNotEscape())
2166
26
          continue;
2167
524
        VD->setEscapingByref();
2168
524
      }
2169
      // Check whether the captured variable is or contains an object of
2170
      // non-trivial C union type.
2171
3.18k
      QualType CapType = BC.getVariable()->getType();
2172
3.18k
      if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
2173
3.18k
          
CapType.hasNonTrivialToPrimitiveCopyCUnion()3.17k
)
2174
6
        S.checkNonTrivialCUnion(BC.getVariable()->getType(),
2175
6
                                BD->getCaretLocation(),
2176
6
                                Sema::NTCUC_BlockCapture,
2177
6
                                Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
2178
3.18k
    }
2179
3.11k
  }
2180
2181
4.27M
  for (VarDecl *VD : FSI.ByrefBlockVars) {
2182
    // __block variables might require us to capture a copy-initializer.
2183
498
    if (!VD->isEscapingByref())
2184
81
      continue;
2185
    // It's currently invalid to ever have a __block variable with an
2186
    // array type; should we diagnose that here?
2187
    // Regardless, we don't want to ignore array nesting when
2188
    // constructing this copy.
2189
417
    if (VD->getType()->isStructureOrClassType())
2190
102
      checkEscapingByref(VD, S);
2191
417
  }
2192
4.27M
}
2193
2194
/// Pop a function (or block or lambda or captured region) scope from the stack.
2195
///
2196
/// \param WP The warning policy to use for CFG-based warnings, or null if such
2197
///        warnings should not be produced.
2198
/// \param D The declaration corresponding to this function scope, if producing
2199
///        CFG-based warnings.
2200
/// \param BlockType The type of the block expression, if D is a BlockDecl.
2201
Sema::PoppedFunctionScopePtr
2202
Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
2203
4.27M
                           const Decl *D, QualType BlockType) {
2204
4.27M
  assert(!FunctionScopes.empty() && "mismatched push/pop!");
2205
2206
0
  markEscapingByrefs(*FunctionScopes.back(), *this);
2207
2208
4.27M
  PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
2209
4.27M
                               PoppedFunctionScopeDeleter(this));
2210
2211
4.27M
  if (LangOpts.OpenMP)
2212
663k
    popOpenMPFunctionRegion(Scope.get());
2213
2214
  // Issue any analysis-based warnings.
2215
4.27M
  if (WP && 
D3.13M
)
2216
3.13M
    AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
2217
1.13M
  else
2218
1.13M
    for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2219
22.3k
      Diag(PUD.Loc, PUD.PD);
2220
2221
4.27M
  return Scope;
2222
4.27M
}
2223
2224
void Sema::PoppedFunctionScopeDeleter::
2225
4.27M
operator()(sema::FunctionScopeInfo *Scope) const {
2226
  // Stash the function scope for later reuse if it's for a normal function.
2227
4.27M
  if (Scope->isPlainFunction() && 
!Self->CachedFunctionScope3.68M
)
2228
3.54M
    Self->CachedFunctionScope.reset(Scope);
2229
723k
  else
2230
723k
    delete Scope;
2231
4.27M
}
2232
2233
4.38M
void Sema::PushCompoundScope(bool IsStmtExpr) {
2234
4.38M
  getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo(IsStmtExpr));
2235
4.38M
}
2236
2237
4.38M
void Sema::PopCompoundScope() {
2238
4.38M
  FunctionScopeInfo *CurFunction = getCurFunction();
2239
4.38M
  assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2240
2241
0
  CurFunction->CompoundScopes.pop_back();
2242
4.38M
}
2243
2244
/// Determine whether any errors occurred within this function/method/
2245
/// block.
2246
15.2k
bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
2247
15.2k
  return getCurFunction()->hasUnrecoverableErrorOccurred();
2248
15.2k
}
2249
2250
9.07k
void Sema::setFunctionHasBranchIntoScope() {
2251
9.07k
  if (!FunctionScopes.empty())
2252
9.07k
    FunctionScopes.back()->setHasBranchIntoScope();
2253
9.07k
}
2254
2255
1.51M
void Sema::setFunctionHasBranchProtectedScope() {
2256
1.51M
  if (!FunctionScopes.empty())
2257
1.51M
    FunctionScopes.back()->setHasBranchProtectedScope();
2258
1.51M
}
2259
2260
130
void Sema::setFunctionHasIndirectGoto() {
2261
130
  if (!FunctionScopes.empty())
2262
130
    FunctionScopes.back()->setHasIndirectGoto();
2263
130
}
2264
2265
70
void Sema::setFunctionHasMustTail() {
2266
70
  if (!FunctionScopes.empty())
2267
70
    FunctionScopes.back()->setHasMustTail();
2268
70
}
2269
2270
168k
BlockScopeInfo *Sema::getCurBlock() {
2271
168k
  if (FunctionScopes.empty())
2272
1.22k
    return nullptr;
2273
2274
167k
  auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2275
167k
  if (CurBSI && 
CurBSI->TheDecl7.90k
&&
2276
167k
      
!CurBSI->TheDecl->Encloses(CurContext)7.90k
) {
2277
    // We have switched contexts due to template instantiation.
2278
0
    assert(!CodeSynthesisContexts.empty());
2279
0
    return nullptr;
2280
0
  }
2281
2282
167k
  return CurBSI;
2283
167k
}
2284
2285
3.49k
FunctionScopeInfo *Sema::getEnclosingFunction() const {
2286
3.49k
  if (FunctionScopes.empty())
2287
584
    return nullptr;
2288
2289
2.91k
  
for (int e = FunctionScopes.size() - 1; 2.91k
e >= 0;
--e4
) {
2290
2.91k
    if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
2291
4
      continue;
2292
2.91k
    return FunctionScopes[e];
2293
2.91k
  }
2294
0
  return nullptr;
2295
2.91k
}
2296
2297
224k
LambdaScopeInfo *Sema::getEnclosingLambda() const {
2298
224k
  for (auto *Scope : llvm::reverse(FunctionScopes)) {
2299
13.9k
    if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
2300
1.00k
      if (LSI->Lambda && 
!LSI->Lambda->Encloses(CurContext)173
) {
2301
        // We have switched contexts due to template instantiation.
2302
        // FIXME: We should swap out the FunctionScopes during code synthesis
2303
        // so that we don't need to check for this.
2304
6
        assert(!CodeSynthesisContexts.empty());
2305
0
        return nullptr;
2306
6
      }
2307
997
      return LSI;
2308
1.00k
    }
2309
13.9k
  }
2310
223k
  return nullptr;
2311
224k
}
2312
2313
12.7M
LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2314
12.7M
  if (FunctionScopes.empty())
2315
1.61M
    return nullptr;
2316
2317
11.1M
  auto I = FunctionScopes.rbegin();
2318
11.1M
  if (IgnoreNonLambdaCapturingScope) {
2319
9.87M
    auto E = FunctionScopes.rend();
2320
13.2M
    while (I != E && 
isa<CapturingScopeInfo>(*I)13.2M
&&
!isa<LambdaScopeInfo>(*I)3.37M
)
2321
3.34M
      ++I;
2322
9.87M
    if (I == E)
2323
130
      return nullptr;
2324
9.87M
  }
2325
11.1M
  auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2326
11.1M
  if (CurLSI && 
CurLSI->Lambda96.1k
&&
2327
11.1M
      
!CurLSI->Lambda->Encloses(CurContext)56.2k
) {
2328
    // We have switched contexts due to template instantiation.
2329
66
    assert(!CodeSynthesisContexts.empty());
2330
0
    return nullptr;
2331
66
  }
2332
2333
11.1M
  return CurLSI;
2334
11.1M
}
2335
2336
// We have a generic lambda if we parsed auto parameters, or we have
2337
// an associated template parameter list.
2338
3.96k
LambdaScopeInfo *Sema::getCurGenericLambda() {
2339
3.96k
  if (LambdaScopeInfo *LSI =  getCurLambda()) {
2340
3.96k
    return (LSI->TemplateParams.size() ||
2341
3.96k
                    
LSI->GLTemplateParameterList1.74k
) ?
LSI2.41k
:
nullptr1.54k
;
2342
3.96k
  }
2343
0
  return nullptr;
2344
3.96k
}
2345
2346
2347
71.7M
void Sema::ActOnComment(SourceRange Comment) {
2348
71.7M
  if (!LangOpts.RetainCommentsFromSystemHeaders &&
2349
71.7M
      
SourceMgr.isInSystemHeader(Comment.getBegin())71.7M
)
2350
18.1M
    return;
2351
53.6M
  RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2352
53.6M
  if (RC.isAlmostTrailingComment()) {
2353
69
    SourceRange MagicMarkerRange(Comment.getBegin(),
2354
69
                                 Comment.getBegin().getLocWithOffset(3));
2355
69
    StringRef MagicMarkerText;
2356
69
    switch (RC.getKind()) {
2357
18
    case RawComment::RCK_OrdinaryBCPL:
2358
18
      MagicMarkerText = "///<";
2359
18
      break;
2360
51
    case RawComment::RCK_OrdinaryC:
2361
51
      MagicMarkerText = "/**<";
2362
51
      break;
2363
0
    default:
2364
0
      llvm_unreachable("if this is an almost Doxygen comment, "
2365
69
                       "it should be ordinary");
2366
69
    }
2367
69
    Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2368
69
      FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2369
69
  }
2370
53.6M
  Context.addComment(RC);
2371
53.6M
}
2372
2373
// Pin this vtable to this file.
2374
14.0k
ExternalSemaSource::~ExternalSemaSource() {}
2375
char ExternalSemaSource::ID;
2376
2377
0
void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
2378
0
void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
2379
2380
void ExternalSemaSource::ReadKnownNamespaces(
2381
1
                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
2382
1
}
2383
2384
void ExternalSemaSource::ReadUndefinedButUsed(
2385
1
    llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2386
2387
void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
2388
10
    FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2389
2390
/// Figure out if an expression could be turned into a call.
2391
///
2392
/// Use this when trying to recover from an error where the programmer may have
2393
/// written just the name of a function instead of actually calling it.
2394
///
2395
/// \param E - The expression to examine.
2396
/// \param ZeroArgCallReturnTy - If the expression can be turned into a call
2397
///  with no arguments, this parameter is set to the type returned by such a
2398
///  call; otherwise, it is set to an empty QualType.
2399
/// \param OverloadSet - If the expression is an overloaded function
2400
///  name, this parameter is populated with the decls of the various overloads.
2401
bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2402
337
                         UnresolvedSetImpl &OverloadSet) {
2403
337
  ZeroArgCallReturnTy = QualType();
2404
337
  OverloadSet.clear();
2405
2406
337
  const OverloadExpr *Overloads = nullptr;
2407
337
  bool IsMemExpr = false;
2408
337
  if (E.getType() == Context.OverloadTy) {
2409
100
    OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
2410
2411
    // Ignore overloads that are pointer-to-member constants.
2412
100
    if (FR.HasFormOfMemberPointer)
2413
18
      return false;
2414
2415
82
    Overloads = FR.Expression;
2416
237
  } else if (E.getType() == Context.BoundMemberTy) {
2417
78
    Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
2418
78
    IsMemExpr = true;
2419
78
  }
2420
2421
319
  bool Ambiguous = false;
2422
319
  bool IsMV = false;
2423
2424
319
  if (Overloads) {
2425
111
    for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2426
294
         DeclsEnd = Overloads->decls_end(); it != DeclsEnd; 
++it183
) {
2427
183
      OverloadSet.addDecl(*it);
2428
2429
      // Check whether the function is a non-template, non-member which takes no
2430
      // arguments.
2431
183
      if (IsMemExpr)
2432
36
        continue;
2433
147
      if (const FunctionDecl *OverloadDecl
2434
147
            = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2435
95
        if (OverloadDecl->getMinRequiredArguments() == 0) {
2436
46
          if (!ZeroArgCallReturnTy.isNull() && 
!Ambiguous5
&&
2437
46
              
(5
!IsMV5
||
!(2
OverloadDecl->isCPUDispatchMultiVersion()2
||
2438
3
                          
OverloadDecl->isCPUSpecificMultiVersion()2
))) {
2439
3
            ZeroArgCallReturnTy = QualType();
2440
3
            Ambiguous = true;
2441
43
          } else {
2442
43
            ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2443
43
            IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2444
43
                   OverloadDecl->isCPUSpecificMultiVersion();
2445
43
          }
2446
46
        }
2447
95
      }
2448
147
    }
2449
2450
    // If it's not a member, use better machinery to try to resolve the call
2451
111
    if (!IsMemExpr)
2452
82
      return !ZeroArgCallReturnTy.isNull();
2453
111
  }
2454
2455
  // Attempt to call the member with no arguments - this will correctly handle
2456
  // member templates with defaults/deduction of template arguments, overloads
2457
  // with default arguments, etc.
2458
237
  if (IsMemExpr && 
!E.isTypeDependent()78
) {
2459
75
    Sema::TentativeAnalysisScope Trap(*this);
2460
75
    ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
2461
75
                                             None, SourceLocation());
2462
75
    if (R.isUsable()) {
2463
56
      ZeroArgCallReturnTy = R.get()->getType();
2464
56
      return true;
2465
56
    }
2466
19
    return false;
2467
75
  }
2468
2469
162
  if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
2470
111
    if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2471
90
      if (Fun->getMinRequiredArguments() == 0)
2472
74
        ZeroArgCallReturnTy = Fun->getReturnType();
2473
90
      return true;
2474
90
    }
2475
111
  }
2476
2477
  // We don't have an expression that's convenient to get a FunctionDecl from,
2478
  // but we can at least check if the type is "function of 0 arguments".
2479
72
  QualType ExprTy = E.getType();
2480
72
  const FunctionType *FunTy = nullptr;
2481
72
  QualType PointeeTy = ExprTy->getPointeeType();
2482
72
  if (!PointeeTy.isNull())
2483
17
    FunTy = PointeeTy->getAs<FunctionType>();
2484
72
  if (!FunTy)
2485
72
    FunTy = ExprTy->getAs<FunctionType>();
2486
2487
72
  if (const FunctionProtoType *FPT =
2488
72
      dyn_cast_or_null<FunctionProtoType>(FunTy)) {
2489
6
    if (FPT->getNumParams() == 0)
2490
0
      ZeroArgCallReturnTy = FunTy->getReturnType();
2491
6
    return true;
2492
6
  }
2493
66
  return false;
2494
72
}
2495
2496
/// Give notes for a set of overloads.
2497
///
2498
/// A companion to tryExprAsCall. In cases when the name that the programmer
2499
/// wrote was an overloaded function, we may be able to make some guesses about
2500
/// plausible overloads based on their return types; such guesses can be handed
2501
/// off to this method to be emitted as notes.
2502
///
2503
/// \param Overloads - The overloads to note.
2504
/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2505
///  -fshow-overloads=best, this is the location to attach to the note about too
2506
///  many candidates. Typically this will be the location of the original
2507
///  ill-formed expression.
2508
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2509
211
                          const SourceLocation FinalNoteLoc) {
2510
211
  unsigned ShownOverloads = 0;
2511
211
  unsigned SuppressedOverloads = 0;
2512
211
  for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2513
388
       DeclsEnd = Overloads.end(); It != DeclsEnd; 
++It177
) {
2514
177
    if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
2515
0
      ++SuppressedOverloads;
2516
0
      continue;
2517
0
    }
2518
2519
177
    NamedDecl *Fn = (*It)->getUnderlyingDecl();
2520
    // Don't print overloads for non-default multiversioned functions.
2521
177
    if (const auto *FD = Fn->getAsFunction()) {
2522
177
      if (FD->isMultiVersion() && 
FD->hasAttr<TargetAttr>()2
&&
2523
177
          
!FD->getAttr<TargetAttr>()->isDefaultVersion()2
)
2524
1
        continue;
2525
177
    }
2526
176
    S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
2527
176
    ++ShownOverloads;
2528
176
  }
2529
2530
211
  S.Diags.overloadCandidatesShown(ShownOverloads);
2531
2532
211
  if (SuppressedOverloads)
2533
0
    S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2534
0
      << SuppressedOverloads;
2535
211
}
2536
2537
static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
2538
                                   const UnresolvedSetImpl &Overloads,
2539
211
                                   bool (*IsPlausibleResult)(QualType)) {
2540
211
  if (!IsPlausibleResult)
2541
200
    return noteOverloads(S, Overloads, Loc);
2542
2543
11
  UnresolvedSet<2> PlausibleOverloads;
2544
11
  for (OverloadExpr::decls_iterator It = Overloads.begin(),
2545
11
         DeclsEnd = Overloads.end(); It != DeclsEnd; 
++It0
) {
2546
0
    const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
2547
0
    QualType OverloadResultTy = OverloadDecl->getReturnType();
2548
0
    if (IsPlausibleResult(OverloadResultTy))
2549
0
      PlausibleOverloads.addDecl(It.getDecl());
2550
0
  }
2551
11
  noteOverloads(S, PlausibleOverloads, Loc);
2552
11
}
2553
2554
/// Determine whether the given expression can be called by just
2555
/// putting parentheses after it.  Notably, expressions with unary
2556
/// operators can't be because the unary operator will start parsing
2557
/// outside the call.
2558
105
static bool IsCallableWithAppend(Expr *E) {
2559
105
  E = E->IgnoreImplicit();
2560
105
  return (!isa<CStyleCastExpr>(E) &&
2561
105
          !isa<UnaryOperator>(E) &&
2562
105
          
!isa<BinaryOperator>(E)101
&&
2563
105
          
!isa<CXXOperatorCallExpr>(E)95
);
2564
105
}
2565
2566
217
static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
2567
217
  if (const auto *UO = dyn_cast<UnaryOperator>(E))
2568
25
    E = UO->getSubExpr();
2569
2570
217
  if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2571
81
    if (ULE->getNumDecls() == 0)
2572
1
      return false;
2573
2574
80
    const NamedDecl *ND = *ULE->decls_begin();
2575
80
    if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2576
50
      return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
2577
80
  }
2578
166
  return false;
2579
217
}
2580
2581
bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2582
                                bool ForceComplain,
2583
311
                                bool (*IsPlausibleResult)(QualType)) {
2584
311
  SourceLocation Loc = E.get()->getExprLoc();
2585
311
  SourceRange Range = E.get()->getSourceRange();
2586
311
  UnresolvedSet<4> Overloads;
2587
2588
  // If this is a SFINAE context, don't try anything that might trigger ADL
2589
  // prematurely.
2590
311
  if (!isSFINAEContext()) {
2591
252
    QualType ZeroArgCallTy;
2592
252
    if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
2593
252
        
!ZeroArgCallTy.isNull()105
&&
2594
252
        
(105
!IsPlausibleResult105
||
IsPlausibleResult(ZeroArgCallTy)11
)) {
2595
      // At this point, we know E is potentially callable with 0
2596
      // arguments and that it returns something of a reasonable type,
2597
      // so we can emit a fixit and carry on pretending that E was
2598
      // actually a CallExpr.
2599
105
      SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
2600
105
      bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2601
105
      Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2602
105
                    << (IsCallableWithAppend(E.get())
2603
105
                            ? FixItHint::CreateInsertion(ParenInsertionLoc,
2604
95
                                                         "()")
2605
105
                            : 
FixItHint()10
);
2606
105
      if (!IsMV)
2607
101
        notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2608
2609
      // FIXME: Try this before emitting the fixit, and suppress diagnostics
2610
      // while doing so.
2611
105
      E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None,
2612
105
                        Range.getEnd().getLocWithOffset(1));
2613
105
      return true;
2614
105
    }
2615
252
  }
2616
206
  if (!ForceComplain) 
return false94
;
2617
2618
112
  bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2619
112
  Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2620
112
  if (!IsMV)
2621
110
    notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2622
112
  E = ExprError();
2623
112
  return true;
2624
206
}
2625
2626
79
IdentifierInfo *Sema::getSuperIdentifier() const {
2627
79
  if (!Ident_super)
2628
34
    Ident_super = &Context.Idents.get("super");
2629
79
  return Ident_super;
2630
79
}
2631
2632
0
IdentifierInfo *Sema::getFloat128Identifier() const {
2633
0
  if (!Ident___float128)
2634
0
    Ident___float128 = &Context.Idents.get("__float128");
2635
0
  return Ident___float128;
2636
0
}
2637
2638
void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
2639
                                   CapturedRegionKind K,
2640
572k
                                   unsigned OpenMPCaptureLevel) {
2641
572k
  auto *CSI = new CapturedRegionScopeInfo(
2642
572k
      getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2643
572k
      (getLangOpts().OpenMP && 
K == CR_OpenMP572k
) ?
getOpenMPNestingLevel()571k
:
0256
,
2644
572k
      OpenMPCaptureLevel);
2645
572k
  CSI->ReturnType = Context.VoidTy;
2646
572k
  FunctionScopes.push_back(CSI);
2647
572k
}
2648
2649
544k
CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
2650
544k
  if (FunctionScopes.empty())
2651
653
    return nullptr;
2652
2653
544k
  return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2654
544k
}
2655
2656
const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
2657
3.45k
Sema::getMismatchingDeleteExpressions() const {
2658
3.45k
  return DeleteExprs;
2659
3.45k
}
2660
2661
Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S)
2662
    : S(S), OldFPFeaturesState(S.CurFPFeatures),
2663
      OldOverrides(S.FpPragmaStack.CurrentValue),
2664
      OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
2665
5.03M
      OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
2666
2667
5.03M
Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() {
2668
5.03M
  S.CurFPFeatures = OldFPFeaturesState;
2669
5.03M
  S.FpPragmaStack.CurrentValue = OldOverrides;
2670
5.03M
  S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
2671
5.03M
}