Coverage Report

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