Coverage Report

Created: 2020-09-22 08:39

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