Coverage Report

Created: 2021-01-23 06:44

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