Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-11-124948-33004-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

/build/llvm-toolchain-snapshot-14~++20220111111457+2c5c5ca8681a/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/ASTFwd.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Availability.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LocInfoType.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/PrettyPrinter.h"
34#include "clang/AST/StmtCXX.h"
35#include "clang/AST/StmtOpenMP.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/TypeOrdering.h"
38#include "clang/Basic/BitmaskEnum.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/DarwinSDKInfo.h"
41#include "clang/Basic/ExpressionTraits.h"
42#include "clang/Basic/Module.h"
43#include "clang/Basic/OpenCLOptions.h"
44#include "clang/Basic/OpenMPKinds.h"
45#include "clang/Basic/PragmaKinds.h"
46#include "clang/Basic/Specifiers.h"
47#include "clang/Basic/TemplateKinds.h"
48#include "clang/Basic/TypeTraits.h"
49#include "clang/Sema/AnalysisBasedWarnings.h"
50#include "clang/Sema/CleanupInfo.h"
51#include "clang/Sema/DeclSpec.h"
52#include "clang/Sema/ExternalSemaSource.h"
53#include "clang/Sema/IdentifierResolver.h"
54#include "clang/Sema/ObjCMethodList.h"
55#include "clang/Sema/Ownership.h"
56#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaConcept.h"
58#include "clang/Sema/TypoCorrection.h"
59#include "clang/Sema/Weak.h"
60#include "llvm/ADT/ArrayRef.h"
61#include "llvm/ADT/Optional.h"
62#include "llvm/ADT/SetVector.h"
63#include "llvm/ADT/SmallBitVector.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/SmallSet.h"
66#include "llvm/ADT/SmallVector.h"
67#include "llvm/ADT/TinyPtrVector.h"
68#include "llvm/Frontend/OpenMP/OMPConstants.h"
69#include <deque>
70#include <memory>
71#include <string>
72#include <tuple>
73#include <vector>
74
75namespace llvm {
76 class APSInt;
77 template <typename ValueT, typename ValueInfoT> class DenseSet;
78 class SmallBitVector;
79 struct InlineAsmIdentifierInfo;
80}
81
82namespace clang {
83 class ADLResult;
84 class ASTConsumer;
85 class ASTContext;
86 class ASTMutationListener;
87 class ASTReader;
88 class ASTWriter;
89 class ArrayType;
90 class ParsedAttr;
91 class BindingDecl;
92 class BlockDecl;
93 class CapturedDecl;
94 class CXXBasePath;
95 class CXXBasePaths;
96 class CXXBindTemporaryExpr;
97 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
98 class CXXConstructorDecl;
99 class CXXConversionDecl;
100 class CXXDeleteExpr;
101 class CXXDestructorDecl;
102 class CXXFieldCollector;
103 class CXXMemberCallExpr;
104 class CXXMethodDecl;
105 class CXXScopeSpec;
106 class CXXTemporary;
107 class CXXTryStmt;
108 class CallExpr;
109 class ClassTemplateDecl;
110 class ClassTemplatePartialSpecializationDecl;
111 class ClassTemplateSpecializationDecl;
112 class VarTemplatePartialSpecializationDecl;
113 class CodeCompleteConsumer;
114 class CodeCompletionAllocator;
115 class CodeCompletionTUInfo;
116 class CodeCompletionResult;
117 class CoroutineBodyStmt;
118 class Decl;
119 class DeclAccessPair;
120 class DeclContext;
121 class DeclRefExpr;
122 class DeclaratorDecl;
123 class DeducedTemplateArgument;
124 class DependentDiagnostic;
125 class DesignatedInitExpr;
126 class Designation;
127 class EnableIfAttr;
128 class EnumConstantDecl;
129 class Expr;
130 class ExtVectorType;
131 class FormatAttr;
132 class FriendDecl;
133 class FunctionDecl;
134 class FunctionProtoType;
135 class FunctionTemplateDecl;
136 class ImplicitConversionSequence;
137 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138 class InitListExpr;
139 class InitializationKind;
140 class InitializationSequence;
141 class InitializedEntity;
142 class IntegerLiteral;
143 class LabelStmt;
144 class LambdaExpr;
145 class LangOptions;
146 class LocalInstantiationScope;
147 class LookupResult;
148 class MacroInfo;
149 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
150 class ModuleLoader;
151 class MultiLevelTemplateArgumentList;
152 class NamedDecl;
153 class ObjCCategoryDecl;
154 class ObjCCategoryImplDecl;
155 class ObjCCompatibleAliasDecl;
156 class ObjCContainerDecl;
157 class ObjCImplDecl;
158 class ObjCImplementationDecl;
159 class ObjCInterfaceDecl;
160 class ObjCIvarDecl;
161 template <class T> class ObjCList;
162 class ObjCMessageExpr;
163 class ObjCMethodDecl;
164 class ObjCPropertyDecl;
165 class ObjCProtocolDecl;
166 class OMPThreadPrivateDecl;
167 class OMPRequiresDecl;
168 class OMPDeclareReductionDecl;
169 class OMPDeclareSimdDecl;
170 class OMPClause;
171 struct OMPVarListLocTy;
172 struct OverloadCandidate;
173 enum class OverloadCandidateParamOrder : char;
174 enum OverloadCandidateRewriteKind : unsigned;
175 class OverloadCandidateSet;
176 class OverloadExpr;
177 class ParenListExpr;
178 class ParmVarDecl;
179 class Preprocessor;
180 class PseudoDestructorTypeStorage;
181 class PseudoObjectExpr;
182 class QualType;
183 class StandardConversionSequence;
184 class Stmt;
185 class StringLiteral;
186 class SwitchStmt;
187 class TemplateArgument;
188 class TemplateArgumentList;
189 class TemplateArgumentLoc;
190 class TemplateDecl;
191 class TemplateInstantiationCallback;
192 class TemplateParameterList;
193 class TemplatePartialOrderingContext;
194 class TemplateTemplateParmDecl;
195 class Token;
196 class TypeAliasDecl;
197 class TypedefDecl;
198 class TypedefNameDecl;
199 class TypeLoc;
200 class TypoCorrectionConsumer;
201 class UnqualifiedId;
202 class UnresolvedLookupExpr;
203 class UnresolvedMemberExpr;
204 class UnresolvedSetImpl;
205 class UnresolvedSetIterator;
206 class UsingDecl;
207 class UsingShadowDecl;
208 class ValueDecl;
209 class VarDecl;
210 class VarTemplateSpecializationDecl;
211 class VisibilityAttr;
212 class VisibleDeclConsumer;
213 class IndirectFieldDecl;
214 struct DeductionFailureInfo;
215 class TemplateSpecCandidateSet;
216
217namespace sema {
218 class AccessedEntity;
219 class BlockScopeInfo;
220 class Capture;
221 class CapturedRegionScopeInfo;
222 class CapturingScopeInfo;
223 class CompoundScopeInfo;
224 class DelayedDiagnostic;
225 class DelayedDiagnosticPool;
226 class FunctionScopeInfo;
227 class LambdaScopeInfo;
228 class PossiblyUnreachableDiag;
229 class SemaPPCallbacks;
230 class TemplateDeductionInfo;
231}
232
233namespace threadSafety {
234 class BeforeSet;
235 void threadSafetyCleanup(BeforeSet* Cache);
236}
237
238// FIXME: No way to easily map from TemplateTypeParmTypes to
239// TemplateTypeParmDecls, so we have this horrible PointerUnion.
240typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
241 SourceLocation> UnexpandedParameterPack;
242
243/// Describes whether we've seen any nullability information for the given
244/// file.
245struct FileNullability {
246 /// The first pointer declarator (of any pointer kind) in the file that does
247 /// not have a corresponding nullability annotation.
248 SourceLocation PointerLoc;
249
250 /// The end location for the first pointer declarator in the file. Used for
251 /// placing fix-its.
252 SourceLocation PointerEndLoc;
253
254 /// Which kind of pointer declarator we saw.
255 uint8_t PointerKind;
256
257 /// Whether we saw any type nullability annotations in the given file.
258 bool SawTypeNullability = false;
259};
260
261/// A mapping from file IDs to a record of whether we've seen nullability
262/// information in that file.
263class FileNullabilityMap {
264 /// A mapping from file IDs to the nullability information for each file ID.
265 llvm::DenseMap<FileID, FileNullability> Map;
266
267 /// A single-element cache based on the file ID.
268 struct {
269 FileID File;
270 FileNullability Nullability;
271 } Cache;
272
273public:
274 FileNullability &operator[](FileID file) {
275 // Check the single-element cache.
276 if (file == Cache.File)
277 return Cache.Nullability;
278
279 // It's not in the single-element cache; flush the cache if we have one.
280 if (!Cache.File.isInvalid()) {
281 Map[Cache.File] = Cache.Nullability;
282 }
283
284 // Pull this entry into the cache.
285 Cache.File = file;
286 Cache.Nullability = Map[file];
287 return Cache.Nullability;
288 }
289};
290
291/// Tracks expected type during expression parsing, for use in code completion.
292/// The type is tied to a particular token, all functions that update or consume
293/// the type take a start location of the token they are looking at as a
294/// parameter. This avoids updating the type on hot paths in the parser.
295class PreferredTypeBuilder {
296public:
297 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
298
299 void enterCondition(Sema &S, SourceLocation Tok);
300 void enterReturn(Sema &S, SourceLocation Tok);
301 void enterVariableInit(SourceLocation Tok, Decl *D);
302 /// Handles e.g. BaseType{ .D = Tok...
303 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
304 const Designation &D);
305 /// Computing a type for the function argument may require running
306 /// overloading, so we postpone its computation until it is actually needed.
307 ///
308 /// Clients should be very careful when using this funciton, as it stores a
309 /// function_ref, clients should make sure all calls to get() with the same
310 /// location happen while function_ref is alive.
311 ///
312 /// The callback should also emit signature help as a side-effect, but only
313 /// if the completion point has been reached.
314 void enterFunctionArgument(SourceLocation Tok,
315 llvm::function_ref<QualType()> ComputeType);
316
317 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
318 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
319 SourceLocation OpLoc);
320 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
321 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
322 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
323 /// Handles all type casts, including C-style cast, C++ casts, etc.
324 void enterTypeCast(SourceLocation Tok, QualType CastType);
325
326 /// Get the expected type associated with this location, if any.
327 ///
328 /// If the location is a function argument, determining the expected type
329 /// involves considering all function overloads and the arguments so far.
330 /// In this case, signature help for these function overloads will be reported
331 /// as a side-effect (only if the completion point has been reached).
332 QualType get(SourceLocation Tok) const {
333 if (!Enabled || Tok != ExpectedLoc)
334 return QualType();
335 if (!Type.isNull())
336 return Type;
337 if (ComputeType)
338 return ComputeType();
339 return QualType();
340 }
341
342private:
343 bool Enabled;
344 /// Start position of a token for which we store expected type.
345 SourceLocation ExpectedLoc;
346 /// Expected type for a token starting at ExpectedLoc.
347 QualType Type;
348 /// A function to compute expected type at ExpectedLoc. It is only considered
349 /// if Type is null.
350 llvm::function_ref<QualType()> ComputeType;
351};
352
353/// Sema - This implements semantic analysis and AST building for C.
354class Sema final {
355 Sema(const Sema &) = delete;
356 void operator=(const Sema &) = delete;
357
358 ///Source of additional semantic information.
359 ExternalSemaSource *ExternalSource;
360
361 ///Whether Sema has generated a multiplexer and has to delete it.
362 bool isMultiplexExternalSource;
363
364 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
365
366 bool isVisibleSlow(const NamedDecl *D);
367
368 /// Determine whether two declarations should be linked together, given that
369 /// the old declaration might not be visible and the new declaration might
370 /// not have external linkage.
371 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
372 const NamedDecl *New) {
373 if (isVisible(Old))
374 return true;
375 // See comment in below overload for why it's safe to compute the linkage
376 // of the new declaration here.
377 if (New->isExternallyDeclarable()) {
378 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 379, __extension__ __PRETTY_FUNCTION__
))
379 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 379, __extension__ __PRETTY_FUNCTION__
))
;
380 return true;
381 }
382 return false;
383 }
384 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
385
386 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
387 QualType ResultTy,
388 ArrayRef<QualType> Args);
389
390public:
391 /// The maximum alignment, same as in llvm::Value. We duplicate them here
392 /// because that allows us not to duplicate the constants in clang code,
393 /// which we must to since we can't directly use the llvm constants.
394 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
395 ///
396 /// This is the greatest alignment value supported by load, store, and alloca
397 /// instructions, and global values.
398 static const unsigned MaxAlignmentExponent = 32;
399 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
400
401 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
402 typedef OpaquePtr<TemplateName> TemplateTy;
403 typedef OpaquePtr<QualType> TypeTy;
404
405 OpenCLOptions OpenCLFeatures;
406 FPOptions CurFPFeatures;
407
408 const LangOptions &LangOpts;
409 Preprocessor &PP;
410 ASTContext &Context;
411 ASTConsumer &Consumer;
412 DiagnosticsEngine &Diags;
413 SourceManager &SourceMgr;
414
415 /// Flag indicating whether or not to collect detailed statistics.
416 bool CollectStats;
417
418 /// Code-completion consumer.
419 CodeCompleteConsumer *CodeCompleter;
420
421 /// CurContext - This is the current declaration context of parsing.
422 DeclContext *CurContext;
423
424 /// Generally null except when we temporarily switch decl contexts,
425 /// like in \see ActOnObjCTemporaryExitContainerContext.
426 DeclContext *OriginalLexicalContext;
427
428 /// VAListTagName - The declaration name corresponding to __va_list_tag.
429 /// This is used as part of a hack to omit that class from ADL results.
430 DeclarationName VAListTagName;
431
432 bool MSStructPragmaOn; // True when \#pragma ms_struct on
433
434 /// Controls member pointer representation format under the MS ABI.
435 LangOptions::PragmaMSPointersToMembersKind
436 MSPointerToMemberRepresentationMethod;
437
438 /// Stack of active SEH __finally scopes. Can be empty.
439 SmallVector<Scope*, 2> CurrentSEHFinally;
440
441 /// Source location for newly created implicit MSInheritanceAttrs
442 SourceLocation ImplicitMSInheritanceAttrLoc;
443
444 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
445 /// `TransformTypos` in order to keep track of any TypoExprs that are created
446 /// recursively during typo correction and wipe them away if the correction
447 /// fails.
448 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
449
450 /// pragma clang section kind
451 enum PragmaClangSectionKind {
452 PCSK_Invalid = 0,
453 PCSK_BSS = 1,
454 PCSK_Data = 2,
455 PCSK_Rodata = 3,
456 PCSK_Text = 4,
457 PCSK_Relro = 5
458 };
459
460 enum PragmaClangSectionAction {
461 PCSA_Set = 0,
462 PCSA_Clear = 1
463 };
464
465 struct PragmaClangSection {
466 std::string SectionName;
467 bool Valid = false;
468 SourceLocation PragmaLocation;
469 };
470
471 PragmaClangSection PragmaClangBSSSection;
472 PragmaClangSection PragmaClangDataSection;
473 PragmaClangSection PragmaClangRodataSection;
474 PragmaClangSection PragmaClangRelroSection;
475 PragmaClangSection PragmaClangTextSection;
476
477 enum PragmaMsStackAction {
478 PSK_Reset = 0x0, // #pragma ()
479 PSK_Set = 0x1, // #pragma (value)
480 PSK_Push = 0x2, // #pragma (push[, id])
481 PSK_Pop = 0x4, // #pragma (pop[, id])
482 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
483 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
484 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
485 };
486
487 // #pragma pack and align.
488 class AlignPackInfo {
489 public:
490 // `Native` represents default align mode, which may vary based on the
491 // platform.
492 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
493
494 // #pragma pack info constructor
495 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
496 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
497 assert(Num == PackNumber && "The pack number has been truncated.")(static_cast <bool> (Num == PackNumber && "The pack number has been truncated."
) ? void (0) : __assert_fail ("Num == PackNumber && \"The pack number has been truncated.\""
, "clang/include/clang/Sema/Sema.h", 497, __extension__ __PRETTY_FUNCTION__
))
;
498 }
499
500 // #pragma align info constructor
501 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
502 : PackAttr(false), AlignMode(M),
503 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
504
505 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
506
507 AlignPackInfo() : AlignPackInfo(Native, false) {}
508
509 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
510 // integer encoding for it. This should only be passed to
511 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
512 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
513 std::uint32_t Encoding{};
514 if (Info.IsXLStack())
515 Encoding |= IsXLMask;
516
517 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
518
519 if (Info.IsPackAttr())
520 Encoding |= PackAttrMask;
521
522 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
523
524 return Encoding;
525 }
526
527 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
528 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
529 AlignPackInfo::Mode M =
530 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
531 int PackNumber = (Encoding & PackNumMask) >> 4;
532
533 if (Encoding & PackAttrMask)
534 return AlignPackInfo(M, PackNumber, IsXL);
535
536 return AlignPackInfo(M, IsXL);
537 }
538
539 bool IsPackAttr() const { return PackAttr; }
540
541 bool IsAlignAttr() const { return !PackAttr; }
542
543 Mode getAlignMode() const { return AlignMode; }
544
545 unsigned getPackNumber() const { return PackNumber; }
546
547 bool IsPackSet() const {
548 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
549 // attriute on a decl.
550 return PackNumber != UninitPackVal && PackNumber != 0;
551 }
552
553 bool IsXLStack() const { return XLStack; }
554
555 bool operator==(const AlignPackInfo &Info) const {
556 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
557 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
558 Info.XLStack);
559 }
560
561 bool operator!=(const AlignPackInfo &Info) const {
562 return !(*this == Info);
563 }
564
565 private:
566 /// \brief True if this is a pragma pack attribute,
567 /// not a pragma align attribute.
568 bool PackAttr;
569
570 /// \brief The alignment mode that is in effect.
571 Mode AlignMode;
572
573 /// \brief The pack number of the stack.
574 unsigned char PackNumber;
575
576 /// \brief True if it is a XL #pragma align/pack stack.
577 bool XLStack;
578
579 /// \brief Uninitialized pack value.
580 static constexpr unsigned char UninitPackVal = -1;
581
582 // Masks to encode and decode an AlignPackInfo.
583 static constexpr uint32_t IsXLMask{0x0000'0001};
584 static constexpr uint32_t AlignModeMask{0x0000'0006};
585 static constexpr uint32_t PackAttrMask{0x00000'0008};
586 static constexpr uint32_t PackNumMask{0x0000'01F0};
587 };
588
589 template<typename ValueType>
590 struct PragmaStack {
591 struct Slot {
592 llvm::StringRef StackSlotLabel;
593 ValueType Value;
594 SourceLocation PragmaLocation;
595 SourceLocation PragmaPushLocation;
596 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
597 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
598 : StackSlotLabel(StackSlotLabel), Value(Value),
599 PragmaLocation(PragmaLocation),
600 PragmaPushLocation(PragmaPushLocation) {}
601 };
602
603 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
604 llvm::StringRef StackSlotLabel, ValueType Value) {
605 if (Action == PSK_Reset) {
606 CurrentValue = DefaultValue;
607 CurrentPragmaLocation = PragmaLocation;
608 return;
609 }
610 if (Action & PSK_Push)
611 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
612 PragmaLocation);
613 else if (Action & PSK_Pop) {
614 if (!StackSlotLabel.empty()) {
615 // If we've got a label, try to find it and jump there.
616 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
617 return x.StackSlotLabel == StackSlotLabel;
618 });
619 // If we found the label so pop from there.
620 if (I != Stack.rend()) {
621 CurrentValue = I->Value;
622 CurrentPragmaLocation = I->PragmaLocation;
623 Stack.erase(std::prev(I.base()), Stack.end());
624 }
625 } else if (!Stack.empty()) {
626 // We do not have a label, just pop the last entry.
627 CurrentValue = Stack.back().Value;
628 CurrentPragmaLocation = Stack.back().PragmaLocation;
629 Stack.pop_back();
630 }
631 }
632 if (Action & PSK_Set) {
633 CurrentValue = Value;
634 CurrentPragmaLocation = PragmaLocation;
635 }
636 }
637
638 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
639 // method body to restore the stacks on exit, so it works like this:
640 //
641 // struct S {
642 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
643 // void Method {}
644 // #pragma <name>(pop, InternalPragmaSlot)
645 // };
646 //
647 // It works even with #pragma vtordisp, although MSVC doesn't support
648 // #pragma vtordisp(push [, id], n)
649 // syntax.
650 //
651 // Push / pop a named sentinel slot.
652 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
653 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 654, __extension__ __PRETTY_FUNCTION__
))
654 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 654, __extension__ __PRETTY_FUNCTION__
))
;
655 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
656 }
657
658 // Constructors.
659 explicit PragmaStack(const ValueType &Default)
660 : DefaultValue(Default), CurrentValue(Default) {}
661
662 bool hasValue() const { return CurrentValue != DefaultValue; }
663
664 SmallVector<Slot, 2> Stack;
665 ValueType DefaultValue; // Value used for PSK_Reset action.
666 ValueType CurrentValue;
667 SourceLocation CurrentPragmaLocation;
668 };
669 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
670 // we shouldn't do so if they're in a module).
671
672 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
673 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
674 ///
675 /// 0: Suppress all vtordisps
676 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
677 /// structors
678 /// 2: Always insert vtordisps to support RTTI on partially constructed
679 /// objects
680 PragmaStack<MSVtorDispMode> VtorDispStack;
681 PragmaStack<AlignPackInfo> AlignPackStack;
682 // The current #pragma align/pack values and locations at each #include.
683 struct AlignPackIncludeState {
684 AlignPackInfo CurrentValue;
685 SourceLocation CurrentPragmaLocation;
686 bool HasNonDefaultValue, ShouldWarnOnInclude;
687 };
688 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
689 // Segment #pragmas.
690 PragmaStack<StringLiteral *> DataSegStack;
691 PragmaStack<StringLiteral *> BSSSegStack;
692 PragmaStack<StringLiteral *> ConstSegStack;
693 PragmaStack<StringLiteral *> CodeSegStack;
694
695 // This stack tracks the current state of Sema.CurFPFeatures.
696 PragmaStack<FPOptionsOverride> FpPragmaStack;
697 FPOptionsOverride CurFPFeatureOverrides() {
698 FPOptionsOverride result;
699 if (!FpPragmaStack.hasValue()) {
700 result = FPOptionsOverride();
701 } else {
702 result = FpPragmaStack.CurrentValue;
703 }
704 return result;
705 }
706
707 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
708 // Actions should be performed only if we enter / exit a C++ method body.
709 class PragmaStackSentinelRAII {
710 public:
711 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
712 ~PragmaStackSentinelRAII();
713
714 private:
715 Sema &S;
716 StringRef SlotLabel;
717 bool ShouldAct;
718 };
719
720 /// A mapping that describes the nullability we've seen in each header file.
721 FileNullabilityMap NullabilityMap;
722
723 /// Last section used with #pragma init_seg.
724 StringLiteral *CurInitSeg;
725 SourceLocation CurInitSegLoc;
726
727 /// VisContext - Manages the stack for \#pragma GCC visibility.
728 void *VisContext; // Really a "PragmaVisStack*"
729
730 /// This an attribute introduced by \#pragma clang attribute.
731 struct PragmaAttributeEntry {
732 SourceLocation Loc;
733 ParsedAttr *Attribute;
734 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
735 bool IsUsed;
736 };
737
738 /// A push'd group of PragmaAttributeEntries.
739 struct PragmaAttributeGroup {
740 /// The location of the push attribute.
741 SourceLocation Loc;
742 /// The namespace of this push group.
743 const IdentifierInfo *Namespace;
744 SmallVector<PragmaAttributeEntry, 2> Entries;
745 };
746
747 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
748
749 /// The declaration that is currently receiving an attribute from the
750 /// #pragma attribute stack.
751 const Decl *PragmaAttributeCurrentTargetDecl;
752
753 /// This represents the last location of a "#pragma clang optimize off"
754 /// directive if such a directive has not been closed by an "on" yet. If
755 /// optimizations are currently "on", this is set to an invalid location.
756 SourceLocation OptimizeOffPragmaLocation;
757
758 /// Flag indicating if Sema is building a recovery call expression.
759 ///
760 /// This flag is used to avoid building recovery call expressions
761 /// if Sema is already doing so, which would cause infinite recursions.
762 bool IsBuildingRecoveryCallExpr;
763
764 /// Used to control the generation of ExprWithCleanups.
765 CleanupInfo Cleanup;
766
767 /// ExprCleanupObjects - This is the stack of objects requiring
768 /// cleanup that are created by the current full expression.
769 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
770
771 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
772 /// to a variable (constant) that may or may not be odr-used in this Expr, and
773 /// we won't know until all lvalue-to-rvalue and discarded value conversions
774 /// have been applied to all subexpressions of the enclosing full expression.
775 /// This is cleared at the end of each full expression.
776 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
777 llvm::SmallPtrSet<Expr *, 4>>;
778 MaybeODRUseExprSet MaybeODRUseExprs;
779
780 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
781
782 /// Stack containing information about each of the nested
783 /// function, block, and method scopes that are currently active.
784 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
785
786 /// The index of the first FunctionScope that corresponds to the current
787 /// context.
788 unsigned FunctionScopesStart = 0;
789
790 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
791 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
792 FunctionScopes.end());
793 }
794
795 /// Stack containing information needed when in C++2a an 'auto' is encountered
796 /// in a function declaration parameter type specifier in order to invent a
797 /// corresponding template parameter in the enclosing abbreviated function
798 /// template. This information is also present in LambdaScopeInfo, stored in
799 /// the FunctionScopes stack.
800 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
801
802 /// The index of the first InventedParameterInfo that refers to the current
803 /// context.
804 unsigned InventedParameterInfosStart = 0;
805
806 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
807 return llvm::makeArrayRef(InventedParameterInfos.begin() +
808 InventedParameterInfosStart,
809 InventedParameterInfos.end());
810 }
811
812 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
813 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
814 ExtVectorDeclsType;
815
816 /// ExtVectorDecls - This is a list all the extended vector types. This allows
817 /// us to associate a raw vector type with one of the ext_vector type names.
818 /// This is only necessary for issuing pretty diagnostics.
819 ExtVectorDeclsType ExtVectorDecls;
820
821 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
822 std::unique_ptr<CXXFieldCollector> FieldCollector;
823
824 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
825
826 /// Set containing all declared private fields that are not used.
827 NamedDeclSetType UnusedPrivateFields;
828
829 /// Set containing all typedefs that are likely unused.
830 llvm::SmallSetVector<const TypedefNameDecl *, 4>
831 UnusedLocalTypedefNameCandidates;
832
833 /// Delete-expressions to be analyzed at the end of translation unit
834 ///
835 /// This list contains class members, and locations of delete-expressions
836 /// that could not be proven as to whether they mismatch with new-expression
837 /// used in initializer of the field.
838 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
839 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
840 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
841
842 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
843
844 /// PureVirtualClassDiagSet - a set of class declarations which we have
845 /// emitted a list of pure virtual functions. Used to prevent emitting the
846 /// same list more than once.
847 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
848
849 /// ParsingInitForAutoVars - a set of declarations with auto types for which
850 /// we are currently parsing the initializer.
851 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
852
853 /// Look for a locally scoped extern "C" declaration by the given name.
854 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
855
856 typedef LazyVector<VarDecl *, ExternalSemaSource,
857 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
858 TentativeDefinitionsType;
859
860 /// All the tentative definitions encountered in the TU.
861 TentativeDefinitionsType TentativeDefinitions;
862
863 /// All the external declarations encoutered and used in the TU.
864 SmallVector<VarDecl *, 4> ExternalDeclarations;
865
866 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
867 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
868 UnusedFileScopedDeclsType;
869
870 /// The set of file scoped decls seen so far that have not been used
871 /// and must warn if not used. Only contains the first declaration.
872 UnusedFileScopedDeclsType UnusedFileScopedDecls;
873
874 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
875 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
876 DelegatingCtorDeclsType;
877
878 /// All the delegating constructors seen so far in the file, used for
879 /// cycle detection at the end of the TU.
880 DelegatingCtorDeclsType DelegatingCtorDecls;
881
882 /// All the overriding functions seen during a class definition
883 /// that had their exception spec checks delayed, plus the overridden
884 /// function.
885 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
886 DelayedOverridingExceptionSpecChecks;
887
888 /// All the function redeclarations seen during a class definition that had
889 /// their exception spec checks delayed, plus the prior declaration they
890 /// should be checked against. Except during error recovery, the new decl
891 /// should always be a friend declaration, as that's the only valid way to
892 /// redeclare a special member before its class is complete.
893 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
894 DelayedEquivalentExceptionSpecChecks;
895
896 typedef llvm::MapVector<const FunctionDecl *,
897 std::unique_ptr<LateParsedTemplate>>
898 LateParsedTemplateMapT;
899 LateParsedTemplateMapT LateParsedTemplateMap;
900
901 /// Callback to the parser to parse templated functions when needed.
902 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
903 typedef void LateTemplateParserCleanupCB(void *P);
904 LateTemplateParserCB *LateTemplateParser;
905 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
906 void *OpaqueParser;
907
908 void SetLateTemplateParser(LateTemplateParserCB *LTP,
909 LateTemplateParserCleanupCB *LTPCleanup,
910 void *P) {
911 LateTemplateParser = LTP;
912 LateTemplateParserCleanup = LTPCleanup;
913 OpaqueParser = P;
914 }
915
916 class DelayedDiagnostics;
917
918 class DelayedDiagnosticsState {
919 sema::DelayedDiagnosticPool *SavedPool;
920 friend class Sema::DelayedDiagnostics;
921 };
922 typedef DelayedDiagnosticsState ParsingDeclState;
923 typedef DelayedDiagnosticsState ProcessingContextState;
924
925 /// A class which encapsulates the logic for delaying diagnostics
926 /// during parsing and other processing.
927 class DelayedDiagnostics {
928 /// The current pool of diagnostics into which delayed
929 /// diagnostics should go.
930 sema::DelayedDiagnosticPool *CurPool;
931
932 public:
933 DelayedDiagnostics() : CurPool(nullptr) {}
934
935 /// Adds a delayed diagnostic.
936 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
937
938 /// Determines whether diagnostics should be delayed.
939 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
940
941 /// Returns the current delayed-diagnostics pool.
942 sema::DelayedDiagnosticPool *getCurrentPool() const {
943 return CurPool;
944 }
945
946 /// Enter a new scope. Access and deprecation diagnostics will be
947 /// collected in this pool.
948 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
949 DelayedDiagnosticsState state;
950 state.SavedPool = CurPool;
951 CurPool = &pool;
952 return state;
953 }
954
955 /// Leave a delayed-diagnostic state that was previously pushed.
956 /// Do not emit any of the diagnostics. This is performed as part
957 /// of the bookkeeping of popping a pool "properly".
958 void popWithoutEmitting(DelayedDiagnosticsState state) {
959 CurPool = state.SavedPool;
960 }
961
962 /// Enter a new scope where access and deprecation diagnostics are
963 /// not delayed.
964 DelayedDiagnosticsState pushUndelayed() {
965 DelayedDiagnosticsState state;
966 state.SavedPool = CurPool;
967 CurPool = nullptr;
968 return state;
969 }
970
971 /// Undo a previous pushUndelayed().
972 void popUndelayed(DelayedDiagnosticsState state) {
973 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "clang/include/clang/Sema/Sema.h", 973
, __extension__ __PRETTY_FUNCTION__))
;
974 CurPool = state.SavedPool;
975 }
976 } DelayedDiagnostics;
977
978 /// A RAII object to temporarily push a declaration context.
979 class ContextRAII {
980 private:
981 Sema &S;
982 DeclContext *SavedContext;
983 ProcessingContextState SavedContextState;
984 QualType SavedCXXThisTypeOverride;
985 unsigned SavedFunctionScopesStart;
986 unsigned SavedInventedParameterInfosStart;
987
988 public:
989 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
990 : S(S), SavedContext(S.CurContext),
991 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
992 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
993 SavedFunctionScopesStart(S.FunctionScopesStart),
994 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
995 {
996 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "clang/include/clang/Sema/Sema.h", 996, __extension__ __PRETTY_FUNCTION__
))
;
997 S.CurContext = ContextToPush;
998 if (NewThisContext)
999 S.CXXThisTypeOverride = QualType();
1000 // Any saved FunctionScopes do not refer to this context.
1001 S.FunctionScopesStart = S.FunctionScopes.size();
1002 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1003 }
1004
1005 void pop() {
1006 if (!SavedContext) return;
1007 S.CurContext = SavedContext;
1008 S.DelayedDiagnostics.popUndelayed(SavedContextState);
1009 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1010 S.FunctionScopesStart = SavedFunctionScopesStart;
1011 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1012 SavedContext = nullptr;
1013 }
1014
1015 ~ContextRAII() {
1016 pop();
1017 }
1018 };
1019
1020 /// Whether the AST is currently being rebuilt to correct immediate
1021 /// invocations. Immediate invocation candidates and references to consteval
1022 /// functions aren't tracked when this is set.
1023 bool RebuildingImmediateInvocation = false;
1024
1025 /// Used to change context to isConstantEvaluated without pushing a heavy
1026 /// ExpressionEvaluationContextRecord object.
1027 bool isConstantEvaluatedOverride;
1028
1029 bool isConstantEvaluated() {
1030 return ExprEvalContexts.back().isConstantEvaluated() ||
1031 isConstantEvaluatedOverride;
1032 }
1033
1034 /// RAII object to handle the state changes required to synthesize
1035 /// a function body.
1036 class SynthesizedFunctionScope {
1037 Sema &S;
1038 Sema::ContextRAII SavedContext;
1039 bool PushedCodeSynthesisContext = false;
1040
1041 public:
1042 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1043 : S(S), SavedContext(S, DC) {
1044 S.PushFunctionScope();
1045 S.PushExpressionEvaluationContext(
1046 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1047 if (auto *FD = dyn_cast<FunctionDecl>(DC))
1048 FD->setWillHaveBody(true);
1049 else
1050 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "clang/include/clang/Sema/Sema.h"
, 1050, __extension__ __PRETTY_FUNCTION__))
;
1051 }
1052
1053 void addContextNote(SourceLocation UseLoc) {
1054 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "clang/include/clang/Sema/Sema.h"
, 1054, __extension__ __PRETTY_FUNCTION__))
;
1055
1056 Sema::CodeSynthesisContext Ctx;
1057 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1058 Ctx.PointOfInstantiation = UseLoc;
1059 Ctx.Entity = cast<Decl>(S.CurContext);
1060 S.pushCodeSynthesisContext(Ctx);
1061
1062 PushedCodeSynthesisContext = true;
1063 }
1064
1065 ~SynthesizedFunctionScope() {
1066 if (PushedCodeSynthesisContext)
1067 S.popCodeSynthesisContext();
1068 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1069 FD->setWillHaveBody(false);
1070 S.PopExpressionEvaluationContext();
1071 S.PopFunctionScopeInfo();
1072 }
1073 };
1074
1075 /// WeakUndeclaredIdentifiers - Identifiers contained in
1076 /// \#pragma weak before declared. rare. may alias another
1077 /// identifier, declared or undeclared
1078 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
1079
1080 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1081 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1082 /// to define functions that occur in multiple standards to call the version
1083 /// in the currently selected standard.
1084 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1085
1086
1087 /// Load weak undeclared identifiers from the external source.
1088 void LoadExternalWeakUndeclaredIdentifiers();
1089
1090 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1091 /// \#pragma weak during processing of other Decls.
1092 /// I couldn't figure out a clean way to generate these in-line, so
1093 /// we store them here and handle separately -- which is a hack.
1094 /// It would be best to refactor this.
1095 SmallVector<Decl*,2> WeakTopLevelDecl;
1096
1097 IdentifierResolver IdResolver;
1098
1099 /// Translation Unit Scope - useful to Objective-C actions that need
1100 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1101 /// For example, user-defined classes, built-in "id" type, etc.
1102 Scope *TUScope;
1103
1104 /// The C++ "std" namespace, where the standard library resides.
1105 LazyDeclPtr StdNamespace;
1106
1107 /// The C++ "std::bad_alloc" class, which is defined by the C++
1108 /// standard library.
1109 LazyDeclPtr StdBadAlloc;
1110
1111 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1112 /// standard library.
1113 LazyDeclPtr StdAlignValT;
1114
1115 /// The C++ "std::experimental" namespace, where the experimental parts
1116 /// of the standard library resides.
1117 NamespaceDecl *StdExperimentalNamespaceCache;
1118
1119 /// The C++ "std::initializer_list" template, which is defined in
1120 /// \<initializer_list>.
1121 ClassTemplateDecl *StdInitializerList;
1122
1123 /// The C++ "std::coroutine_traits" template, which is defined in
1124 /// \<coroutine_traits>
1125 ClassTemplateDecl *StdCoroutineTraitsCache;
1126 /// The namespace where coroutine components are defined. In standard,
1127 /// they are defined in std namespace. And in the previous implementation,
1128 /// they are defined in std::experimental namespace.
1129 NamespaceDecl *CoroTraitsNamespaceCache;
1130
1131 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1132 RecordDecl *CXXTypeInfoDecl;
1133
1134 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1135 RecordDecl *MSVCGuidDecl;
1136
1137 /// Caches identifiers/selectors for NSFoundation APIs.
1138 std::unique_ptr<NSAPI> NSAPIObj;
1139
1140 /// The declaration of the Objective-C NSNumber class.
1141 ObjCInterfaceDecl *NSNumberDecl;
1142
1143 /// The declaration of the Objective-C NSValue class.
1144 ObjCInterfaceDecl *NSValueDecl;
1145
1146 /// Pointer to NSNumber type (NSNumber *).
1147 QualType NSNumberPointer;
1148
1149 /// Pointer to NSValue type (NSValue *).
1150 QualType NSValuePointer;
1151
1152 /// The Objective-C NSNumber methods used to create NSNumber literals.
1153 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1154
1155 /// The declaration of the Objective-C NSString class.
1156 ObjCInterfaceDecl *NSStringDecl;
1157
1158 /// Pointer to NSString type (NSString *).
1159 QualType NSStringPointer;
1160
1161 /// The declaration of the stringWithUTF8String: method.
1162 ObjCMethodDecl *StringWithUTF8StringMethod;
1163
1164 /// The declaration of the valueWithBytes:objCType: method.
1165 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1166
1167 /// The declaration of the Objective-C NSArray class.
1168 ObjCInterfaceDecl *NSArrayDecl;
1169
1170 /// The declaration of the arrayWithObjects:count: method.
1171 ObjCMethodDecl *ArrayWithObjectsMethod;
1172
1173 /// The declaration of the Objective-C NSDictionary class.
1174 ObjCInterfaceDecl *NSDictionaryDecl;
1175
1176 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1177 ObjCMethodDecl *DictionaryWithObjectsMethod;
1178
1179 /// id<NSCopying> type.
1180 QualType QIDNSCopying;
1181
1182 /// will hold 'respondsToSelector:'
1183 Selector RespondsToSelectorSel;
1184
1185 /// A flag to remember whether the implicit forms of operator new and delete
1186 /// have been declared.
1187 bool GlobalNewDeleteDeclared;
1188
1189 /// Describes how the expressions currently being parsed are
1190 /// evaluated at run-time, if at all.
1191 enum class ExpressionEvaluationContext {
1192 /// The current expression and its subexpressions occur within an
1193 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1194 /// \c sizeof, where the type of the expression may be significant but
1195 /// no code will be generated to evaluate the value of the expression at
1196 /// run time.
1197 Unevaluated,
1198
1199 /// The current expression occurs within a braced-init-list within
1200 /// an unevaluated operand. This is mostly like a regular unevaluated
1201 /// context, except that we still instantiate constexpr functions that are
1202 /// referenced here so that we can perform narrowing checks correctly.
1203 UnevaluatedList,
1204
1205 /// The current expression occurs within a discarded statement.
1206 /// This behaves largely similarly to an unevaluated operand in preventing
1207 /// definitions from being required, but not in other ways.
1208 DiscardedStatement,
1209
1210 /// The current expression occurs within an unevaluated
1211 /// operand that unconditionally permits abstract references to
1212 /// fields, such as a SIZE operator in MS-style inline assembly.
1213 UnevaluatedAbstract,
1214
1215 /// The current context is "potentially evaluated" in C++11 terms,
1216 /// but the expression is evaluated at compile-time (like the values of
1217 /// cases in a switch statement).
1218 ConstantEvaluated,
1219
1220 /// In addition of being constant evaluated, the current expression
1221 /// occurs in an immediate function context - either a consteval function
1222 /// or a consteval if function.
1223 ImmediateFunctionContext,
1224
1225 /// The current expression is potentially evaluated at run time,
1226 /// which means that code may be generated to evaluate the value of the
1227 /// expression at run time.
1228 PotentiallyEvaluated,
1229
1230 /// The current expression is potentially evaluated, but any
1231 /// declarations referenced inside that expression are only used if
1232 /// in fact the current expression is used.
1233 ///
1234 /// This value is used when parsing default function arguments, for which
1235 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1236 /// through varargs) but do not want to mark declarations as "referenced"
1237 /// until the default argument is used.
1238 PotentiallyEvaluatedIfUsed
1239 };
1240
1241 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1242
1243 /// Data structure used to record current or nested
1244 /// expression evaluation contexts.
1245 struct ExpressionEvaluationContextRecord {
1246 /// The expression evaluation context.
1247 ExpressionEvaluationContext Context;
1248
1249 /// Whether the enclosing context needed a cleanup.
1250 CleanupInfo ParentCleanup;
1251
1252 /// The number of active cleanup objects when we entered
1253 /// this expression evaluation context.
1254 unsigned NumCleanupObjects;
1255
1256 /// The number of typos encountered during this expression evaluation
1257 /// context (i.e. the number of TypoExprs created).
1258 unsigned NumTypos;
1259
1260 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1261
1262 /// The lambdas that are present within this context, if it
1263 /// is indeed an unevaluated context.
1264 SmallVector<LambdaExpr *, 2> Lambdas;
1265
1266 /// The declaration that provides context for lambda expressions
1267 /// and block literals if the normal declaration context does not
1268 /// suffice, e.g., in a default function argument.
1269 Decl *ManglingContextDecl;
1270
1271 /// If we are processing a decltype type, a set of call expressions
1272 /// for which we have deferred checking the completeness of the return type.
1273 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1274
1275 /// If we are processing a decltype type, a set of temporary binding
1276 /// expressions for which we have deferred checking the destructor.
1277 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1278
1279 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1280
1281 /// Expressions appearing as the LHS of a volatile assignment in this
1282 /// context. We produce a warning for these when popping the context if
1283 /// they are not discarded-value expressions nor unevaluated operands.
1284 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1285
1286 /// Set of candidates for starting an immediate invocation.
1287 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1288
1289 /// Set of DeclRefExprs referencing a consteval function when used in a
1290 /// context not already known to be immediately invoked.
1291 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1292
1293 /// \brief Describes whether we are in an expression constext which we have
1294 /// to handle differently.
1295 enum ExpressionKind {
1296 EK_Decltype, EK_TemplateArgument, EK_Other
1297 } ExprContext;
1298
1299 // A context can be nested in both a discarded statement context and
1300 // an immediate function context, so they need to be tracked independently.
1301 bool InDiscardedStatement;
1302 bool InImmediateFunctionContext;
1303
1304 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1305 unsigned NumCleanupObjects,
1306 CleanupInfo ParentCleanup,
1307 Decl *ManglingContextDecl,
1308 ExpressionKind ExprContext)
1309 : Context(Context), ParentCleanup(ParentCleanup),
1310 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1311 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
1312 InDiscardedStatement(false), InImmediateFunctionContext(false) {}
1313
1314 bool isUnevaluated() const {
1315 return Context == ExpressionEvaluationContext::Unevaluated ||
1316 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1317 Context == ExpressionEvaluationContext::UnevaluatedList;
1318 }
1319
1320 bool isConstantEvaluated() const {
1321 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1322 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1323 }
1324
1325 bool isImmediateFunctionContext() const {
1326 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
1327 (Context == ExpressionEvaluationContext::DiscardedStatement &&
1328 InImmediateFunctionContext);
1329 }
1330
1331 bool isDiscardedStatementContext() const {
1332 return Context == ExpressionEvaluationContext::DiscardedStatement ||
1333 (Context ==
1334 ExpressionEvaluationContext::ImmediateFunctionContext &&
1335 InDiscardedStatement);
1336 }
1337 };
1338
1339 /// A stack of expression evaluation contexts.
1340 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1341
1342 /// Emit a warning for all pending noderef expressions that we recorded.
1343 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1344
1345 /// Compute the mangling number context for a lambda expression or
1346 /// block literal. Also return the extra mangling decl if any.
1347 ///
1348 /// \param DC - The DeclContext containing the lambda expression or
1349 /// block literal.
1350 std::tuple<MangleNumberingContext *, Decl *>
1351 getCurrentMangleNumberContext(const DeclContext *DC);
1352
1353
1354 /// SpecialMemberOverloadResult - The overloading result for a special member
1355 /// function.
1356 ///
1357 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1358 /// integer are used to determine whether overload resolution succeeded.
1359 class SpecialMemberOverloadResult {
1360 public:
1361 enum Kind {
1362 NoMemberOrDeleted,
1363 Ambiguous,
1364 Success
1365 };
1366
1367 private:
1368 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1369
1370 public:
1371 SpecialMemberOverloadResult() {}
1372 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1373 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1374
1375 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1376 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1377
1378 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1379 void setKind(Kind K) { Pair.setInt(K); }
1380 };
1381
1382 class SpecialMemberOverloadResultEntry
1383 : public llvm::FastFoldingSetNode,
1384 public SpecialMemberOverloadResult {
1385 public:
1386 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1387 : FastFoldingSetNode(ID)
1388 {}
1389 };
1390
1391 /// A cache of special member function overload resolution results
1392 /// for C++ records.
1393 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1394
1395 /// A cache of the flags available in enumerations with the flag_bits
1396 /// attribute.
1397 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1398
1399 /// The kind of translation unit we are processing.
1400 ///
1401 /// When we're processing a complete translation unit, Sema will perform
1402 /// end-of-translation-unit semantic tasks (such as creating
1403 /// initializers for tentative definitions in C) once parsing has
1404 /// completed. Modules and precompiled headers perform different kinds of
1405 /// checks.
1406 const TranslationUnitKind TUKind;
1407
1408 llvm::BumpPtrAllocator BumpAlloc;
1409
1410 /// The number of SFINAE diagnostics that have been trapped.
1411 unsigned NumSFINAEErrors;
1412
1413 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1414 UnparsedDefaultArgInstantiationsMap;
1415
1416 /// A mapping from parameters with unparsed default arguments to the
1417 /// set of instantiations of each parameter.
1418 ///
1419 /// This mapping is a temporary data structure used when parsing
1420 /// nested class templates or nested classes of class templates,
1421 /// where we might end up instantiating an inner class before the
1422 /// default arguments of its methods have been parsed.
1423 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1424
1425 // Contains the locations of the beginning of unparsed default
1426 // argument locations.
1427 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1428
1429 /// UndefinedInternals - all the used, undefined objects which require a
1430 /// definition in this translation unit.
1431 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1432
1433 /// Determine if VD, which must be a variable or function, is an external
1434 /// symbol that nonetheless can't be referenced from outside this translation
1435 /// unit because its type has no linkage and it's not extern "C".
1436 bool isExternalWithNoLinkageType(ValueDecl *VD);
1437
1438 /// Obtain a sorted list of functions that are undefined but ODR-used.
1439 void getUndefinedButUsed(
1440 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1441
1442 /// Retrieves list of suspicious delete-expressions that will be checked at
1443 /// the end of translation unit.
1444 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1445 getMismatchingDeleteExpressions() const;
1446
1447 class GlobalMethodPool {
1448 public:
1449 using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1450 using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1451 iterator begin() { return Methods.begin(); }
1452 iterator end() { return Methods.end(); }
1453 iterator find(Selector Sel) { return Methods.find(Sel); }
1454 std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1455 return Methods.insert(Val);
1456 }
1457 int count(Selector Sel) const { return Methods.count(Sel); }
1458 bool empty() const { return Methods.empty(); }
1459
1460 private:
1461 llvm::DenseMap<Selector, Lists> Methods;
1462 };
1463
1464 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1465 /// We need to maintain a list, since selectors can have differing signatures
1466 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1467 /// of selectors are "overloaded").
1468 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1469 /// methods inside categories with a particular selector.
1470 GlobalMethodPool MethodPool;
1471
1472 /// Method selectors used in a \@selector expression. Used for implementation
1473 /// of -Wselector.
1474 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1475
1476 /// List of SourceLocations where 'self' is implicitly retained inside a
1477 /// block.
1478 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1479 ImplicitlyRetainedSelfLocs;
1480
1481 /// Kinds of C++ special members.
1482 enum CXXSpecialMember {
1483 CXXDefaultConstructor,
1484 CXXCopyConstructor,
1485 CXXMoveConstructor,
1486 CXXCopyAssignment,
1487 CXXMoveAssignment,
1488 CXXDestructor,
1489 CXXInvalid
1490 };
1491
1492 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1493 SpecialMemberDecl;
1494
1495 /// The C++ special members which we are currently in the process of
1496 /// declaring. If this process recursively triggers the declaration of the
1497 /// same special member, we should act as if it is not yet declared.
1498 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1499
1500 /// Kinds of defaulted comparison operator functions.
1501 enum class DefaultedComparisonKind : unsigned char {
1502 /// This is not a defaultable comparison operator.
1503 None,
1504 /// This is an operator== that should be implemented as a series of
1505 /// subobject comparisons.
1506 Equal,
1507 /// This is an operator<=> that should be implemented as a series of
1508 /// subobject comparisons.
1509 ThreeWay,
1510 /// This is an operator!= that should be implemented as a rewrite in terms
1511 /// of a == comparison.
1512 NotEqual,
1513 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1514 /// terms of a <=> comparison.
1515 Relational,
1516 };
1517
1518 /// The function definitions which were renamed as part of typo-correction
1519 /// to match their respective declarations. We want to keep track of them
1520 /// to ensure that we don't emit a "redefinition" error if we encounter a
1521 /// correctly named definition after the renamed definition.
1522 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1523
1524 /// Stack of types that correspond to the parameter entities that are
1525 /// currently being copy-initialized. Can be empty.
1526 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1527
1528 void ReadMethodPool(Selector Sel);
1529 void updateOutOfDateSelector(Selector Sel);
1530
1531 /// Private Helper predicate to check for 'self'.
1532 bool isSelfExpr(Expr *RExpr);
1533 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1534
1535 /// Cause the active diagnostic on the DiagosticsEngine to be
1536 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1537 /// should not be used elsewhere.
1538 void EmitCurrentDiagnostic(unsigned DiagID);
1539
1540 /// Records and restores the CurFPFeatures state on entry/exit of compound
1541 /// statements.
1542 class FPFeaturesStateRAII {
1543 public:
1544 FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
1545 OldOverrides = S.FpPragmaStack.CurrentValue;
1546 }
1547 ~FPFeaturesStateRAII() {
1548 S.CurFPFeatures = OldFPFeaturesState;
1549 S.FpPragmaStack.CurrentValue = OldOverrides;
1550 }
1551 FPOptionsOverride getOverrides() { return OldOverrides; }
1552
1553 private:
1554 Sema& S;
1555 FPOptions OldFPFeaturesState;
1556 FPOptionsOverride OldOverrides;
1557 };
1558
1559 void addImplicitTypedef(StringRef Name, QualType T);
1560
1561 bool WarnedStackExhausted = false;
1562
1563 /// Increment when we find a reference; decrement when we find an ignored
1564 /// assignment. Ultimately the value is 0 if every reference is an ignored
1565 /// assignment.
1566 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1567
1568 Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1569
1570public:
1571 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1572 TranslationUnitKind TUKind = TU_Complete,
1573 CodeCompleteConsumer *CompletionConsumer = nullptr);
1574 ~Sema();
1575
1576 /// Perform initialization that occurs after the parser has been
1577 /// initialized but before it parses anything.
1578 void Initialize();
1579
1580 /// This virtual key function only exists to limit the emission of debug info
1581 /// describing the Sema class. GCC and Clang only emit debug info for a class
1582 /// with a vtable when the vtable is emitted. Sema is final and not
1583 /// polymorphic, but the debug info size savings are so significant that it is
1584 /// worth adding a vtable just to take advantage of this optimization.
1585 virtual void anchor();
1586
1587 const LangOptions &getLangOpts() const { return LangOpts; }
1588 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1589 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1590
1591 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1592 SourceManager &getSourceManager() const { return SourceMgr; }
1593 Preprocessor &getPreprocessor() const { return PP; }
1594 ASTContext &getASTContext() const { return Context; }
1595 ASTConsumer &getASTConsumer() const { return Consumer; }
1596 ASTMutationListener *getASTMutationListener() const;
1597 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1598 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1599 StringRef Platform);
1600
1601 ///Registers an external source. If an external source already exists,
1602 /// creates a multiplex external source and appends to it.
1603 ///
1604 ///\param[in] E - A non-null external sema source.
1605 ///
1606 void addExternalSource(ExternalSemaSource *E);
1607
1608 void PrintStats() const;
1609
1610 /// Warn that the stack is nearly exhausted.
1611 void warnStackExhausted(SourceLocation Loc);
1612
1613 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1614 /// guaranteed). Produces a warning if we're low on stack space and allocates
1615 /// more in that case. Use this in code that may recurse deeply (for example,
1616 /// in template instantiation) to avoid stack overflow.
1617 void runWithSufficientStackSpace(SourceLocation Loc,
1618 llvm::function_ref<void()> Fn);
1619
1620 /// Helper class that creates diagnostics with optional
1621 /// template instantiation stacks.
1622 ///
1623 /// This class provides a wrapper around the basic DiagnosticBuilder
1624 /// class that emits diagnostics. ImmediateDiagBuilder is
1625 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1626 /// does) and, if the diagnostic comes from inside a template
1627 /// instantiation, printing the template instantiation stack as
1628 /// well.
1629 class ImmediateDiagBuilder : public DiagnosticBuilder {
1630 Sema &SemaRef;
1631 unsigned DiagID;
1632
1633 public:
1634 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1635 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1636 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1637 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1638
1639 // This is a cunning lie. DiagnosticBuilder actually performs move
1640 // construction in its copy constructor (but due to varied uses, it's not
1641 // possible to conveniently express this as actual move construction). So
1642 // the default copy ctor here is fine, because the base class disables the
1643 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1644 // in that case anwyay.
1645 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1646
1647 ~ImmediateDiagBuilder() {
1648 // If we aren't active, there is nothing to do.
1649 if (!isActive()) return;
1650
1651 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1652 // builder itself so it won't emit the diagnostic in its own destructor.
1653 //
1654 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1655 // do its own needless checks to see if the diagnostic needs to be
1656 // emitted. However, because we take care to ensure that the builder
1657 // objects never escape, a sufficiently smart compiler will be able to
1658 // eliminate that code.
1659 Clear();
1660
1661 // Dispatch to Sema to emit the diagnostic.
1662 SemaRef.EmitCurrentDiagnostic(DiagID);
1663 }
1664
1665 /// Teach operator<< to produce an object of the correct type.
1666 template <typename T>
1667 friend const ImmediateDiagBuilder &
1668 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1669 const DiagnosticBuilder &BaseDiag = Diag;
1670 BaseDiag << Value;
1671 return Diag;
1672 }
1673
1674 // It is necessary to limit this to rvalue reference to avoid calling this
1675 // function with a bitfield lvalue argument since non-const reference to
1676 // bitfield is not allowed.
1677 template <typename T, typename = typename std::enable_if<
1678 !std::is_lvalue_reference<T>::value>::type>
1679 const ImmediateDiagBuilder &operator<<(T &&V) const {
1680 const DiagnosticBuilder &BaseDiag = *this;
1681 BaseDiag << std::move(V);
1682 return *this;
1683 }
1684 };
1685
1686 /// A generic diagnostic builder for errors which may or may not be deferred.
1687 ///
1688 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1689 /// which are not allowed to appear inside __device__ functions and are
1690 /// allowed to appear in __host__ __device__ functions only if the host+device
1691 /// function is never codegen'ed.
1692 ///
1693 /// To handle this, we use the notion of "deferred diagnostics", where we
1694 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1695 ///
1696 /// This class lets you emit either a regular diagnostic, a deferred
1697 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1698 /// its constructor, thus simplifying the process of creating these "maybe
1699 /// deferred" diagnostics.
1700 class SemaDiagnosticBuilder {
1701 public:
1702 enum Kind {
1703 /// Emit no diagnostics.
1704 K_Nop,
1705 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1706 K_Immediate,
1707 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1708 /// emit a call stack showing how this function can be reached by an a
1709 /// priori known-emitted function.
1710 K_ImmediateWithCallStack,
1711 /// Create a deferred diagnostic, which is emitted only if the function
1712 /// it's attached to is codegen'ed. Also emit a call stack as with
1713 /// K_ImmediateWithCallStack.
1714 K_Deferred
1715 };
1716
1717 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1718 FunctionDecl *Fn, Sema &S);
1719 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1720 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1721 ~SemaDiagnosticBuilder();
1722
1723 bool isImmediate() const { return ImmediateDiag.hasValue(); }
1724
1725 /// Convertible to bool: True if we immediately emitted an error, false if
1726 /// we didn't emit an error or we created a deferred error.
1727 ///
1728 /// Example usage:
1729 ///
1730 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1731 /// return ExprError();
1732 ///
1733 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1734 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1735 operator bool() const { return isImmediate(); }
1736
1737 template <typename T>
1738 friend const SemaDiagnosticBuilder &
1739 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1740 if (Diag.ImmediateDiag.hasValue())
1741 *Diag.ImmediateDiag << Value;
1742 else if (Diag.PartialDiagId.hasValue())
1743 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1744 << Value;
1745 return Diag;
1746 }
1747
1748 // It is necessary to limit this to rvalue reference to avoid calling this
1749 // function with a bitfield lvalue argument since non-const reference to
1750 // bitfield is not allowed.
1751 template <typename T, typename = typename std::enable_if<
1752 !std::is_lvalue_reference<T>::value>::type>
1753 const SemaDiagnosticBuilder &operator<<(T &&V) const {
1754 if (ImmediateDiag.hasValue())
1755 *ImmediateDiag << std::move(V);
1756 else if (PartialDiagId.hasValue())
1757 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1758 return *this;
1759 }
1760
1761 friend const SemaDiagnosticBuilder &
1762 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1763 if (Diag.ImmediateDiag.hasValue())
1764 PD.Emit(*Diag.ImmediateDiag);
1765 else if (Diag.PartialDiagId.hasValue())
1766 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1767 return Diag;
1768 }
1769
1770 void AddFixItHint(const FixItHint &Hint) const {
1771 if (ImmediateDiag.hasValue())
1772 ImmediateDiag->AddFixItHint(Hint);
1773 else if (PartialDiagId.hasValue())
1774 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1775 }
1776
1777 friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1778 return ExprError();
1779 }
1780 friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1781 return StmtError();
1782 }
1783 operator ExprResult() const { return ExprError(); }
1784 operator StmtResult() const { return StmtError(); }
1785 operator TypeResult() const { return TypeError(); }
1786 operator DeclResult() const { return DeclResult(true); }
1787 operator MemInitResult() const { return MemInitResult(true); }
1788
1789 private:
1790 Sema &S;
1791 SourceLocation Loc;
1792 unsigned DiagID;
1793 FunctionDecl *Fn;
1794 bool ShowCallStack;
1795
1796 // Invariant: At most one of these Optionals has a value.
1797 // FIXME: Switch these to a Variant once that exists.
1798 llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1799 llvm::Optional<unsigned> PartialDiagId;
1800 };
1801
1802 /// Is the last error level diagnostic immediate. This is used to determined
1803 /// whether the next info diagnostic should be immediate.
1804 bool IsLastErrorImmediate = true;
1805
1806 /// Emit a diagnostic.
1807 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1808 bool DeferHint = false);
1809
1810 /// Emit a partial diagnostic.
1811 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1812 bool DeferHint = false);
1813
1814 /// Build a partial diagnostic.
1815 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1816
1817 /// Whether deferrable diagnostics should be deferred.
1818 bool DeferDiags = false;
1819
1820 /// RAII class to control scope of DeferDiags.
1821 class DeferDiagsRAII {
1822 Sema &S;
1823 bool SavedDeferDiags = false;
1824
1825 public:
1826 DeferDiagsRAII(Sema &S, bool DeferDiags)
1827 : S(S), SavedDeferDiags(S.DeferDiags) {
1828 S.DeferDiags = DeferDiags;
1829 }
1830 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1831 };
1832
1833 /// Whether uncompilable error has occurred. This includes error happens
1834 /// in deferred diagnostics.
1835 bool hasUncompilableErrorOccurred() const;
1836
1837 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1838
1839 /// Get a string to suggest for zero-initialization of a type.
1840 std::string
1841 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1842 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1843
1844 /// Calls \c Lexer::getLocForEndOfToken()
1845 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1846
1847 /// Retrieve the module loader associated with the preprocessor.
1848 ModuleLoader &getModuleLoader() const;
1849
1850 /// Invent a new identifier for parameters of abbreviated templates.
1851 IdentifierInfo *
1852 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1853 unsigned Index);
1854
1855 void emitAndClearUnusedLocalTypedefWarnings();
1856
1857 private:
1858 /// Function or variable declarations to be checked for whether the deferred
1859 /// diagnostics should be emitted.
1860 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1861
1862 public:
1863 // Emit all deferred diagnostics.
1864 void emitDeferredDiags();
1865
1866 enum TUFragmentKind {
1867 /// The global module fragment, between 'module;' and a module-declaration.
1868 Global,
1869 /// A normal translation unit fragment. For a non-module unit, this is the
1870 /// entire translation unit. Otherwise, it runs from the module-declaration
1871 /// to the private-module-fragment (if any) or the end of the TU (if not).
1872 Normal,
1873 /// The private module fragment, between 'module :private;' and the end of
1874 /// the translation unit.
1875 Private
1876 };
1877
1878 void ActOnStartOfTranslationUnit();
1879 void ActOnEndOfTranslationUnit();
1880 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1881
1882 void CheckDelegatingCtorCycles();
1883
1884 Scope *getScopeForContext(DeclContext *Ctx);
1885
1886 void PushFunctionScope();