Coverage Report

Created: 2021-08-24 07:12

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