Bug Summary

File:clang/lib/Sema/SemaTemplateInstantiate.cpp
Warning:line 2295, column 41
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiate.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp

1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
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// This file implements C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
12#include "clang/Sema/SemaInternal.h"
13#include "TreeTransform.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/PrettyDeclStackTrace.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/Stack.h"
23#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Template.h"
27#include "clang/Sema/TemplateDeduction.h"
28#include "clang/Sema/TemplateInstCallback.h"
29#include "llvm/Support/TimeProfiler.h"
30
31using namespace clang;
32using namespace sema;
33
34//===----------------------------------------------------------------------===/
35// Template Instantiation Support
36//===----------------------------------------------------------------------===/
37
38/// Retrieve the template argument list(s) that should be used to
39/// instantiate the definition of the given declaration.
40///
41/// \param D the declaration for which we are computing template instantiation
42/// arguments.
43///
44/// \param Innermost if non-NULL, the innermost template argument list.
45///
46/// \param RelativeToPrimary true if we should get the template
47/// arguments relative to the primary template, even when we're
48/// dealing with a specialization. This is only relevant for function
49/// template specializations.
50///
51/// \param Pattern If non-NULL, indicates the pattern from which we will be
52/// instantiating the definition of the given declaration, \p D. This is
53/// used to determine the proper set of template instantiation arguments for
54/// friend function template specializations.
55MultiLevelTemplateArgumentList
56Sema::getTemplateInstantiationArgs(NamedDecl *D,
57 const TemplateArgumentList *Innermost,
58 bool RelativeToPrimary,
59 const FunctionDecl *Pattern) {
60 // Accumulate the set of template argument lists in this structure.
61 MultiLevelTemplateArgumentList Result;
62
63 if (Innermost)
64 Result.addOuterTemplateArguments(Innermost);
65
66 DeclContext *Ctx = dyn_cast<DeclContext>(D);
67 if (!Ctx) {
68 Ctx = D->getDeclContext();
69
70 // Add template arguments from a variable template instantiation. For a
71 // class-scope explicit specialization, there are no template arguments
72 // at this level, but there may be enclosing template arguments.
73 VarTemplateSpecializationDecl *Spec =
74 dyn_cast<VarTemplateSpecializationDecl>(D);
75 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
76 // We're done when we hit an explicit specialization.
77 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
78 !isa<VarTemplatePartialSpecializationDecl>(Spec))
79 return Result;
80
81 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
82
83 // If this variable template specialization was instantiated from a
84 // specialized member that is a variable template, we're done.
85 assert(Spec->getSpecializedTemplate() && "No variable template?")((Spec->getSpecializedTemplate() && "No variable template?"
) ? static_cast<void> (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No variable template?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 85, __PRETTY_FUNCTION__))
;
86 llvm::PointerUnion<VarTemplateDecl*,
87 VarTemplatePartialSpecializationDecl*> Specialized
88 = Spec->getSpecializedTemplateOrPartial();
89 if (VarTemplatePartialSpecializationDecl *Partial =
90 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
91 if (Partial->isMemberSpecialization())
92 return Result;
93 } else {
94 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
95 if (Tmpl->isMemberSpecialization())
96 return Result;
97 }
98 }
99
100 // If we have a template template parameter with translation unit context,
101 // then we're performing substitution into a default template argument of
102 // this template template parameter before we've constructed the template
103 // that will own this template template parameter. In this case, we
104 // use empty template parameter lists for all of the outer templates
105 // to avoid performing any substitutions.
106 if (Ctx->isTranslationUnit()) {
107 if (TemplateTemplateParmDecl *TTP
108 = dyn_cast<TemplateTemplateParmDecl>(D)) {
109 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
110 Result.addOuterTemplateArguments(None);
111 return Result;
112 }
113 }
114 }
115
116 while (!Ctx->isFileContext()) {
117 // Add template arguments from a class template instantiation.
118 ClassTemplateSpecializationDecl *Spec
119 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
120 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
121 // We're done when we hit an explicit specialization.
122 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
123 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
124 break;
125
126 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
127
128 // If this class template specialization was instantiated from a
129 // specialized member that is a class template, we're done.
130 assert(Spec->getSpecializedTemplate() && "No class template?")((Spec->getSpecializedTemplate() && "No class template?"
) ? static_cast<void> (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No class template?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 130, __PRETTY_FUNCTION__))
;
131 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
132 break;
133 }
134 // Add template arguments from a function template specialization.
135 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
136 if (!RelativeToPrimary &&
137 Function->getTemplateSpecializationKindForInstantiation() ==
138 TSK_ExplicitSpecialization)
139 break;
140
141 if (const TemplateArgumentList *TemplateArgs
142 = Function->getTemplateSpecializationArgs()) {
143 // Add the template arguments for this specialization.
144 Result.addOuterTemplateArguments(TemplateArgs);
145
146 // If this function was instantiated from a specialized member that is
147 // a function template, we're done.
148 assert(Function->getPrimaryTemplate() && "No function template?")((Function->getPrimaryTemplate() && "No function template?"
) ? static_cast<void> (0) : __assert_fail ("Function->getPrimaryTemplate() && \"No function template?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 148, __PRETTY_FUNCTION__))
;
149 if (Function->getPrimaryTemplate()->isMemberSpecialization())
150 break;
151
152 // If this function is a generic lambda specialization, we are done.
153 if (isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
154 break;
155
156 } else if (FunctionTemplateDecl *FunTmpl
157 = Function->getDescribedFunctionTemplate()) {
158 // Add the "injected" template arguments.
159 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
160 }
161
162 // If this is a friend declaration and it declares an entity at
163 // namespace scope, take arguments from its lexical parent
164 // instead of its semantic parent, unless of course the pattern we're
165 // instantiating actually comes from the file's context!
166 if (Function->getFriendObjectKind() &&
167 Function->getDeclContext()->isFileContext() &&
168 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
169 Ctx = Function->getLexicalDeclContext();
170 RelativeToPrimary = false;
171 continue;
172 }
173 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
174 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
175 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
176 const TemplateSpecializationType *TST =
177 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
178 Result.addOuterTemplateArguments(
179 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
180 if (ClassTemplate->isMemberSpecialization())
181 break;
182 }
183 }
184
185 Ctx = Ctx->getParent();
186 RelativeToPrimary = false;
187 }
188
189 return Result;
190}
191
192bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
193 switch (Kind) {
194 case TemplateInstantiation:
195 case ExceptionSpecInstantiation:
196 case DefaultTemplateArgumentInstantiation:
197 case DefaultFunctionArgumentInstantiation:
198 case ExplicitTemplateArgumentSubstitution:
199 case DeducedTemplateArgumentSubstitution:
200 case PriorTemplateArgumentSubstitution:
201 case ConstraintsCheck:
202 return true;
203
204 case DefaultTemplateArgumentChecking:
205 case DeclaringSpecialMember:
206 case DeclaringImplicitEqualityComparison:
207 case DefiningSynthesizedFunction:
208 case ExceptionSpecEvaluation:
209 case ConstraintSubstitution:
210 case ParameterMappingSubstitution:
211 case ConstraintNormalization:
212 case RewritingOperatorAsSpaceship:
213 return false;
214
215 // This function should never be called when Kind's value is Memoization.
216 case Memoization:
217 break;
218 }
219
220 llvm_unreachable("Invalid SynthesisKind!")::llvm::llvm_unreachable_internal("Invalid SynthesisKind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 220)
;
221}
222
223Sema::InstantiatingTemplate::InstantiatingTemplate(
224 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
225 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
226 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
227 sema::TemplateDeductionInfo *DeductionInfo)
228 : SemaRef(SemaRef) {
229 // Don't allow further instantiation if a fatal error and an uncompilable
230 // error have occurred. Any diagnostics we might have raised will not be
231 // visible, and we do not need to construct a correct AST.
232 if (SemaRef.Diags.hasFatalErrorOccurred() &&
36
Assuming the condition is false
233 SemaRef.Diags.hasUncompilableErrorOccurred()) {
234 Invalid = true;
235 return;
236 }
237 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
37
Calling 'InstantiatingTemplate::CheckInstantiationDepth'
43
Returning from 'InstantiatingTemplate::CheckInstantiationDepth'
238 if (!Invalid
43.1
Field 'Invalid' is false
43.1
Field 'Invalid' is false
) {
44
Taking true branch
239 CodeSynthesisContext Inst;
240 Inst.Kind = Kind;
241 Inst.PointOfInstantiation = PointOfInstantiation;
242 Inst.Entity = Entity;
243 Inst.Template = Template;
244 Inst.TemplateArgs = TemplateArgs.data();
245 Inst.NumTemplateArgs = TemplateArgs.size();
246 Inst.DeductionInfo = DeductionInfo;
247 Inst.InstantiationRange = InstantiationRange;
248 SemaRef.pushCodeSynthesisContext(Inst);
249
250 AlreadyInstantiating =
251 !SemaRef.InstantiatingSpecializations
45
Assuming field 'second' is true
252 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
253 .second;
254 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
255 }
256}
257
258Sema::InstantiatingTemplate::InstantiatingTemplate(
259 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
260 SourceRange InstantiationRange)
261 : InstantiatingTemplate(SemaRef,
35
Calling constructor for 'InstantiatingTemplate'
46
Returning from constructor for 'InstantiatingTemplate'
262 CodeSynthesisContext::TemplateInstantiation,
263 PointOfInstantiation, InstantiationRange, Entity) {}
264
265Sema::InstantiatingTemplate::InstantiatingTemplate(
266 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
267 ExceptionSpecification, SourceRange InstantiationRange)
268 : InstantiatingTemplate(
269 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
270 PointOfInstantiation, InstantiationRange, Entity) {}
271
272Sema::InstantiatingTemplate::InstantiatingTemplate(
273 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
274 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
275 SourceRange InstantiationRange)
276 : InstantiatingTemplate(
277 SemaRef,
278 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
279 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
280 Template, TemplateArgs) {}
281
282Sema::InstantiatingTemplate::InstantiatingTemplate(
283 Sema &SemaRef, SourceLocation PointOfInstantiation,
284 FunctionTemplateDecl *FunctionTemplate,
285 ArrayRef<TemplateArgument> TemplateArgs,
286 CodeSynthesisContext::SynthesisKind Kind,
287 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
288 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
289 InstantiationRange, FunctionTemplate, nullptr,
290 TemplateArgs, &DeductionInfo) {
291 assert(((Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? static_cast<void> (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 293, __PRETTY_FUNCTION__))
292 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||((Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? static_cast<void> (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 293, __PRETTY_FUNCTION__))
293 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution)((Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? static_cast<void> (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 293, __PRETTY_FUNCTION__))
;
294}
295
296Sema::InstantiatingTemplate::InstantiatingTemplate(
297 Sema &SemaRef, SourceLocation PointOfInstantiation,
298 TemplateDecl *Template,
299 ArrayRef<TemplateArgument> TemplateArgs,
300 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
301 : InstantiatingTemplate(
302 SemaRef,
303 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
304 PointOfInstantiation, InstantiationRange, Template, nullptr,
305 TemplateArgs, &DeductionInfo) {}
306
307Sema::InstantiatingTemplate::InstantiatingTemplate(
308 Sema &SemaRef, SourceLocation PointOfInstantiation,
309 ClassTemplatePartialSpecializationDecl *PartialSpec,
310 ArrayRef<TemplateArgument> TemplateArgs,
311 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
312 : InstantiatingTemplate(
313 SemaRef,
314 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
315 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
316 TemplateArgs, &DeductionInfo) {}
317
318Sema::InstantiatingTemplate::InstantiatingTemplate(
319 Sema &SemaRef, SourceLocation PointOfInstantiation,
320 VarTemplatePartialSpecializationDecl *PartialSpec,
321 ArrayRef<TemplateArgument> TemplateArgs,
322 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
323 : InstantiatingTemplate(
324 SemaRef,
325 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
326 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
327 TemplateArgs, &DeductionInfo) {}
328
329Sema::InstantiatingTemplate::InstantiatingTemplate(
330 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
331 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
332 : InstantiatingTemplate(
333 SemaRef,
334 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
335 PointOfInstantiation, InstantiationRange, Param, nullptr,
336 TemplateArgs) {}
337
338Sema::InstantiatingTemplate::InstantiatingTemplate(
339 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
340 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
341 SourceRange InstantiationRange)
342 : InstantiatingTemplate(
343 SemaRef,
344 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
345 PointOfInstantiation, InstantiationRange, Param, Template,
346 TemplateArgs) {}
347
348Sema::InstantiatingTemplate::InstantiatingTemplate(
349 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
350 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
351 SourceRange InstantiationRange)
352 : InstantiatingTemplate(
353 SemaRef,
354 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
355 PointOfInstantiation, InstantiationRange, Param, Template,
356 TemplateArgs) {}
357
358Sema::InstantiatingTemplate::InstantiatingTemplate(
359 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
360 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
361 SourceRange InstantiationRange)
362 : InstantiatingTemplate(
363 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
364 PointOfInstantiation, InstantiationRange, Param, Template,
365 TemplateArgs) {}
366
367Sema::InstantiatingTemplate::InstantiatingTemplate(
368 Sema &SemaRef, SourceLocation PointOfInstantiation,
369 ConstraintsCheck, NamedDecl *Template,
370 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
371 : InstantiatingTemplate(
372 SemaRef, CodeSynthesisContext::ConstraintsCheck,
373 PointOfInstantiation, InstantiationRange, Template, nullptr,
374 TemplateArgs) {}
375
376Sema::InstantiatingTemplate::InstantiatingTemplate(
377 Sema &SemaRef, SourceLocation PointOfInstantiation,
378 ConstraintSubstitution, NamedDecl *Template,
379 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
380 : InstantiatingTemplate(
381 SemaRef, CodeSynthesisContext::ConstraintSubstitution,
382 PointOfInstantiation, InstantiationRange, Template, nullptr,
383 {}, &DeductionInfo) {}
384
385Sema::InstantiatingTemplate::InstantiatingTemplate(
386 Sema &SemaRef, SourceLocation PointOfInstantiation,
387 ConstraintNormalization, NamedDecl *Template,
388 SourceRange InstantiationRange)
389 : InstantiatingTemplate(
390 SemaRef, CodeSynthesisContext::ConstraintNormalization,
391 PointOfInstantiation, InstantiationRange, Template) {}
392
393Sema::InstantiatingTemplate::InstantiatingTemplate(
394 Sema &SemaRef, SourceLocation PointOfInstantiation,
395 ParameterMappingSubstitution, NamedDecl *Template,
396 SourceRange InstantiationRange)
397 : InstantiatingTemplate(
398 SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
399 PointOfInstantiation, InstantiationRange, Template) {}
400
401void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
402 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
403 InNonInstantiationSFINAEContext = false;
404
405 CodeSynthesisContexts.push_back(Ctx);
406
407 if (!Ctx.isInstantiationRecord())
408 ++NonInstantiationEntries;
409
410 // Check to see if we're low on stack space. We can't do anything about this
411 // from here, but we can at least warn the user.
412 if (isStackNearlyExhausted())
413 warnStackExhausted(Ctx.PointOfInstantiation);
414}
415
416void Sema::popCodeSynthesisContext() {
417 auto &Active = CodeSynthesisContexts.back();
418 if (!Active.isInstantiationRecord()) {
419 assert(NonInstantiationEntries > 0)((NonInstantiationEntries > 0) ? static_cast<void> (
0) : __assert_fail ("NonInstantiationEntries > 0", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 419, __PRETTY_FUNCTION__))
;
420 --NonInstantiationEntries;
421 }
422
423 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
424
425 // Name lookup no longer looks in this template's defining module.
426 assert(CodeSynthesisContexts.size() >=((CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules
.size() && "forgot to remove a lookup module for a template instantiation"
) ? static_cast<void> (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 428, __PRETTY_FUNCTION__))
427 CodeSynthesisContextLookupModules.size() &&((CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules
.size() && "forgot to remove a lookup module for a template instantiation"
) ? static_cast<void> (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 428, __PRETTY_FUNCTION__))
428 "forgot to remove a lookup module for a template instantiation")((CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules
.size() && "forgot to remove a lookup module for a template instantiation"
) ? static_cast<void> (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 428, __PRETTY_FUNCTION__))
;
429 if (CodeSynthesisContexts.size() ==
430 CodeSynthesisContextLookupModules.size()) {
431 if (Module *M = CodeSynthesisContextLookupModules.back())
432 LookupModulesCache.erase(M);
433 CodeSynthesisContextLookupModules.pop_back();
434 }
435
436 // If we've left the code synthesis context for the current context stack,
437 // stop remembering that we've emitted that stack.
438 if (CodeSynthesisContexts.size() ==
439 LastEmittedCodeSynthesisContextDepth)
440 LastEmittedCodeSynthesisContextDepth = 0;
441
442 CodeSynthesisContexts.pop_back();
443}
444
445void Sema::InstantiatingTemplate::Clear() {
446 if (!Invalid) {
447 if (!AlreadyInstantiating) {
448 auto &Active = SemaRef.CodeSynthesisContexts.back();
449 SemaRef.InstantiatingSpecializations.erase(
450 std::make_pair(Active.Entity, Active.Kind));
451 }
452
453 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
454 SemaRef.CodeSynthesisContexts.back());
455
456 SemaRef.popCodeSynthesisContext();
457 Invalid = true;
458 }
459}
460
461bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
462 SourceLocation PointOfInstantiation,
463 SourceRange InstantiationRange) {
464 assert(SemaRef.NonInstantiationEntries <=((SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts
.size()) ? static_cast<void> (0) : __assert_fail ("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 465, __PRETTY_FUNCTION__))
38
Assuming the condition is true
39
'?' condition is true
465 SemaRef.CodeSynthesisContexts.size())((SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts
.size()) ? static_cast<void> (0) : __assert_fail ("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 465, __PRETTY_FUNCTION__))
;
466 if ((SemaRef.CodeSynthesisContexts.size() -
40
Assuming the condition is true
41
Taking true branch
467 SemaRef.NonInstantiationEntries)
468 <= SemaRef.getLangOpts().InstantiationDepth)
469 return false;
42
Returning zero, which participates in a condition later
470
471 SemaRef.Diag(PointOfInstantiation,
472 diag::err_template_recursion_depth_exceeded)
473 << SemaRef.getLangOpts().InstantiationDepth
474 << InstantiationRange;
475 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
476 << SemaRef.getLangOpts().InstantiationDepth;
477 return true;
478}
479
480/// Prints the current instantiation stack through a series of
481/// notes.
482void Sema::PrintInstantiationStack() {
483 // Determine which template instantiations to skip, if any.
484 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
485 unsigned Limit = Diags.getTemplateBacktraceLimit();
486 if (Limit && Limit < CodeSynthesisContexts.size()) {
487 SkipStart = Limit / 2 + Limit % 2;
488 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
489 }
490
491 // FIXME: In all of these cases, we need to show the template arguments
492 unsigned InstantiationIdx = 0;
493 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
494 Active = CodeSynthesisContexts.rbegin(),
495 ActiveEnd = CodeSynthesisContexts.rend();
496 Active != ActiveEnd;
497 ++Active, ++InstantiationIdx) {
498 // Skip this instantiation?
499 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
500 if (InstantiationIdx == SkipStart) {
501 // Note that we're skipping instantiations.
502 Diags.Report(Active->PointOfInstantiation,
503 diag::note_instantiation_contexts_suppressed)
504 << unsigned(CodeSynthesisContexts.size() - Limit);
505 }
506 continue;
507 }
508
509 switch (Active->Kind) {
510 case CodeSynthesisContext::TemplateInstantiation: {
511 Decl *D = Active->Entity;
512 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
513 unsigned DiagID = diag::note_template_member_class_here;
514 if (isa<ClassTemplateSpecializationDecl>(Record))
515 DiagID = diag::note_template_class_instantiation_here;
516 Diags.Report(Active->PointOfInstantiation, DiagID)
517 << Record << Active->InstantiationRange;
518 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
519 unsigned DiagID;
520 if (Function->getPrimaryTemplate())
521 DiagID = diag::note_function_template_spec_here;
522 else
523 DiagID = diag::note_template_member_function_here;
524 Diags.Report(Active->PointOfInstantiation, DiagID)
525 << Function
526 << Active->InstantiationRange;
527 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
528 Diags.Report(Active->PointOfInstantiation,
529 VD->isStaticDataMember()?
530 diag::note_template_static_data_member_def_here
531 : diag::note_template_variable_def_here)
532 << VD
533 << Active->InstantiationRange;
534 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
535 Diags.Report(Active->PointOfInstantiation,
536 diag::note_template_enum_def_here)
537 << ED
538 << Active->InstantiationRange;
539 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
540 Diags.Report(Active->PointOfInstantiation,
541 diag::note_template_nsdmi_here)
542 << FD << Active->InstantiationRange;
543 } else {
544 Diags.Report(Active->PointOfInstantiation,
545 diag::note_template_type_alias_instantiation_here)
546 << cast<TypeAliasTemplateDecl>(D)
547 << Active->InstantiationRange;
548 }
549 break;
550 }
551
552 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
553 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
554 SmallVector<char, 128> TemplateArgsStr;
555 llvm::raw_svector_ostream OS(TemplateArgsStr);
556 Template->printName(OS);
557 printTemplateArgumentList(OS, Active->template_arguments(),
558 getPrintingPolicy());
559 Diags.Report(Active->PointOfInstantiation,
560 diag::note_default_arg_instantiation_here)
561 << OS.str()
562 << Active->InstantiationRange;
563 break;
564 }
565
566 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
567 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
568 Diags.Report(Active->PointOfInstantiation,
569 diag::note_explicit_template_arg_substitution_here)
570 << FnTmpl
571 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
572 Active->TemplateArgs,
573 Active->NumTemplateArgs)
574 << Active->InstantiationRange;
575 break;
576 }
577
578 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
579 if (FunctionTemplateDecl *FnTmpl =
580 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
581 Diags.Report(Active->PointOfInstantiation,
582 diag::note_function_template_deduction_instantiation_here)
583 << FnTmpl
584 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
585 Active->TemplateArgs,
586 Active->NumTemplateArgs)
587 << Active->InstantiationRange;
588 } else {
589 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
590 isa<VarTemplateSpecializationDecl>(Active->Entity);
591 bool IsTemplate = false;
592 TemplateParameterList *Params;
593 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
594 IsTemplate = true;
595 Params = D->getTemplateParameters();
596 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
597 Active->Entity)) {
598 Params = D->getTemplateParameters();
599 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
600 Active->Entity)) {
601 Params = D->getTemplateParameters();
602 } else {
603 llvm_unreachable("unexpected template kind")::llvm::llvm_unreachable_internal("unexpected template kind",
"/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 603)
;
604 }
605
606 Diags.Report(Active->PointOfInstantiation,
607 diag::note_deduced_template_arg_substitution_here)
608 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
609 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
610 Active->NumTemplateArgs)
611 << Active->InstantiationRange;
612 }
613 break;
614 }
615
616 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
617 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
618 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
619
620 SmallVector<char, 128> TemplateArgsStr;
621 llvm::raw_svector_ostream OS(TemplateArgsStr);
622 FD->printName(OS);
623 printTemplateArgumentList(OS, Active->template_arguments(),
624 getPrintingPolicy());
625 Diags.Report(Active->PointOfInstantiation,
626 diag::note_default_function_arg_instantiation_here)
627 << OS.str()
628 << Active->InstantiationRange;
629 break;
630 }
631
632 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
633 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
634 std::string Name;
635 if (!Parm->getName().empty())
636 Name = std::string(" '") + Parm->getName().str() + "'";
637
638 TemplateParameterList *TemplateParams = nullptr;
639 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
640 TemplateParams = Template->getTemplateParameters();
641 else
642 TemplateParams =
643 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
644 ->getTemplateParameters();
645 Diags.Report(Active->PointOfInstantiation,
646 diag::note_prior_template_arg_substitution)
647 << isa<TemplateTemplateParmDecl>(Parm)
648 << Name
649 << getTemplateArgumentBindingsText(TemplateParams,
650 Active->TemplateArgs,
651 Active->NumTemplateArgs)
652 << Active->InstantiationRange;
653 break;
654 }
655
656 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
657 TemplateParameterList *TemplateParams = nullptr;
658 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
659 TemplateParams = Template->getTemplateParameters();
660 else
661 TemplateParams =
662 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
663 ->getTemplateParameters();
664
665 Diags.Report(Active->PointOfInstantiation,
666 diag::note_template_default_arg_checking)
667 << getTemplateArgumentBindingsText(TemplateParams,
668 Active->TemplateArgs,
669 Active->NumTemplateArgs)
670 << Active->InstantiationRange;
671 break;
672 }
673
674 case CodeSynthesisContext::ExceptionSpecEvaluation:
675 Diags.Report(Active->PointOfInstantiation,
676 diag::note_evaluating_exception_spec_here)
677 << cast<FunctionDecl>(Active->Entity);
678 break;
679
680 case CodeSynthesisContext::ExceptionSpecInstantiation:
681 Diags.Report(Active->PointOfInstantiation,
682 diag::note_template_exception_spec_instantiation_here)
683 << cast<FunctionDecl>(Active->Entity)
684 << Active->InstantiationRange;
685 break;
686
687 case CodeSynthesisContext::DeclaringSpecialMember:
688 Diags.Report(Active->PointOfInstantiation,
689 diag::note_in_declaration_of_implicit_special_member)
690 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
691 break;
692
693 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
694 Diags.Report(Active->Entity->getLocation(),
695 diag::note_in_declaration_of_implicit_equality_comparison);
696 break;
697
698 case CodeSynthesisContext::DefiningSynthesizedFunction: {
699 // FIXME: For synthesized functions that are not defaulted,
700 // produce a note.
701 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
702 DefaultedFunctionKind DFK =
703 FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();
704 if (DFK.isSpecialMember()) {
705 auto *MD = cast<CXXMethodDecl>(FD);
706 Diags.Report(Active->PointOfInstantiation,
707 diag::note_member_synthesized_at)
708 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
709 << Context.getTagDeclType(MD->getParent());
710 } else if (DFK.isComparison()) {
711 Diags.Report(Active->PointOfInstantiation,
712 diag::note_comparison_synthesized_at)
713 << (int)DFK.asComparison()
714 << Context.getTagDeclType(
715 cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
716 }
717 break;
718 }
719
720 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
721 Diags.Report(Active->Entity->getLocation(),
722 diag::note_rewriting_operator_as_spaceship);
723 break;
724
725 case CodeSynthesisContext::Memoization:
726 break;
727
728 case CodeSynthesisContext::ConstraintsCheck: {
729 unsigned DiagID = 0;
730 if (isa<ConceptDecl>(Active->Entity))
731 DiagID = diag::note_concept_specialization_here;
732 else if (isa<TemplateDecl>(Active->Entity))
733 DiagID = diag::note_checking_constraints_for_template_id_here;
734 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
735 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
736 else {
737 assert(isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))((isa<ClassTemplatePartialSpecializationDecl>(Active->
Entity)) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplatePartialSpecializationDecl>(Active->Entity)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 737, __PRETTY_FUNCTION__))
;
738 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
739 }
740 SmallVector<char, 128> TemplateArgsStr;
741 llvm::raw_svector_ostream OS(TemplateArgsStr);
742 cast<NamedDecl>(Active->Entity)->printName(OS);
743 printTemplateArgumentList(OS, Active->template_arguments(),
744 getPrintingPolicy());
745 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
746 << Active->InstantiationRange;
747 break;
748 }
749 case CodeSynthesisContext::ConstraintSubstitution:
750 Diags.Report(Active->PointOfInstantiation,
751 diag::note_constraint_substitution_here)
752 << Active->InstantiationRange;
753 break;
754 case CodeSynthesisContext::ConstraintNormalization:
755 Diags.Report(Active->PointOfInstantiation,
756 diag::note_constraint_normalization_here)
757 << cast<NamedDecl>(Active->Entity)->getName()
758 << Active->InstantiationRange;
759 break;
760 case CodeSynthesisContext::ParameterMappingSubstitution:
761 Diags.Report(Active->PointOfInstantiation,
762 diag::note_parameter_mapping_substitution_here)
763 << Active->InstantiationRange;
764 break;
765 }
766 }
767}
768
769Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
770 if (InNonInstantiationSFINAEContext)
771 return Optional<TemplateDeductionInfo *>(nullptr);
772
773 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
774 Active = CodeSynthesisContexts.rbegin(),
775 ActiveEnd = CodeSynthesisContexts.rend();
776 Active != ActiveEnd;
777 ++Active)
778 {
779 switch (Active->Kind) {
780 case CodeSynthesisContext::TemplateInstantiation:
781 // An instantiation of an alias template may or may not be a SFINAE
782 // context, depending on what else is on the stack.
783 if (isa<TypeAliasTemplateDecl>(Active->Entity))
784 break;
785 LLVM_FALLTHROUGH[[gnu::fallthrough]];
786 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
787 case CodeSynthesisContext::ExceptionSpecInstantiation:
788 case CodeSynthesisContext::ConstraintsCheck:
789 case CodeSynthesisContext::ParameterMappingSubstitution:
790 case CodeSynthesisContext::ConstraintNormalization:
791 // This is a template instantiation, so there is no SFINAE.
792 return None;
793
794 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
795 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
796 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
797 // A default template argument instantiation and substitution into
798 // template parameters with arguments for prior parameters may or may
799 // not be a SFINAE context; look further up the stack.
800 break;
801
802 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
803 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
804 case CodeSynthesisContext::ConstraintSubstitution:
805 // We're either substituting explicitly-specified template arguments
806 // or deduced template arguments or a constraint expression, so SFINAE
807 // applies.
808 assert(Active->DeductionInfo && "Missing deduction info pointer")((Active->DeductionInfo && "Missing deduction info pointer"
) ? static_cast<void> (0) : __assert_fail ("Active->DeductionInfo && \"Missing deduction info pointer\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 808, __PRETTY_FUNCTION__))
;
809 return Active->DeductionInfo;
810
811 case CodeSynthesisContext::DeclaringSpecialMember:
812 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
813 case CodeSynthesisContext::DefiningSynthesizedFunction:
814 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
815 // This happens in a context unrelated to template instantiation, so
816 // there is no SFINAE.
817 return None;
818
819 case CodeSynthesisContext::ExceptionSpecEvaluation:
820 // FIXME: This should not be treated as a SFINAE context, because
821 // we will cache an incorrect exception specification. However, clang
822 // bootstrap relies this! See PR31692.
823 break;
824
825 case CodeSynthesisContext::Memoization:
826 break;
827 }
828
829 // The inner context was transparent for SFINAE. If it occurred within a
830 // non-instantiation SFINAE context, then SFINAE applies.
831 if (Active->SavedInNonInstantiationSFINAEContext)
832 return Optional<TemplateDeductionInfo *>(nullptr);
833 }
834
835 return None;
836}
837
838//===----------------------------------------------------------------------===/
839// Template Instantiation for Types
840//===----------------------------------------------------------------------===/
841namespace {
842 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
843 const MultiLevelTemplateArgumentList &TemplateArgs;
844 SourceLocation Loc;
845 DeclarationName Entity;
846
847 public:
848 typedef TreeTransform<TemplateInstantiator> inherited;
849
850 TemplateInstantiator(Sema &SemaRef,
851 const MultiLevelTemplateArgumentList &TemplateArgs,
852 SourceLocation Loc,
853 DeclarationName Entity)
854 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
855 Entity(Entity) { }
856
857 /// Determine whether the given type \p T has already been
858 /// transformed.
859 ///
860 /// For the purposes of template instantiation, a type has already been
861 /// transformed if it is NULL or if it is not dependent.
862 bool AlreadyTransformed(QualType T);
863
864 /// Returns the location of the entity being instantiated, if known.
865 SourceLocation getBaseLocation() { return Loc; }
866
867 /// Returns the name of the entity being instantiated, if any.
868 DeclarationName getBaseEntity() { return Entity; }
869
870 /// Sets the "base" location and entity when that
871 /// information is known based on another transformation.
872 void setBase(SourceLocation Loc, DeclarationName Entity) {
873 this->Loc = Loc;
874 this->Entity = Entity;
875 }
876
877 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
878 SourceRange PatternRange,
879 ArrayRef<UnexpandedParameterPack> Unexpanded,
880 bool &ShouldExpand, bool &RetainExpansion,
881 Optional<unsigned> &NumExpansions) {
882 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
883 PatternRange, Unexpanded,
884 TemplateArgs,
885 ShouldExpand,
886 RetainExpansion,
887 NumExpansions);
888 }
889
890 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
891 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
892 }
893
894 TemplateArgument ForgetPartiallySubstitutedPack() {
895 TemplateArgument Result;
896 if (NamedDecl *PartialPack
897 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
898 MultiLevelTemplateArgumentList &TemplateArgs
899 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
900 unsigned Depth, Index;
901 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
902 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
903 Result = TemplateArgs(Depth, Index);
904 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
905 }
906 }
907
908 return Result;
909 }
910
911 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
912 if (Arg.isNull())
913 return;
914
915 if (NamedDecl *PartialPack
916 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
917 MultiLevelTemplateArgumentList &TemplateArgs
918 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
919 unsigned Depth, Index;
920 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
921 TemplateArgs.setArgument(Depth, Index, Arg);
922 }
923 }
924
925 /// Transform the given declaration by instantiating a reference to
926 /// this declaration.
927 Decl *TransformDecl(SourceLocation Loc, Decl *D);
928
929 void transformAttrs(Decl *Old, Decl *New) {
930 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
931 }
932
933 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
934 if (Old->isParameterPack()) {
935 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
936 for (auto *New : NewDecls)
937 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
938 Old, cast<VarDecl>(New));
939 return;
940 }
941
942 assert(NewDecls.size() == 1 &&((NewDecls.size() == 1 && "should only have multiple expansions for a pack"
) ? static_cast<void> (0) : __assert_fail ("NewDecls.size() == 1 && \"should only have multiple expansions for a pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 943, __PRETTY_FUNCTION__))
943 "should only have multiple expansions for a pack")((NewDecls.size() == 1 && "should only have multiple expansions for a pack"
) ? static_cast<void> (0) : __assert_fail ("NewDecls.size() == 1 && \"should only have multiple expansions for a pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 943, __PRETTY_FUNCTION__))
;
944 Decl *New = NewDecls.front();
945
946 // If we've instantiated the call operator of a lambda or the call
947 // operator template of a generic lambda, update the "instantiation of"
948 // information.
949 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
950 if (NewMD && isLambdaCallOperator(NewMD)) {
951 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
952 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
953 NewTD->setInstantiatedFromMemberTemplate(
954 OldMD->getDescribedFunctionTemplate());
955 else
956 NewMD->setInstantiationOfMemberFunction(OldMD,
957 TSK_ImplicitInstantiation);
958 }
959
960 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
961
962 // We recreated a local declaration, but not by instantiating it. There
963 // may be pending dependent diagnostics to produce.
964 if (auto *DC = dyn_cast<DeclContext>(Old))
965 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
966 }
967
968 /// Transform the definition of the given declaration by
969 /// instantiating it.
970 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
971
972 /// Transform the first qualifier within a scope by instantiating the
973 /// declaration.
974 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
975
976 /// Rebuild the exception declaration and register the declaration
977 /// as an instantiated local.
978 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
979 TypeSourceInfo *Declarator,
980 SourceLocation StartLoc,
981 SourceLocation NameLoc,
982 IdentifierInfo *Name);
983
984 /// Rebuild the Objective-C exception declaration and register the
985 /// declaration as an instantiated local.
986 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
987 TypeSourceInfo *TSInfo, QualType T);
988
989 /// Check for tag mismatches when instantiating an
990 /// elaborated type.
991 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
992 ElaboratedTypeKeyword Keyword,
993 NestedNameSpecifierLoc QualifierLoc,
994 QualType T);
995
996 TemplateName
997 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
998 SourceLocation NameLoc,
999 QualType ObjectType = QualType(),
1000 NamedDecl *FirstQualifierInScope = nullptr,
1001 bool AllowInjectedClassName = false);
1002
1003 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1004
1005 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1006 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1007 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1008
1009 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1010 NonTypeTemplateParmDecl *D);
1011 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1012 SubstNonTypeTemplateParmPackExpr *E);
1013
1014 /// Rebuild a DeclRefExpr for a VarDecl reference.
1015 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1016
1017 /// Transform a reference to a function or init-capture parameter pack.
1018 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1019
1020 /// Transform a FunctionParmPackExpr which was built when we couldn't
1021 /// expand a function parameter pack reference which refers to an expanded
1022 /// pack.
1023 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1024
1025 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1026 FunctionProtoTypeLoc TL) {
1027 // Call the base version; it will forward to our overridden version below.
1028 return inherited::TransformFunctionProtoType(TLB, TL);
1029 }
1030
1031 template<typename Fn>
1032 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1033 FunctionProtoTypeLoc TL,
1034 CXXRecordDecl *ThisContext,
1035 Qualifiers ThisTypeQuals,
1036 Fn TransformExceptionSpec);
1037
1038 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1039 int indexAdjustment,
1040 Optional<unsigned> NumExpansions,
1041 bool ExpectParameterPack);
1042
1043 /// Transforms a template type parameter type by performing
1044 /// substitution of the corresponding template type argument.
1045 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1046 TemplateTypeParmTypeLoc TL);
1047
1048 /// Transforms an already-substituted template type parameter pack
1049 /// into either itself (if we aren't substituting into its pack expansion)
1050 /// or the appropriate substituted argument.
1051 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1052 SubstTemplateTypeParmPackTypeLoc TL);
1053
1054 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1055 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1056 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
1057 }
1058
1059 TemplateParameterList *TransformTemplateParameterList(
1060 TemplateParameterList *OrigTPL) {
1061 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1062
1063 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1064 TemplateDeclInstantiator DeclInstantiator(getSema(),
1065 /* DeclContext *Owner */ Owner, TemplateArgs);
1066 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1067 }
1068 private:
1069 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1070 SourceLocation loc,
1071 TemplateArgument arg);
1072 };
1073}
1074
1075bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1076 if (T.isNull())
1077 return true;
1078
1079 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
1080 return false;
1081
1082 getSema().MarkDeclarationsReferencedInType(Loc, T);
1083 return true;
1084}
1085
1086static TemplateArgument
1087getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
1088 assert(S.ArgumentPackSubstitutionIndex >= 0)((S.ArgumentPackSubstitutionIndex >= 0) ? static_cast<void
> (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex >= 0"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1088, __PRETTY_FUNCTION__))
;
1089 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size())((S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()) ?
static_cast<void> (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1089, __PRETTY_FUNCTION__))
;
1090 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1091 if (Arg.isPackExpansion())
1092 Arg = Arg.getPackExpansionPattern();
1093 return Arg;
1094}
1095
1096Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1097 if (!D)
1098 return nullptr;
1099
1100 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1101 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1102 // If the corresponding template argument is NULL or non-existent, it's
1103 // because we are performing instantiation from explicitly-specified
1104 // template arguments in a function template, but there were some
1105 // arguments left unspecified.
1106 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1107 TTP->getPosition()))
1108 return D;
1109
1110 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1111
1112 if (TTP->isParameterPack()) {
1113 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1114, __PRETTY_FUNCTION__))
1114 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1114, __PRETTY_FUNCTION__))
;
1115 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1116 }
1117
1118 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1119 assert(!Template.isNull() && Template.getAsTemplateDecl() &&((!Template.isNull() && Template.getAsTemplateDecl() &&
"Wrong kind of template template argument") ? static_cast<
void> (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1120, __PRETTY_FUNCTION__))
1120 "Wrong kind of template template argument")((!Template.isNull() && Template.getAsTemplateDecl() &&
"Wrong kind of template template argument") ? static_cast<
void> (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1120, __PRETTY_FUNCTION__))
;
1121 return Template.getAsTemplateDecl();
1122 }
1123
1124 // Fall through to find the instantiated declaration for this template
1125 // template parameter.
1126 }
1127
1128 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1129}
1130
1131Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1132 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1133 if (!Inst)
1134 return nullptr;
1135
1136 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1137 return Inst;
1138}
1139
1140NamedDecl *
1141TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1142 SourceLocation Loc) {
1143 // If the first part of the nested-name-specifier was a template type
1144 // parameter, instantiate that type parameter down to a tag type.
1145 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1146 const TemplateTypeParmType *TTP
1147 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1148
1149 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1150 // FIXME: This needs testing w/ member access expressions.
1151 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1152
1153 if (TTP->isParameterPack()) {
1154 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1155, __PRETTY_FUNCTION__))
1155 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1155, __PRETTY_FUNCTION__))
;
1156
1157 if (getSema().ArgumentPackSubstitutionIndex == -1)
1158 return nullptr;
1159
1160 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1161 }
1162
1163 QualType T = Arg.getAsType();
1164 if (T.isNull())
1165 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1166
1167 if (const TagType *Tag = T->getAs<TagType>())
1168 return Tag->getDecl();
1169
1170 // The resulting type is not a tag; complain.
1171 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1172 return nullptr;
1173 }
1174 }
1175
1176 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1177}
1178
1179VarDecl *
1180TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1181 TypeSourceInfo *Declarator,
1182 SourceLocation StartLoc,
1183 SourceLocation NameLoc,
1184 IdentifierInfo *Name) {
1185 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1186 StartLoc, NameLoc, Name);
1187 if (Var)
1188 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1189 return Var;
1190}
1191
1192VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1193 TypeSourceInfo *TSInfo,
1194 QualType T) {
1195 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1196 if (Var)
1197 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1198 return Var;
1199}
1200
1201QualType
1202TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1203 ElaboratedTypeKeyword Keyword,
1204 NestedNameSpecifierLoc QualifierLoc,
1205 QualType T) {
1206 if (const TagType *TT = T->getAs<TagType>()) {
1207 TagDecl* TD = TT->getDecl();
1208
1209 SourceLocation TagLocation = KeywordLoc;
1210
1211 IdentifierInfo *Id = TD->getIdentifier();
1212
1213 // TODO: should we even warn on struct/class mismatches for this? Seems
1214 // like it's likely to produce a lot of spurious errors.
1215 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1216 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1217 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1218 TagLocation, Id)) {
1219 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1220 << Id
1221 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1222 TD->getKindName());
1223 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1224 }
1225 }
1226 }
1227
1228 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1229 Keyword,
1230 QualifierLoc,
1231 T);
1232}
1233
1234TemplateName TemplateInstantiator::TransformTemplateName(
1235 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1236 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1237 bool AllowInjectedClassName) {
1238 if (TemplateTemplateParmDecl *TTP
1239 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1240 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1241 // If the corresponding template argument is NULL or non-existent, it's
1242 // because we are performing instantiation from explicitly-specified
1243 // template arguments in a function template, but there were some
1244 // arguments left unspecified.
1245 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1246 TTP->getPosition()))
1247 return Name;
1248
1249 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1250
1251 if (TTP->isParameterPack()) {
1252 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1253, __PRETTY_FUNCTION__))
1253 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1253, __PRETTY_FUNCTION__))
;
1254
1255 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1256 // We have the template argument pack to substitute, but we're not
1257 // actually expanding the enclosing pack expansion yet. So, just
1258 // keep the entire argument pack.
1259 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1260 }
1261
1262 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1263 }
1264
1265 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1266 assert(!Template.isNull() && "Null template template argument")((!Template.isNull() && "Null template template argument"
) ? static_cast<void> (0) : __assert_fail ("!Template.isNull() && \"Null template template argument\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1266, __PRETTY_FUNCTION__))
;
1267 assert(!Template.getAsQualifiedTemplateName() &&((!Template.getAsQualifiedTemplateName() && "template decl to substitute is qualified?"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1268, __PRETTY_FUNCTION__))
1268 "template decl to substitute is qualified?")((!Template.getAsQualifiedTemplateName() && "template decl to substitute is qualified?"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1268, __PRETTY_FUNCTION__))
;
1269
1270 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1271 return Template;
1272 }
1273 }
1274
1275 if (SubstTemplateTemplateParmPackStorage *SubstPack
1276 = Name.getAsSubstTemplateTemplateParmPack()) {
1277 if (getSema().ArgumentPackSubstitutionIndex == -1)
1278 return Name;
1279
1280 TemplateArgument Arg = SubstPack->getArgumentPack();
1281 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1282 return Arg.getAsTemplate().getNameToSubstitute();
1283 }
1284
1285 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1286 FirstQualifierInScope,
1287 AllowInjectedClassName);
1288}
1289
1290ExprResult
1291TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1292 if (!E->isTypeDependent())
1293 return E;
1294
1295 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1296}
1297
1298ExprResult
1299TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1300 NonTypeTemplateParmDecl *NTTP) {
1301 // If the corresponding template argument is NULL or non-existent, it's
1302 // because we are performing instantiation from explicitly-specified
1303 // template arguments in a function template, but there were some
1304 // arguments left unspecified.
1305 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1306 NTTP->getPosition()))
1307 return E;
1308
1309 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1310
1311 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1312 // We're performing a partial substitution, so the substituted argument
1313 // could be dependent. As a result we can't create a SubstNonType*Expr
1314 // node now, since that represents a fully-substituted argument.
1315 // FIXME: We should have some AST representation for this.
1316 if (Arg.getKind() == TemplateArgument::Pack) {
1317 // FIXME: This won't work for alias templates.
1318 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion
() && "unexpected pack arguments in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1319, __PRETTY_FUNCTION__))
1319 "unexpected pack arguments in partial substitution")((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion
() && "unexpected pack arguments in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1319, __PRETTY_FUNCTION__))
;
1320 Arg = Arg.pack_begin()->getPackExpansionPattern();
1321 }
1322 assert(Arg.getKind() == TemplateArgument::Expression &&((Arg.getKind() == TemplateArgument::Expression && "unexpected nontype template argument kind in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1323, __PRETTY_FUNCTION__))
1323 "unexpected nontype template argument kind in partial substitution")((Arg.getKind() == TemplateArgument::Expression && "unexpected nontype template argument kind in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1323, __PRETTY_FUNCTION__))
;
1324 return Arg.getAsExpr();
1325 }
1326
1327 if (NTTP->isParameterPack()) {
1328 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1329, __PRETTY_FUNCTION__))
1329 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1329, __PRETTY_FUNCTION__))
;
1330
1331 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1332 // We have an argument pack, but we can't select a particular argument
1333 // out of it yet. Therefore, we'll build an expression to hold on to that
1334 // argument pack.
1335 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1336 E->getLocation(),
1337 NTTP->getDeclName());
1338 if (TargetType.isNull())
1339 return ExprError();
1340
1341 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1342 TargetType.getNonLValueExprType(SemaRef.Context),
1343 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1344 E->getLocation(), Arg);
1345 }
1346
1347 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1348 }
1349
1350 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1351}
1352
1353const LoopHintAttr *
1354TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1355 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1356
1357 if (TransformedExpr == LH->getValue())
1358 return LH;
1359
1360 // Generate error if there is a problem with the value.
1361 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1362 return LH;
1363
1364 // Create new LoopHintValueAttr with integral expression in place of the
1365 // non-type template parameter.
1366 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1367 LH->getState(), TransformedExpr, *LH);
1368}
1369
1370ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1371 NonTypeTemplateParmDecl *parm,
1372 SourceLocation loc,
1373 TemplateArgument arg) {
1374 ExprResult result;
1375 QualType type;
1376
1377 // The template argument itself might be an expression, in which
1378 // case we just return that expression.
1379 if (arg.getKind() == TemplateArgument::Expression) {
1380 Expr *argExpr = arg.getAsExpr();
1381 result = argExpr;
1382 type = argExpr->getType();
1383
1384 } else if (arg.getKind() == TemplateArgument::Declaration ||
1385 arg.getKind() == TemplateArgument::NullPtr) {
1386 ValueDecl *VD;
1387 if (arg.getKind() == TemplateArgument::Declaration) {
1388 VD = arg.getAsDecl();
1389
1390 // Find the instantiation of the template argument. This is
1391 // required for nested templates.
1392 VD = cast_or_null<ValueDecl>(
1393 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1394 if (!VD)
1395 return ExprError();
1396 } else {
1397 // Propagate NULL template argument.
1398 VD = nullptr;
1399 }
1400
1401 // Derive the type we want the substituted decl to have. This had
1402 // better be non-dependent, or these checks will have serious problems.
1403 if (parm->isExpandedParameterPack()) {
1404 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1405 } else if (parm->isParameterPack() &&
1406 isa<PackExpansionType>(parm->getType())) {
1407 type = SemaRef.SubstType(
1408 cast<PackExpansionType>(parm->getType())->getPattern(),
1409 TemplateArgs, loc, parm->getDeclName());
1410 } else {
1411 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1412 TemplateArgs, loc, parm->getDeclName());
1413 }
1414 assert(!type.isNull() && "type substitution failed for param type")((!type.isNull() && "type substitution failed for param type"
) ? static_cast<void> (0) : __assert_fail ("!type.isNull() && \"type substitution failed for param type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1414, __PRETTY_FUNCTION__))
;
1415 assert(!type->isDependentType() && "param type still dependent")((!type->isDependentType() && "param type still dependent"
) ? static_cast<void> (0) : __assert_fail ("!type->isDependentType() && \"param type still dependent\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1415, __PRETTY_FUNCTION__))
;
1416 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1417
1418 if (!result.isInvalid()) type = result.get()->getType();
1419 } else {
1420 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1421
1422 // Note that this type can be different from the type of 'result',
1423 // e.g. if it's an enum type.
1424 type = arg.getIntegralType();
1425 }
1426 if (result.isInvalid()) return ExprError();
1427
1428 Expr *resultExpr = result.get();
1429 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1430 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1431}
1432
1433ExprResult
1434TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1435 SubstNonTypeTemplateParmPackExpr *E) {
1436 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1437 // We aren't expanding the parameter pack, so just return ourselves.
1438 return E;
1439 }
1440
1441 TemplateArgument Arg = E->getArgumentPack();
1442 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1443 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1444 E->getParameterPackLocation(),
1445 Arg);
1446}
1447
1448ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1449 SourceLocation Loc) {
1450 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1451 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1452}
1453
1454ExprResult
1455TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1456 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1457 // We can expand this parameter pack now.
1458 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1459 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1460 if (!VD)
1461 return ExprError();
1462 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1463 }
1464
1465 QualType T = TransformType(E->getType());
1466 if (T.isNull())
1467 return ExprError();
1468
1469 // Transform each of the parameter expansions into the corresponding
1470 // parameters in the instantiation of the function decl.
1471 SmallVector<VarDecl *, 8> Vars;
1472 Vars.reserve(E->getNumExpansions());
1473 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1474 I != End; ++I) {
1475 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1476 if (!D)
1477 return ExprError();
1478 Vars.push_back(D);
1479 }
1480
1481 auto *PackExpr =
1482 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1483 E->getParameterPackLocation(), Vars);
1484 getSema().MarkFunctionParmPackReferenced(PackExpr);
1485 return PackExpr;
1486}
1487
1488ExprResult
1489TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1490 VarDecl *PD) {
1491 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1492 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1493 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1494 assert(Found && "no instantiation for parameter pack")((Found && "no instantiation for parameter pack") ? static_cast
<void> (0) : __assert_fail ("Found && \"no instantiation for parameter pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1494, __PRETTY_FUNCTION__))
;
1495
1496 Decl *TransformedDecl;
1497 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1498 // If this is a reference to a function parameter pack which we can
1499 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1500 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1501 QualType T = TransformType(E->getType());
1502 if (T.isNull())
1503 return ExprError();
1504 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1505 E->getExprLoc(), *Pack);
1506 getSema().MarkFunctionParmPackReferenced(PackExpr);
1507 return PackExpr;
1508 }
1509
1510 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1511 } else {
1512 TransformedDecl = Found->get<Decl*>();
1513 }
1514
1515 // We have either an unexpanded pack or a specific expansion.
1516 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1517}
1518
1519ExprResult
1520TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1521 NamedDecl *D = E->getDecl();
1522
1523 // Handle references to non-type template parameters and non-type template
1524 // parameter packs.
1525 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1526 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1527 return TransformTemplateParmRefExpr(E, NTTP);
1528
1529 // We have a non-type template parameter that isn't fully substituted;
1530 // FindInstantiatedDecl will find it in the local instantiation scope.
1531 }
1532
1533 // Handle references to function parameter packs.
1534 if (VarDecl *PD = dyn_cast<VarDecl>(D))
1535 if (PD->isParameterPack())
1536 return TransformFunctionParmPackRefExpr(E, PD);
1537
1538 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1539}
1540
1541ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1542 CXXDefaultArgExpr *E) {
1543 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->((!cast<FunctionDecl>(E->getParam()->getDeclContext
())-> getDescribedFunctionTemplate() && "Default arg expressions are never formed in dependent cases."
) ? static_cast<void> (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1545, __PRETTY_FUNCTION__))
1544 getDescribedFunctionTemplate() &&((!cast<FunctionDecl>(E->getParam()->getDeclContext
())-> getDescribedFunctionTemplate() && "Default arg expressions are never formed in dependent cases."
) ? static_cast<void> (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1545, __PRETTY_FUNCTION__))
1545 "Default arg expressions are never formed in dependent cases.")((!cast<FunctionDecl>(E->getParam()->getDeclContext
())-> getDescribedFunctionTemplate() && "Default arg expressions are never formed in dependent cases."
) ? static_cast<void> (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1545, __PRETTY_FUNCTION__))
;
1546 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1547 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1548 E->getParam());
1549}
1550
1551template<typename Fn>
1552QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1553 FunctionProtoTypeLoc TL,
1554 CXXRecordDecl *ThisContext,
1555 Qualifiers ThisTypeQuals,
1556 Fn TransformExceptionSpec) {
1557 // We need a local instantiation scope for this function prototype.
1558 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1559 return inherited::TransformFunctionProtoType(
1560 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1561}
1562
1563ParmVarDecl *
1564TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1565 int indexAdjustment,
1566 Optional<unsigned> NumExpansions,
1567 bool ExpectParameterPack) {
1568 auto NewParm =
1569 SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1570 NumExpansions, ExpectParameterPack);
1571 if (NewParm && SemaRef.getLangOpts().OpenCL)
1572 SemaRef.deduceOpenCLAddressSpace(NewParm);
1573 return NewParm;
1574}
1575
1576QualType
1577TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1578 TemplateTypeParmTypeLoc TL) {
1579 const TemplateTypeParmType *T = TL.getTypePtr();
1580 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1581 // Replace the template type parameter with its corresponding
1582 // template argument.
1583
1584 // If the corresponding template argument is NULL or doesn't exist, it's
1585 // because we are performing instantiation from explicitly-specified
1586 // template arguments in a function template class, but there were some
1587 // arguments left unspecified.
1588 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1589 TemplateTypeParmTypeLoc NewTL
1590 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1591 NewTL.setNameLoc(TL.getNameLoc());
1592 return TL.getType();
1593 }
1594
1595 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1596
1597 if (T->isParameterPack()) {
1598 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1599, __PRETTY_FUNCTION__))
1599 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1599, __PRETTY_FUNCTION__))
;
1600
1601 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1602 // We have the template argument pack, but we're not expanding the
1603 // enclosing pack expansion yet. Just save the template argument
1604 // pack for later substitution.
1605 QualType Result
1606 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1607 SubstTemplateTypeParmPackTypeLoc NewTL
1608 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1609 NewTL.setNameLoc(TL.getNameLoc());
1610 return Result;
1611 }
1612
1613 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1614 }
1615
1616 assert(Arg.getKind() == TemplateArgument::Type &&((Arg.getKind() == TemplateArgument::Type && "Template argument kind mismatch"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1617, __PRETTY_FUNCTION__))
1617 "Template argument kind mismatch")((Arg.getKind() == TemplateArgument::Type && "Template argument kind mismatch"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1617, __PRETTY_FUNCTION__))
;
1618
1619 QualType Replacement = Arg.getAsType();
1620
1621 // TODO: only do this uniquing once, at the start of instantiation.
1622 QualType Result
1623 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1624 SubstTemplateTypeParmTypeLoc NewTL
1625 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1626 NewTL.setNameLoc(TL.getNameLoc());
1627 return Result;
1628 }
1629
1630 // The template type parameter comes from an inner template (e.g.,
1631 // the template parameter list of a member template inside the
1632 // template we are instantiating). Create a new template type
1633 // parameter with the template "level" reduced by one.
1634 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1635 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1636 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1637 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1638
1639 QualType Result = getSema().Context.getTemplateTypeParmType(
1640 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1641 T->isParameterPack(), NewTTPDecl);
1642 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1643 NewTL.setNameLoc(TL.getNameLoc());
1644 return Result;
1645}
1646
1647QualType
1648TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1649 TypeLocBuilder &TLB,
1650 SubstTemplateTypeParmPackTypeLoc TL) {
1651 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1652 // We aren't expanding the parameter pack, so just return ourselves.
1653 SubstTemplateTypeParmPackTypeLoc NewTL
1654 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1655 NewTL.setNameLoc(TL.getNameLoc());
1656 return TL.getType();
1657 }
1658
1659 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1660 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1661 QualType Result = Arg.getAsType();
1662
1663 Result = getSema().Context.getSubstTemplateTypeParmType(
1664 TL.getTypePtr()->getReplacedParameter(),
1665 Result);
1666 SubstTemplateTypeParmTypeLoc NewTL
1667 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1668 NewTL.setNameLoc(TL.getNameLoc());
1669 return Result;
1670}
1671
1672/// Perform substitution on the type T with a given set of template
1673/// arguments.
1674///
1675/// This routine substitutes the given template arguments into the
1676/// type T and produces the instantiated type.
1677///
1678/// \param T the type into which the template arguments will be
1679/// substituted. If this type is not dependent, it will be returned
1680/// immediately.
1681///
1682/// \param Args the template arguments that will be
1683/// substituted for the top-level template parameters within T.
1684///
1685/// \param Loc the location in the source code where this substitution
1686/// is being performed. It will typically be the location of the
1687/// declarator (if we're instantiating the type of some declaration)
1688/// or the location of the type in the source code (if, e.g., we're
1689/// instantiating the type of a cast expression).
1690///
1691/// \param Entity the name of the entity associated with a declaration
1692/// being instantiated (if any). May be empty to indicate that there
1693/// is no such entity (if, e.g., this is a type that occurs as part of
1694/// a cast expression) or that the entity has no name (e.g., an
1695/// unnamed function parameter).
1696///
1697/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1698/// acceptable as the top level type of the result.
1699///
1700/// \returns If the instantiation succeeds, the instantiated
1701/// type. Otherwise, produces diagnostics and returns a NULL type.
1702TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1703 const MultiLevelTemplateArgumentList &Args,
1704 SourceLocation Loc,
1705 DeclarationName Entity,
1706 bool AllowDeducedTST) {
1707 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1709, __PRETTY_FUNCTION__))
1708 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1709, __PRETTY_FUNCTION__))
1709 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1709, __PRETTY_FUNCTION__))
;
1710
1711 if (!T->getType()->isInstantiationDependentType() &&
1712 !T->getType()->isVariablyModifiedType())
1713 return T;
1714
1715 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1716 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1717 : Instantiator.TransformType(T);
1718}
1719
1720TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1721 const MultiLevelTemplateArgumentList &Args,
1722 SourceLocation Loc,
1723 DeclarationName Entity) {
1724 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1726, __PRETTY_FUNCTION__))
1725 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1726, __PRETTY_FUNCTION__))
1726 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1726, __PRETTY_FUNCTION__))
;
1727
1728 if (TL.getType().isNull())
1729 return nullptr;
1730
1731 if (!TL.getType()->isInstantiationDependentType() &&
1732 !TL.getType()->isVariablyModifiedType()) {
1733 // FIXME: Make a copy of the TypeLoc data here, so that we can
1734 // return a new TypeSourceInfo. Inefficient!
1735 TypeLocBuilder TLB;
1736 TLB.pushFullCopy(TL);
1737 return TLB.getTypeSourceInfo(Context, TL.getType());
1738 }
1739
1740 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1741 TypeLocBuilder TLB;
1742 TLB.reserve(TL.getFullDataSize());
1743 QualType Result = Instantiator.TransformType(TLB, TL);
1744 if (Result.isNull())
1745 return nullptr;
1746
1747 return TLB.getTypeSourceInfo(Context, Result);
1748}
1749
1750/// Deprecated form of the above.
1751QualType Sema::SubstType(QualType T,
1752 const MultiLevelTemplateArgumentList &TemplateArgs,
1753 SourceLocation Loc, DeclarationName Entity) {
1754 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1756, __PRETTY_FUNCTION__))
1755 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1756, __PRETTY_FUNCTION__))
1756 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1756, __PRETTY_FUNCTION__))
;
1757
1758 // If T is not a dependent type or a variably-modified type, there
1759 // is nothing to do.
1760 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1761 return T;
1762
1763 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1764 return Instantiator.TransformType(T);
1765}
1766
1767static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1768 if (T->getType()->isInstantiationDependentType() ||
1769 T->getType()->isVariablyModifiedType())
1770 return true;
1771
1772 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1773 if (!TL.getAs<FunctionProtoTypeLoc>())
1774 return false;
1775
1776 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1777 for (ParmVarDecl *P : FP.getParams()) {
1778 // This must be synthesized from a typedef.
1779 if (!P) continue;
1780
1781 // If there are any parameters, a new TypeSourceInfo that refers to the
1782 // instantiated parameters must be built.
1783 return true;
1784 }
1785
1786 return false;
1787}
1788
1789/// A form of SubstType intended specifically for instantiating the
1790/// type of a FunctionDecl. Its purpose is solely to force the
1791/// instantiation of default-argument expressions and to avoid
1792/// instantiating an exception-specification.
1793TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1794 const MultiLevelTemplateArgumentList &Args,
1795 SourceLocation Loc,
1796 DeclarationName Entity,
1797 CXXRecordDecl *ThisContext,
1798 Qualifiers ThisTypeQuals) {
1799 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1801, __PRETTY_FUNCTION__))
1800 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1801, __PRETTY_FUNCTION__))
1801 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1801, __PRETTY_FUNCTION__))
;
1802
1803 if (!NeedsInstantiationAsFunctionType(T))
1804 return T;
1805
1806 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1807
1808 TypeLocBuilder TLB;
1809
1810 TypeLoc TL = T->getTypeLoc();
1811 TLB.reserve(TL.getFullDataSize());
1812
1813 QualType Result;
1814
1815 if (FunctionProtoTypeLoc Proto =
1816 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1817 // Instantiate the type, other than its exception specification. The
1818 // exception specification is instantiated in InitFunctionInstantiation
1819 // once we've built the FunctionDecl.
1820 // FIXME: Set the exception specification to EST_Uninstantiated here,
1821 // instead of rebuilding the function type again later.
1822 Result = Instantiator.TransformFunctionProtoType(
1823 TLB, Proto, ThisContext, ThisTypeQuals,
1824 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1825 bool &Changed) { return false; });
1826 } else {
1827 Result = Instantiator.TransformType(TLB, TL);
1828 }
1829 if (Result.isNull())
1830 return nullptr;
1831
1832 return TLB.getTypeSourceInfo(Context, Result);
1833}
1834
1835bool Sema::SubstExceptionSpec(SourceLocation Loc,
1836 FunctionProtoType::ExceptionSpecInfo &ESI,
1837 SmallVectorImpl<QualType> &ExceptionStorage,
1838 const MultiLevelTemplateArgumentList &Args) {
1839 assert(ESI.Type != EST_Uninstantiated)((ESI.Type != EST_Uninstantiated) ? static_cast<void> (
0) : __assert_fail ("ESI.Type != EST_Uninstantiated", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1839, __PRETTY_FUNCTION__))
;
1840
1841 bool Changed = false;
1842 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1843 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1844 Changed);
1845}
1846
1847void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1848 const MultiLevelTemplateArgumentList &Args) {
1849 FunctionProtoType::ExceptionSpecInfo ESI =
1850 Proto->getExtProtoInfo().ExceptionSpec;
1851
1852 SmallVector<QualType, 4> ExceptionStorage;
1853 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
1854 ESI, ExceptionStorage, Args))
1855 // On error, recover by dropping the exception specification.
1856 ESI.Type = EST_None;
1857
1858 UpdateExceptionSpec(New, ESI);
1859}
1860
1861ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1862 const MultiLevelTemplateArgumentList &TemplateArgs,
1863 int indexAdjustment,
1864 Optional<unsigned> NumExpansions,
1865 bool ExpectParameterPack) {
1866 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1867 TypeSourceInfo *NewDI = nullptr;
1868
1869 TypeLoc OldTL = OldDI->getTypeLoc();
1870 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1871
1872 // We have a function parameter pack. Substitute into the pattern of the
1873 // expansion.
1874 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1875 OldParm->getLocation(), OldParm->getDeclName());
1876 if (!NewDI)
1877 return nullptr;
1878
1879 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1880 // We still have unexpanded parameter packs, which means that
1881 // our function parameter is still a function parameter pack.
1882 // Therefore, make its type a pack expansion type.
1883 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1884 NumExpansions);
1885 } else if (ExpectParameterPack) {
1886 // We expected to get a parameter pack but didn't (because the type
1887 // itself is not a pack expansion type), so complain. This can occur when
1888 // the substitution goes through an alias template that "loses" the
1889 // pack expansion.
1890 Diag(OldParm->getLocation(),
1891 diag::err_function_parameter_pack_without_parameter_packs)
1892 << NewDI->getType();
1893 return nullptr;
1894 }
1895 } else {
1896 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1897 OldParm->getDeclName());
1898 }
1899
1900 if (!NewDI)
1901 return nullptr;
1902
1903 if (NewDI->getType()->isVoidType()) {
1904 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1905 return nullptr;
1906 }
1907
1908 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1909 OldParm->getInnerLocStart(),
1910 OldParm->getLocation(),
1911 OldParm->getIdentifier(),
1912 NewDI->getType(), NewDI,
1913 OldParm->getStorageClass());
1914 if (!NewParm)
1915 return nullptr;
1916
1917 // Mark the (new) default argument as uninstantiated (if any).
1918 if (OldParm->hasUninstantiatedDefaultArg()) {
1919 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1920 NewParm->setUninstantiatedDefaultArg(Arg);
1921 } else if (OldParm->hasUnparsedDefaultArg()) {
1922 NewParm->setUnparsedDefaultArg();
1923 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1924 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1925 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1926 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1927 // Instantiate default arguments for methods of local classes (DR1484)
1928 // and non-defining declarations.
1929 Sema::ContextRAII SavedContext(*this, OwningFunc);
1930 LocalInstantiationScope Local(*this, true);
1931 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1932 if (NewArg.isUsable()) {
1933 // It would be nice if we still had this.
1934 SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
1935 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1936 }
1937 } else {
1938 // FIXME: if we non-lazily instantiated non-dependent default args for
1939 // non-dependent parameter types we could remove a bunch of duplicate
1940 // conversion warnings for such arguments.
1941 NewParm->setUninstantiatedDefaultArg(Arg);
1942 }
1943 }
1944
1945 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1946
1947 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1948 // Add the new parameter to the instantiated parameter pack.
1949 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1950 } else {
1951 // Introduce an Old -> New mapping
1952 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1953 }
1954
1955 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1956 // can be anything, is this right ?
1957 NewParm->setDeclContext(CurContext);
1958
1959 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1960 OldParm->getFunctionScopeIndex() + indexAdjustment);
1961
1962 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1963
1964 return NewParm;
1965}
1966
1967/// Substitute the given template arguments into the given set of
1968/// parameters, producing the set of parameter types that would be generated
1969/// from such a substitution.
1970bool Sema::SubstParmTypes(
1971 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1972 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1973 const MultiLevelTemplateArgumentList &TemplateArgs,
1974 SmallVectorImpl<QualType> &ParamTypes,
1975 SmallVectorImpl<ParmVarDecl *> *OutParams,
1976 ExtParameterInfoBuilder &ParamInfos) {
1977 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1979, __PRETTY_FUNCTION__))
1978 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1979, __PRETTY_FUNCTION__))
1979 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1979, __PRETTY_FUNCTION__))
;
1980
1981 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1982 DeclarationName());
1983 return Instantiator.TransformFunctionTypeParams(
1984 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1985}
1986
1987/// Perform substitution on the base class specifiers of the
1988/// given class template specialization.
1989///
1990/// Produces a diagnostic and returns true on error, returns false and
1991/// attaches the instantiated base classes to the class template
1992/// specialization if successful.
1993bool
1994Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1995 CXXRecordDecl *Pattern,
1996 const MultiLevelTemplateArgumentList &TemplateArgs) {
1997 bool Invalid = false;
1998 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1999 for (const auto &Base : Pattern->bases()) {
2000 if (!Base.getType()->isDependentType()) {
2001 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
2002 if (RD->isInvalidDecl())
2003 Instantiation->setInvalidDecl();
2004 }
2005 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
2006 continue;
2007 }
2008
2009 SourceLocation EllipsisLoc;
2010 TypeSourceInfo *BaseTypeLoc;
2011 if (Base.isPackExpansion()) {
2012 // This is a pack expansion. See whether we should expand it now, or
2013 // wait until later.
2014 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2015 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
2016 Unexpanded);
2017 bool ShouldExpand = false;
2018 bool RetainExpansion = false;
2019 Optional<unsigned> NumExpansions;
2020 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
2021 Base.getSourceRange(),
2022 Unexpanded,
2023 TemplateArgs, ShouldExpand,
2024 RetainExpansion,
2025 NumExpansions)) {
2026 Invalid = true;
2027 continue;
2028 }
2029
2030 // If we should expand this pack expansion now, do so.
2031 if (ShouldExpand) {
2032 for (unsigned I = 0; I != *NumExpansions; ++I) {
2033 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2034
2035 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2036 TemplateArgs,
2037 Base.getSourceRange().getBegin(),
2038 DeclarationName());
2039 if (!BaseTypeLoc) {
2040 Invalid = true;
2041 continue;
2042 }
2043
2044 if (CXXBaseSpecifier *InstantiatedBase
2045 = CheckBaseSpecifier(Instantiation,
2046 Base.getSourceRange(),
2047 Base.isVirtual(),
2048 Base.getAccessSpecifierAsWritten(),
2049 BaseTypeLoc,
2050 SourceLocation()))
2051 InstantiatedBases.push_back(InstantiatedBase);
2052 else
2053 Invalid = true;
2054 }
2055
2056 continue;
2057 }
2058
2059 // The resulting base specifier will (still) be a pack expansion.
2060 EllipsisLoc = Base.getEllipsisLoc();
2061 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2062 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2063 TemplateArgs,
2064 Base.getSourceRange().getBegin(),
2065 DeclarationName());
2066 } else {
2067 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2068 TemplateArgs,
2069 Base.getSourceRange().getBegin(),
2070 DeclarationName());
2071 }
2072
2073 if (!BaseTypeLoc) {
2074 Invalid = true;
2075 continue;
2076 }
2077
2078 if (CXXBaseSpecifier *InstantiatedBase
2079 = CheckBaseSpecifier(Instantiation,
2080 Base.getSourceRange(),
2081 Base.isVirtual(),
2082 Base.getAccessSpecifierAsWritten(),
2083 BaseTypeLoc,
2084 EllipsisLoc))
2085 InstantiatedBases.push_back(InstantiatedBase);
2086 else
2087 Invalid = true;
2088 }
2089
2090 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
2091 Invalid = true;
2092
2093 return Invalid;
2094}
2095
2096// Defined via #include from SemaTemplateInstantiateDecl.cpp
2097namespace clang {
2098 namespace sema {
2099 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
2100 const MultiLevelTemplateArgumentList &TemplateArgs);
2101 Attr *instantiateTemplateAttributeForDecl(
2102 const Attr *At, ASTContext &C, Sema &S,
2103 const MultiLevelTemplateArgumentList &TemplateArgs);
2104 }
2105}
2106
2107/// Instantiate the definition of a class from a given pattern.
2108///
2109/// \param PointOfInstantiation The point of instantiation within the
2110/// source code.
2111///
2112/// \param Instantiation is the declaration whose definition is being
2113/// instantiated. This will be either a class template specialization
2114/// or a member class of a class template specialization.
2115///
2116/// \param Pattern is the pattern from which the instantiation
2117/// occurs. This will be either the declaration of a class template or
2118/// the declaration of a member class of a class template.
2119///
2120/// \param TemplateArgs The template arguments to be substituted into
2121/// the pattern.
2122///
2123/// \param TSK the kind of implicit or explicit instantiation to perform.
2124///
2125/// \param Complain whether to complain if the class cannot be instantiated due
2126/// to the lack of a definition.
2127///
2128/// \returns true if an error occurred, false otherwise.
2129bool
2130Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2131 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
2132 const MultiLevelTemplateArgumentList &TemplateArgs,
2133 TemplateSpecializationKind TSK,
2134 bool Complain) {
2135 CXXRecordDecl *PatternDef
2136 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
27
Assuming the object is a 'CXXRecordDecl'
2137 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
28
Assuming the condition is false
29
Taking false branch
2138 Instantiation->getInstantiatedFromMemberClass(),
2139 Pattern, PatternDef, TSK, Complain))
2140 return true;
2141
2142 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
2143 std::string Name;
2144 llvm::raw_string_ostream OS(Name);
2145 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2146 /*Qualified=*/true);
2147 return Name;
2148 });
2149
2150 Pattern = PatternDef;
2151
2152 // Record the point of instantiation.
2153 if (MemberSpecializationInfo *MSInfo
30
Assuming 'MSInfo' is null
31
Taking false branch
2154 = Instantiation->getMemberSpecializationInfo()) {
2155 MSInfo->setTemplateSpecializationKind(TSK);
2156 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2157 } else if (ClassTemplateSpecializationDecl *Spec
32.1
'Spec' is null
32.1
'Spec' is null
33
Taking false branch
2158 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
32
Assuming 'Instantiation' is not a 'ClassTemplateSpecializationDecl'
2159 Spec->setTemplateSpecializationKind(TSK); 2160 Spec->setPointOfInstantiation(PointOfInstantiation); 2161 } 2162 2163 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
34
Calling constructor for 'InstantiatingTemplate'
47
Returning from constructor for 'InstantiatingTemplate'
2164 if (Inst.isInvalid())
48
Calling 'InstantiatingTemplate::isInvalid'
50
Returning from 'InstantiatingTemplate::isInvalid'
51
Taking false branch
2165 return true; 2166 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller")((!Inst.isAlreadyInstantiating() && "should have been caught by caller"
) ? static_cast<void> (0) : __assert_fail ("!Inst.isAlreadyInstantiating() && \"should have been caught by caller\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2166, __PRETTY_FUNCTION__))
;
52
'?' condition is true
2167 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), 2168 "instantiating class definition"); 2169 2170 // Enter the scope of this instantiation. We don't use 2171 // PushDeclContext because we don't have a scope. 2172 ContextRAII SavedContext(*this, Instantiation); 2173 EnterExpressionEvaluationContext EvalContext( 2174 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 2175 2176 // If this is an instantiation of a local class, merge this local 2177 // instantiation scope with the enclosing scope. Otherwise, every 2178 // instantiation of a class has its own local instantiation scope. 2179 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod(); 2180 LocalInstantiationScope Scope(*this, MergeWithParentScope); 2181 2182 // Some class state isn't processed immediately but delayed till class 2183 // instantiation completes. We may not be ready to handle any delayed state 2184 // already on the stack as it might correspond to a different class, so save 2185 // it now and put it back later. 2186 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this); 2187 2188 // Pull attributes from the pattern onto the instantiation. 2189 InstantiateAttrs(TemplateArgs, Pattern, Instantiation); 2190 2191 // Start the definition of this instantiation. 2192 Instantiation->startDefinition(); 2193 2194 // The instantiation is visible here, even if it was first declared in an 2195 // unimported module. 2196 Instantiation->setVisibleDespiteOwningModule(); 2197 2198 // FIXME: This loses the as-written tag kind for an explicit instantiation. 2199 Instantiation->setTagKind(Pattern->getTagKind()); 2200 2201 // Do substitution on the base class specifiers. 2202 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
53
Taking false branch
2203 Instantiation->setInvalidDecl(); 2204 2205 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); 2206 SmallVector<Decl*, 4> Fields; 2207 // Delay instantiation of late parsed attributes. 2208 LateInstantiatedAttrVec LateAttrs; 2209 Instantiator.enableLateAttributeInstantiation(&LateAttrs); 2210 2211 bool MightHaveConstexprVirtualFunctions = false; 2212 for (auto *Member : Pattern->decls()) { 2213 // Don't instantiate members not belonging in this semantic context. 2214 // e.g. for: 2215 // @code 2216 // template <int i> class A { 2217 // class B *g; 2218 // }; 2219 // @endcode 2220 // 'class B' has the template as lexical context but semantically it is 2221 // introduced in namespace scope. 2222 if (Member->getDeclContext() != Pattern) 2223 continue; 2224 2225 // BlockDecls can appear in a default-member-initializer. They must be the 2226 // child of a BlockExpr, so we only know how to instantiate them from there. 2227 if (isa<BlockDecl>(Member)) 2228 continue; 2229 2230 if (Member->isInvalidDecl()) { 2231 Instantiation->setInvalidDecl(); 2232 continue; 2233 } 2234 2235 Decl *NewMember = Instantiator.Visit(Member); 2236 if (NewMember) { 2237 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) { 2238 Fields.push_back(Field); 2239 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) { 2240 // C++11 [temp.inst]p1: The implicit instantiation of a class template 2241 // specialization causes the implicit instantiation of the definitions 2242 // of unscoped member enumerations. 2243 // Record a point of instantiation for this implicit instantiation. 2244 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() && 2245 Enum->isCompleteDefinition()) { 2246 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo(); 2247 assert(MSInfo && "no spec info for member enum specialization")((MSInfo && "no spec info for member enum specialization"
) ? static_cast<void> (0) : __assert_fail ("MSInfo && \"no spec info for member enum specialization\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2247, __PRETTY_FUNCTION__))
; 2248 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation); 2249 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2250 } 2251 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) { 2252 if (SA->isFailed()) { 2253 // A static_assert failed. Bail out; instantiating this 2254 // class is probably not meaningful. 2255 Instantiation->setInvalidDecl(); 2256 break; 2257 } 2258 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) { 2259 if (MD->isConstexpr() && !MD->getFriendObjectKind() && 2260 (MD->isVirtualAsWritten() || Instantiation->getNumBases())) 2261 MightHaveConstexprVirtualFunctions = true; 2262 } 2263 2264 if (NewMember->isInvalidDecl()) 2265 Instantiation->setInvalidDecl(); 2266 } else { 2267 // FIXME: Eventually, a NULL return will mean that one of the 2268 // instantiations was a semantic disaster, and we'll want to mark the 2269 // declaration invalid. 2270 // For now, we expect to skip some members that we can't yet handle. 2271 } 2272 } 2273 2274 // Finish checking fields. 2275 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields, 2276 SourceLocation(), SourceLocation(), ParsedAttributesView()); 2277 CheckCompletedCXXClass(nullptr, Instantiation); 2278 2279 // Default arguments are parsed, if not instantiated. We can go instantiate 2280 // default arg exprs for default constructors if necessary now. Unless we're 2281 // parsing a class, in which case wait until that's finished. 2282 if (ParsingClassDepth == 0)
54
Assuming field 'ParsingClassDepth' is not equal to 0
55
Taking false branch
2283 ActOnFinishCXXNonNestedClass(); 2284 2285 // Instantiate late parsed attributes, and attach them to their decls. 2286 // See Sema::InstantiateAttrs 2287 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
57
Loop condition is true. Entering loop body
2288 E = LateAttrs.end(); I != E; ++I) {
56
Assuming 'I' is not equal to 'E'
2289 assert(CurrentInstantiationScope == Instantiator.getStartingScope())((CurrentInstantiationScope == Instantiator.getStartingScope(
)) ? static_cast<void> (0) : __assert_fail ("CurrentInstantiationScope == Instantiator.getStartingScope()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2289, __PRETTY_FUNCTION__))
;
58
Assuming the condition is true
59
'?' condition is true
2290 CurrentInstantiationScope = I->Scope; 2291 2292 // Allow 'this' within late-parsed attributes. 2293 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
60
Assuming field 'NewDecl' is not a 'NamedDecl'
61
'ND' initialized to a null pointer value
2294 CXXRecordDecl *ThisContext = 2295 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
62
Called C++ object pointer is null
2296 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(), 2297 ND && ND->isCXXInstanceMember()); 2298 2299 Attr *NewAttr = 2300 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs); 2301 I->NewDecl->addAttr(NewAttr); 2302 LocalInstantiationScope::deleteScopes(I->Scope, 2303 Instantiator.getStartingScope()); 2304 } 2305 Instantiator.disableLateAttributeInstantiation(); 2306 LateAttrs.clear(); 2307 2308 ActOnFinishDelayedMemberInitializers(Instantiation); 2309 2310 // FIXME: We should do something similar for explicit instantiations so they 2311 // end up in the right module. 2312 if (TSK == TSK_ImplicitInstantiation) { 2313 Instantiation->setLocation(Pattern->getLocation()); 2314 Instantiation->setLocStart(Pattern->getInnerLocStart()); 2315 Instantiation->setBraceRange(Pattern->getBraceRange()); 2316 } 2317 2318 if (!Instantiation->isInvalidDecl()) { 2319 // Perform any dependent diagnostics from the pattern. 2320 PerformDependentDiagnostics(Pattern, TemplateArgs); 2321 2322 // Instantiate any out-of-line class template partial 2323 // specializations now. 2324 for (TemplateDeclInstantiator::delayed_partial_spec_iterator 2325 P = Instantiator.delayed_partial_spec_begin(), 2326 PEnd = Instantiator.delayed_partial_spec_end(); 2327 P != PEnd; ++P) { 2328 if (!Instantiator.InstantiateClassTemplatePartialSpecialization( 2329 P->first, P->second)) { 2330 Instantiation->setInvalidDecl(); 2331 break; 2332 } 2333 } 2334 2335 // Instantiate any out-of-line variable template partial 2336 // specializations now. 2337 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator 2338 P = Instantiator.delayed_var_partial_spec_begin(), 2339 PEnd = Instantiator.delayed_var_partial_spec_end(); 2340 P != PEnd; ++P) { 2341 if (!Instantiator.InstantiateVarTemplatePartialSpecialization( 2342 P->first, P->second)) { 2343 Instantiation->setInvalidDecl(); 2344 break; 2345 } 2346 } 2347 } 2348 2349 // Exit the scope of this instantiation. 2350 SavedContext.pop(); 2351 2352 if (!Instantiation->isInvalidDecl()) { 2353 Consumer.HandleTagDeclDefinition(Instantiation); 2354 2355 // Always emit the vtable for an explicit instantiation definition 2356 // of a polymorphic class template specialization. Otherwise, eagerly 2357 // instantiate only constexpr virtual functions in preparation for their use 2358 // in constant evaluation. 2359 if (TSK == TSK_ExplicitInstantiationDefinition) 2360 MarkVTableUsed(PointOfInstantiation, Instantiation, true); 2361 else if (MightHaveConstexprVirtualFunctions) 2362 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation, 2363 /*ConstexprOnly*/ true); 2364 } 2365 2366 return Instantiation->isInvalidDecl(); 2367} 2368 2369/// Instantiate the definition of an enum from a given pattern. 2370/// 2371/// \param PointOfInstantiation The point of instantiation within the 2372/// source code. 2373/// \param Instantiation is the declaration whose definition is being 2374/// instantiated. This will be a member enumeration of a class 2375/// temploid specialization, or a local enumeration within a 2376/// function temploid specialization. 2377/// \param Pattern The templated declaration from which the instantiation 2378/// occurs. 2379/// \param TemplateArgs The template arguments to be substituted into 2380/// the pattern. 2381/// \param TSK The kind of implicit or explicit instantiation to perform. 2382/// 2383/// \return \c true if an error occurred, \c false otherwise. 2384bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation, 2385 EnumDecl *Instantiation, EnumDecl *Pattern, 2386 const MultiLevelTemplateArgumentList &TemplateArgs, 2387 TemplateSpecializationKind TSK) { 2388 EnumDecl *PatternDef = Pattern->getDefinition(); 2389 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation, 2390 Instantiation->getInstantiatedFromMemberEnum(), 2391 Pattern, PatternDef, TSK,/*Complain*/true)) 2392 return true; 2393 Pattern = PatternDef; 2394 2395 // Record the point of instantiation. 2396 if (MemberSpecializationInfo *MSInfo 2397 = Instantiation->getMemberSpecializationInfo()) { 2398 MSInfo->setTemplateSpecializationKind(TSK); 2399 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2400 } 2401 2402 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 2403 if (Inst.isInvalid()) 2404 return true; 2405 if (Inst.isAlreadyInstantiating()) 2406 return false; 2407 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), 2408 "instantiating enum definition"); 2409 2410 // The instantiation is visible here, even if it was first declared in an 2411 // unimported module. 2412 Instantiation->setVisibleDespiteOwningModule(); 2413 2414 // Enter the scope of this instantiation. We don't use 2415 // PushDeclContext because we don't have a scope. 2416 ContextRAII SavedContext(*this, Instantiation); 2417 EnterExpressionEvaluationContext EvalContext( 2418 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 2419 2420 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true); 2421 2422 // Pull attributes from the pattern onto the instantiation. 2423 InstantiateAttrs(TemplateArgs, Pattern, Instantiation); 2424 2425 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); 2426 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern); 2427 2428 // Exit the scope of this instantiation. 2429 SavedContext.pop(); 2430 2431 return Instantiation->isInvalidDecl(); 2432} 2433 2434 2435/// Instantiate the definition of a field from the given pattern. 2436/// 2437/// \param PointOfInstantiation The point of instantiation within the 2438/// source code. 2439/// \param Instantiation is the declaration whose definition is being 2440/// instantiated. This will be a class of a class temploid 2441/// specialization, or a local enumeration within a function temploid 2442/// specialization. 2443/// \param Pattern The templated declaration from which the instantiation 2444/// occurs. 2445/// \param TemplateArgs The template arguments to be substituted into 2446/// the pattern. 2447/// 2448/// \return \c true if an error occurred, \c false otherwise. 2449bool Sema::InstantiateInClassInitializer( 2450 SourceLocation PointOfInstantiation, FieldDecl *Instantiation, 2451 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) { 2452 // If there is no initializer, we don't need to do anything. 2453 if (!Pattern->hasInClassInitializer()) 2454 return false; 2455 2456 assert(Instantiation->getInClassInitStyle() ==((Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle
() && "pattern and instantiation disagree about init style"
) ? static_cast<void> (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2458, __PRETTY_FUNCTION__))
2457 Pattern->getInClassInitStyle() &&((Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle
() && "pattern and instantiation disagree about init style"
) ? static_cast<void> (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2458, __PRETTY_FUNCTION__))
2458 "pattern and instantiation disagree about init style")((Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle
() && "pattern and instantiation disagree about init style"
) ? static_cast<void> (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2458, __PRETTY_FUNCTION__))
; 2459 2460 // Error out if we haven't parsed the initializer of the pattern yet because 2461 // we are waiting for the closing brace of the outer class. 2462 Expr *OldInit = Pattern->getInClassInitializer(); 2463 if (!OldInit) { 2464 RecordDecl *PatternRD = Pattern->getParent(); 2465 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext(); 2466 Diag(PointOfInstantiation, 2467 diag::err_in_class_initializer_not_yet_parsed) 2468 << OutermostClass << Pattern; 2469 Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 2470 Instantiation->setInvalidDecl(); 2471 return true; 2472 } 2473 2474 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 2475 if (Inst.isInvalid()) 2476 return true; 2477 if (Inst.isAlreadyInstantiating()) { 2478 // Error out if we hit an instantiation cycle for this initializer. 2479 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle) 2480 << Instantiation; 2481 return true; 2482 } 2483 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), 2484 "instantiating default member init"); 2485 2486 // Enter the scope of this instantiation. We don't use PushDeclContext because 2487 // we don't have a scope. 2488 ContextRAII SavedContext(*this, Instantiation->getParent()); 2489 EnterExpressionEvaluationContext EvalContext( 2490 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 2491 2492 LocalInstantiationScope Scope(*this, true); 2493 2494 // Instantiate the initializer. 2495 ActOnStartCXXInClassMemberInitializer(); 2496 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers()); 2497 2498 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs, 2499 /*CXXDirectInit=*/false); 2500 Expr *Init = NewInit.get(); 2501 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class")(((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class"
) ? static_cast<void> (0) : __assert_fail ("(!Init || !isa<ParenListExpr>(Init)) && \"call-style init in class\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2501, __PRETTY_FUNCTION__))
; 2502 ActOnFinishCXXInClassMemberInitializer( 2503 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init); 2504 2505 if (auto *L = getASTMutationListener()) 2506 L->DefaultMemberInitializerInstantiated(Instantiation); 2507 2508 // Return true if the in-class initializer is still missing. 2509 return !Instantiation->getInClassInitializer(); 2510} 2511 2512namespace { 2513 /// A partial specialization whose template arguments have matched 2514 /// a given template-id. 2515 struct PartialSpecMatchResult { 2516 ClassTemplatePartialSpecializationDecl *Partial; 2517 TemplateArgumentList *Args; 2518 }; 2519} 2520 2521bool Sema::usesPartialOrExplicitSpecialization( 2522 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) { 2523 if (ClassTemplateSpec->getTemplateSpecializationKind() == 2524 TSK_ExplicitSpecialization) 2525 return true; 2526 2527 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 2528 ClassTemplateSpec->getSpecializedTemplate() 2529 ->getPartialSpecializations(PartialSpecs); 2530 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 2531 TemplateDeductionInfo Info(Loc); 2532 if (!DeduceTemplateArguments(PartialSpecs[I], 2533 ClassTemplateSpec->getTemplateArgs(), Info)) 2534 return true; 2535 } 2536 2537 return false; 2538} 2539 2540/// Get the instantiation pattern to use to instantiate the definition of a 2541/// given ClassTemplateSpecializationDecl (either the pattern of the primary 2542/// template or of a partial specialization). 2543static CXXRecordDecl * 2544getPatternForClassTemplateSpecialization( 2545 Sema &S, SourceLocation PointOfInstantiation, 2546 ClassTemplateSpecializationDecl *ClassTemplateSpec, 2547 TemplateSpecializationKind TSK, bool Complain) { 2548 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec); 2549 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 2550 return nullptr; 2551 2552 llvm::PointerUnion<ClassTemplateDecl *, 2553 ClassTemplatePartialSpecializationDecl *> 2554 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); 2555 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) { 2556 // Find best matching specialization. 2557 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 2558 2559 // C++ [temp.class.spec.match]p1: 2560 // When a class template is used in a context that requires an 2561 // instantiation of the class, it is necessary to determine 2562 // whether the instantiation is to be generated using the primary 2563 // template or one of the partial specializations. This is done by 2564 // matching the template arguments of the class template 2565 // specialization with the template argument lists of the partial 2566 // specializations. 2567 typedef PartialSpecMatchResult MatchResult; 2568 SmallVector<MatchResult, 4> Matched; 2569 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 2570 Template->getPartialSpecializations(PartialSpecs); 2571 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation); 2572 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 2573 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; 2574 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 2575 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments( 2576 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) { 2577 // Store the failed-deduction information for use in diagnostics, later. 2578 // TODO: Actually use the failed-deduction info? 2579 FailedCandidates.addCandidate().set( 2580 DeclAccessPair::make(Template, AS_public), Partial, 2581 MakeDeductionFailureInfo(S.Context, Result, Info)); 2582 (void)Result; 2583 } else { 2584 Matched.push_back(PartialSpecMatchResult()); 2585 Matched.back().Partial = Partial; 2586 Matched.back().Args = Info.take(); 2587 } 2588 } 2589 2590 // If we're dealing with a member template where the template parameters 2591 // have been instantiated, this provides the original template parameters 2592 // from which the member template's parameters were instantiated. 2593 2594 if (Matched.size() >= 1) { 2595 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin(); 2596 if (Matched.size() == 1) { 2597 // -- If exactly one matching specialization is found, the 2598 // instantiation is generated from that specialization. 2599 // We don't need to do anything for this. 2600 } else { 2601 // -- If more than one matching specialization is found, the 2602 // partial order rules (14.5.4.2) are used to determine 2603 // whether one of the specializations is more specialized 2604 // than the others. If none of the specializations is more 2605 // specialized than all of the other matching 2606 // specializations, then the use of the class template is 2607 // ambiguous and the program is ill-formed. 2608 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1, 2609 PEnd = Matched.end(); 2610 P != PEnd; ++P) { 2611 if (S.getMoreSpecializedPartialSpecialization( 2612 P->Partial, Best->Partial, PointOfInstantiation) == 2613 P->Partial) 2614 Best = P; 2615 } 2616 2617 // Determine if the best partial specialization is more specialized than 2618 // the others. 2619 bool Ambiguous = false; 2620 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), 2621 PEnd = Matched.end(); 2622 P != PEnd; ++P) { 2623 if (P != Best && S.getMoreSpecializedPartialSpecialization( 2624 P->Partial, Best->Partial, 2625 PointOfInstantiation) != Best->Partial) { 2626 Ambiguous = true; 2627 break; 2628 } 2629 } 2630 2631 if (Ambiguous) { 2632 // Partial ordering did not produce a clear winner. Complain. 2633 Inst.Clear(); 2634 ClassTemplateSpec->setInvalidDecl(); 2635 S.Diag(PointOfInstantiation, 2636 diag::err_partial_spec_ordering_ambiguous) 2637 << ClassTemplateSpec; 2638 2639 // Print the matching partial specializations. 2640 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), 2641 PEnd = Matched.end(); 2642 P != PEnd; ++P) 2643 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match) 2644 << S.getTemplateArgumentBindingsText( 2645 P->Partial->getTemplateParameters(), *P->Args); 2646 2647 return nullptr; 2648 } 2649 } 2650 2651 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args); 2652 } else { 2653 // -- If no matches are found, the instantiation is generated 2654 // from the primary template. 2655 } 2656 } 2657 2658 CXXRecordDecl *Pattern = nullptr; 2659 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); 2660 if (auto *PartialSpec = 2661 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { 2662 // Instantiate using the best class template partial specialization. 2663 while (PartialSpec->getInstantiatedFromMember()) { 2664 // If we've found an explicit specialization of this class template, 2665 // stop here and use that as the pattern. 2666 if (PartialSpec->isMemberSpecialization()) 2667 break; 2668 2669 PartialSpec = PartialSpec->getInstantiatedFromMember(); 2670 } 2671 Pattern = PartialSpec; 2672 } else { 2673 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 2674 while (Template->getInstantiatedFromMemberTemplate()) { 2675 // If we've found an explicit specialization of this class template, 2676 // stop here and use that as the pattern. 2677 if (Template->isMemberSpecialization()) 2678 break; 2679 2680 Template = Template->getInstantiatedFromMemberTemplate(); 2681 } 2682 Pattern = Template->getTemplatedDecl(); 2683 } 2684 2685 return Pattern; 2686} 2687 2688bool Sema::InstantiateClassTemplateSpecialization( 2689 SourceLocation PointOfInstantiation, 2690 ClassTemplateSpecializationDecl *ClassTemplateSpec, 2691 TemplateSpecializationKind TSK, bool Complain) { 2692 // Perform the actual instantiation on the canonical declaration. 2693 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( 2694 ClassTemplateSpec->getCanonicalDecl()); 2695 if (ClassTemplateSpec->isInvalidDecl()) 2696 return true; 2697 2698 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization( 2699 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain); 2700 if (!Pattern) 2701 return true; 2702 2703 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern, 2704 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, 2705 Complain); 2706} 2707 2708/// Instantiates the definitions of all of the member 2709/// of the given class, which is an instantiation of a class template 2710/// or a member class of a template. 2711void 2712Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, 2713 CXXRecordDecl *Instantiation, 2714 const MultiLevelTemplateArgumentList &TemplateArgs, 2715 TemplateSpecializationKind TSK) { 2716 // FIXME: We need to notify the ASTMutationListener that we did all of these 2717 // things, in case we have an explicit instantiation definition in a PCM, a 2718 // module, or preamble, and the declaration is in an imported AST. 2719 assert((((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2723, __PRETTY_FUNCTION__))
1
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDefinition
2
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDeclaration
3
Assuming 'TSK' is equal to TSK_ImplicitInstantiation
4
'?' condition is true
2720 (TSK == TSK_ExplicitInstantiationDefinition ||(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2723, __PRETTY_FUNCTION__))
2721 TSK == TSK_ExplicitInstantiationDeclaration ||(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2723, __PRETTY_FUNCTION__))
2722 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2723, __PRETTY_FUNCTION__))
2723 "Unexpected template specialization kind!")(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2723, __PRETTY_FUNCTION__))
; 2724 for (auto *D : Instantiation->decls()) { 2725 bool SuppressNew = false; 2726 if (auto *Function
5.1
'Function' is null
5.1
'Function' is null
= dyn_cast<FunctionDecl>(D)) {
5
Assuming 'D' is not a 'FunctionDecl'
6
Taking false branch
2727 if (FunctionDecl *Pattern = 2728 Function->getInstantiatedFromMemberFunction()) { 2729 2730 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 2731 continue; 2732 2733 MemberSpecializationInfo *MSInfo = 2734 Function->getMemberSpecializationInfo(); 2735 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2735, __PRETTY_FUNCTION__))
; 2736 if (MSInfo->getTemplateSpecializationKind() 2737 == TSK_ExplicitSpecialization) 2738 continue; 2739 2740 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 2741 Function, 2742 MSInfo->getTemplateSpecializationKind(), 2743 MSInfo->getPointOfInstantiation(), 2744 SuppressNew) || 2745 SuppressNew) 2746 continue; 2747 2748 // C++11 [temp.explicit]p8: 2749 // An explicit instantiation definition that names a class template 2750 // specialization explicitly instantiates the class template 2751 // specialization and is only an explicit instantiation definition 2752 // of members whose definition is visible at the point of 2753 // instantiation. 2754 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined()) 2755 continue; 2756 2757 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2758 2759 if (Function->isDefined()) { 2760 // Let the ASTConsumer know that this function has been explicitly 2761 // instantiated now, and its linkage might have changed. 2762 Consumer.HandleTopLevelDecl(DeclGroupRef(Function)); 2763 } else if (TSK == TSK_ExplicitInstantiationDefinition) { 2764 InstantiateFunctionDefinition(PointOfInstantiation, Function); 2765 } else if (TSK == TSK_ImplicitInstantiation) { 2766 PendingLocalImplicitInstantiations.push_back( 2767 std::make_pair(Function, PointOfInstantiation)); 2768 } 2769 } 2770 } else if (auto *Var
7.1
'Var' is null
7.1
'Var' is null
= dyn_cast<VarDecl>(D)) {
7
Assuming 'D' is not a 'VarDecl'
8
Taking false branch
2771 if (isa<VarTemplateSpecializationDecl>(Var)) 2772 continue; 2773 2774 if (Var->isStaticDataMember()) { 2775 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 2776 continue; 2777 2778 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 2779 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2779, __PRETTY_FUNCTION__))
; 2780 if (MSInfo->getTemplateSpecializationKind() 2781 == TSK_ExplicitSpecialization) 2782 continue; 2783 2784 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 2785 Var, 2786 MSInfo->getTemplateSpecializationKind(), 2787 MSInfo->getPointOfInstantiation(), 2788 SuppressNew) || 2789 SuppressNew) 2790 continue; 2791 2792 if (TSK == TSK_ExplicitInstantiationDefinition) { 2793 // C++0x [temp.explicit]p8: 2794 // An explicit instantiation definition that names a class template 2795 // specialization explicitly instantiates the class template 2796 // specialization and is only an explicit instantiation definition 2797 // of members whose definition is visible at the point of 2798 // instantiation. 2799 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition()) 2800 continue; 2801 2802 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2803 InstantiateVariableDefinition(PointOfInstantiation, Var); 2804 } else { 2805 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2806 } 2807 } 2808 } else if (auto *Record
9.1
'Record' is non-null
9.1
'Record' is non-null
= dyn_cast<CXXRecordDecl>(D)) {
9
Assuming 'D' is a 'CXXRecordDecl'
10
Taking true branch
2809 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
11
Taking false branch
2810 continue; 2811 2812 // Always skip the injected-class-name, along with any 2813 // redeclarations of nested classes, since both would cause us 2814 // to try to instantiate the members of a class twice. 2815 // Skip closure types; they'll get instantiated when we instantiate 2816 // the corresponding lambda-expression. 2817 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
12
Assuming the condition is false
13
Taking false branch
2818 Record->isLambda()) 2819 continue; 2820 2821 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); 2822 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2822, __PRETTY_FUNCTION__))
;
14
Assuming 'MSInfo' is non-null
15
'?' condition is true
2823 2824 if (MSInfo->getTemplateSpecializationKind()
16
Assuming the condition is false
17
Taking false branch
2825 == TSK_ExplicitSpecialization) 2826 continue; 2827 2828 if (Context.getTargetInfo().getTriple().isOSWindows() && 2829 TSK == TSK_ExplicitInstantiationDeclaration) { 2830 // On Windows, explicit instantiation decl of the outer class doesn't 2831 // affect the inner class. Typically extern template declarations are 2832 // used in combination with dll import/export annotations, but those 2833 // are not propagated from the outer class templates to inner classes. 2834 // Therefore, do not instantiate inner classes on this platform, so 2835 // that users don't end up with undefined symbols during linking. 2836 continue; 2837 } 2838 2839 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
18
Assuming the condition is false
19
Assuming the condition is false
20
Taking false branch
2840 Record, 2841 MSInfo->getTemplateSpecializationKind(), 2842 MSInfo->getPointOfInstantiation(), 2843 SuppressNew) || 2844 SuppressNew) 2845 continue; 2846 2847 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 2848 assert(Pattern && "Missing instantiated-from-template information")((Pattern && "Missing instantiated-from-template information"
) ? static_cast<void> (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2848, __PRETTY_FUNCTION__))
;
21
Assuming 'Pattern' is non-null
22
'?' condition is true
2849 2850 if (!Record->getDefinition()) {
23
Taking true branch
2851 if (!Pattern->getDefinition()) {
24
Assuming the condition is false
25
Taking false branch
2852 // C++0x [temp.explicit]p8: 2853 // An explicit instantiation definition that names a class template 2854 // specialization explicitly instantiates the class template 2855 // specialization and is only an explicit instantiation definition 2856 // of members whose definition is visible at the point of 2857 // instantiation. 2858 if (TSK == TSK_ExplicitInstantiationDeclaration) { 2859 MSInfo->setTemplateSpecializationKind(TSK); 2860 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2861 } 2862 2863 continue; 2864 } 2865 2866 InstantiateClass(PointOfInstantiation, Record, Pattern,
26
Calling 'Sema::InstantiateClass'
2867 TemplateArgs, 2868 TSK); 2869 } else { 2870 if (TSK == TSK_ExplicitInstantiationDefinition && 2871 Record->getTemplateSpecializationKind() == 2872 TSK_ExplicitInstantiationDeclaration) { 2873 Record->setTemplateSpecializationKind(TSK); 2874 MarkVTableUsed(PointOfInstantiation, Record, true); 2875 } 2876 } 2877 2878 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 2879 if (Pattern) 2880 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, 2881 TSK); 2882 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) { 2883 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo(); 2884 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2884, __PRETTY_FUNCTION__))
; 2885 2886 if (MSInfo->getTemplateSpecializationKind() 2887 == TSK_ExplicitSpecialization) 2888 continue; 2889 2890 if (CheckSpecializationInstantiationRedecl( 2891 PointOfInstantiation, TSK, Enum, 2892 MSInfo->getTemplateSpecializationKind(), 2893 MSInfo->getPointOfInstantiation(), SuppressNew) || 2894 SuppressNew) 2895 continue; 2896 2897 if (Enum->getDefinition()) 2898 continue; 2899 2900 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern(); 2901 assert(Pattern && "Missing instantiated-from-template information")((Pattern && "Missing instantiated-from-template information"
) ? static_cast<void> (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2901, __PRETTY_FUNCTION__))
; 2902 2903 if (TSK == TSK_ExplicitInstantiationDefinition) { 2904 if (!Pattern->getDefinition()) 2905 continue; 2906 2907 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK); 2908 } else { 2909 MSInfo->setTemplateSpecializationKind(TSK); 2910 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2911 } 2912 } else if (auto *Field = dyn_cast<FieldDecl>(D)) { 2913 // No need to instantiate in-class initializers during explicit 2914 // instantiation. 2915 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) { 2916 CXXRecordDecl *ClassPattern = 2917 Instantiation->getTemplateInstantiationPattern(); 2918 DeclContext::lookup_result Lookup = 2919 ClassPattern->lookup(Field->getDeclName()); 2920 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front()); 2921 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern, 2922 TemplateArgs); 2923 } 2924 } 2925 } 2926} 2927 2928/// Instantiate the definitions of all of the members of the 2929/// given class template specialization, which was named as part of an 2930/// explicit instantiation. 2931void 2932Sema::InstantiateClassTemplateSpecializationMembers( 2933 SourceLocation PointOfInstantiation, 2934 ClassTemplateSpecializationDecl *ClassTemplateSpec, 2935 TemplateSpecializationKind TSK) { 2936 // C++0x [temp.explicit]p7: 2937 // An explicit instantiation that names a class template 2938 // specialization is an explicit instantion of the same kind 2939 // (declaration or definition) of each of its members (not 2940 // including members inherited from base classes) that has not 2941 // been previously explicitly specialized in the translation unit 2942 // containing the explicit instantiation, except as described 2943 // below. 2944 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec, 2945 getTemplateInstantiationArgs(ClassTemplateSpec), 2946 TSK); 2947} 2948 2949StmtResult 2950Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { 2951 if (!S) 2952 return S; 2953 2954 TemplateInstantiator Instantiator(*this, TemplateArgs, 2955 SourceLocation(), 2956 DeclarationName()); 2957 return Instantiator.TransformStmt(S); 2958} 2959 2960bool Sema::SubstTemplateArguments( 2961 ArrayRef<TemplateArgumentLoc> Args, 2962 const MultiLevelTemplateArgumentList &TemplateArgs, 2963 TemplateArgumentListInfo &Out) { 2964 TemplateInstantiator Instantiator(*this, TemplateArgs, 2965 SourceLocation(), 2966 DeclarationName()); 2967 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), 2968 Out); 2969} 2970 2971ExprResult 2972Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { 2973 if (!E) 2974 return E; 2975 2976 TemplateInstantiator Instantiator(*this, TemplateArgs, 2977 SourceLocation(), 2978 DeclarationName()); 2979 return Instantiator.TransformExpr(E); 2980} 2981 2982ExprResult Sema::SubstInitializer(Expr *Init, 2983 const MultiLevelTemplateArgumentList &TemplateArgs, 2984 bool CXXDirectInit) { 2985 TemplateInstantiator Instantiator(*this, TemplateArgs, 2986 SourceLocation(), 2987 DeclarationName()); 2988 return Instantiator.TransformInitializer(Init, CXXDirectInit); 2989} 2990 2991bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, 2992 const MultiLevelTemplateArgumentList &TemplateArgs, 2993 SmallVectorImpl<Expr *> &Outputs) { 2994 if (Exprs.empty()) 2995 return false; 2996 2997 TemplateInstantiator Instantiator(*this, TemplateArgs, 2998 SourceLocation(), 2999 DeclarationName()); 3000 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(), 3001 IsCall, Outputs); 3002} 3003 3004NestedNameSpecifierLoc 3005Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 3006 const MultiLevelTemplateArgumentList &TemplateArgs) { 3007 if (!NNS) 3008 return NestedNameSpecifierLoc(); 3009 3010 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(), 3011 DeclarationName()); 3012 return Instantiator.TransformNestedNameSpecifierLoc(NNS); 3013} 3014 3015/// Do template substitution on declaration name info. 3016DeclarationNameInfo 3017Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 3018 const MultiLevelTemplateArgumentList &TemplateArgs) { 3019 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(), 3020 NameInfo.getName()); 3021 return Instantiator.TransformDeclarationNameInfo(NameInfo); 3022} 3023 3024TemplateName 3025Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, 3026 TemplateName Name, SourceLocation Loc, 3027 const MultiLevelTemplateArgumentList &TemplateArgs) { 3028 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 3029 DeclarationName()); 3030 CXXScopeSpec SS; 3031 SS.Adopt(QualifierLoc); 3032 return Instantiator.TransformTemplateName(SS, Name, Loc); 3033} 3034 3035bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 3036 TemplateArgumentListInfo &Result, 3037 const MultiLevelTemplateArgumentList &TemplateArgs) { 3038 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), 3039 DeclarationName()); 3040 3041 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result); 3042} 3043 3044static const Decl *getCanonicalParmVarDecl(const Decl *D) { 3045 // When storing ParmVarDecls in the local instantiation scope, we always 3046 // want to use the ParmVarDecl from the canonical function declaration, 3047 // since the map is then valid for any redeclaration or definition of that 3048 // function. 3049 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) { 3050 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 3051 unsigned i = PV->getFunctionScopeIndex(); 3052 // This parameter might be from a freestanding function type within the 3053 // function and isn't necessarily referring to one of FD's parameters. 3054 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV) 3055 return FD->getCanonicalDecl()->getParamDecl(i); 3056 } 3057 } 3058 return D; 3059} 3060 3061 3062llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> * 3063LocalInstantiationScope::findInstantiationOf(const Decl *D) { 3064 D = getCanonicalParmVarDecl(D); 3065 for (LocalInstantiationScope *Current = this; Current; 3066 Current = Current->Outer) { 3067 3068 // Check if we found something within this scope. 3069 const Decl *CheckD = D; 3070 do { 3071 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD); 3072 if (Found != Current->LocalDecls.end()) 3073 return &Found->second; 3074 3075 // If this is a tag declaration, it's possible that we need to look for 3076 // a previous declaration. 3077 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD)) 3078 CheckD = Tag->getPreviousDecl(); 3079 else 3080 CheckD = nullptr; 3081 } while (CheckD); 3082 3083 // If we aren't combined with our outer scope, we're done. 3084 if (!Current->CombineWithOuterScope) 3085 break; 3086 } 3087 3088 // If we're performing a partial substitution during template argument 3089 // deduction, we may not have values for template parameters yet. 3090 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 3091 isa<TemplateTemplateParmDecl>(D)) 3092 return nullptr; 3093 3094 // Local types referenced prior to definition may require instantiation. 3095 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 3096 if (RD->isLocalClass()) 3097 return nullptr; 3098 3099 // Enumeration types referenced prior to definition may appear as a result of 3100 // error recovery. 3101 if (isa<EnumDecl>(D)) 3102 return nullptr; 3103 3104 // If we didn't find the decl, then we either have a sema bug, or we have a 3105 // forward reference to a label declaration. Return null to indicate that 3106 // we have an uninstantiated label. 3107 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope")((isa<LabelDecl>(D) && "declaration not instantiated in this scope"
) ? static_cast<void> (0) : __assert_fail ("isa<LabelDecl>(D) && \"declaration not instantiated in this scope\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3107, __PRETTY_FUNCTION__))
; 3108 return nullptr; 3109} 3110 3111void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) { 3112 D = getCanonicalParmVarDecl(D); 3113 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; 3114 if (Stored.isNull()) { 3115#ifndef NDEBUG 3116 // It should not be present in any surrounding scope either. 3117 LocalInstantiationScope *Current = this; 3118 while (Current->CombineWithOuterScope && Current->Outer) { 3119 Current = Current->Outer; 3120 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Instantiated local in inner and outer scopes")
? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3121, __PRETTY_FUNCTION__))
3121 "Instantiated local in inner and outer scopes")((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Instantiated local in inner and outer scopes")
? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3121, __PRETTY_FUNCTION__))
; 3122 } 3123#endif 3124 Stored = Inst; 3125 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) { 3126 Pack->push_back(cast<VarDecl>(Inst)); 3127 } else { 3128 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local")((Stored.get<Decl *>() == Inst && "Already instantiated this local"
) ? static_cast<void> (0) : __assert_fail ("Stored.get<Decl *>() == Inst && \"Already instantiated this local\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3128, __PRETTY_FUNCTION__))
; 3129 } 3130} 3131 3132void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D, 3133 VarDecl *Inst) { 3134 D = getCanonicalParmVarDecl(D); 3135 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>(); 3136 Pack->push_back(Inst); 3137} 3138 3139void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) { 3140#ifndef NDEBUG 3141 // This should be the first time we've been told about this decl. 3142 for (LocalInstantiationScope *Current = this; 3143 Current && Current->CombineWithOuterScope; Current = Current->Outer) 3144 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Creating local pack after instantiation of local"
) ? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3145, __PRETTY_FUNCTION__))
3145 "Creating local pack after instantiation of local")((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Creating local pack after instantiation of local"
) ? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3145, __PRETTY_FUNCTION__))
; 3146#endif 3147 3148 D = getCanonicalParmVarDecl(D); 3149 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; 3150 DeclArgumentPack *Pack = new DeclArgumentPack; 3151 Stored = Pack; 3152 ArgumentPacks.push_back(Pack); 3153} 3154 3155void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, 3156 const TemplateArgument *ExplicitArgs, 3157 unsigned NumExplicitArgs) { 3158 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&(((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack
) && "Already have a partially-substituted pack") ? static_cast
<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3159, __PRETTY_FUNCTION__))
3159 "Already have a partially-substituted pack")(((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack
) && "Already have a partially-substituted pack") ? static_cast
<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3159, __PRETTY_FUNCTION__))
; 3160 assert((!PartiallySubstitutedPack(((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? static_cast<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3162, __PRETTY_FUNCTION__))
3161 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&(((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? static_cast<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3162, __PRETTY_FUNCTION__))
3162 "Wrong number of arguments in partially-substituted pack")(((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? static_cast<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3162, __PRETTY_FUNCTION__))
; 3163 PartiallySubstitutedPack = Pack; 3164 ArgsInPartiallySubstitutedPack = ExplicitArgs; 3165 NumArgsInPartiallySubstitutedPack = NumExplicitArgs; 3166} 3167 3168NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack( 3169 const TemplateArgument **ExplicitArgs, 3170 unsigned *NumExplicitArgs) const { 3171 if (ExplicitArgs) 3172 *ExplicitArgs = nullptr; 3173 if (NumExplicitArgs) 3174 *NumExplicitArgs = 0; 3175 3176 for (const LocalInstantiationScope *Current = this; Current; 3177 Current = Current->Outer) { 3178 if (Current->PartiallySubstitutedPack) { 3179 if (ExplicitArgs) 3180 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack; 3181 if (NumExplicitArgs) 3182 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack; 3183 3184 return Current->PartiallySubstitutedPack; 3185 } 3186 3187 if (!Current->CombineWithOuterScope) 3188 break; 3189 } 3190 3191 return nullptr; 3192}

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
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 defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/Availability.h"
20#include "clang/AST/ComparisonCategories.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExternalASTSource.h"
27#include "clang/AST/LocInfoType.h"
28#include "clang/AST/MangleNumberingContext.h"
29#include "clang/AST/NSAPI.h"
30#include "clang/AST/PrettyPrinter.h"
31#include "clang/AST/StmtCXX.h"
32#include "clang/AST/TypeLoc.h"
33#include "clang/AST/TypeOrdering.h"
34#include "clang/Basic/BitmaskEnum.h"
35#include "clang/Basic/ExpressionTraits.h"
36#include "clang/Basic/Module.h"
37#include "clang/Basic/OpenMPKinds.h"
38#include "clang/Basic/PragmaKinds.h"
39#include "clang/Basic/Specifiers.h"
40#include "clang/Basic/TemplateKinds.h"
41#include "clang/Basic/TypeTraits.h"
42#include "clang/Sema/AnalysisBasedWarnings.h"
43#include "clang/Sema/CleanupInfo.h"
44#include "clang/Sema/DeclSpec.h"
45#include "clang/Sema/ExternalSemaSource.h"
46#include "clang/Sema/IdentifierResolver.h"
47#include "clang/Sema/ObjCMethodList.h"
48#include "clang/Sema/Ownership.h"
49#include "clang/Sema/Scope.h"
50#include "clang/Sema/SemaConcept.h"
51#include "clang/Sema/TypoCorrection.h"
52#include "clang/Sema/Weak.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/Optional.h"
55#include "llvm/ADT/SetVector.h"
56#include "llvm/ADT/SmallBitVector.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/SmallVector.h"
59#include "llvm/ADT/TinyPtrVector.h"
60#include "llvm/Frontend/OpenMP/OMPConstants.h"
61#include <deque>
62#include <memory>
63#include <string>
64#include <tuple>
65#include <vector>
66
67namespace llvm {
68 class APSInt;
69 template <typename ValueT> struct DenseMapInfo;
70 template <typename ValueT, typename ValueInfoT> class DenseSet;
71 class SmallBitVector;
72 struct InlineAsmIdentifierInfo;
73}
74
75namespace clang {
76 class ADLResult;
77 class ASTConsumer;
78 class ASTContext;
79 class ASTMutationListener;
80 class ASTReader;
81 class ASTWriter;
82 class ArrayType;
83 class ParsedAttr;
84 class BindingDecl;
85 class BlockDecl;
86 class CapturedDecl;
87 class CXXBasePath;
88 class CXXBasePaths;
89 class CXXBindTemporaryExpr;
90 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
91 class CXXConstructorDecl;
92 class CXXConversionDecl;
93 class CXXDeleteExpr;
94 class CXXDestructorDecl;
95 class CXXFieldCollector;
96 class CXXMemberCallExpr;
97 class CXXMethodDecl;
98 class CXXScopeSpec;
99 class CXXTemporary;
100 class CXXTryStmt;
101 class CallExpr;
102 class ClassTemplateDecl;
103 class ClassTemplatePartialSpecializationDecl;
104 class ClassTemplateSpecializationDecl;
105 class VarTemplatePartialSpecializationDecl;
106 class CodeCompleteConsumer;
107 class CodeCompletionAllocator;
108 class CodeCompletionTUInfo;
109 class CodeCompletionResult;
110 class CoroutineBodyStmt;
111 class Decl;
112 class DeclAccessPair;
113 class DeclContext;
114 class DeclRefExpr;
115 class DeclaratorDecl;
116 class DeducedTemplateArgument;
117 class DependentDiagnostic;
118 class DesignatedInitExpr;
119 class Designation;
120 class EnableIfAttr;
121 class EnumConstantDecl;
122 class Expr;
123 class ExtVectorType;
124 class FormatAttr;
125 class FriendDecl;
126 class FunctionDecl;
127 class FunctionProtoType;
128 class FunctionTemplateDecl;
129 class ImplicitConversionSequence;
130 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
131 class InitListExpr;
132 class InitializationKind;
133 class InitializationSequence;
134 class InitializedEntity;
135 class IntegerLiteral;
136 class LabelStmt;
137 class LambdaExpr;
138 class LangOptions;
139 class LocalInstantiationScope;
140 class LookupResult;
141 class MacroInfo;
142 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
143 class ModuleLoader;
144 class MultiLevelTemplateArgumentList;
145 class NamedDecl;
146 class ObjCCategoryDecl;
147 class ObjCCategoryImplDecl;
148 class ObjCCompatibleAliasDecl;
149 class ObjCContainerDecl;
150 class ObjCImplDecl;
151 class ObjCImplementationDecl;
152 class ObjCInterfaceDecl;
153 class ObjCIvarDecl;
154 template <class T> class ObjCList;
155 class ObjCMessageExpr;
156 class ObjCMethodDecl;
157 class ObjCPropertyDecl;
158 class ObjCProtocolDecl;
159 class OMPThreadPrivateDecl;
160 class OMPRequiresDecl;
161 class OMPDeclareReductionDecl;
162 class OMPDeclareSimdDecl;
163 class OMPClause;
164 struct OMPVarListLocTy;
165 struct OverloadCandidate;
166 enum class OverloadCandidateParamOrder : char;
167 enum OverloadCandidateRewriteKind : unsigned;
168 class OverloadCandidateSet;
169 class OverloadExpr;
170 class ParenListExpr;
171 class ParmVarDecl;
172 class Preprocessor;
173 class PseudoDestructorTypeStorage;
174 class PseudoObjectExpr;
175 class QualType;
176 class StandardConversionSequence;
177 class Stmt;
178 class StringLiteral;
179 class SwitchStmt;
180 class TemplateArgument;
181 class TemplateArgumentList;
182 class TemplateArgumentLoc;
183 class TemplateDecl;
184 class TemplateInstantiationCallback;
185 class TemplateParameterList;
186 class TemplatePartialOrderingContext;
187 class TemplateTemplateParmDecl;
188 class Token;
189 class TypeAliasDecl;
190 class TypedefDecl;
191 class TypedefNameDecl;
192 class TypeLoc;
193 class TypoCorrectionConsumer;
194 class UnqualifiedId;
195 class UnresolvedLookupExpr;
196 class UnresolvedMemberExpr;
197 class UnresolvedSetImpl;
198 class UnresolvedSetIterator;
199 class UsingDecl;
200 class UsingShadowDecl;
201 class ValueDecl;
202 class VarDecl;
203 class VarTemplateSpecializationDecl;
204 class VisibilityAttr;
205 class VisibleDeclConsumer;
206 class IndirectFieldDecl;
207 struct DeductionFailureInfo;
208 class TemplateSpecCandidateSet;
209
210namespace sema {
211 class AccessedEntity;
212 class BlockScopeInfo;
213 class Capture;
214 class CapturedRegionScopeInfo;
215 class CapturingScopeInfo;
216 class CompoundScopeInfo;
217 class DelayedDiagnostic;
218 class DelayedDiagnosticPool;
219 class FunctionScopeInfo;
220 class LambdaScopeInfo;
221 class PossiblyUnreachableDiag;
222 class SemaPPCallbacks;
223 class TemplateDeductionInfo;
224}
225
226namespace threadSafety {
227 class BeforeSet;
228 void threadSafetyCleanup(BeforeSet* Cache);
229}
230
231// FIXME: No way to easily map from TemplateTypeParmTypes to
232// TemplateTypeParmDecls, so we have this horrible PointerUnion.
233typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
234 SourceLocation> UnexpandedParameterPack;
235
236/// Describes whether we've seen any nullability information for the given
237/// file.
238struct FileNullability {
239 /// The first pointer declarator (of any pointer kind) in the file that does
240 /// not have a corresponding nullability annotation.
241 SourceLocation PointerLoc;
242
243 /// The end location for the first pointer declarator in the file. Used for
244 /// placing fix-its.
245 SourceLocation PointerEndLoc;
246
247 /// Which kind of pointer declarator we saw.
248 uint8_t PointerKind;
249
250 /// Whether we saw any type nullability annotations in the given file.
251 bool SawTypeNullability = false;
252};
253
254/// A mapping from file IDs to a record of whether we've seen nullability
255/// information in that file.
256class FileNullabilityMap {
257 /// A mapping from file IDs to the nullability information for each file ID.
258 llvm::DenseMap<FileID, FileNullability> Map;
259
260 /// A single-element cache based on the file ID.
261 struct {
262 FileID File;
263 FileNullability Nullability;
264 } Cache;
265
266public:
267 FileNullability &operator[](FileID file) {
268 // Check the single-element cache.
269 if (file == Cache.File)
270 return Cache.Nullability;
271
272 // It's not in the single-element cache; flush the cache if we have one.
273 if (!Cache.File.isInvalid()) {
274 Map[Cache.File] = Cache.Nullability;
275 }
276
277 // Pull this entry into the cache.
278 Cache.File = file;
279 Cache.Nullability = Map[file];
280 return Cache.Nullability;
281 }
282};
283
284/// Keeps track of expected type during expression parsing. The type is tied to
285/// a particular token, all functions that update or consume the type take a
286/// start location of the token they are looking at as a parameter. This allows
287/// to avoid updating the type on hot paths in the parser.
288class PreferredTypeBuilder {
289public:
290 PreferredTypeBuilder() = default;
291 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
292
293 void enterCondition(Sema &S, SourceLocation Tok);
294 void enterReturn(Sema &S, SourceLocation Tok);
295 void enterVariableInit(SourceLocation Tok, Decl *D);
296 /// Computing a type for the function argument may require running
297 /// overloading, so we postpone its computation until it is actually needed.
298 ///
299 /// Clients should be very careful when using this funciton, as it stores a
300 /// function_ref, clients should make sure all calls to get() with the same
301 /// location happen while function_ref is alive.
302 void enterFunctionArgument(SourceLocation Tok,
303 llvm::function_ref<QualType()> ComputeType);
304
305 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
306 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
307 SourceLocation OpLoc);
308 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
309 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
310 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
311 /// Handles all type casts, including C-style cast, C++ casts, etc.
312 void enterTypeCast(SourceLocation Tok, QualType CastType);
313
314 QualType get(SourceLocation Tok) const {
315 if (Tok != ExpectedLoc)
316 return QualType();
317 if (!Type.isNull())
318 return Type;
319 if (ComputeType)
320 return ComputeType();
321 return QualType();
322 }
323
324private:
325 /// Start position of a token for which we store expected type.
326 SourceLocation ExpectedLoc;
327 /// Expected type for a token starting at ExpectedLoc.
328 QualType Type;
329 /// A function to compute expected type at ExpectedLoc. It is only considered
330 /// if Type is null.
331 llvm::function_ref<QualType()> ComputeType;
332};
333
334/// Sema - This implements semantic analysis and AST building for C.
335class Sema final {
336 Sema(const Sema &) = delete;
337 void operator=(const Sema &) = delete;
338
339 /// A key method to reduce duplicate debug info from Sema.
340 virtual void anchor();
341
342 ///Source of additional semantic information.
343 ExternalSemaSource *ExternalSource;
344
345 ///Whether Sema has generated a multiplexer and has to delete it.
346 bool isMultiplexExternalSource;
347
348 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
349
350 bool isVisibleSlow(const NamedDecl *D);
351
352 /// Determine whether two declarations should be linked together, given that
353 /// the old declaration might not be visible and the new declaration might
354 /// not have external linkage.
355 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
356 const NamedDecl *New) {
357 if (isVisible(Old))
358 return true;
359 // See comment in below overload for why it's safe to compute the linkage
360 // of the new declaration here.
361 if (New->isExternallyDeclarable()) {
362 assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 363, __PRETTY_FUNCTION__))
363 "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 363, __PRETTY_FUNCTION__))
;
364 return true;
365 }
366 return false;
367 }
368 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
369
370 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
371 QualType ResultTy,
372 ArrayRef<QualType> Args);
373
374public:
375 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
376 typedef OpaquePtr<TemplateName> TemplateTy;
377 typedef OpaquePtr<QualType> TypeTy;
378
379 OpenCLOptions OpenCLFeatures;
380 FPOptions FPFeatures;
381
382 const LangOptions &LangOpts;
383 Preprocessor &PP;
384 ASTContext &Context;
385 ASTConsumer &Consumer;
386 DiagnosticsEngine &Diags;
387 SourceManager &SourceMgr;
388
389 /// Flag indicating whether or not to collect detailed statistics.
390 bool CollectStats;
391
392 /// Code-completion consumer.
393 CodeCompleteConsumer *CodeCompleter;
394
395 /// CurContext - This is the current declaration context of parsing.
396 DeclContext *CurContext;
397
398 /// Generally null except when we temporarily switch decl contexts,
399 /// like in \see ActOnObjCTemporaryExitContainerContext.
400 DeclContext *OriginalLexicalContext;
401
402 /// VAListTagName - The declaration name corresponding to __va_list_tag.
403 /// This is used as part of a hack to omit that class from ADL results.
404 DeclarationName VAListTagName;
405
406 bool MSStructPragmaOn; // True when \#pragma ms_struct on
407
408 /// Controls member pointer representation format under the MS ABI.
409 LangOptions::PragmaMSPointersToMembersKind
410 MSPointerToMemberRepresentationMethod;
411
412 /// Stack of active SEH __finally scopes. Can be empty.
413 SmallVector<Scope*, 2> CurrentSEHFinally;
414
415 /// Source location for newly created implicit MSInheritanceAttrs
416 SourceLocation ImplicitMSInheritanceAttrLoc;
417
418 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
419 /// `TransformTypos` in order to keep track of any TypoExprs that are created
420 /// recursively during typo correction and wipe them away if the correction
421 /// fails.
422 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
423
424 /// pragma clang section kind
425 enum PragmaClangSectionKind {
426 PCSK_Invalid = 0,
427 PCSK_BSS = 1,
428 PCSK_Data = 2,
429 PCSK_Rodata = 3,
430 PCSK_Text = 4,
431 PCSK_Relro = 5
432 };
433
434 enum PragmaClangSectionAction {
435 PCSA_Set = 0,
436 PCSA_Clear = 1
437 };
438
439 struct PragmaClangSection {
440 std::string SectionName;
441 bool Valid = false;
442 SourceLocation PragmaLocation;
443
444 void Act(SourceLocation PragmaLocation,
445 PragmaClangSectionAction Action,
446 StringLiteral* Name);
447 };
448
449 PragmaClangSection PragmaClangBSSSection;
450 PragmaClangSection PragmaClangDataSection;
451 PragmaClangSection PragmaClangRodataSection;
452 PragmaClangSection PragmaClangRelroSection;
453 PragmaClangSection PragmaClangTextSection;
454
455 enum PragmaMsStackAction {
456 PSK_Reset = 0x0, // #pragma ()
457 PSK_Set = 0x1, // #pragma (value)
458 PSK_Push = 0x2, // #pragma (push[, id])
459 PSK_Pop = 0x4, // #pragma (pop[, id])
460 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
461 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
462 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
463 };
464
465 template<typename ValueType>
466 struct PragmaStack {
467 struct Slot {
468 llvm::StringRef StackSlotLabel;
469 ValueType Value;
470 SourceLocation PragmaLocation;
471 SourceLocation PragmaPushLocation;
472 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
473 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
474 : StackSlotLabel(StackSlotLabel), Value(Value),
475 PragmaLocation(PragmaLocation),
476 PragmaPushLocation(PragmaPushLocation) {}
477 };
478 void Act(SourceLocation PragmaLocation,
479 PragmaMsStackAction Action,
480 llvm::StringRef StackSlotLabel,
481 ValueType Value);
482
483 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
484 // method body to restore the stacks on exit, so it works like this:
485 //
486 // struct S {
487 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
488 // void Method {}
489 // #pragma <name>(pop, InternalPragmaSlot)
490 // };
491 //
492 // It works even with #pragma vtordisp, although MSVC doesn't support
493 // #pragma vtordisp(push [, id], n)
494 // syntax.
495 //
496 // Push / pop a named sentinel slot.
497 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
498 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 499, __PRETTY_FUNCTION__))
499 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 499, __PRETTY_FUNCTION__))
;
500 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
501 }
502
503 // Constructors.
504 explicit PragmaStack(const ValueType &Default)
505 : DefaultValue(Default), CurrentValue(Default) {}
506
507 bool hasValue() const { return CurrentValue != DefaultValue; }
508
509 SmallVector<Slot, 2> Stack;
510 ValueType DefaultValue; // Value used for PSK_Reset action.
511 ValueType CurrentValue;
512 SourceLocation CurrentPragmaLocation;
513 };
514 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
515 // we shouldn't do so if they're in a module).
516
517 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
518 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
519 ///
520 /// 0: Suppress all vtordisps
521 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
522 /// structors
523 /// 2: Always insert vtordisps to support RTTI on partially constructed
524 /// objects
525 PragmaStack<MSVtorDispMode> VtorDispStack;
526 // #pragma pack.
527 // Sentinel to represent when the stack is set to mac68k alignment.
528 static const unsigned kMac68kAlignmentSentinel = ~0U;
529 PragmaStack<unsigned> PackStack;
530 // The current #pragma pack values and locations at each #include.
531 struct PackIncludeState {
532 unsigned CurrentValue;
533 SourceLocation CurrentPragmaLocation;
534 bool HasNonDefaultValue, ShouldWarnOnInclude;
535 };
536 SmallVector<PackIncludeState, 8> PackIncludeStack;
537 // Segment #pragmas.
538 PragmaStack<StringLiteral *> DataSegStack;
539 PragmaStack<StringLiteral *> BSSSegStack;
540 PragmaStack<StringLiteral *> ConstSegStack;
541 PragmaStack<StringLiteral *> CodeSegStack;
542
543 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
544 // Actions should be performed only if we enter / exit a C++ method body.
545 class PragmaStackSentinelRAII {
546 public:
547 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
548 ~PragmaStackSentinelRAII();
549
550 private:
551 Sema &S;
552 StringRef SlotLabel;
553 bool ShouldAct;
554 };
555
556 /// A mapping that describes the nullability we've seen in each header file.
557 FileNullabilityMap NullabilityMap;
558
559 /// Last section used with #pragma init_seg.
560 StringLiteral *CurInitSeg;
561 SourceLocation CurInitSegLoc;
562
563 /// VisContext - Manages the stack for \#pragma GCC visibility.
564 void *VisContext; // Really a "PragmaVisStack*"
565
566 /// This an attribute introduced by \#pragma clang attribute.
567 struct PragmaAttributeEntry {
568 SourceLocation Loc;
569 ParsedAttr *Attribute;
570 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
571 bool IsUsed;
572 };
573
574 /// A push'd group of PragmaAttributeEntries.
575 struct PragmaAttributeGroup {
576 /// The location of the push attribute.
577 SourceLocation Loc;
578 /// The namespace of this push group.
579 const IdentifierInfo *Namespace;
580 SmallVector<PragmaAttributeEntry, 2> Entries;
581 };
582
583 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
584
585 /// The declaration that is currently receiving an attribute from the
586 /// #pragma attribute stack.
587 const Decl *PragmaAttributeCurrentTargetDecl;
588
589 /// This represents the last location of a "#pragma clang optimize off"
590 /// directive if such a directive has not been closed by an "on" yet. If
591 /// optimizations are currently "on", this is set to an invalid location.
592 SourceLocation OptimizeOffPragmaLocation;
593
594 /// Flag indicating if Sema is building a recovery call expression.
595 ///
596 /// This flag is used to avoid building recovery call expressions
597 /// if Sema is already doing so, which would cause infinite recursions.
598 bool IsBuildingRecoveryCallExpr;
599
600 /// Used to control the generation of ExprWithCleanups.
601 CleanupInfo Cleanup;
602
603 /// ExprCleanupObjects - This is the stack of objects requiring
604 /// cleanup that are created by the current full expression. The
605 /// element type here is ExprWithCleanups::Object.
606 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
607
608 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
609 /// to a variable (constant) that may or may not be odr-used in this Expr, and
610 /// we won't know until all lvalue-to-rvalue and discarded value conversions
611 /// have been applied to all subexpressions of the enclosing full expression.
612 /// This is cleared at the end of each full expression.
613 using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
614 MaybeODRUseExprSet MaybeODRUseExprs;
615
616 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
617
618 /// Stack containing information about each of the nested
619 /// function, block, and method scopes that are currently active.
620 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
621
622 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
623 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
624 ExtVectorDeclsType;
625
626 /// ExtVectorDecls - This is a list all the extended vector types. This allows
627 /// us to associate a raw vector type with one of the ext_vector type names.
628 /// This is only necessary for issuing pretty diagnostics.
629 ExtVectorDeclsType ExtVectorDecls;
630
631 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
632 std::unique_ptr<CXXFieldCollector> FieldCollector;
633
634 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
635
636 /// Set containing all declared private fields that are not used.
637 NamedDeclSetType UnusedPrivateFields;
638
639 /// Set containing all typedefs that are likely unused.
640 llvm::SmallSetVector<const TypedefNameDecl *, 4>
641 UnusedLocalTypedefNameCandidates;
642
643 /// Delete-expressions to be analyzed at the end of translation unit
644 ///
645 /// This list contains class members, and locations of delete-expressions
646 /// that could not be proven as to whether they mismatch with new-expression
647 /// used in initializer of the field.
648 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
649 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
650 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
651
652 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
653
654 /// PureVirtualClassDiagSet - a set of class declarations which we have
655 /// emitted a list of pure virtual functions. Used to prevent emitting the
656 /// same list more than once.
657 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
658
659 /// ParsingInitForAutoVars - a set of declarations with auto types for which
660 /// we are currently parsing the initializer.
661 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
662
663 /// Look for a locally scoped extern "C" declaration by the given name.
664 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
665
666 typedef LazyVector<VarDecl *, ExternalSemaSource,
667 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
668 TentativeDefinitionsType;
669
670 /// All the tentative definitions encountered in the TU.
671 TentativeDefinitionsType TentativeDefinitions;
672
673 /// All the external declarations encoutered and used in the TU.
674 SmallVector<VarDecl *, 4> ExternalDeclarations;
675
676 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
677 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
678 UnusedFileScopedDeclsType;
679
680 /// The set of file scoped decls seen so far that have not been used
681 /// and must warn if not used. Only contains the first declaration.
682 UnusedFileScopedDeclsType UnusedFileScopedDecls;
683
684 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
685 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
686 DelegatingCtorDeclsType;
687
688 /// All the delegating constructors seen so far in the file, used for
689 /// cycle detection at the end of the TU.
690 DelegatingCtorDeclsType DelegatingCtorDecls;
691
692 /// All the overriding functions seen during a class definition
693 /// that had their exception spec checks delayed, plus the overridden
694 /// function.
695 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
696 DelayedOverridingExceptionSpecChecks;
697
698 /// All the function redeclarations seen during a class definition that had
699 /// their exception spec checks delayed, plus the prior declaration they
700 /// should be checked against. Except during error recovery, the new decl
701 /// should always be a friend declaration, as that's the only valid way to
702 /// redeclare a special member before its class is complete.
703 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
704 DelayedEquivalentExceptionSpecChecks;
705
706 typedef llvm::MapVector<const FunctionDecl *,
707 std::unique_ptr<LateParsedTemplate>>
708 LateParsedTemplateMapT;
709 LateParsedTemplateMapT LateParsedTemplateMap;
710
711 /// Callback to the parser to parse templated functions when needed.
712 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
713 typedef void LateTemplateParserCleanupCB(void *P);
714 LateTemplateParserCB *LateTemplateParser;
715 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
716 void *OpaqueParser;
717
718 void SetLateTemplateParser(LateTemplateParserCB *LTP,
719 LateTemplateParserCleanupCB *LTPCleanup,
720 void *P) {
721 LateTemplateParser = LTP;
722 LateTemplateParserCleanup = LTPCleanup;
723 OpaqueParser = P;
724 }
725
726 class DelayedDiagnostics;
727
728 class DelayedDiagnosticsState {
729 sema::DelayedDiagnosticPool *SavedPool;
730 friend class Sema::DelayedDiagnostics;
731 };
732 typedef DelayedDiagnosticsState ParsingDeclState;
733 typedef DelayedDiagnosticsState ProcessingContextState;
734
735 /// A class which encapsulates the logic for delaying diagnostics
736 /// during parsing and other processing.
737 class DelayedDiagnostics {
738 /// The current pool of diagnostics into which delayed
739 /// diagnostics should go.
740 sema::DelayedDiagnosticPool *CurPool;
741
742 public:
743 DelayedDiagnostics() : CurPool(nullptr) {}
744
745 /// Adds a delayed diagnostic.
746 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
747
748 /// Determines whether diagnostics should be delayed.
749 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
750
751 /// Returns the current delayed-diagnostics pool.
752 sema::DelayedDiagnosticPool *getCurrentPool() const {
753 return CurPool;
754 }
755
756 /// Enter a new scope. Access and deprecation diagnostics will be
757 /// collected in this pool.
758 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
759 DelayedDiagnosticsState state;
760 state.SavedPool = CurPool;
761 CurPool = &pool;
762 return state;
763 }
764
765 /// Leave a delayed-diagnostic state that was previously pushed.
766 /// Do not emit any of the diagnostics. This is performed as part
767 /// of the bookkeeping of popping a pool "properly".
768 void popWithoutEmitting(DelayedDiagnosticsState state) {
769 CurPool = state.SavedPool;
770 }
771
772 /// Enter a new scope where access and deprecation diagnostics are
773 /// not delayed.
774 DelayedDiagnosticsState pushUndelayed() {
775 DelayedDiagnosticsState state;
776 state.SavedPool = CurPool;
777 CurPool = nullptr;
778 return state;
779 }
780
781 /// Undo a previous pushUndelayed().
782 void popUndelayed(DelayedDiagnosticsState state) {
783 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 783, __PRETTY_FUNCTION__))
;
784 CurPool = state.SavedPool;
785 }
786 } DelayedDiagnostics;
787
788 /// A RAII object to temporarily push a declaration context.
789 class ContextRAII {
790 private:
791 Sema &S;
792 DeclContext *SavedContext;
793 ProcessingContextState SavedContextState;
794 QualType SavedCXXThisTypeOverride;
795
796 public:
797 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
798 : S(S), SavedContext(S.CurContext),
799 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
800 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
801 {
802 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 802, __PRETTY_FUNCTION__))
;
803 S.CurContext = ContextToPush;
804 if (NewThisContext)
805 S.CXXThisTypeOverride = QualType();
806 }
807
808 void pop() {
809 if (!SavedContext) return;
810 S.CurContext = SavedContext;
811 S.DelayedDiagnostics.popUndelayed(SavedContextState);
812 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
813 SavedContext = nullptr;
814 }
815
816 ~ContextRAII() {
817 pop();
818 }
819 };
820
821 /// Used to change context to isConstantEvaluated without pushing a heavy
822 /// ExpressionEvaluationContextRecord object.
823 bool isConstantEvaluatedOverride;
824
825 bool isConstantEvaluated() {
826 return ExprEvalContexts.back().isConstantEvaluated() ||
827 isConstantEvaluatedOverride;
828 }
829
830 /// RAII object to handle the state changes required to synthesize
831 /// a function body.
832 class SynthesizedFunctionScope {
833 Sema &S;
834 Sema::ContextRAII SavedContext;
835 bool PushedCodeSynthesisContext = false;
836
837 public:
838 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
839 : S(S), SavedContext(S, DC) {
840 S.PushFunctionScope();
841 S.PushExpressionEvaluationContext(
842 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
843 if (auto *FD = dyn_cast<FunctionDecl>(DC))
844 FD->setWillHaveBody(true);
845 else
846 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 846, __PRETTY_FUNCTION__))
;
847 }
848
849 void addContextNote(SourceLocation UseLoc) {
850 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 850, __PRETTY_FUNCTION__))
;
851
852 Sema::CodeSynthesisContext Ctx;
853 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
854 Ctx.PointOfInstantiation = UseLoc;
855 Ctx.Entity = cast<Decl>(S.CurContext);
856 S.pushCodeSynthesisContext(Ctx);
857
858 PushedCodeSynthesisContext = true;
859 }
860
861 ~SynthesizedFunctionScope() {
862 if (PushedCodeSynthesisContext)
863 S.popCodeSynthesisContext();
864 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
865 FD->setWillHaveBody(false);
866 S.PopExpressionEvaluationContext();
867 S.PopFunctionScopeInfo();
868 }
869 };
870
871 /// WeakUndeclaredIdentifiers - Identifiers contained in
872 /// \#pragma weak before declared. rare. may alias another
873 /// identifier, declared or undeclared
874 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
875
876 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
877 /// \#pragma redefine_extname before declared. Used in Solaris system headers
878 /// to define functions that occur in multiple standards to call the version
879 /// in the currently selected standard.
880 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
881
882
883 /// Load weak undeclared identifiers from the external source.
884 void LoadExternalWeakUndeclaredIdentifiers();
885
886 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
887 /// \#pragma weak during processing of other Decls.
888 /// I couldn't figure out a clean way to generate these in-line, so
889 /// we store them here and handle separately -- which is a hack.
890 /// It would be best to refactor this.
891 SmallVector<Decl*,2> WeakTopLevelDecl;
892
893 IdentifierResolver IdResolver;
894
895 /// Translation Unit Scope - useful to Objective-C actions that need
896 /// to lookup file scope declarations in the "ordinary" C decl namespace.
897 /// For example, user-defined classes, built-in "id" type, etc.
898 Scope *TUScope;
899
900 /// The C++ "std" namespace, where the standard library resides.
901 LazyDeclPtr StdNamespace;
902
903 /// The C++ "std::bad_alloc" class, which is defined by the C++
904 /// standard library.
905 LazyDeclPtr StdBadAlloc;
906
907 /// The C++ "std::align_val_t" enum class, which is defined by the C++
908 /// standard library.
909 LazyDeclPtr StdAlignValT;
910
911 /// The C++ "std::experimental" namespace, where the experimental parts
912 /// of the standard library resides.
913 NamespaceDecl *StdExperimentalNamespaceCache;
914
915 /// The C++ "std::initializer_list" template, which is defined in
916 /// \<initializer_list>.
917 ClassTemplateDecl *StdInitializerList;
918
919 /// The C++ "std::coroutine_traits" template, which is defined in
920 /// \<coroutine_traits>
921 ClassTemplateDecl *StdCoroutineTraitsCache;
922
923 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
924 RecordDecl *CXXTypeInfoDecl;
925
926 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
927 RecordDecl *MSVCGuidDecl;
928
929 /// Caches identifiers/selectors for NSFoundation APIs.
930 std::unique_ptr<NSAPI> NSAPIObj;
931
932 /// The declaration of the Objective-C NSNumber class.
933 ObjCInterfaceDecl *NSNumberDecl;
934
935 /// The declaration of the Objective-C NSValue class.
936 ObjCInterfaceDecl *NSValueDecl;
937
938 /// Pointer to NSNumber type (NSNumber *).
939 QualType NSNumberPointer;
940
941 /// Pointer to NSValue type (NSValue *).
942 QualType NSValuePointer;
943
944 /// The Objective-C NSNumber methods used to create NSNumber literals.
945 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
946
947 /// The declaration of the Objective-C NSString class.
948 ObjCInterfaceDecl *NSStringDecl;
949
950 /// Pointer to NSString type (NSString *).
951 QualType NSStringPointer;
952
953 /// The declaration of the stringWithUTF8String: method.
954 ObjCMethodDecl *StringWithUTF8StringMethod;
955
956 /// The declaration of the valueWithBytes:objCType: method.
957 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
958
959 /// The declaration of the Objective-C NSArray class.
960 ObjCInterfaceDecl *NSArrayDecl;
961
962 /// The declaration of the arrayWithObjects:count: method.
963 ObjCMethodDecl *ArrayWithObjectsMethod;
964
965 /// The declaration of the Objective-C NSDictionary class.
966 ObjCInterfaceDecl *NSDictionaryDecl;
967
968 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
969 ObjCMethodDecl *DictionaryWithObjectsMethod;
970
971 /// id<NSCopying> type.
972 QualType QIDNSCopying;
973
974 /// will hold 'respondsToSelector:'
975 Selector RespondsToSelectorSel;
976
977 /// A flag to remember whether the implicit forms of operator new and delete
978 /// have been declared.
979 bool GlobalNewDeleteDeclared;
980
981 /// A flag to indicate that we're in a context that permits abstract
982 /// references to fields. This is really a
983 bool AllowAbstractFieldReference;
984
985 /// Describes how the expressions currently being parsed are
986 /// evaluated at run-time, if at all.
987 enum class ExpressionEvaluationContext {
988 /// The current expression and its subexpressions occur within an
989 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
990 /// \c sizeof, where the type of the expression may be significant but
991 /// no code will be generated to evaluate the value of the expression at
992 /// run time.
993 Unevaluated,
994
995 /// The current expression occurs within a braced-init-list within
996 /// an unevaluated operand. This is mostly like a regular unevaluated
997 /// context, except that we still instantiate constexpr functions that are
998 /// referenced here so that we can perform narrowing checks correctly.
999 UnevaluatedList,
1000
1001 /// The current expression occurs within a discarded statement.
1002 /// This behaves largely similarly to an unevaluated operand in preventing
1003 /// definitions from being required, but not in other ways.
1004 DiscardedStatement,
1005
1006 /// The current expression occurs within an unevaluated
1007 /// operand that unconditionally permits abstract references to
1008 /// fields, such as a SIZE operator in MS-style inline assembly.
1009 UnevaluatedAbstract,
1010
1011 /// The current context is "potentially evaluated" in C++11 terms,
1012 /// but the expression is evaluated at compile-time (like the values of
1013 /// cases in a switch statement).
1014 ConstantEvaluated,
1015
1016 /// The current expression is potentially evaluated at run time,
1017 /// which means that code may be generated to evaluate the value of the
1018 /// expression at run time.
1019 PotentiallyEvaluated,
1020
1021 /// The current expression is potentially evaluated, but any
1022 /// declarations referenced inside that expression are only used if
1023 /// in fact the current expression is used.
1024 ///
1025 /// This value is used when parsing default function arguments, for which
1026 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1027 /// through varargs) but do not want to mark declarations as "referenced"
1028 /// until the default argument is used.
1029 PotentiallyEvaluatedIfUsed
1030 };
1031
1032 /// Data structure used to record current or nested
1033 /// expression evaluation contexts.
1034 struct ExpressionEvaluationContextRecord {
1035 /// The expression evaluation context.
1036 ExpressionEvaluationContext Context;
1037
1038 /// Whether the enclosing context needed a cleanup.
1039 CleanupInfo ParentCleanup;
1040
1041 /// Whether we are in a decltype expression.
1042 bool IsDecltype;
1043
1044 /// The number of active cleanup objects when we entered
1045 /// this expression evaluation context.
1046 unsigned NumCleanupObjects;
1047
1048 /// The number of typos encountered during this expression evaluation
1049 /// context (i.e. the number of TypoExprs created).
1050 unsigned NumTypos;
1051
1052 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1053
1054 /// The lambdas that are present within this context, if it
1055 /// is indeed an unevaluated context.
1056 SmallVector<LambdaExpr *, 2> Lambdas;
1057
1058 /// The declaration that provides context for lambda expressions
1059 /// and block literals if the normal declaration context does not
1060 /// suffice, e.g., in a default function argument.
1061 Decl *ManglingContextDecl;
1062
1063 /// If we are processing a decltype type, a set of call expressions
1064 /// for which we have deferred checking the completeness of the return type.
1065 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1066
1067 /// If we are processing a decltype type, a set of temporary binding
1068 /// expressions for which we have deferred checking the destructor.
1069 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1070
1071 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1072
1073 /// Expressions appearing as the LHS of a volatile assignment in this
1074 /// context. We produce a warning for these when popping the context if
1075 /// they are not discarded-value expressions nor unevaluated operands.
1076 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1077
1078 /// \brief Describes whether we are in an expression constext which we have
1079 /// to handle differently.
1080 enum ExpressionKind {
1081 EK_Decltype, EK_TemplateArgument, EK_Other
1082 } ExprContext;
1083
1084 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1085 unsigned NumCleanupObjects,
1086 CleanupInfo ParentCleanup,
1087 Decl *ManglingContextDecl,
1088 ExpressionKind ExprContext)
1089 : Context(Context), ParentCleanup(ParentCleanup),
1090 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1091 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1092
1093 bool isUnevaluated() const {
1094 return Context == ExpressionEvaluationContext::Unevaluated ||
1095 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1096 Context == ExpressionEvaluationContext::UnevaluatedList;
1097 }
1098 bool isConstantEvaluated() const {
1099 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1100 }
1101 };
1102
1103 /// A stack of expression evaluation contexts.
1104 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1105
1106 /// Emit a warning for all pending noderef expressions that we recorded.
1107 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1108
1109 /// Compute the mangling number context for a lambda expression or
1110 /// block literal. Also return the extra mangling decl if any.
1111 ///
1112 /// \param DC - The DeclContext containing the lambda expression or
1113 /// block literal.
1114 std::tuple<MangleNumberingContext *, Decl *>
1115 getCurrentMangleNumberContext(const DeclContext *DC);
1116
1117
1118 /// SpecialMemberOverloadResult - The overloading result for a special member
1119 /// function.
1120 ///
1121 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1122 /// integer are used to determine whether overload resolution succeeded.
1123 class SpecialMemberOverloadResult {
1124 public:
1125 enum Kind {
1126 NoMemberOrDeleted,
1127 Ambiguous,
1128 Success
1129 };
1130
1131 private:
1132 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1133
1134 public:
1135 SpecialMemberOverloadResult() : Pair() {}
1136 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1137 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1138
1139 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1140 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1141
1142 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1143 void setKind(Kind K) { Pair.setInt(K); }
1144 };
1145
1146 class SpecialMemberOverloadResultEntry
1147 : public llvm::FastFoldingSetNode,
1148 public SpecialMemberOverloadResult {
1149 public:
1150 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1151 : FastFoldingSetNode(ID)
1152 {}
1153 };
1154
1155 /// A cache of special member function overload resolution results
1156 /// for C++ records.
1157 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1158
1159 /// A cache of the flags available in enumerations with the flag_bits
1160 /// attribute.
1161 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1162
1163 /// The kind of translation unit we are processing.
1164 ///
1165 /// When we're processing a complete translation unit, Sema will perform
1166 /// end-of-translation-unit semantic tasks (such as creating
1167 /// initializers for tentative definitions in C) once parsing has
1168 /// completed. Modules and precompiled headers perform different kinds of
1169 /// checks.
1170 TranslationUnitKind TUKind;
1171
1172 llvm::BumpPtrAllocator BumpAlloc;
1173
1174 /// The number of SFINAE diagnostics that have been trapped.
1175 unsigned NumSFINAEErrors;
1176
1177 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1178 UnparsedDefaultArgInstantiationsMap;
1179
1180 /// A mapping from parameters with unparsed default arguments to the
1181 /// set of instantiations of each parameter.
1182 ///
1183 /// This mapping is a temporary data structure used when parsing
1184 /// nested class templates or nested classes of class templates,
1185 /// where we might end up instantiating an inner class before the
1186 /// default arguments of its methods have been parsed.
1187 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1188
1189 // Contains the locations of the beginning of unparsed default
1190 // argument locations.
1191 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1192
1193 /// UndefinedInternals - all the used, undefined objects which require a
1194 /// definition in this translation unit.
1195 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1196
1197 /// Determine if VD, which must be a variable or function, is an external
1198 /// symbol that nonetheless can't be referenced from outside this translation
1199 /// unit because its type has no linkage and it's not extern "C".
1200 bool isExternalWithNoLinkageType(ValueDecl *VD);
1201
1202 /// Obtain a sorted list of functions that are undefined but ODR-used.
1203 void getUndefinedButUsed(
1204 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1205
1206 /// Retrieves list of suspicious delete-expressions that will be checked at
1207 /// the end of translation unit.
1208 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1209 getMismatchingDeleteExpressions() const;
1210
1211 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1212 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1213
1214 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1215 /// We need to maintain a list, since selectors can have differing signatures
1216 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1217 /// of selectors are "overloaded").
1218 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1219 /// methods inside categories with a particular selector.
1220 GlobalMethodPool MethodPool;
1221
1222 /// Method selectors used in a \@selector expression. Used for implementation
1223 /// of -Wselector.
1224 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1225
1226 /// List of SourceLocations where 'self' is implicitly retained inside a
1227 /// block.
1228 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1229 ImplicitlyRetainedSelfLocs;
1230
1231 /// Kinds of C++ special members.
1232 enum CXXSpecialMember {
1233 CXXDefaultConstructor,
1234 CXXCopyConstructor,
1235 CXXMoveConstructor,
1236 CXXCopyAssignment,
1237 CXXMoveAssignment,
1238 CXXDestructor,
1239 CXXInvalid
1240 };
1241
1242 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1243 SpecialMemberDecl;
1244
1245 /// The C++ special members which we are currently in the process of
1246 /// declaring. If this process recursively triggers the declaration of the
1247 /// same special member, we should act as if it is not yet declared.
1248 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1249
1250 /// Kinds of defaulted comparison operator functions.
1251 enum class DefaultedComparisonKind : unsigned char {
1252 /// This is not a defaultable comparison operator.
1253 None,
1254 /// This is an operator== that should be implemented as a series of
1255 /// subobject comparisons.
1256 Equal,
1257 /// This is an operator<=> that should be implemented as a series of
1258 /// subobject comparisons.
1259 ThreeWay,
1260 /// This is an operator!= that should be implemented as a rewrite in terms
1261 /// of a == comparison.
1262 NotEqual,
1263 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1264 /// terms of a <=> comparison.
1265 Relational,
1266 };
1267
1268 /// The function definitions which were renamed as part of typo-correction
1269 /// to match their respective declarations. We want to keep track of them
1270 /// to ensure that we don't emit a "redefinition" error if we encounter a
1271 /// correctly named definition after the renamed definition.
1272 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1273
1274 /// Stack of types that correspond to the parameter entities that are
1275 /// currently being copy-initialized. Can be empty.
1276 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1277
1278 void ReadMethodPool(Selector Sel);
1279 void updateOutOfDateSelector(Selector Sel);
1280
1281 /// Private Helper predicate to check for 'self'.
1282 bool isSelfExpr(Expr *RExpr);
1283 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1284
1285 /// Cause the active diagnostic on the DiagosticsEngine to be
1286 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1287 /// should not be used elsewhere.
1288 void EmitCurrentDiagnostic(unsigned DiagID);
1289
1290 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1291 /// statements.
1292 class FPContractStateRAII {
1293 public:
1294 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1295 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1296
1297 private:
1298 Sema& S;
1299 FPOptions OldFPFeaturesState;
1300 };
1301
1302 void addImplicitTypedef(StringRef Name, QualType T);
1303
1304 bool WarnedStackExhausted = false;
1305
1306public:
1307 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1308 TranslationUnitKind TUKind = TU_Complete,
1309 CodeCompleteConsumer *CompletionConsumer = nullptr);
1310 ~Sema();
1311
1312 /// Perform initialization that occurs after the parser has been
1313 /// initialized but before it parses anything.
1314 void Initialize();
1315
1316 const LangOptions &getLangOpts() const { return LangOpts; }
1317 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1318 FPOptions &getFPOptions() { return FPFeatures; }
1319
1320 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1321 SourceManager &getSourceManager() const { return SourceMgr; }
1322 Preprocessor &getPreprocessor() const { return PP; }
1323 ASTContext &getASTContext() const { return Context; }
1324 ASTConsumer &getASTConsumer() const { return Consumer; }
1325 ASTMutationListener *getASTMutationListener() const;
1326 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1327
1328 ///Registers an external source. If an external source already exists,
1329 /// creates a multiplex external source and appends to it.
1330 ///
1331 ///\param[in] E - A non-null external sema source.
1332 ///
1333 void addExternalSource(ExternalSemaSource *E);
1334
1335 void PrintStats() const;
1336
1337 /// Warn that the stack is nearly exhausted.
1338 void warnStackExhausted(SourceLocation Loc);
1339
1340 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1341 /// guaranteed). Produces a warning if we're low on stack space and allocates
1342 /// more in that case. Use this in code that may recurse deeply (for example,
1343 /// in template instantiation) to avoid stack overflow.
1344 void runWithSufficientStackSpace(SourceLocation Loc,
1345 llvm::function_ref<void()> Fn);
1346
1347 /// Helper class that creates diagnostics with optional
1348 /// template instantiation stacks.
1349 ///
1350 /// This class provides a wrapper around the basic DiagnosticBuilder
1351 /// class that emits diagnostics. SemaDiagnosticBuilder is
1352 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1353 /// does) and, if the diagnostic comes from inside a template
1354 /// instantiation, printing the template instantiation stack as
1355 /// well.
1356 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1357 Sema &SemaRef;
1358 unsigned DiagID;
1359
1360 public:
1361 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1362 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1363
1364 // This is a cunning lie. DiagnosticBuilder actually performs move
1365 // construction in its copy constructor (but due to varied uses, it's not
1366 // possible to conveniently express this as actual move construction). So
1367 // the default copy ctor here is fine, because the base class disables the
1368 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1369 // in that case anwyay.
1370 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1371
1372 ~SemaDiagnosticBuilder() {
1373 // If we aren't active, there is nothing to do.
1374 if (!isActive()) return;
1375
1376 // Otherwise, we need to emit the diagnostic. First flush the underlying
1377 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1378 // won't emit the diagnostic in its own destructor.
1379 //
1380 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1381 // do its own needless checks to see if the diagnostic needs to be
1382 // emitted. However, because we take care to ensure that the builder
1383 // objects never escape, a sufficiently smart compiler will be able to
1384 // eliminate that code.
1385 FlushCounts();
1386 Clear();
1387
1388 // Dispatch to Sema to emit the diagnostic.
1389 SemaRef.EmitCurrentDiagnostic(DiagID);
1390 }
1391
1392 /// Teach operator<< to produce an object of the correct type.
1393 template<typename T>
1394 friend const SemaDiagnosticBuilder &operator<<(
1395 const SemaDiagnosticBuilder &Diag, const T &Value) {
1396 const DiagnosticBuilder &BaseDiag = Diag;
1397 BaseDiag << Value;
1398 return Diag;
1399 }
1400 };
1401
1402 /// Emit a diagnostic.
1403 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1404 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1405 return SemaDiagnosticBuilder(DB, *this, DiagID);
1406 }
1407
1408 /// Emit a partial diagnostic.
1409 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1410
1411 /// Build a partial diagnostic.
1412 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1413
1414 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1415
1416 /// Get a string to suggest for zero-initialization of a type.
1417 std::string
1418 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1419 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1420
1421 /// Calls \c Lexer::getLocForEndOfToken()
1422 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1423
1424 /// Retrieve the module loader associated with the preprocessor.
1425 ModuleLoader &getModuleLoader() const;
1426
1427 void emitAndClearUnusedLocalTypedefWarnings();
1428
1429 enum TUFragmentKind {
1430 /// The global module fragment, between 'module;' and a module-declaration.
1431 Global,
1432 /// A normal translation unit fragment. For a non-module unit, this is the
1433 /// entire translation unit. Otherwise, it runs from the module-declaration
1434 /// to the private-module-fragment (if any) or the end of the TU (if not).
1435 Normal,
1436 /// The private module fragment, between 'module :private;' and the end of
1437 /// the translation unit.
1438 Private
1439 };
1440
1441 void ActOnStartOfTranslationUnit();
1442 void ActOnEndOfTranslationUnit();
1443 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1444
1445 void CheckDelegatingCtorCycles();
1446
1447 Scope *getScopeForContext(DeclContext *Ctx);
1448
1449 void PushFunctionScope();
1450 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1451 sema::LambdaScopeInfo *PushLambdaScope();
1452
1453 /// This is used to inform Sema what the current TemplateParameterDepth
1454 /// is during Parsing. Currently it is used to pass on the depth
1455 /// when parsing generic lambda 'auto' parameters.
1456 void RecordParsingTemplateParameterDepth(unsigned Depth);
1457
1458 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1459 RecordDecl *RD, CapturedRegionKind K,
1460 unsigned OpenMPCaptureLevel = 0);
1461
1462 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1463 /// time after they've been popped.
1464 class PoppedFunctionScopeDeleter {
1465 Sema *Self;
1466
1467 public:
1468 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1469 void operator()(sema::FunctionScopeInfo *Scope) const;
1470 };
1471
1472 using PoppedFunctionScopePtr =
1473 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1474
1475 PoppedFunctionScopePtr
1476 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1477 const Decl *D = nullptr,
1478 QualType BlockType = QualType());
1479
1480 sema::FunctionScopeInfo *getCurFunction() const {
1481 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1482 }
1483
1484 sema::FunctionScopeInfo *getEnclosingFunction() const;
1485
1486 void setFunctionHasBranchIntoScope();
1487 void setFunctionHasBranchProtectedScope();
1488 void setFunctionHasIndirectGoto();
1489
1490 void PushCompoundScope(bool IsStmtExpr);
1491 void PopCompoundScope();
1492
1493 sema::CompoundScopeInfo &getCurCompoundScope() const;
1494
1495 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1496
1497 /// Retrieve the current block, if any.
1498 sema::BlockScopeInfo *getCurBlock();
1499
1500 /// Get the innermost lambda enclosing the current location, if any. This
1501 /// looks through intervening non-lambda scopes such as local functions and
1502 /// blocks.
1503 sema::LambdaScopeInfo *getEnclosingLambda() const;
1504
1505 /// Retrieve the current lambda scope info, if any.
1506 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1507 /// lambda scope info ignoring all inner capturing scopes that are not
1508 /// lambda scopes.
1509 sema::LambdaScopeInfo *
1510 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1511
1512 /// Retrieve the current generic lambda info, if any.
1513 sema::LambdaScopeInfo *getCurGenericLambda();
1514
1515 /// Retrieve the current captured region, if any.
1516 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1517
1518 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1519 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1520
1521 void ActOnComment(SourceRange Comment);
1522
1523 //===--------------------------------------------------------------------===//
1524 // Type Analysis / Processing: SemaType.cpp.
1525 //
1526
1527 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1528 const DeclSpec *DS = nullptr);
1529 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1530 const DeclSpec *DS = nullptr);
1531 QualType BuildPointerType(QualType T,
1532 SourceLocation Loc, DeclarationName Entity);
1533 QualType BuildReferenceType(QualType T, bool LValueRef,
1534 SourceLocation Loc, DeclarationName Entity);
1535 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1536 Expr *ArraySize, unsigned Quals,
1537 SourceRange Brackets, DeclarationName Entity);
1538 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1539 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1540 SourceLocation AttrLoc);
1541 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1542 SourceLocation AttrLoc);
1543
1544 /// Same as above, but constructs the AddressSpace index if not provided.
1545 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1546 SourceLocation AttrLoc);
1547
1548 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1549
1550 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1551
1552 /// Build a function type.
1553 ///
1554 /// This routine checks the function type according to C++ rules and
1555 /// under the assumption that the result type and parameter types have
1556 /// just been instantiated from a template. It therefore duplicates
1557 /// some of the behavior of GetTypeForDeclarator, but in a much
1558 /// simpler form that is only suitable for this narrow use case.
1559 ///
1560 /// \param T The return type of the function.
1561 ///
1562 /// \param ParamTypes The parameter types of the function. This array
1563 /// will be modified to account for adjustments to the types of the
1564 /// function parameters.
1565 ///
1566 /// \param Loc The location of the entity whose type involves this
1567 /// function type or, if there is no such entity, the location of the
1568 /// type that will have function type.
1569 ///
1570 /// \param Entity The name of the entity that involves the function
1571 /// type, if known.
1572 ///
1573 /// \param EPI Extra information about the function type. Usually this will
1574 /// be taken from an existing function with the same prototype.
1575 ///
1576 /// \returns A suitable function type, if there are no errors. The
1577 /// unqualified type will always be a FunctionProtoType.
1578 /// Otherwise, returns a NULL type.
1579 QualType BuildFunctionType(QualType T,
1580 MutableArrayRef<QualType> ParamTypes,
1581 SourceLocation Loc, DeclarationName Entity,
1582 const FunctionProtoType::ExtProtoInfo &EPI);
1583
1584 QualType BuildMemberPointerType(QualType T, QualType Class,
1585 SourceLocation Loc,
1586 DeclarationName Entity);
1587 QualType BuildBlockPointerType(QualType T,
1588 SourceLocation Loc, DeclarationName Entity);
1589 QualType BuildParenType(QualType T);
1590 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1591 QualType BuildReadPipeType(QualType T,
1592 SourceLocation Loc);
1593 QualType BuildWritePipeType(QualType T,
1594 SourceLocation Loc);
1595
1596 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1597 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1598
1599 /// Package the given type and TSI into a ParsedType.
1600 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1601 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1602 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1603 static QualType GetTypeFromParser(ParsedType Ty,
1604 TypeSourceInfo **TInfo = nullptr);
1605 CanThrowResult canThrow(const Stmt *E);
1606 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1607 const FunctionProtoType *FPT);
1608 void UpdateExceptionSpec(FunctionDecl *FD,
1609 const FunctionProtoType::ExceptionSpecInfo &ESI);
1610 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1611 bool CheckDistantExceptionSpec(QualType T);
1612 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1613 bool CheckEquivalentExceptionSpec(
1614 const FunctionProtoType *Old, SourceLocation OldLoc,
1615 const FunctionProtoType *New, SourceLocation NewLoc);
1616 bool CheckEquivalentExceptionSpec(
1617 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1618 const FunctionProtoType *Old, SourceLocation OldLoc,
1619 const FunctionProtoType *New, SourceLocation NewLoc);
1620 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1621 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1622 const PartialDiagnostic &NestedDiagID,
1623 const PartialDiagnostic &NoteID,
1624 const PartialDiagnostic &NoThrowDiagID,
1625 const FunctionProtoType *Superset,
1626 SourceLocation SuperLoc,
1627 const FunctionProtoType *Subset,
1628 SourceLocation SubLoc);
1629 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1630 const PartialDiagnostic &NoteID,
1631 const FunctionProtoType *Target,
1632 SourceLocation TargetLoc,
1633 const FunctionProtoType *Source,
1634 SourceLocation SourceLoc);
1635
1636 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1637
1638 /// The parser has parsed the context-sensitive type 'instancetype'
1639 /// in an Objective-C message declaration. Return the appropriate type.
1640 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1641
1642 /// Abstract class used to diagnose incomplete types.
1643 struct TypeDiagnoser {
1644 TypeDiagnoser() {}
1645
1646 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1647 virtual ~TypeDiagnoser() {}
1648 };
1649
1650 static int getPrintable(int I) { return I; }
1651 static unsigned getPrintable(unsigned I) { return I; }
1652 static bool getPrintable(bool B) { return B; }
1653 static const char * getPrintable(const char *S) { return S; }
1654 static StringRef getPrintable(StringRef S) { return S; }
1655 static const std::string &getPrintable(const std::string &S) { return S; }
1656 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1657 return II;
1658 }
1659 static DeclarationName getPrintable(DeclarationName N) { return N; }
1660 static QualType getPrintable(QualType T) { return T; }
1661 static SourceRange getPrintable(SourceRange R) { return R; }
1662 static SourceRange getPrintable(SourceLocation L) { return L; }
1663 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1664 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1665
1666 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1667 unsigned DiagID;
1668 std::tuple<const Ts &...> Args;
1669
1670 template <std::size_t... Is>
1671 void emit(const SemaDiagnosticBuilder &DB,
1672 std::index_sequence<Is...>) const {
1673 // Apply all tuple elements to the builder in order.
1674 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1675 (void)Dummy;
1676 }
1677
1678 public:
1679 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1680 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1681 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 1681, __PRETTY_FUNCTION__))
;
1682 }
1683
1684 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1685 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1686 emit(DB, std::index_sequence_for<Ts...>());
1687 DB << T;
1688 }
1689 };
1690
1691private:
1692 /// Methods for marking which expressions involve dereferencing a pointer
1693 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1694 /// they are parsed, meaning that a noderef pointer may not be accessed. For
1695 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1696 /// `*p`, but need to check that `address of` is called on it. This requires
1697 /// keeping a container of all pending expressions and checking if the address
1698 /// of them are eventually taken.
1699 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1700 void CheckAddressOfNoDeref(const Expr *E);
1701 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1702
1703 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1704 TypeDiagnoser *Diagnoser);
1705
1706 struct ModuleScope {
1707 SourceLocation BeginLoc;
1708 clang::Module *Module = nullptr;
1709 bool ModuleInterface = false;
1710 bool ImplicitGlobalModuleFragment = false;
1711 VisibleModuleSet OuterVisibleModules;
1712 };
1713 /// The modules we're currently parsing.
1714 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1715
1716 /// Namespace definitions that we will export when they finish.
1717 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1718
1719 /// Get the module whose scope we are currently within.
1720 Module *getCurrentModule() const {
1721 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1722 }
1723
1724 VisibleModuleSet VisibleModules;
1725
1726public:
1727 /// Get the module owning an entity.
1728 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1729
1730 /// Make a merged definition of an existing hidden definition \p ND
1731 /// visible at the specified location.
1732 void makeMergedDefinitionVisible(NamedDecl *ND);
1733
1734 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1735
1736 /// Determine whether a declaration is visible to name lookup.
1737 bool isVisible(const NamedDecl *D) {
1738 return !D->isHidden() || isVisibleSlow(D);
1739 }
1740
1741 /// Determine whether any declaration of an entity is visible.
1742 bool
1743 hasVisibleDeclaration(const NamedDecl *D,
1744 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1745 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1746 }
1747 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1748 llvm::SmallVectorImpl<Module *> *Modules);
1749
1750 bool hasVisibleMergedDefinition(NamedDecl *Def);
1751 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1752
1753 /// Determine if \p D and \p Suggested have a structurally compatible
1754 /// layout as described in C11 6.2.7/1.
1755 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1756
1757 /// Determine if \p D has a visible definition. If not, suggest a declaration
1758 /// that should be made visible to expose the definition.
1759 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1760 bool OnlyNeedComplete = false);
1761 bool hasVisibleDefinition(const NamedDecl *D) {
1762 NamedDecl *Hidden;
1763 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1764 }
1765
1766 /// Determine if the template parameter \p D has a visible default argument.
1767 bool
1768 hasVisibleDefaultArgument(const NamedDecl *D,
1769 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1770
1771 /// Determine if there is a visible declaration of \p D that is an explicit
1772 /// specialization declaration for a specialization of a template. (For a
1773 /// member specialization, use hasVisibleMemberSpecialization.)
1774 bool hasVisibleExplicitSpecialization(
1775 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1776
1777 /// Determine if there is a visible declaration of \p D that is a member
1778 /// specialization declaration (as opposed to an instantiated declaration).
1779 bool hasVisibleMemberSpecialization(
1780 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1781
1782 /// Determine if \p A and \p B are equivalent internal linkage declarations
1783 /// from different modules, and thus an ambiguity error can be downgraded to
1784 /// an extension warning.
1785 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1786 const NamedDecl *B);
1787 void diagnoseEquivalentInternalLinkageDeclarations(
1788 SourceLocation Loc, const NamedDecl *D,
1789 ArrayRef<const NamedDecl *> Equiv);
1790
1791 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1792
1793 bool isCompleteType(SourceLocation Loc, QualType T) {
1794 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1795 }
1796 bool RequireCompleteType(SourceLocation Loc, QualType T,
1797 TypeDiagnoser &Diagnoser);
1798 bool RequireCompleteType(SourceLocation Loc, QualType T,
1799 unsigned DiagID);
1800
1801 template <typename... Ts>
1802 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1803 const Ts &...Args) {
1804 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1805 return RequireCompleteType(Loc, T, Diagnoser);
1806 }
1807
1808 void completeExprArrayBound(Expr *E);
1809 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1810 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1811
1812 template <typename... Ts>
1813 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1814 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1815 return RequireCompleteExprType(E, Diagnoser);
1816 }
1817
1818 bool RequireLiteralType(SourceLocation Loc, QualType T,
1819 TypeDiagnoser &Diagnoser);
1820 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1821
1822 template <typename... Ts>
1823 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1824 const Ts &...Args) {
1825 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1826 return RequireLiteralType(Loc, T, Diagnoser);
1827 }
1828
1829 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1830 const CXXScopeSpec &SS, QualType T,
1831 TagDecl *OwnedTagDecl = nullptr);
1832
1833 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1834 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1835 /// context, such as when building a type for decltype(auto).
1836 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1837 bool AsUnevaluated = true);
1838 QualType BuildUnaryTransformType(QualType BaseType,
1839 UnaryTransformType::UTTKind UKind,
1840 SourceLocation Loc);
1841
1842 //===--------------------------------------------------------------------===//
1843 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1844 //
1845
1846 struct SkipBodyInfo {
1847 SkipBodyInfo()
1848 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1849 New(nullptr) {}
1850 bool ShouldSkip;
1851 bool CheckSameAsPrevious;
1852 NamedDecl *Previous;
1853 NamedDecl *New;
1854 };
1855
1856 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1857
1858 void DiagnoseUseOfUnimplementedSelectors();
1859
1860 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1861
1862 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1863 Scope *S, CXXScopeSpec *SS = nullptr,
1864 bool isClassName = false, bool HasTrailingDot = false,
1865 ParsedType ObjectType = nullptr,
1866 bool IsCtorOrDtorName = false,
1867 bool WantNontrivialTypeSourceInfo = false,
1868 bool IsClassTemplateDeductionContext = true,
1869 IdentifierInfo **CorrectedII = nullptr);
1870 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1871 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1872 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1873 SourceLocation IILoc,
1874 Scope *S,
1875 CXXScopeSpec *SS,
1876 ParsedType &SuggestedType,
1877 bool IsTemplateName = false);
1878
1879 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1880 /// type name has failed in a dependent context. In these situations, we
1881 /// automatically form a DependentTypeName that will retry lookup in a related
1882 /// scope during instantiation.
1883 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1884 SourceLocation NameLoc,
1885 bool IsTemplateTypeArg);
1886
1887 /// Describes the result of the name lookup and resolution performed
1888 /// by \c ClassifyName().
1889 enum NameClassificationKind {
1890 /// This name is not a type or template in this context, but might be
1891 /// something else.
1892 NC_Unknown,
1893 /// Classification failed; an error has been produced.
1894 NC_Error,
1895 /// The name has been typo-corrected to a keyword.
1896 NC_Keyword,
1897 /// The name was classified as a type.
1898 NC_Type,
1899 /// The name was classified as a specific non-type, non-template
1900 /// declaration. ActOnNameClassifiedAsNonType should be called to
1901 /// convert the declaration to an expression.
1902 NC_NonType,
1903 /// The name was classified as an ADL-only function name.
1904 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1905 /// result to an expression.
1906 NC_UndeclaredNonType,
1907 /// The name denotes a member of a dependent type that could not be
1908 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1909 /// convert the result to an expression.
1910 NC_DependentNonType,
1911 /// The name was classified as a non-type, and an expression representing
1912 /// that name has been formed.
1913 NC_ContextIndependentExpr,
1914 /// The name was classified as a template whose specializations are types.
1915 NC_TypeTemplate,
1916 /// The name was classified as a variable template name.
1917 NC_VarTemplate,
1918 /// The name was classified as a function template name.
1919 NC_FunctionTemplate,
1920 /// The name was classified as an ADL-only function template name.
1921 NC_UndeclaredTemplate,
1922 };
1923
1924 class NameClassification {
1925 NameClassificationKind Kind;
1926 union {
1927 ExprResult Expr;
1928 NamedDecl *NonTypeDecl;
1929 TemplateName Template;
1930 ParsedType Type;
1931 };
1932
1933 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1934
1935 public:
1936 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1937
1938 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1939
1940 static NameClassification Error() {
1941 return NameClassification(NC_Error);
1942 }
1943
1944 static NameClassification Unknown() {
1945 return NameClassification(NC_Unknown);
1946 }
1947
1948 static NameClassification ContextIndependentExpr(ExprResult E) {
1949 NameClassification Result(NC_ContextIndependentExpr);
1950 Result.Expr = E;
1951 return Result;
1952 }
1953
1954 static NameClassification NonType(NamedDecl *D) {
1955 NameClassification Result(NC_NonType);
1956 Result.NonTypeDecl = D;
1957 return Result;
1958 }
1959
1960 static NameClassification UndeclaredNonType() {
1961 return NameClassification(NC_UndeclaredNonType);
1962 }
1963
1964 static NameClassification DependentNonType() {
1965 return NameClassification(NC_DependentNonType);
1966 }
1967
1968 static NameClassification TypeTemplate(TemplateName Name) {
1969 NameClassification Result(NC_TypeTemplate);
1970 Result.Template = Name;
1971 return Result;
1972 }
1973
1974 static NameClassification VarTemplate(TemplateName Name) {
1975 NameClassification Result(NC_VarTemplate);
1976 Result.Template = Name;
1977 return Result;
1978 }
1979
1980 static NameClassification FunctionTemplate(TemplateName Name) {
1981 NameClassification Result(NC_FunctionTemplate);
1982 Result.Template = Name;
1983 return Result;
1984 }
1985
1986 static NameClassification UndeclaredTemplate(TemplateName Name) {
1987 NameClassification Result(NC_UndeclaredTemplate);
1988 Result.Template = Name;
1989 return Result;
1990 }
1991
1992 NameClassificationKind getKind() const { return Kind; }
1993
1994 ExprResult getExpression() const {
1995 assert(Kind == NC_ContextIndependentExpr)((Kind == NC_ContextIndependentExpr) ? static_cast<void>
(0) : __assert_fail ("Kind == NC_ContextIndependentExpr", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 1995, __PRETTY_FUNCTION__))
;
1996 return Expr;
1997 }
1998
1999 ParsedType getType() const {
2000 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 2000, __PRETTY_FUNCTION__))
;
2001 return Type;
2002 }
2003
2004 NamedDecl *getNonTypeDecl() const {
2005 assert(Kind == NC_NonType)((Kind == NC_NonType) ? static_cast<void> (0) : __assert_fail
("Kind == NC_NonType", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 2005, __PRETTY_FUNCTION__))
;
2006 return NonTypeDecl;
2007 }
2008
2009 TemplateName getTemplateName() const {
2010 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 2011, __PRETTY_FUNCTION__))
2011 Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 2011, __PRETTY_FUNCTION__))
;
2012 return Template;
2013 }
2014
2015 TemplateNameKind getTemplateNameKind() const {
2016 switch (Kind) {
2017 case NC_TypeTemplate:
2018 return TNK_Type_template;
2019 case NC_FunctionTemplate:
2020 return TNK_Function_template;
2021 case NC_VarTemplate:
2022 return TNK_Var_template;
2023 case NC_UndeclaredTemplate:
2024 return TNK_Undeclared_template;
2025 default:
2026 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 2026)
;
2027 }
2028 }
2029 };
2030
2031 /// Perform name lookup on the given name, classifying it based on
2032 /// the results of name lookup and the following token.
2033 ///
2034 /// This routine is used by the parser to resolve identifiers and help direct
2035 /// parsing. When the identifier cannot be found, this routine will attempt
2036 /// to correct the typo and classify based on the resulting name.
2037 ///
2038 /// \param S The scope in which we're performing name lookup.
2039 ///
2040 /// \param SS The nested-name-specifier that precedes the name.
2041 ///
2042 /// \param Name The identifier. If typo correction finds an alternative name,
2043 /// this pointer parameter will be updated accordingly.
2044 ///
2045 /// \param NameLoc The location of the identifier.
2046 ///
2047 /// \param NextToken The token following the identifier. Used to help
2048 /// disambiguate the name.
2049 ///
2050 /// \param CCC The correction callback, if typo correction is desired.
2051 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2052 IdentifierInfo *&Name, SourceLocation NameLoc,
2053 const Token &NextToken,
2054 CorrectionCandidateCallback *CCC = nullptr);
2055
2056 /// Act on the result of classifying a name as an undeclared (ADL-only)
2057 /// non-type declaration.
2058 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2059 SourceLocation NameLoc);
2060 /// Act on the result of classifying a name as an undeclared member of a
2061 /// dependent base class.
2062 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2063 IdentifierInfo *Name,
2064 SourceLocation NameLoc,
2065 bool IsAddressOfOperand);
2066 /// Act on the result of classifying a name as a specific non-type
2067 /// declaration.
2068 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2069 NamedDecl *Found,
2070 SourceLocation NameLoc,
2071 const Token &NextToken);
2072
2073 /// Describes the detailed kind of a template name. Used in diagnostics.
2074 enum class TemplateNameKindForDiagnostics {
2075 ClassTemplate,
2076 FunctionTemplate,
2077 VarTemplate,
2078 AliasTemplate,
2079 TemplateTemplateParam,
2080 Concept,
2081 DependentTemplate
2082 };
2083 TemplateNameKindForDiagnostics
2084 getTemplateNameKindForDiagnostics(TemplateName Name);
2085
2086 /// Determine whether it's plausible that E was intended to be a
2087 /// template-name.
2088 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2089 if (!getLangOpts().CPlusPlus || E.isInvalid())
2090 return false;
2091 Dependent = false;
2092 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2093 return !DRE->hasExplicitTemplateArgs();
2094 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2095 return !ME->hasExplicitTemplateArgs();
2096 Dependent = true;
2097 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2098 return !DSDRE->hasExplicitTemplateArgs();
2099 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2100 return !DSME->hasExplicitTemplateArgs();
2101 // Any additional cases recognized here should also be handled by
2102 // diagnoseExprIntendedAsTemplateName.
2103 return false;
2104 }
2105 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2106 SourceLocation Less,
2107 SourceLocation Greater);
2108
2109 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2110
2111 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2112 MultiTemplateParamsArg TemplateParameterLists);
2113 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2114 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2115 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2116 DeclarationName Name, SourceLocation Loc,
2117 bool IsTemplateId);
2118 void
2119 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2120 SourceLocation FallbackLoc,
2121 SourceLocation ConstQualLoc = SourceLocation(),
2122 SourceLocation VolatileQualLoc = SourceLocation(),
2123 SourceLocation RestrictQualLoc = SourceLocation(),
2124 SourceLocation AtomicQualLoc = SourceLocation(),
2125 SourceLocation UnalignedQualLoc = SourceLocation());
2126
2127 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2128 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2129 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2130 const LookupResult &R);
2131 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2132 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2133 const LookupResult &R);
2134 void CheckShadow(Scope *S, VarDecl *D);
2135
2136 /// Warn if 'E', which is an expression that is about to be modified, refers
2137 /// to a shadowing declaration.
2138 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2139
2140 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2141
2142private:
2143 /// Map of current shadowing declarations to shadowed declarations. Warn if
2144 /// it looks like the user is trying to modify the shadowing declaration.
2145 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2146
2147public:
2148 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2149 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2150 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2151 TypedefNameDecl *NewTD);
2152 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2153 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2154 TypeSourceInfo *TInfo,
2155 LookupResult &Previous);
2156 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2157 LookupResult &Previous, bool &Redeclaration);
2158 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2159 TypeSourceInfo *TInfo,
2160 LookupResult &Previous,
2161 MultiTemplateParamsArg TemplateParamLists,
2162 bool &AddToScope,
2163 ArrayRef<BindingDecl *> Bindings = None);
2164 NamedDecl *
2165 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2166 MultiTemplateParamsArg TemplateParamLists);
2167 // Returns true if the variable declaration is a redeclaration
2168 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2169 void CheckVariableDeclarationType(VarDecl *NewVD);
2170 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2171 Expr *Init);
2172 void CheckCompleteVariableDeclaration(VarDecl *VD);
2173 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2174 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2175
2176 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2177 TypeSourceInfo *TInfo,
2178 LookupResult &Previous,
2179 MultiTemplateParamsArg TemplateParamLists,
2180 bool &AddToScope);
2181 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2182
2183 enum class CheckConstexprKind {
2184 /// Diagnose issues that are non-constant or that are extensions.
2185 Diagnose,
2186 /// Identify whether this function satisfies the formal rules for constexpr
2187 /// functions in the current lanugage mode (with no extensions).
2188 CheckValid
2189 };
2190
2191 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2192 CheckConstexprKind Kind);
2193
2194 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2195 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2196 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2197 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2198 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2199 // Returns true if the function declaration is a redeclaration
2200 bool CheckFunctionDeclaration(Scope *S,
2201 FunctionDecl *NewFD, LookupResult &Previous,
2202 bool IsMemberSpecialization);
2203 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2204 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2205 QualType NewT, QualType OldT);
2206 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2207 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2208 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2209 bool IsDefinition);
2210 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2211 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2212 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2213 SourceLocation Loc,
2214 QualType T);
2215 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2216 SourceLocation NameLoc, IdentifierInfo *Name,
2217 QualType T, TypeSourceInfo *TSInfo,
2218 StorageClass SC);
2219 void ActOnParamDefaultArgument(Decl *param,
2220 SourceLocation EqualLoc,
2221 Expr *defarg);
2222 void ActOnParamUnparsedDefaultArgument(Decl *param,
2223 SourceLocation EqualLoc,
2224 SourceLocation ArgLoc);
2225 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2226 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2227 SourceLocation EqualLoc);
2228
2229 // Contexts where using non-trivial C union types can be disallowed. This is
2230 // passed to err_non_trivial_c_union_in_invalid_context.
2231 enum NonTrivialCUnionContext {
2232 // Function parameter.
2233 NTCUC_FunctionParam,
2234 // Function return.
2235 NTCUC_FunctionReturn,
2236 // Default-initialized object.
2237 NTCUC_DefaultInitializedObject,
2238 // Variable with automatic storage duration.
2239 NTCUC_AutoVar,
2240 // Initializer expression that might copy from another object.
2241 NTCUC_CopyInit,
2242 // Assignment.
2243 NTCUC_Assignment,
2244 // Compound literal.
2245 NTCUC_CompoundLiteral,
2246 // Block capture.
2247 NTCUC_BlockCapture,
2248 // lvalue-to-rvalue conversion of volatile type.
2249 NTCUC_LValueToRValueVolatile,
2250 };
2251
2252 /// Emit diagnostics if the initializer or any of its explicit or
2253 /// implicitly-generated subexpressions require copying or
2254 /// default-initializing a type that is or contains a C union type that is
2255 /// non-trivial to copy or default-initialize.
2256 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2257
2258 // These flags are passed to checkNonTrivialCUnion.
2259 enum NonTrivialCUnionKind {
2260 NTCUK_Init = 0x1,
2261 NTCUK_Destruct = 0x2,
2262 NTCUK_Copy = 0x4,
2263 };
2264
2265 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2266 /// a non-trivial C union is used in an invalid context.
2267 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2268 NonTrivialCUnionContext UseContext,
2269 unsigned NonTrivialKind);
2270
2271 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2272 void ActOnUninitializedDecl(Decl *dcl);
2273 void ActOnInitializerError(Decl *Dcl);
2274
2275 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2276 void ActOnCXXForRangeDecl(Decl *D);
2277 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2278 IdentifierInfo *Ident,
2279 ParsedAttributes &Attrs,
2280 SourceLocation AttrEnd);
2281 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2282 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2283 void CheckStaticLocalForDllExport(VarDecl *VD);
2284 void FinalizeDeclaration(Decl *D);
2285 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2286 ArrayRef<Decl *> Group);
2287 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2288
2289 /// Should be called on all declarations that might have attached
2290 /// documentation comments.
2291 void ActOnDocumentableDecl(Decl *D);
2292 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2293
2294 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2295 SourceLocation LocAfterDecls);
2296 void CheckForFunctionRedefinition(
2297 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2298 SkipBodyInfo *SkipBody = nullptr);
2299 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2300 MultiTemplateParamsArg TemplateParamLists,
2301 SkipBodyInfo *SkipBody = nullptr);
2302 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2303 SkipBodyInfo *SkipBody = nullptr);
2304 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2305 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2306 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2307 bool isObjCMethodDecl(Decl *D) {
2308 return D && isa<ObjCMethodDecl>(D);
2309 }
2310
2311 /// Determine whether we can delay parsing the body of a function or
2312 /// function template until it is used, assuming we don't care about emitting
2313 /// code for that function.
2314 ///
2315 /// This will be \c false if we may need the body of the function in the
2316 /// middle of parsing an expression (where it's impractical to switch to
2317 /// parsing a different function), for instance, if it's constexpr in C++11
2318 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2319 bool canDelayFunctionBody(const Declarator &D);
2320
2321 /// Determine whether we can skip parsing the body of a function
2322 /// definition, assuming we don't care about analyzing its body or emitting
2323 /// code for that function.
2324 ///
2325 /// This will be \c false only if we may need the body of the function in
2326 /// order to parse the rest of the program (for instance, if it is
2327 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2328 bool canSkipFunctionBody(Decl *D);
2329
2330 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2331 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2332 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2333 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2334 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2335
2336 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2337 /// attribute for which parsing is delayed.
2338 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2339
2340 /// Diagnose any unused parameters in the given sequence of
2341 /// ParmVarDecl pointers.
2342 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2343
2344 /// Diagnose whether the size of parameters or return value of a
2345 /// function or obj-c method definition is pass-by-value and larger than a
2346 /// specified threshold.
2347 void
2348 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2349 QualType ReturnTy, NamedDecl *D);
2350
2351 void DiagnoseInvalidJumps(Stmt *Body);
2352 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2353 SourceLocation AsmLoc,
2354 SourceLocation RParenLoc);
2355
2356 /// Handle a C++11 empty-declaration and attribute-declaration.
2357 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2358 SourceLocation SemiLoc);
2359
2360 enum class ModuleDeclKind {
2361 Interface, ///< 'export module X;'
2362 Implementation, ///< 'module X;'
2363 };
2364
2365 /// The parser has processed a module-declaration that begins the definition
2366 /// of a module interface or implementation.
2367 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2368 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2369 ModuleIdPath Path, bool IsFirstDecl);
2370
2371 /// The parser has processed a global-module-fragment declaration that begins
2372 /// the definition of the global module fragment of the current module unit.
2373 /// \param ModuleLoc The location of the 'module' keyword.
2374 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2375
2376 /// The parser has processed a private-module-fragment declaration that begins
2377 /// the definition of the private module fragment of the current module unit.
2378 /// \param ModuleLoc The location of the 'module' keyword.
2379 /// \param PrivateLoc The location of the 'private' keyword.
2380 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2381 SourceLocation PrivateLoc);
2382
2383 /// The parser has processed a module import declaration.
2384 ///
2385 /// \param StartLoc The location of the first token in the declaration. This
2386 /// could be the location of an '@', 'export', or 'import'.
2387 /// \param ExportLoc The location of the 'export' keyword, if any.
2388 /// \param ImportLoc The location of the 'import' keyword.
2389 /// \param Path The module access path.
2390 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2391 SourceLocation ExportLoc,
2392 SourceLocation ImportLoc, ModuleIdPath Path);
2393 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2394 SourceLocation ExportLoc,
2395 SourceLocation ImportLoc, Module *M,
2396 ModuleIdPath Path = {});
2397
2398 /// The parser has processed a module import translated from a
2399 /// #include or similar preprocessing directive.
2400 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2401 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2402
2403 /// The parsed has entered a submodule.
2404 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2405 /// The parser has left a submodule.
2406 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2407
2408 /// Create an implicit import of the given module at the given
2409 /// source location, for error recovery, if possible.
2410 ///
2411 /// This routine is typically used when an entity found by name lookup
2412 /// is actually hidden within a module that we know about but the user
2413 /// has forgotten to import.
2414 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2415 Module *Mod);
2416
2417 /// Kinds of missing import. Note, the values of these enumerators correspond
2418 /// to %select values in diagnostics.
2419 enum class MissingImportKind {
2420 Declaration,
2421 Definition,
2422 DefaultArgument,
2423 ExplicitSpecialization,
2424 PartialSpecialization
2425 };
2426
2427 /// Diagnose that the specified declaration needs to be visible but
2428 /// isn't, and suggest a module import that would resolve the problem.
2429 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2430 MissingImportKind MIK, bool Recover = true);
2431 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2432 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2433 MissingImportKind MIK, bool Recover);
2434
2435 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2436 SourceLocation LBraceLoc);
2437 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2438 SourceLocation RBraceLoc);
2439
2440 /// We've found a use of a templated declaration that would trigger an
2441 /// implicit instantiation. Check that any relevant explicit specializations
2442 /// and partial specializations are visible, and diagnose if not.
2443 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2444
2445 /// We've found a use of a template specialization that would select a
2446 /// partial specialization. Check that the partial specialization is visible,
2447 /// and diagnose if not.
2448 void checkPartialSpecializationVisibility(SourceLocation Loc,
2449 NamedDecl *Spec);
2450
2451 /// Retrieve a suitable printing policy for diagnostics.
2452 PrintingPolicy getPrintingPolicy() const {
2453 return getPrintingPolicy(Context, PP);
2454 }
2455
2456 /// Retrieve a suitable printing policy for diagnostics.
2457 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2458 const Preprocessor &PP);
2459
2460 /// Scope actions.
2461 void ActOnPopScope(SourceLocation Loc, Scope *S);
2462 void ActOnTranslationUnitScope(Scope *S);
2463
2464 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2465 RecordDecl *&AnonRecord);
2466 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2467 MultiTemplateParamsArg TemplateParams,
2468 bool IsExplicitInstantiation,
2469 RecordDecl *&AnonRecord);
2470
2471 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2472 AccessSpecifier AS,
2473 RecordDecl *Record,
2474 const PrintingPolicy &Policy);
2475
2476 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2477 RecordDecl *Record);
2478
2479 /// Common ways to introduce type names without a tag for use in diagnostics.
2480 /// Keep in sync with err_tag_reference_non_tag.
2481 enum NonTagKind {
2482 NTK_NonStruct,
2483 NTK_NonClass,
2484 NTK_NonUnion,
2485 NTK_NonEnum,
2486 NTK_Typedef,
2487 NTK_TypeAlias,
2488 NTK_Template,
2489 NTK_TypeAliasTemplate,
2490 NTK_TemplateTemplateArgument,
2491 };
2492
2493 /// Given a non-tag type declaration, returns an enum useful for indicating
2494 /// what kind of non-tag type this is.
2495 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2496
2497 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2498 TagTypeKind NewTag, bool isDefinition,
2499 SourceLocation NewTagLoc,
2500 const IdentifierInfo *Name);
2501
2502 enum TagUseKind {
2503 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2504 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2505 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2506 TUK_Friend // Friend declaration: 'friend struct foo;'
2507 };
2508
2509 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2510 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2511 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2512 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2513 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2514 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2515 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2516 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2517 SkipBodyInfo *SkipBody = nullptr);
2518
2519 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2520 unsigned TagSpec, SourceLocation TagLoc,
2521 CXXScopeSpec &SS, IdentifierInfo *Name,
2522 SourceLocation NameLoc,
2523 const ParsedAttributesView &Attr,
2524 MultiTemplateParamsArg TempParamLists);
2525
2526 TypeResult ActOnDependentTag(Scope *S,
2527 unsigned TagSpec,
2528 TagUseKind TUK,
2529 const CXXScopeSpec &SS,
2530 IdentifierInfo *Name,
2531 SourceLocation TagLoc,
2532 SourceLocation NameLoc);
2533
2534 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2535 IdentifierInfo *ClassName,
2536 SmallVectorImpl<Decl *> &Decls);
2537 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2538 Declarator &D, Expr *BitfieldWidth);
2539
2540 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2541 Declarator &D, Expr *BitfieldWidth,
2542