Bug Summary

File:tools/clang/include/clang/AST/DeclTemplate.h
Warning:line 1895, column 31
Access to field 'PartialSpecialization' results in a dereference of a null pointer (loaded from variable 'PS')

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h

1//===- DeclTemplate.h - Classes for representing C++ templates --*- 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/// \file
10/// Defines the C++ template declaration subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
15#define LLVM_CLANG_AST_DECLTEMPLATE_H
16
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclarationName.h"
21#include "clang/AST/Redeclarable.h"
22#include "clang/AST/TemplateBase.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/LLVM.h"
25#include "clang/Basic/SourceLocation.h"
26#include "clang/Basic/Specifiers.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/FoldingSet.h"
29#include "llvm/ADT/PointerIntPair.h"
30#include "llvm/ADT/PointerUnion.h"
31#include "llvm/ADT/iterator.h"
32#include "llvm/ADT/iterator_range.h"
33#include "llvm/Support/Casting.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Support/TrailingObjects.h"
36#include <cassert>
37#include <cstddef>
38#include <cstdint>
39#include <iterator>
40#include <utility>
41
42namespace clang {
43
44enum BuiltinTemplateKind : int;
45class ClassTemplateDecl;
46class ClassTemplatePartialSpecializationDecl;
47class Expr;
48class FunctionTemplateDecl;
49class IdentifierInfo;
50class NonTypeTemplateParmDecl;
51class TemplateDecl;
52class TemplateTemplateParmDecl;
53class TemplateTypeParmDecl;
54class UnresolvedSetImpl;
55class VarTemplateDecl;
56class VarTemplatePartialSpecializationDecl;
57
58/// Stores a template parameter of any kind.
59using TemplateParameter =
60 llvm::PointerUnion3<TemplateTypeParmDecl *, NonTypeTemplateParmDecl *,
61 TemplateTemplateParmDecl *>;
62
63NamedDecl *getAsNamedDecl(TemplateParameter P);
64
65/// Stores a list of template parameters for a TemplateDecl and its
66/// derived classes.
67class TemplateParameterList final
68 : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *,
69 Expr *> {
70 /// The location of the 'template' keyword.
71 SourceLocation TemplateLoc;
72
73 /// The locations of the '<' and '>' angle brackets.
74 SourceLocation LAngleLoc, RAngleLoc;
75
76 /// The number of template parameters in this template
77 /// parameter list.
78 unsigned NumParams : 30;
79
80 /// Whether this template parameter list contains an unexpanded parameter
81 /// pack.
82 unsigned ContainsUnexpandedParameterPack : 1;
83
84 /// Whether this template parameter list has an associated requires-clause
85 unsigned HasRequiresClause : 1;
86
87protected:
88 TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
89 ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc,
90 Expr *RequiresClause);
91
92 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
93 return NumParams;
94 }
95
96 size_t numTrailingObjects(OverloadToken<Expr *>) const {
97 return HasRequiresClause;
98 }
99
100public:
101 template <size_t N, bool HasRequiresClause>
102 friend class FixedSizeTemplateParameterListStorage;
103 friend TrailingObjects;
104
105 static TemplateParameterList *Create(const ASTContext &C,
106 SourceLocation TemplateLoc,
107 SourceLocation LAngleLoc,
108 ArrayRef<NamedDecl *> Params,
109 SourceLocation RAngleLoc,
110 Expr *RequiresClause);
111
112 /// Iterates through the template parameters in this list.
113 using iterator = NamedDecl **;
114
115 /// Iterates through the template parameters in this list.
116 using const_iterator = NamedDecl * const *;
117
118 iterator begin() { return getTrailingObjects<NamedDecl *>(); }
119 const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
120 iterator end() { return begin() + NumParams; }
121 const_iterator end() const { return begin() + NumParams; }
122
123 unsigned size() const { return NumParams; }
124
125 ArrayRef<NamedDecl*> asArray() {
126 return llvm::makeArrayRef(begin(), end());
127 }
128 ArrayRef<const NamedDecl*> asArray() const {
129 return llvm::makeArrayRef(begin(), size());
130 }
131
132 NamedDecl* getParam(unsigned Idx) {
133 assert(Idx < size() && "Template parameter index out-of-range")((Idx < size() && "Template parameter index out-of-range"
) ? static_cast<void> (0) : __assert_fail ("Idx < size() && \"Template parameter index out-of-range\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 133, __PRETTY_FUNCTION__))
;
134 return begin()[Idx];
135 }
136 const NamedDecl* getParam(unsigned Idx) const {
137 assert(Idx < size() && "Template parameter index out-of-range")((Idx < size() && "Template parameter index out-of-range"
) ? static_cast<void> (0) : __assert_fail ("Idx < size() && \"Template parameter index out-of-range\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 137, __PRETTY_FUNCTION__))
;
138 return begin()[Idx];
139 }
140
141 /// Returns the minimum number of arguments needed to form a
142 /// template specialization.
143 ///
144 /// This may be fewer than the number of template parameters, if some of
145 /// the parameters have default arguments or if there is a parameter pack.
146 unsigned getMinRequiredArguments() const;
147
148 /// Get the depth of this template parameter list in the set of
149 /// template parameter lists.
150 ///
151 /// The first template parameter list in a declaration will have depth 0,
152 /// the second template parameter list will have depth 1, etc.
153 unsigned getDepth() const;
154
155 /// Determine whether this template parameter list contains an
156 /// unexpanded parameter pack.
157 bool containsUnexpandedParameterPack() const {
158 return ContainsUnexpandedParameterPack;
159 }
160
161 /// The constraint-expression of the associated requires-clause.
162 Expr *getRequiresClause() {
163 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
164 }
165
166 /// The constraint-expression of the associated requires-clause.
167 const Expr *getRequiresClause() const {
168 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
169 }
170
171 SourceLocation getTemplateLoc() const { return TemplateLoc; }
172 SourceLocation getLAngleLoc() const { return LAngleLoc; }
173 SourceLocation getRAngleLoc() const { return RAngleLoc; }
174
175 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
176 return SourceRange(TemplateLoc, RAngleLoc);
177 }
178
179 void print(raw_ostream &Out, const ASTContext &Context,
180 bool OmitTemplateKW = false) const;
181 void print(raw_ostream &Out, const ASTContext &Context,
182 const PrintingPolicy &Policy, bool OmitTemplateKW = false) const;
183
184public:
185 // FIXME: workaround for MSVC 2013; remove when no longer needed
186 using FixedSizeStorageOwner = TrailingObjects::FixedSizeStorageOwner;
187};
188
189/// Stores a list of template parameters and the associated
190/// requires-clause (if any) for a TemplateDecl and its derived classes.
191/// Suitable for creating on the stack.
192template <size_t N, bool HasRequiresClause>
193class FixedSizeTemplateParameterListStorage
194 : public TemplateParameterList::FixedSizeStorageOwner {
195 typename TemplateParameterList::FixedSizeStorage<
196 NamedDecl *, Expr *>::with_counts<
197 N, HasRequiresClause ? 1u : 0u
198 >::type storage;
199
200public:
201 FixedSizeTemplateParameterListStorage(SourceLocation TemplateLoc,
202 SourceLocation LAngleLoc,
203 ArrayRef<NamedDecl *> Params,
204 SourceLocation RAngleLoc,
205 Expr *RequiresClause)
206 : FixedSizeStorageOwner(
207 (assert(N == Params.size())((N == Params.size()) ? static_cast<void> (0) : __assert_fail
("N == Params.size()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 207, __PRETTY_FUNCTION__))
,
208 assert(HasRequiresClause == static_cast<bool>(RequiresClause))((HasRequiresClause == static_cast<bool>(RequiresClause
)) ? static_cast<void> (0) : __assert_fail ("HasRequiresClause == static_cast<bool>(RequiresClause)"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 208, __PRETTY_FUNCTION__))
,
209 new (static_cast<void *>(&storage)) TemplateParameterList(
210 TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause))) {}
211};
212
213/// A template argument list.
214class TemplateArgumentList final
215 : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
216 /// The template argument list.
217 const TemplateArgument *Arguments;
218
219 /// The number of template arguments in this template
220 /// argument list.
221 unsigned NumArguments;
222
223 // Constructs an instance with an internal Argument list, containing
224 // a copy of the Args array. (Called by CreateCopy)
225 TemplateArgumentList(ArrayRef<TemplateArgument> Args);
226
227public:
228 friend TrailingObjects;
229
230 TemplateArgumentList(const TemplateArgumentList &) = delete;
231 TemplateArgumentList &operator=(const TemplateArgumentList &) = delete;
232
233 /// Type used to indicate that the template argument list itself is a
234 /// stack object. It does not own its template arguments.
235 enum OnStackType { OnStack };
236
237 /// Create a new template argument list that copies the given set of
238 /// template arguments.
239 static TemplateArgumentList *CreateCopy(ASTContext &Context,
240 ArrayRef<TemplateArgument> Args);
241
242 /// Construct a new, temporary template argument list on the stack.
243 ///
244 /// The template argument list does not own the template arguments
245 /// provided.
246 explicit TemplateArgumentList(OnStackType, ArrayRef<TemplateArgument> Args)
247 : Arguments(Args.data()), NumArguments(Args.size()) {}
248
249 /// Produces a shallow copy of the given template argument list.
250 ///
251 /// This operation assumes that the input argument list outlives it.
252 /// This takes the list as a pointer to avoid looking like a copy
253 /// constructor, since this really really isn't safe to use that
254 /// way.
255 explicit TemplateArgumentList(const TemplateArgumentList *Other)
256 : Arguments(Other->data()), NumArguments(Other->size()) {}
257
258 /// Retrieve the template argument at a given index.
259 const TemplateArgument &get(unsigned Idx) const {
260 assert(Idx < NumArguments && "Invalid template argument index")((Idx < NumArguments && "Invalid template argument index"
) ? static_cast<void> (0) : __assert_fail ("Idx < NumArguments && \"Invalid template argument index\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 260, __PRETTY_FUNCTION__))
;
261 return data()[Idx];
262 }
263
264 /// Retrieve the template argument at a given index.
265 const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
266
267 /// Produce this as an array ref.
268 ArrayRef<TemplateArgument> asArray() const {
269 return llvm::makeArrayRef(data(), size());
270 }
271
272 /// Retrieve the number of template arguments in this
273 /// template argument list.
274 unsigned size() const { return NumArguments; }
275
276 /// Retrieve a pointer to the template argument list.
277 const TemplateArgument *data() const { return Arguments; }
278};
279
280void *allocateDefaultArgStorageChain(const ASTContext &C);
281
282/// Storage for a default argument. This is conceptually either empty, or an
283/// argument value, or a pointer to a previous declaration that had a default
284/// argument.
285///
286/// However, this is complicated by modules: while we require all the default
287/// arguments for a template to be equivalent, there may be more than one, and
288/// we need to track all the originating parameters to determine if the default
289/// argument is visible.
290template<typename ParmDecl, typename ArgType>
291class DefaultArgStorage {
292 /// Storage for both the value *and* another parameter from which we inherit
293 /// the default argument. This is used when multiple default arguments for a
294 /// parameter are merged together from different modules.
295 struct Chain {
296 ParmDecl *PrevDeclWithDefaultArg;
297 ArgType Value;
298 };
299 static_assert(sizeof(Chain) == sizeof(void *) * 2,
300 "non-pointer argument type?");
301
302 llvm::PointerUnion3<ArgType, ParmDecl*, Chain*> ValueOrInherited;
303
304 static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
305 const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
306 if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl *>())
307 Parm = Prev;
308 assert(!Parm->getDefaultArgStorage()((!Parm->getDefaultArgStorage() .ValueOrInherited.template
is<ParmDecl *>() && "should only be one level of indirection"
) ? static_cast<void> (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 310, __PRETTY_FUNCTION__))
309 .ValueOrInherited.template is<ParmDecl *>() &&((!Parm->getDefaultArgStorage() .ValueOrInherited.template
is<ParmDecl *>() && "should only be one level of indirection"
) ? static_cast<void> (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 310, __PRETTY_FUNCTION__))
310 "should only be one level of indirection")((!Parm->getDefaultArgStorage() .ValueOrInherited.template
is<ParmDecl *>() && "should only be one level of indirection"
) ? static_cast<void> (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 310, __PRETTY_FUNCTION__))
;
311 return Parm;
312 }
313
314public:
315 DefaultArgStorage() : ValueOrInherited(ArgType()) {}
316
317 /// Determine whether there is a default argument for this parameter.
318 bool isSet() const { return !ValueOrInherited.isNull(); }
319
320 /// Determine whether the default argument for this parameter was inherited
321 /// from a previous declaration of the same entity.
322 bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
323
324 /// Get the default argument's value. This does not consider whether the
325 /// default argument is visible.
326 ArgType get() const {
327 const DefaultArgStorage *Storage = this;
328 if (const auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl *>())
329 Storage = &Prev->getDefaultArgStorage();
330 if (const auto *C = Storage->ValueOrInherited.template dyn_cast<Chain *>())
331 return C->Value;
332 return Storage->ValueOrInherited.template get<ArgType>();
333 }
334
335 /// Get the parameter from which we inherit the default argument, if any.
336 /// This is the parameter on which the default argument was actually written.
337 const ParmDecl *getInheritedFrom() const {
338 if (const auto *D = ValueOrInherited.template dyn_cast<ParmDecl *>())
339 return D;
340 if (const auto *C = ValueOrInherited.template dyn_cast<Chain *>())
341 return C->PrevDeclWithDefaultArg;
342 return nullptr;
343 }
344
345 /// Set the default argument.
346 void set(ArgType Arg) {
347 assert(!isSet() && "default argument already set")((!isSet() && "default argument already set") ? static_cast
<void> (0) : __assert_fail ("!isSet() && \"default argument already set\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 347, __PRETTY_FUNCTION__))
;
348 ValueOrInherited = Arg;
349 }
350
351 /// Set that the default argument was inherited from another parameter.
352 void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
353 assert(!isInherited() && "default argument already inherited")((!isInherited() && "default argument already inherited"
) ? static_cast<void> (0) : __assert_fail ("!isInherited() && \"default argument already inherited\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 353, __PRETTY_FUNCTION__))
;
354 InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
355 if (!isSet())
356 ValueOrInherited = InheritedFrom;
357 else
358 ValueOrInherited = new (allocateDefaultArgStorageChain(C))
359 Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
360 }
361
362 /// Remove the default argument, even if it was inherited.
363 void clear() {
364 ValueOrInherited = ArgType();
365 }
366};
367
368//===----------------------------------------------------------------------===//
369// Kinds of Templates
370//===----------------------------------------------------------------------===//
371
372/// Stores the template parameter list and associated constraints for
373/// \c TemplateDecl objects that track associated constraints.
374class ConstrainedTemplateDeclInfo {
375 friend TemplateDecl;
376
377public:
378 ConstrainedTemplateDeclInfo() = default;
379
380 TemplateParameterList *getTemplateParameters() const {
381 return TemplateParams;
382 }
383
384 Expr *getAssociatedConstraints() const { return AssociatedConstraints; }
385
386protected:
387 void setTemplateParameters(TemplateParameterList *TParams) {
388 TemplateParams = TParams;
389 }
390
391 void setAssociatedConstraints(Expr *AC) { AssociatedConstraints = AC; }
392
393 TemplateParameterList *TemplateParams = nullptr;
394 Expr *AssociatedConstraints = nullptr;
395};
396
397
398/// The base class of all kinds of template declarations (e.g.,
399/// class, function, etc.).
400///
401/// The TemplateDecl class stores the list of template parameters and a
402/// reference to the templated scoped declaration: the underlying AST node.
403class TemplateDecl : public NamedDecl {
404 void anchor() override;
405
406protected:
407 // Construct a template decl with the given name and parameters.
408 // Used when there is no templated element (e.g., for tt-params).
409 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
410 SourceLocation L, DeclarationName Name,
411 TemplateParameterList *Params)
412 : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
413 TemplateParams(CTDI) {
414 this->setTemplateParameters(Params);
415 }
416
417 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
418 TemplateParameterList *Params)
419 : TemplateDecl(nullptr, DK, DC, L, Name, Params) {}
420
421 // Construct a template decl with name, parameters, and templated element.
422 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
423 SourceLocation L, DeclarationName Name,
424 TemplateParameterList *Params, NamedDecl *Decl)
425 : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
426 TemplateParams(CTDI) {
427 this->setTemplateParameters(Params);
428 }
429
430 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
431 TemplateParameterList *Params, NamedDecl *Decl)
432 : TemplateDecl(nullptr, DK, DC, L, Name, Params, Decl) {}
433
434public:
435 /// Get the list of template parameters
436 TemplateParameterList *getTemplateParameters() const {
437 const auto *const CTDI =
438 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
439 return CTDI ? CTDI->getTemplateParameters()
440 : TemplateParams.get<TemplateParameterList *>();
441 }
442
443 /// Get the constraint-expression from the associated requires-clause (if any)
444 const Expr *getRequiresClause() const {
445 const TemplateParameterList *const TP = getTemplateParameters();
446 return TP ? TP->getRequiresClause() : nullptr;
447 }
448
449 Expr *getAssociatedConstraints() const {
450 const auto *const C = cast<TemplateDecl>(getCanonicalDecl());
451 const auto *const CTDI =
452 C->TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
453 return CTDI ? CTDI->getAssociatedConstraints() : nullptr;
454 }
455
456 /// Get the underlying, templated declaration.
457 NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
458
459 // Implement isa/cast/dyncast/etc.
460 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
461
462 static bool classofKind(Kind K) {
463 return K >= firstTemplate && K <= lastTemplate;
464 }
465
466 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
467 return SourceRange(getTemplateParameters()->getTemplateLoc(),
468 TemplatedDecl->getSourceRange().getEnd());
469 }
470
471protected:
472 NamedDecl *TemplatedDecl;
473
474 /// The template parameter list and optional requires-clause
475 /// associated with this declaration; alternatively, a
476 /// \c ConstrainedTemplateDeclInfo if the associated constraints of the
477 /// template are being tracked by this particular declaration.
478 llvm::PointerUnion<TemplateParameterList *,
479 ConstrainedTemplateDeclInfo *>
480 TemplateParams;
481
482 void setTemplateParameters(TemplateParameterList *TParams) {
483 if (auto *const CTDI =
484 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>()) {
485 CTDI->setTemplateParameters(TParams);
486 } else {
487 TemplateParams = TParams;
488 }
489 }
490
491 void setAssociatedConstraints(Expr *AC) {
492 assert(isCanonicalDecl() &&((isCanonicalDecl() && "Attaching associated constraints to non-canonical Decl"
) ? static_cast<void> (0) : __assert_fail ("isCanonicalDecl() && \"Attaching associated constraints to non-canonical Decl\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 493, __PRETTY_FUNCTION__))
493 "Attaching associated constraints to non-canonical Decl")((isCanonicalDecl() && "Attaching associated constraints to non-canonical Decl"
) ? static_cast<void> (0) : __assert_fail ("isCanonicalDecl() && \"Attaching associated constraints to non-canonical Decl\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 493, __PRETTY_FUNCTION__))
;
494 TemplateParams.get<ConstrainedTemplateDeclInfo *>()
495 ->setAssociatedConstraints(AC);
496 }
497
498public:
499 /// Initialize the underlying templated declaration and
500 /// template parameters.
501 void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
502 assert(!TemplatedDecl && "TemplatedDecl already set!")((!TemplatedDecl && "TemplatedDecl already set!") ? static_cast
<void> (0) : __assert_fail ("!TemplatedDecl && \"TemplatedDecl already set!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 502, __PRETTY_FUNCTION__))
;
503 assert(!TemplateParams && "TemplateParams already set!")((!TemplateParams && "TemplateParams already set!") ?
static_cast<void> (0) : __assert_fail ("!TemplateParams && \"TemplateParams already set!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 503, __PRETTY_FUNCTION__))
;
504 TemplatedDecl = templatedDecl;
505 TemplateParams = templateParams;
506 }
507};
508
509/// Provides information about a function template specialization,
510/// which is a FunctionDecl that has been explicitly specialization or
511/// instantiated from a function template.
512class FunctionTemplateSpecializationInfo final
513 : public llvm::FoldingSetNode,
514 private llvm::TrailingObjects<FunctionTemplateSpecializationInfo,
515 MemberSpecializationInfo *> {
516 /// The function template specialization that this structure describes and a
517 /// flag indicating if the function is a member specialization.
518 llvm::PointerIntPair<FunctionDecl *, 1, bool> Function;
519
520 /// The function template from which this function template
521 /// specialization was generated.
522 ///
523 /// The two bits contain the top 4 values of TemplateSpecializationKind.
524 llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
525
526public:
527 /// The template arguments used to produce the function template
528 /// specialization from the function template.
529 const TemplateArgumentList *TemplateArguments;
530
531 /// The template arguments as written in the sources, if provided.
532 /// FIXME: Normally null; tail-allocate this.
533 const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
534
535 /// The point at which this function template specialization was
536 /// first instantiated.
537 SourceLocation PointOfInstantiation;
538
539private:
540 FunctionTemplateSpecializationInfo(
541 FunctionDecl *FD, FunctionTemplateDecl *Template,
542 TemplateSpecializationKind TSK, const TemplateArgumentList *TemplateArgs,
543 const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
544 SourceLocation POI, MemberSpecializationInfo *MSInfo)
545 : Function(FD, MSInfo ? 1 : 0), Template(Template, TSK - 1),
546 TemplateArguments(TemplateArgs),
547 TemplateArgumentsAsWritten(TemplateArgsAsWritten),
548 PointOfInstantiation(POI) {
549 if (MSInfo)
550 getTrailingObjects<MemberSpecializationInfo *>()[0] = MSInfo;
551 }
552
553 size_t numTrailingObjects(OverloadToken<MemberSpecializationInfo*>) const {
554 return Function.getInt();
555 }
556
557public:
558 friend TrailingObjects;
559
560 static FunctionTemplateSpecializationInfo *
561 Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
562 TemplateSpecializationKind TSK,
563 const TemplateArgumentList *TemplateArgs,
564 const TemplateArgumentListInfo *TemplateArgsAsWritten,
565 SourceLocation POI, MemberSpecializationInfo *MSInfo);
566
567 /// Retrieve the declaration of the function template specialization.
568 FunctionDecl *getFunction() const { return Function.getPointer(); }
569
570 /// Retrieve the template from which this function was specialized.
571 FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
572
573 /// Determine what kind of template specialization this is.
574 TemplateSpecializationKind getTemplateSpecializationKind() const {
575 return (TemplateSpecializationKind)(Template.getInt() + 1);
576 }
577
578 bool isExplicitSpecialization() const {
579 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
580 }
581
582 /// True if this declaration is an explicit specialization,
583 /// explicit instantiation declaration, or explicit instantiation
584 /// definition.
585 bool isExplicitInstantiationOrSpecialization() const {
586 return isTemplateExplicitInstantiationOrSpecialization(
587 getTemplateSpecializationKind());
588 }
589
590 /// Set the template specialization kind.
591 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
592 assert(TSK != TSK_Undeclared &&((TSK != TSK_Undeclared && "Cannot encode TSK_Undeclared for a function template specialization"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode TSK_Undeclared for a function template specialization\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 593, __PRETTY_FUNCTION__))
593 "Cannot encode TSK_Undeclared for a function template specialization")((TSK != TSK_Undeclared && "Cannot encode TSK_Undeclared for a function template specialization"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode TSK_Undeclared for a function template specialization\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 593, __PRETTY_FUNCTION__))
;
594 Template.setInt(TSK - 1);
595 }
596
597 /// Retrieve the first point of instantiation of this function
598 /// template specialization.
599 ///
600 /// The point of instantiation may be an invalid source location if this
601 /// function has yet to be instantiated.
602 SourceLocation getPointOfInstantiation() const {
603 return PointOfInstantiation;
604 }
605
606 /// Set the (first) point of instantiation of this function template
607 /// specialization.
608 void setPointOfInstantiation(SourceLocation POI) {
609 PointOfInstantiation = POI;
610 }
611
612 /// Get the specialization info if this function template specialization is
613 /// also a member specialization:
614 ///
615 /// \code
616 /// template<typename> struct A {
617 /// template<typename> void f();
618 /// template<> void f<int>(); // ClassScopeFunctionSpecializationDecl
619 /// };
620 /// \endcode
621 ///
622 /// Here, A<int>::f<int> is a function template specialization that is
623 /// an explicit specialization of A<int>::f, but it's also a member
624 /// specialization (an implicit instantiation in this case) of A::f<int>.
625 /// Further:
626 ///
627 /// \code
628 /// template<> template<> void A<int>::f<int>() {}
629 /// \endcode
630 ///
631 /// ... declares a function template specialization that is an explicit
632 /// specialization of A<int>::f, and is also an explicit member
633 /// specialization of A::f<int>.
634 ///
635 /// Note that the TemplateSpecializationKind of the MemberSpecializationInfo
636 /// need not be the same as that returned by getTemplateSpecializationKind(),
637 /// and represents the relationship between the function and the class-scope
638 /// explicit specialization in the original templated class -- whereas our
639 /// TemplateSpecializationKind represents the relationship between the
640 /// function and the function template, and should always be
641 /// TSK_ExplicitSpecialization whenever we have MemberSpecializationInfo.
642 MemberSpecializationInfo *getMemberSpecializationInfo() const {
643 return numTrailingObjects(OverloadToken<MemberSpecializationInfo *>())
644 ? getTrailingObjects<MemberSpecializationInfo *>()[0]
645 : nullptr;
646 }
647
648 void Profile(llvm::FoldingSetNodeID &ID) {
649 Profile(ID, TemplateArguments->asArray(), getFunction()->getASTContext());
650 }
651
652 static void
653 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
654 ASTContext &Context) {
655 ID.AddInteger(TemplateArgs.size());
656 for (const TemplateArgument &TemplateArg : TemplateArgs)
657 TemplateArg.Profile(ID, Context);
658 }
659};
660
661/// Provides information a specialization of a member of a class
662/// template, which may be a member function, static data member,
663/// member class or member enumeration.
664class MemberSpecializationInfo {
665 // The member declaration from which this member was instantiated, and the
666 // manner in which the instantiation occurred (in the lower two bits).
667 llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
668
669 // The point at which this member was first instantiated.
670 SourceLocation PointOfInstantiation;
671
672public:
673 explicit
674 MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
675 SourceLocation POI = SourceLocation())
676 : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
677 assert(TSK != TSK_Undeclared &&((TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 678, __PRETTY_FUNCTION__))
678 "Cannot encode undeclared template specializations for members")((TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 678, __PRETTY_FUNCTION__))
;
679 }
680
681 /// Retrieve the member declaration from which this member was
682 /// instantiated.
683 NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
684
685 /// Determine what kind of template specialization this is.
686 TemplateSpecializationKind getTemplateSpecializationKind() const {
687 return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
688 }
689
690 bool isExplicitSpecialization() const {
691 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
692 }
693
694 /// Set the template specialization kind.
695 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
696 assert(TSK != TSK_Undeclared &&((TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 697, __PRETTY_FUNCTION__))
697 "Cannot encode undeclared template specializations for members")((TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 697, __PRETTY_FUNCTION__))
;
698 MemberAndTSK.setInt(TSK - 1);
699 }
700
701 /// Retrieve the first point of instantiation of this member.
702 /// If the point of instantiation is an invalid location, then this member
703 /// has not yet been instantiated.
704 SourceLocation getPointOfInstantiation() const {
705 return PointOfInstantiation;
706 }
707
708 /// Set the first point of instantiation.
709 void setPointOfInstantiation(SourceLocation POI) {
710 PointOfInstantiation = POI;
711 }
712};
713
714/// Provides information about a dependent function-template
715/// specialization declaration.
716///
717/// Since explicit function template specialization and instantiation
718/// declarations can only appear in namespace scope, and you can only
719/// specialize a member of a fully-specialized class, the only way to
720/// get one of these is in a friend declaration like the following:
721///
722/// \code
723/// template \<class T> void foo(T);
724/// template \<class T> class A {
725/// friend void foo<>(T);
726/// };
727/// \endcode
728class DependentFunctionTemplateSpecializationInfo final
729 : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
730 TemplateArgumentLoc,
731 FunctionTemplateDecl *> {
732 /// The number of potential template candidates.
733 unsigned NumTemplates;
734
735 /// The number of template arguments.
736 unsigned NumArgs;
737
738 /// The locations of the left and right angle brackets.
739 SourceRange AngleLocs;
740
741 size_t numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
742 return NumArgs;
743 }
744 size_t numTrailingObjects(OverloadToken<FunctionTemplateDecl *>) const {
745 return NumTemplates;
746 }
747
748 DependentFunctionTemplateSpecializationInfo(
749 const UnresolvedSetImpl &Templates,
750 const TemplateArgumentListInfo &TemplateArgs);
751
752public:
753 friend TrailingObjects;
754
755 static DependentFunctionTemplateSpecializationInfo *
756 Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
757 const TemplateArgumentListInfo &TemplateArgs);
758
759 /// Returns the number of function templates that this might
760 /// be a specialization of.
761 unsigned getNumTemplates() const { return NumTemplates; }
762
763 /// Returns the i'th template candidate.
764 FunctionTemplateDecl *getTemplate(unsigned I) const {
765 assert(I < getNumTemplates() && "template index out of range")((I < getNumTemplates() && "template index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumTemplates() && \"template index out of range\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 765, __PRETTY_FUNCTION__))
;
766 return getTrailingObjects<FunctionTemplateDecl *>()[I];
767 }
768
769 /// Returns the explicit template arguments that were given.
770 const TemplateArgumentLoc *getTemplateArgs() const {
771 return getTrailingObjects<TemplateArgumentLoc>();
772 }
773
774 /// Returns the number of explicit template arguments that were given.
775 unsigned getNumTemplateArgs() const { return NumArgs; }
776
777 /// Returns the nth template argument.
778 const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
779 assert(I < getNumTemplateArgs() && "template arg index out of range")((I < getNumTemplateArgs() && "template arg index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumTemplateArgs() && \"template arg index out of range\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 779, __PRETTY_FUNCTION__))
;
780 return getTemplateArgs()[I];
781 }
782
783 SourceLocation getLAngleLoc() const {
784 return AngleLocs.getBegin();
785 }
786
787 SourceLocation getRAngleLoc() const {
788 return AngleLocs.getEnd();
789 }
790};
791
792/// Declaration of a redeclarable template.
793class RedeclarableTemplateDecl : public TemplateDecl,
794 public Redeclarable<RedeclarableTemplateDecl>
795{
796 using redeclarable_base = Redeclarable<RedeclarableTemplateDecl>;
797
798 RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
799 return getNextRedeclaration();
800 }
801
802 RedeclarableTemplateDecl *getPreviousDeclImpl() override {
803 return getPreviousDecl();
804 }
805
806 RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
807 return getMostRecentDecl();
808 }
809
810 void anchor() override;
811protected:
812 template <typename EntryType> struct SpecEntryTraits {
813 using DeclType = EntryType;
814
815 static DeclType *getDecl(EntryType *D) {
816 return D;
817 }
818
819 static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
820 return D->getTemplateArgs().asArray();
821 }
822 };
823
824 template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
825 typename DeclType = typename SETraits::DeclType>
826 struct SpecIterator
827 : llvm::iterator_adaptor_base<
828 SpecIterator<EntryType, SETraits, DeclType>,
829 typename llvm::FoldingSetVector<EntryType>::iterator,
830 typename std::iterator_traits<typename llvm::FoldingSetVector<
831 EntryType>::iterator>::iterator_category,
832 DeclType *, ptrdiff_t, DeclType *, DeclType *> {
833 SpecIterator() = default;
834 explicit SpecIterator(
835 typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
836 : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
837
838 DeclType *operator*() const {
839 return SETraits::getDecl(&*this->I)->getMostRecentDecl();
840 }
841
842 DeclType *operator->() const { return **this; }
843 };
844
845 template <typename EntryType>
846 static SpecIterator<EntryType>
847 makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
848 return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
849 }
850
851 void loadLazySpecializationsImpl() const;
852
853 template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
854 findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
855 ArrayRef<TemplateArgument> Args, void *&InsertPos);
856
857 template <class Derived, class EntryType>
858 void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
859 EntryType *Entry, void *InsertPos);
860
861 struct CommonBase {
862 CommonBase() : InstantiatedFromMember(nullptr, false) {}
863
864 /// The template from which this was most
865 /// directly instantiated (or null).
866 ///
867 /// The boolean value indicates whether this template
868 /// was explicitly specialized.
869 llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
870 InstantiatedFromMember;
871
872 /// If non-null, points to an array of specializations (including
873 /// partial specializations) known only by their external declaration IDs.
874 ///
875 /// The first value in the array is the number of specializations/partial
876 /// specializations that follow.
877 uint32_t *LazySpecializations = nullptr;
878 };
879
880 /// Pointer to the common data shared by all declarations of this
881 /// template.
882 mutable CommonBase *Common = nullptr;
883
884 /// Retrieves the "common" pointer shared by all (re-)declarations of
885 /// the same template. Calling this routine may implicitly allocate memory
886 /// for the common pointer.
887 CommonBase *getCommonPtr() const;
888
889 virtual CommonBase *newCommon(ASTContext &C) const = 0;
890
891 // Construct a template decl with name, parameters, and templated element.
892 RedeclarableTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK,
893 ASTContext &C, DeclContext *DC, SourceLocation L,
894 DeclarationName Name, TemplateParameterList *Params,
895 NamedDecl *Decl)
896 : TemplateDecl(CTDI, DK, DC, L, Name, Params, Decl), redeclarable_base(C)
897 {}
898
899 RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
900 SourceLocation L, DeclarationName Name,
901 TemplateParameterList *Params, NamedDecl *Decl)
902 : RedeclarableTemplateDecl(nullptr, DK, C, DC, L, Name, Params, Decl) {}
903
904public:
905 friend class ASTDeclReader;
906 friend class ASTDeclWriter;
907 friend class ASTReader;
908 template <class decl_type> friend class RedeclarableTemplate;
909
910 /// Retrieves the canonical declaration of this template.
911 RedeclarableTemplateDecl *getCanonicalDecl() override {
912 return getFirstDecl();
913 }
914 const RedeclarableTemplateDecl *getCanonicalDecl() const {
915 return getFirstDecl();
916 }
917
918 /// Determines whether this template was a specialization of a
919 /// member template.
920 ///
921 /// In the following example, the function template \c X<int>::f and the
922 /// member template \c X<int>::Inner are member specializations.
923 ///
924 /// \code
925 /// template<typename T>
926 /// struct X {
927 /// template<typename U> void f(T, U);
928 /// template<typename U> struct Inner;
929 /// };
930 ///
931 /// template<> template<typename T>
932 /// void X<int>::f(int, T);
933 /// template<> template<typename T>
934 /// struct X<int>::Inner { /* ... */ };
935 /// \endcode
936 bool isMemberSpecialization() const {
937 return getCommonPtr()->InstantiatedFromMember.getInt();
938 }
939
940 /// Note that this member template is a specialization.
941 void setMemberSpecialization() {
942 assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&((getCommonPtr()->InstantiatedFromMember.getPointer() &&
"Only member templates can be member template specializations"
) ? static_cast<void> (0) : __assert_fail ("getCommonPtr()->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 943, __PRETTY_FUNCTION__))
943 "Only member templates can be member template specializations")((getCommonPtr()->InstantiatedFromMember.getPointer() &&
"Only member templates can be member template specializations"
) ? static_cast<void> (0) : __assert_fail ("getCommonPtr()->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 943, __PRETTY_FUNCTION__))
;
944 getCommonPtr()->InstantiatedFromMember.setInt(true);
945 }
946
947 /// Retrieve the member template from which this template was
948 /// instantiated, or nullptr if this template was not instantiated from a
949 /// member template.
950 ///
951 /// A template is instantiated from a member template when the member
952 /// template itself is part of a class template (or member thereof). For
953 /// example, given
954 ///
955 /// \code
956 /// template<typename T>
957 /// struct X {
958 /// template<typename U> void f(T, U);
959 /// };
960 ///
961 /// void test(X<int> x) {
962 /// x.f(1, 'a');
963 /// };
964 /// \endcode
965 ///
966 /// \c X<int>::f is a FunctionTemplateDecl that describes the function
967 /// template
968 ///
969 /// \code
970 /// template<typename U> void X<int>::f(int, U);
971 /// \endcode
972 ///
973 /// which was itself created during the instantiation of \c X<int>. Calling
974 /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
975 /// retrieve the FunctionTemplateDecl for the original template \c f within
976 /// the class template \c X<T>, i.e.,
977 ///
978 /// \code
979 /// template<typename T>
980 /// template<typename U>
981 /// void X<T>::f(T, U);
982 /// \endcode
983 RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
984 return getCommonPtr()->InstantiatedFromMember.getPointer();
985 }
986
987 void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
988 assert(!getCommonPtr()->InstantiatedFromMember.getPointer())((!getCommonPtr()->InstantiatedFromMember.getPointer()) ? static_cast
<void> (0) : __assert_fail ("!getCommonPtr()->InstantiatedFromMember.getPointer()"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 988, __PRETTY_FUNCTION__))
;
989 getCommonPtr()->InstantiatedFromMember.setPointer(TD);
990 }
991
992 using redecl_range = redeclarable_base::redecl_range;
993 using redecl_iterator = redeclarable_base::redecl_iterator;
994
995 using redeclarable_base::redecls_begin;
996 using redeclarable_base::redecls_end;
997 using redeclarable_base::redecls;
998 using redeclarable_base::getPreviousDecl;
999 using redeclarable_base::getMostRecentDecl;
1000 using redeclarable_base::isFirstDecl;
1001
1002 // Implement isa/cast/dyncast/etc.
1003 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1004
1005 static bool classofKind(Kind K) {
1006 return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
1007 }
1008};
1009
1010template <> struct RedeclarableTemplateDecl::
1011SpecEntryTraits<FunctionTemplateSpecializationInfo> {
1012 using DeclType = FunctionDecl;
1013
1014 static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
1015 return I->getFunction();
1016 }
1017
1018 static ArrayRef<TemplateArgument>
1019 getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
1020 return I->TemplateArguments->asArray();
1021 }
1022};
1023
1024/// Declaration of a template function.
1025class FunctionTemplateDecl : public RedeclarableTemplateDecl {
1026protected:
1027 friend class FunctionDecl;
1028
1029 /// Data that is common to all of the declarations of a given
1030 /// function template.
1031 struct Common : CommonBase {
1032 /// The function template specializations for this function
1033 /// template, including explicit specializations and instantiations.
1034 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
1035
1036 /// The set of "injected" template arguments used within this
1037 /// function template.
1038 ///
1039 /// This pointer refers to the template arguments (there are as
1040 /// many template arguments as template parameaters) for the function
1041 /// template, and is allocated lazily, since most function templates do not
1042 /// require the use of this information.
1043 TemplateArgument *InjectedArgs = nullptr;
1044
1045 Common() = default;
1046 };
1047
1048 FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
1049 DeclarationName Name, TemplateParameterList *Params,
1050 NamedDecl *Decl)
1051 : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
1052 Decl) {}
1053
1054 CommonBase *newCommon(ASTContext &C) const override;
1055
1056 Common *getCommonPtr() const {
1057 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
1058 }
1059
1060 /// Retrieve the set of function template specializations of this
1061 /// function template.
1062 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
1063 getSpecializations() const;
1064
1065 /// Add a specialization of this function template.
1066 ///
1067 /// \param InsertPos Insert position in the FoldingSetVector, must have been
1068 /// retrieved by an earlier call to findSpecialization().
1069 void addSpecialization(FunctionTemplateSpecializationInfo* Info,
1070 void *InsertPos);
1071
1072public:
1073 friend class ASTDeclReader;
1074 friend class ASTDeclWriter;
1075
1076 /// Load any lazily-loaded specializations from the external source.
1077 void LoadLazySpecializations() const;
1078
1079 /// Get the underlying function declaration of the template.
1080 FunctionDecl *getTemplatedDecl() const {
1081 return static_cast<FunctionDecl *>(TemplatedDecl);
1082 }
1083
1084 /// Returns whether this template declaration defines the primary
1085 /// pattern.
1086 bool isThisDeclarationADefinition() const {
1087 return getTemplatedDecl()->isThisDeclarationADefinition();
1088 }
1089
1090 /// Return the specialization with the provided arguments if it exists,
1091 /// otherwise return the insertion point.
1092 FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
1093 void *&InsertPos);
1094
1095 FunctionTemplateDecl *getCanonicalDecl() override {
1096 return cast<FunctionTemplateDecl>(
1097 RedeclarableTemplateDecl::getCanonicalDecl());
1098 }
1099 const FunctionTemplateDecl *getCanonicalDecl() const {
1100 return cast<FunctionTemplateDecl>(
1101 RedeclarableTemplateDecl::getCanonicalDecl());
1102 }
1103
1104 /// Retrieve the previous declaration of this function template, or
1105 /// nullptr if no such declaration exists.
1106 FunctionTemplateDecl *getPreviousDecl() {
1107 return cast_or_null<FunctionTemplateDecl>(
1108 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1109 }
1110 const FunctionTemplateDecl *getPreviousDecl() const {
1111 return cast_or_null<FunctionTemplateDecl>(
1112 static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1113 }
1114
1115 FunctionTemplateDecl *getMostRecentDecl() {
1116 return cast<FunctionTemplateDecl>(
1117 static_cast<RedeclarableTemplateDecl *>(this)
1118 ->getMostRecentDecl());
1119 }
1120 const FunctionTemplateDecl *getMostRecentDecl() const {
1121 return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
1122 }
1123
1124 FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
1125 return cast_or_null<FunctionTemplateDecl>(
1126 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1127 }
1128
1129 using spec_iterator = SpecIterator<FunctionTemplateSpecializationInfo>;
1130 using spec_range = llvm::iterator_range<spec_iterator>;
1131
1132 spec_range specializations() const {
1133 return spec_range(spec_begin(), spec_end());
1134 }
1135
1136 spec_iterator spec_begin() const {
1137 return makeSpecIterator(getSpecializations(), false);
1138 }
1139
1140 spec_iterator spec_end() const {
1141 return makeSpecIterator(getSpecializations(), true);
1142 }
1143
1144 /// Retrieve the "injected" template arguments that correspond to the
1145 /// template parameters of this function template.
1146 ///
1147 /// Although the C++ standard has no notion of the "injected" template
1148 /// arguments for a function template, the notion is convenient when
1149 /// we need to perform substitutions inside the definition of a function
1150 /// template.
1151 ArrayRef<TemplateArgument> getInjectedTemplateArgs();
1152
1153 /// Merge \p Prev with our RedeclarableTemplateDecl::Common.
1154 void mergePrevDecl(FunctionTemplateDecl *Prev);
1155
1156 /// Create a function template node.
1157 static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1158 SourceLocation L,
1159 DeclarationName Name,
1160 TemplateParameterList *Params,
1161 NamedDecl *Decl);
1162
1163 /// Create an empty function template node.
1164 static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1165
1166 // Implement isa/cast/dyncast support
1167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1168 static bool classofKind(Kind K) { return K == FunctionTemplate; }
1169};
1170
1171//===----------------------------------------------------------------------===//
1172// Kinds of Template Parameters
1173//===----------------------------------------------------------------------===//
1174
1175/// Defines the position of a template parameter within a template
1176/// parameter list.
1177///
1178/// Because template parameter can be listed
1179/// sequentially for out-of-line template members, each template parameter is
1180/// given a Depth - the nesting of template parameter scopes - and a Position -
1181/// the occurrence within the parameter list.
1182/// This class is inheritedly privately by different kinds of template
1183/// parameters and is not part of the Decl hierarchy. Just a facility.
1184class TemplateParmPosition {
1185protected:
1186 // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
1187 // position? Maybe?
1188 unsigned Depth;
1189 unsigned Position;
1190
1191 TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {}
1192
1193public:
1194 TemplateParmPosition() = delete;
1195
1196 /// Get the nesting depth of the template parameter.
1197 unsigned getDepth() const { return Depth; }
1198 void setDepth(unsigned D) { Depth = D; }
1199
1200 /// Get the position of the template parameter within its parameter list.
1201 unsigned getPosition() const { return Position; }
1202 void setPosition(unsigned P) { Position = P; }
1203
1204 /// Get the index of the template parameter within its parameter list.
1205 unsigned getIndex() const { return Position; }
1206};
1207
1208/// Declaration of a template type parameter.
1209///
1210/// For example, "T" in
1211/// \code
1212/// template<typename T> class vector;
1213/// \endcode
1214class TemplateTypeParmDecl : public TypeDecl {
1215 /// Sema creates these on the stack during auto type deduction.
1216 friend class Sema;
1217
1218 /// Whether this template type parameter was declaration with
1219 /// the 'typename' keyword.
1220 ///
1221 /// If false, it was declared with the 'class' keyword.
1222 bool Typename : 1;
1223
1224 /// The default template argument, if any.
1225 using DefArgStorage =
1226 DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>;
1227 DefArgStorage DefaultArgument;
1228
1229 TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
1230 SourceLocation IdLoc, IdentifierInfo *Id,
1231 bool Typename)
1232 : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename) {}
1233
1234public:
1235 static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
1236 SourceLocation KeyLoc,
1237 SourceLocation NameLoc,
1238 unsigned D, unsigned P,
1239 IdentifierInfo *Id, bool Typename,
1240 bool ParameterPack);
1241 static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
1242 unsigned ID);
1243
1244 /// Whether this template type parameter was declared with
1245 /// the 'typename' keyword.
1246 ///
1247 /// If not, it was declared with the 'class' keyword.
1248 bool wasDeclaredWithTypename() const { return Typename; }
1249
1250 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1251
1252 /// Determine whether this template parameter has a default
1253 /// argument.
1254 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1255
1256 /// Retrieve the default argument, if any.
1257 QualType getDefaultArgument() const {
1258 return DefaultArgument.get()->getType();
1259 }
1260
1261 /// Retrieves the default argument's source information, if any.
1262 TypeSourceInfo *getDefaultArgumentInfo() const {
1263 return DefaultArgument.get();
1264 }
1265
1266 /// Retrieves the location of the default argument declaration.
1267 SourceLocation getDefaultArgumentLoc() const;
1268
1269 /// Determines whether the default argument was inherited
1270 /// from a previous declaration of this template.
1271 bool defaultArgumentWasInherited() const {
1272 return DefaultArgument.isInherited();
1273 }
1274
1275 /// Set the default argument for this template parameter.
1276 void setDefaultArgument(TypeSourceInfo *DefArg) {
1277 DefaultArgument.set(DefArg);
1278 }
1279
1280 /// Set that this default argument was inherited from another
1281 /// parameter.
1282 void setInheritedDefaultArgument(const ASTContext &C,
1283 TemplateTypeParmDecl *Prev) {
1284 DefaultArgument.setInherited(C, Prev);
1285 }
1286
1287 /// Removes the default argument of this template parameter.
1288 void removeDefaultArgument() {
1289 DefaultArgument.clear();
1290 }
1291
1292 /// Set whether this template type parameter was declared with
1293 /// the 'typename' or 'class' keyword.
1294 void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
1295
1296 /// Retrieve the depth of the template parameter.
1297 unsigned getDepth() const;
1298
1299 /// Retrieve the index of the template parameter.
1300 unsigned getIndex() const;
1301
1302 /// Returns whether this is a parameter pack.
1303 bool isParameterPack() const;
1304
1305 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1306
1307 // Implement isa/cast/dyncast/etc.
1308 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1309 static bool classofKind(Kind K) { return K == TemplateTypeParm; }
1310};
1311
1312/// NonTypeTemplateParmDecl - Declares a non-type template parameter,
1313/// e.g., "Size" in
1314/// @code
1315/// template<int Size> class array { };
1316/// @endcode
1317class NonTypeTemplateParmDecl final
1318 : public DeclaratorDecl,
1319 protected TemplateParmPosition,
1320 private llvm::TrailingObjects<NonTypeTemplateParmDecl,
1321 std::pair<QualType, TypeSourceInfo *>> {
1322 friend class ASTDeclReader;
1323 friend TrailingObjects;
1324
1325 /// The default template argument, if any, and whether or not
1326 /// it was inherited.
1327 using DefArgStorage = DefaultArgStorage<NonTypeTemplateParmDecl, Expr *>;
1328 DefArgStorage DefaultArgument;
1329
1330 // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
1331 // down here to save memory.
1332
1333 /// Whether this non-type template parameter is a parameter pack.
1334 bool ParameterPack;
1335
1336 /// Whether this non-type template parameter is an "expanded"
1337 /// parameter pack, meaning that its type is a pack expansion and we
1338 /// already know the set of types that expansion expands to.
1339 bool ExpandedParameterPack = false;
1340
1341 /// The number of types in an expanded parameter pack.
1342 unsigned NumExpandedTypes = 0;
1343
1344 size_t numTrailingObjects(
1345 OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
1346 return NumExpandedTypes;
1347 }
1348
1349 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1350 SourceLocation IdLoc, unsigned D, unsigned P,
1351 IdentifierInfo *Id, QualType T,
1352 bool ParameterPack, TypeSourceInfo *TInfo)
1353 : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
1354 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1355
1356 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1357 SourceLocation IdLoc, unsigned D, unsigned P,
1358 IdentifierInfo *Id, QualType T,
1359 TypeSourceInfo *TInfo,
1360 ArrayRef<QualType> ExpandedTypes,
1361 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1362
1363public:
1364 static NonTypeTemplateParmDecl *
1365 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1366 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1367 QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
1368
1369 static NonTypeTemplateParmDecl *
1370 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1371 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1372 QualType T, TypeSourceInfo *TInfo, ArrayRef<QualType> ExpandedTypes,
1373 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1374
1375 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1376 unsigned ID);
1377 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1378 unsigned ID,
1379 unsigned NumExpandedTypes);
1380
1381 using TemplateParmPosition::getDepth;
1382 using TemplateParmPosition::setDepth;
1383 using TemplateParmPosition::getPosition;
1384 using TemplateParmPosition::setPosition;
1385 using TemplateParmPosition::getIndex;
1386
1387 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1388
1389 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1390
1391 /// Determine whether this template parameter has a default
1392 /// argument.
1393 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1394
1395 /// Retrieve the default argument, if any.
1396 Expr *getDefaultArgument() const { return DefaultArgument.get(); }
1397
1398 /// Retrieve the location of the default argument, if any.
1399 SourceLocation getDefaultArgumentLoc() const;
1400
1401 /// Determines whether the default argument was inherited
1402 /// from a previous declaration of this template.
1403 bool defaultArgumentWasInherited() const {
1404 return DefaultArgument.isInherited();
1405 }
1406
1407 /// Set the default argument for this template parameter, and
1408 /// whether that default argument was inherited from another
1409 /// declaration.
1410 void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
1411 void setInheritedDefaultArgument(const ASTContext &C,
1412 NonTypeTemplateParmDecl *Parm) {
1413 DefaultArgument.setInherited(C, Parm);
1414 }
1415
1416 /// Removes the default argument of this template parameter.
1417 void removeDefaultArgument() { DefaultArgument.clear(); }
1418
1419 /// Whether this parameter is a non-type template parameter pack.
1420 ///
1421 /// If the parameter is a parameter pack, the type may be a
1422 /// \c PackExpansionType. In the following example, the \c Dims parameter
1423 /// is a parameter pack (whose type is 'unsigned').
1424 ///
1425 /// \code
1426 /// template<typename T, unsigned ...Dims> struct multi_array;
1427 /// \endcode
1428 bool isParameterPack() const { return ParameterPack; }
1429
1430 /// Whether this parameter pack is a pack expansion.
1431 ///
1432 /// A non-type template parameter pack is a pack expansion if its type
1433 /// contains an unexpanded parameter pack. In this case, we will have
1434 /// built a PackExpansionType wrapping the type.
1435 bool isPackExpansion() const {
1436 return ParameterPack && getType()->getAs<PackExpansionType>();
1437 }
1438
1439 /// Whether this parameter is a non-type template parameter pack
1440 /// that has a known list of different types at different positions.
1441 ///
1442 /// A parameter pack is an expanded parameter pack when the original
1443 /// parameter pack's type was itself a pack expansion, and that expansion
1444 /// has already been expanded. For example, given:
1445 ///
1446 /// \code
1447 /// template<typename ...Types>
1448 /// struct X {
1449 /// template<Types ...Values>
1450 /// struct Y { /* ... */ };
1451 /// };
1452 /// \endcode
1453 ///
1454 /// The parameter pack \c Values has a \c PackExpansionType as its type,
1455 /// which expands \c Types. When \c Types is supplied with template arguments
1456 /// by instantiating \c X, the instantiation of \c Values becomes an
1457 /// expanded parameter pack. For example, instantiating
1458 /// \c X<int, unsigned int> results in \c Values being an expanded parameter
1459 /// pack with expansion types \c int and \c unsigned int.
1460 ///
1461 /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
1462 /// return the expansion types.
1463 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1464
1465 /// Retrieves the number of expansion types in an expanded parameter
1466 /// pack.
1467 unsigned getNumExpansionTypes() const {
1468 assert(ExpandedParameterPack && "Not an expansion parameter pack")((ExpandedParameterPack && "Not an expansion parameter pack"
) ? static_cast<void> (0) : __assert_fail ("ExpandedParameterPack && \"Not an expansion parameter pack\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 1468, __PRETTY_FUNCTION__))
;
1469 return NumExpandedTypes;
1470 }
1471
1472 /// Retrieve a particular expansion type within an expanded parameter
1473 /// pack.
1474 QualType getExpansionType(unsigned I) const {
1475 assert(I < NumExpandedTypes && "Out-of-range expansion type index")((I < NumExpandedTypes && "Out-of-range expansion type index"
) ? static_cast<void> (0) : __assert_fail ("I < NumExpandedTypes && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 1475, __PRETTY_FUNCTION__))
;
1476 auto TypesAndInfos =
1477 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1478 return TypesAndInfos[I].first;
1479 }
1480
1481 /// Retrieve a particular expansion type source info within an
1482 /// expanded parameter pack.
1483 TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
1484 assert(I < NumExpandedTypes && "Out-of-range expansion type index")((I < NumExpandedTypes && "Out-of-range expansion type index"
) ? static_cast<void> (0) : __assert_fail ("I < NumExpandedTypes && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 1484, __PRETTY_FUNCTION__))
;
1485 auto TypesAndInfos =
1486 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1487 return TypesAndInfos[I].second;
1488 }
1489
1490 // Implement isa/cast/dyncast/etc.
1491 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1492 static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
1493};
1494
1495/// TemplateTemplateParmDecl - Declares a template template parameter,
1496/// e.g., "T" in
1497/// @code
1498/// template <template <typename> class T> class container { };
1499/// @endcode
1500/// A template template parameter is a TemplateDecl because it defines the
1501/// name of a template and the template parameters allowable for substitution.
1502class TemplateTemplateParmDecl final
1503 : public TemplateDecl,
1504 protected TemplateParmPosition,
1505 private llvm::TrailingObjects<TemplateTemplateParmDecl,
1506 TemplateParameterList *> {
1507 /// The default template argument, if any.
1508 using DefArgStorage =
1509 DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>;
1510 DefArgStorage DefaultArgument;
1511
1512 /// Whether this parameter is a parameter pack.
1513 bool ParameterPack;
1514
1515 /// Whether this template template parameter is an "expanded"
1516 /// parameter pack, meaning that it is a pack expansion and we
1517 /// already know the set of template parameters that expansion expands to.
1518 bool ExpandedParameterPack = false;
1519
1520 /// The number of parameters in an expanded parameter pack.
1521 unsigned NumExpandedParams = 0;
1522
1523 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1524 unsigned D, unsigned P, bool ParameterPack,
1525 IdentifierInfo *Id, TemplateParameterList *Params)
1526 : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
1527 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1528
1529 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1530 unsigned D, unsigned P,
1531 IdentifierInfo *Id, TemplateParameterList *Params,
1532 ArrayRef<TemplateParameterList *> Expansions);
1533
1534 void anchor() override;
1535
1536public:
1537 friend class ASTDeclReader;
1538 friend class ASTDeclWriter;
1539 friend TrailingObjects;
1540
1541 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1542 SourceLocation L, unsigned D,
1543 unsigned P, bool ParameterPack,
1544 IdentifierInfo *Id,
1545 TemplateParameterList *Params);
1546 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1547 SourceLocation L, unsigned D,
1548 unsigned P,
1549 IdentifierInfo *Id,
1550 TemplateParameterList *Params,
1551 ArrayRef<TemplateParameterList *> Expansions);
1552
1553 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1554 unsigned ID);
1555 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1556 unsigned ID,
1557 unsigned NumExpansions);
1558
1559 using TemplateParmPosition::getDepth;
1560 using TemplateParmPosition::setDepth;
1561 using TemplateParmPosition::getPosition;
1562 using TemplateParmPosition::setPosition;
1563 using TemplateParmPosition::getIndex;
1564
1565 /// Whether this template template parameter is a template
1566 /// parameter pack.
1567 ///
1568 /// \code
1569 /// template<template <class T> ...MetaFunctions> struct Apply;
1570 /// \endcode
1571 bool isParameterPack() const { return ParameterPack; }
1572
1573 /// Whether this parameter pack is a pack expansion.
1574 ///
1575 /// A template template parameter pack is a pack expansion if its template
1576 /// parameter list contains an unexpanded parameter pack.
1577 bool isPackExpansion() const {
1578 return ParameterPack &&
1579 getTemplateParameters()->containsUnexpandedParameterPack();
1580 }
1581
1582 /// Whether this parameter is a template template parameter pack that
1583 /// has a known list of different template parameter lists at different
1584 /// positions.
1585 ///
1586 /// A parameter pack is an expanded parameter pack when the original parameter
1587 /// pack's template parameter list was itself a pack expansion, and that
1588 /// expansion has already been expanded. For exampe, given:
1589 ///
1590 /// \code
1591 /// template<typename...Types> struct Outer {
1592 /// template<template<Types> class...Templates> struct Inner;
1593 /// };
1594 /// \endcode
1595 ///
1596 /// The parameter pack \c Templates is a pack expansion, which expands the
1597 /// pack \c Types. When \c Types is supplied with template arguments by
1598 /// instantiating \c Outer, the instantiation of \c Templates is an expanded
1599 /// parameter pack.
1600 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1601
1602 /// Retrieves the number of expansion template parameters in
1603 /// an expanded parameter pack.
1604 unsigned getNumExpansionTemplateParameters() const {
1605 assert(ExpandedParameterPack && "Not an expansion parameter pack")((ExpandedParameterPack && "Not an expansion parameter pack"
) ? static_cast<void> (0) : __assert_fail ("ExpandedParameterPack && \"Not an expansion parameter pack\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 1605, __PRETTY_FUNCTION__))
;
1606 return NumExpandedParams;
1607 }
1608
1609 /// Retrieve a particular expansion type within an expanded parameter
1610 /// pack.
1611 TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
1612 assert(I < NumExpandedParams && "Out-of-range expansion type index")((I < NumExpandedParams && "Out-of-range expansion type index"
) ? static_cast<void> (0) : __assert_fail ("I < NumExpandedParams && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 1612, __PRETTY_FUNCTION__))
;
1613 return getTrailingObjects<TemplateParameterList *>()[I];
1614 }
1615
1616 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1617
1618 /// Determine whether this template parameter has a default
1619 /// argument.
1620 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1621
1622 /// Retrieve the default argument, if any.
1623 const TemplateArgumentLoc &getDefaultArgument() const {
1624 static const TemplateArgumentLoc None;
1625 return DefaultArgument.isSet() ? *DefaultArgument.get() : None;
1626 }
1627
1628 /// Retrieve the location of the default argument, if any.
1629 SourceLocation getDefaultArgumentLoc() const;
1630
1631 /// Determines whether the default argument was inherited
1632 /// from a previous declaration of this template.
1633 bool defaultArgumentWasInherited() const {
1634 return DefaultArgument.isInherited();
1635 }
1636
1637 /// Set the default argument for this template parameter, and
1638 /// whether that default argument was inherited from another
1639 /// declaration.
1640 void setDefaultArgument(const ASTContext &C,
1641 const TemplateArgumentLoc &DefArg);
1642 void setInheritedDefaultArgument(const ASTContext &C,
1643 TemplateTemplateParmDecl *Prev) {
1644 DefaultArgument.setInherited(C, Prev);
1645 }
1646
1647 /// Removes the default argument of this template parameter.
1648 void removeDefaultArgument() { DefaultArgument.clear(); }
1649
1650 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1651 SourceLocation End = getLocation();
1652 if (hasDefaultArgument() && !defaultArgumentWasInherited())
1653 End = getDefaultArgument().getSourceRange().getEnd();
1654 return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
1655 }
1656
1657 // Implement isa/cast/dyncast/etc.
1658 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1659 static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
1660};
1661
1662/// Represents the builtin template declaration which is used to
1663/// implement __make_integer_seq and other builtin templates. It serves
1664/// no real purpose beyond existing as a place to hold template parameters.
1665class BuiltinTemplateDecl : public TemplateDecl {
1666 BuiltinTemplateKind BTK;
1667
1668 BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
1669 DeclarationName Name, BuiltinTemplateKind BTK);
1670
1671 void anchor() override;
1672
1673public:
1674 // Implement isa/cast/dyncast support
1675 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1676 static bool classofKind(Kind K) { return K == BuiltinTemplate; }
1677
1678 static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
1679 DeclarationName Name,
1680 BuiltinTemplateKind BTK) {
1681 return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
1682 }
1683
1684 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1685 return {};
1686 }
1687
1688 BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
1689};
1690
1691/// Represents a class template specialization, which refers to
1692/// a class template with a given set of template arguments.
1693///
1694/// Class template specializations represent both explicit
1695/// specialization of class templates, as in the example below, and
1696/// implicit instantiations of class templates.
1697///
1698/// \code
1699/// template<typename T> class array;
1700///
1701/// template<>
1702/// class array<bool> { }; // class template specialization array<bool>
1703/// \endcode
1704class ClassTemplateSpecializationDecl
1705 : public CXXRecordDecl, public llvm::FoldingSetNode {
1706 /// Structure that stores information about a class template
1707 /// specialization that was instantiated from a class template partial
1708 /// specialization.
1709 struct SpecializedPartialSpecialization {
1710 /// The class template partial specialization from which this
1711 /// class template specialization was instantiated.
1712 ClassTemplatePartialSpecializationDecl *PartialSpecialization;
1713
1714 /// The template argument list deduced for the class template
1715 /// partial specialization itself.
1716 const TemplateArgumentList *TemplateArgs;
1717 };
1718
1719 /// The template that this specialization specializes
1720 llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
1721 SpecializedTemplate;
1722
1723 /// Further info for explicit template specialization/instantiation.
1724 struct ExplicitSpecializationInfo {
1725 /// The type-as-written.
1726 TypeSourceInfo *TypeAsWritten = nullptr;
1727
1728 /// The location of the extern keyword.
1729 SourceLocation ExternLoc;
1730
1731 /// The location of the template keyword.
1732 SourceLocation TemplateKeywordLoc;
1733
1734 ExplicitSpecializationInfo() = default;
1735 };
1736
1737 /// Further info for explicit template specialization/instantiation.
1738 /// Does not apply to implicit specializations.
1739 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
1740
1741 /// The template arguments used to describe this specialization.
1742 const TemplateArgumentList *TemplateArgs;
1743
1744 /// The point where this template was instantiated (if any)
1745 SourceLocation PointOfInstantiation;
1746
1747 /// The kind of specialization this declaration refers to.
1748 /// Really a value of type TemplateSpecializationKind.
1749 unsigned SpecializationKind : 3;
1750
1751protected:
1752 ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
1753 DeclContext *DC, SourceLocation StartLoc,
1754 SourceLocation IdLoc,
1755 ClassTemplateDecl *SpecializedTemplate,
1756 ArrayRef<TemplateArgument> Args,
1757 ClassTemplateSpecializationDecl *PrevDecl);
1758
1759 explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
1760
1761public:
1762 friend class ASTDeclReader;
1763 friend class ASTDeclWriter;
1764
1765 static ClassTemplateSpecializationDecl *
1766 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1767 SourceLocation StartLoc, SourceLocation IdLoc,
1768 ClassTemplateDecl *SpecializedTemplate,
1769 ArrayRef<TemplateArgument> Args,
1770 ClassTemplateSpecializationDecl *PrevDecl);
1771 static ClassTemplateSpecializationDecl *
1772 CreateDeserialized(ASTContext &C, unsigned ID);
1773
1774 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1775 bool Qualified) const override;
1776
1777 // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
1778 // different "most recent" declaration from this function for the same
1779 // declaration, because we don't override getMostRecentDeclImpl(). But
1780 // it's not clear that we should override that, because the most recent
1781 // declaration as a CXXRecordDecl sometimes is the injected-class-name.
1782 ClassTemplateSpecializationDecl *getMostRecentDecl() {
1783 return cast<ClassTemplateSpecializationDecl>(
1784 getMostRecentNonInjectedDecl());
1785 }
1786
1787 /// Retrieve the template that this specialization specializes.
1788 ClassTemplateDecl *getSpecializedTemplate() const;
1789
1790 /// Retrieve the template arguments of the class template
1791 /// specialization.
1792 const TemplateArgumentList &getTemplateArgs() const {
1793 return *TemplateArgs;
1794 }
1795
1796 /// Determine the kind of specialization that this
1797 /// declaration represents.
1798 TemplateSpecializationKind getSpecializationKind() const {
1799 return static_cast<TemplateSpecializationKind>(SpecializationKind);
1800 }
1801
1802 bool isExplicitSpecialization() const {
1803 return getSpecializationKind() == TSK_ExplicitSpecialization;
1804 }
1805
1806 /// Is this an explicit specialization at class scope (within the class that
1807 /// owns the primary template)? For example:
1808 ///
1809 /// \code
1810 /// template<typename T> struct Outer {
1811 /// template<typename U> struct Inner;
1812 /// template<> struct Inner; // class-scope explicit specialization
1813 /// };
1814 /// \endcode
1815 bool isClassScopeExplicitSpecialization() const {
1816 return isExplicitSpecialization() &&
1817 isa<CXXRecordDecl>(getLexicalDeclContext());
1818 }
1819
1820 /// True if this declaration is an explicit specialization,
1821 /// explicit instantiation declaration, or explicit instantiation
1822 /// definition.
1823 bool isExplicitInstantiationOrSpecialization() const {
1824 return isTemplateExplicitInstantiationOrSpecialization(
1825 getTemplateSpecializationKind());
1826 }
1827
1828 void setSpecializationKind(TemplateSpecializationKind TSK) {
1829 SpecializationKind = TSK;
1830 }
1831
1832 /// Get the point of instantiation (if any), or null if none.
1833 SourceLocation getPointOfInstantiation() const {
1834 return PointOfInstantiation;
1835 }
1836
1837 void setPointOfInstantiation(SourceLocation Loc) {
1838 assert(Loc.isValid() && "point of instantiation must be valid!")((Loc.isValid() && "point of instantiation must be valid!"
) ? static_cast<void> (0) : __assert_fail ("Loc.isValid() && \"point of instantiation must be valid!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 1838, __PRETTY_FUNCTION__))
;
1839 PointOfInstantiation = Loc;
1840 }
1841
1842 /// If this class template specialization is an instantiation of
1843 /// a template (rather than an explicit specialization), return the
1844 /// class template or class template partial specialization from which it
1845 /// was instantiated.
1846 llvm::PointerUnion<ClassTemplateDecl *,
1847 ClassTemplatePartialSpecializationDecl *>
1848 getInstantiatedFrom() const {
1849 if (!isTemplateInstantiation(getSpecializationKind()))
1850 return llvm::PointerUnion<ClassTemplateDecl *,
1851 ClassTemplatePartialSpecializationDecl *>();
1852
1853 return getSpecializedTemplateOrPartial();
1854 }
1855
1856 /// Retrieve the class template or class template partial
1857 /// specialization which was specialized by this.
1858 llvm::PointerUnion<ClassTemplateDecl *,
1859 ClassTemplatePartialSpecializationDecl *>
1860 getSpecializedTemplateOrPartial() const {
1861 if (const auto *PartialSpec =
1862 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
1863 return PartialSpec->PartialSpecialization;
1864
1865 return SpecializedTemplate.get<ClassTemplateDecl*>();
1866 }
1867
1868 /// Retrieve the set of template arguments that should be used
1869 /// to instantiate members of the class template or class template partial
1870 /// specialization from which this class template specialization was
1871 /// instantiated.
1872 ///
1873 /// \returns For a class template specialization instantiated from the primary
1874 /// template, this function will return the same template arguments as
1875 /// getTemplateArgs(). For a class template specialization instantiated from
1876 /// a class template partial specialization, this function will return the
1877 /// deduced template arguments for the class template partial specialization
1878 /// itself.
1879 const TemplateArgumentList &getTemplateInstantiationArgs() const {
1880 if (const auto *PartialSpec =
1881 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
1882 return *PartialSpec->TemplateArgs;
1883
1884 return getTemplateArgs();
1885 }
1886
1887 /// Note that this class template specialization is actually an
1888 /// instantiation of the given class template partial specialization whose
1889 /// template arguments have been deduced.
1890 void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
1891 const TemplateArgumentList *TemplateArgs) {
1892 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&((!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a class template partial specialization!"
) ? static_cast<void> (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Already set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 1893, __PRETTY_FUNCTION__))
13
'?' condition is true
1893 "Already set to a class template partial specialization!")((!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a class template partial specialization!"
) ? static_cast<void> (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Already set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 1893, __PRETTY_FUNCTION__))
;
1894 auto *PS = new (getASTContext()) SpecializedPartialSpecialization();
14
'PS' initialized to a null pointer value
1895 PS->PartialSpecialization = PartialSpec;
15
Access to field 'PartialSpecialization' results in a dereference of a null pointer (loaded from variable 'PS')
1896 PS->TemplateArgs = TemplateArgs;
1897 SpecializedTemplate = PS;
1898 }
1899
1900 /// Note that this class template specialization is an instantiation
1901 /// of the given class template.
1902 void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
1903 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&((!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a class template partial specialization!"
) ? static_cast<void> (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Previously set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 1904, __PRETTY_FUNCTION__))
1904 "Previously set to a class template partial specialization!")((!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a class template partial specialization!"
) ? static_cast<void> (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Previously set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 1904, __PRETTY_FUNCTION__))
;
1905 SpecializedTemplate = TemplDecl;
1906 }
1907
1908 /// Sets the type of this specialization as it was written by
1909 /// the user. This will be a class template specialization type.
1910 void setTypeAsWritten(TypeSourceInfo *T) {
1911 if (!ExplicitInfo)
1912 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1913 ExplicitInfo->TypeAsWritten = T;
1914 }
1915
1916 /// Gets the type of this specialization as it was written by
1917 /// the user, if it was so written.
1918 TypeSourceInfo *getTypeAsWritten() const {
1919 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
1920 }
1921
1922 /// Gets the location of the extern keyword, if present.
1923 SourceLocation getExternLoc() const {
1924 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
1925 }
1926
1927 /// Sets the location of the extern keyword.
1928 void setExternLoc(SourceLocation Loc) {
1929 if (!ExplicitInfo)
1930 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1931 ExplicitInfo->ExternLoc = Loc;
1932 }
1933
1934 /// Sets the location of the template keyword.
1935 void setTemplateKeywordLoc(SourceLocation Loc) {
1936 if (!ExplicitInfo)
1937 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1938 ExplicitInfo->TemplateKeywordLoc = Loc;
1939 }
1940
1941 /// Gets the location of the template keyword, if present.
1942 SourceLocation getTemplateKeywordLoc() const {
1943 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
1944 }
1945
1946 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1947
1948 void Profile(llvm::FoldingSetNodeID &ID) const {
1949 Profile(ID, TemplateArgs->asArray(), getASTContext());
1950 }
1951
1952 static void
1953 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
1954 ASTContext &Context) {
1955 ID.AddInteger(TemplateArgs.size());
1956 for (const TemplateArgument &TemplateArg : TemplateArgs)
1957 TemplateArg.Profile(ID, Context);
1958 }
1959
1960 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1961
1962 static bool classofKind(Kind K) {
1963 return K >= firstClassTemplateSpecialization &&
1964 K <= lastClassTemplateSpecialization;
1965 }
1966};
1967
1968class ClassTemplatePartialSpecializationDecl
1969 : public ClassTemplateSpecializationDecl {
1970 /// The list of template parameters
1971 TemplateParameterList* TemplateParams = nullptr;
1972
1973 /// The source info for the template arguments as written.
1974 /// FIXME: redundant with TypeAsWritten?
1975 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
1976
1977 /// The class template partial specialization from which this
1978 /// class template partial specialization was instantiated.
1979 ///
1980 /// The boolean value will be true to indicate that this class template
1981 /// partial specialization was specialized at this level.
1982 llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
1983 InstantiatedFromMember;
1984
1985 ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
1986 DeclContext *DC,
1987 SourceLocation StartLoc,
1988 SourceLocation IdLoc,
1989 TemplateParameterList *Params,
1990 ClassTemplateDecl *SpecializedTemplate,
1991 ArrayRef<TemplateArgument> Args,
1992 const ASTTemplateArgumentListInfo *ArgsAsWritten,
1993 ClassTemplatePartialSpecializationDecl *PrevDecl);
1994
1995 ClassTemplatePartialSpecializationDecl(ASTContext &C)
1996 : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
1997 InstantiatedFromMember(nullptr, false) {}
1998
1999 void anchor() override;
2000
2001public:
2002 friend class ASTDeclReader;
2003 friend class ASTDeclWriter;
2004
2005 static ClassTemplatePartialSpecializationDecl *
2006 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
2007 SourceLocation StartLoc, SourceLocation IdLoc,
2008 TemplateParameterList *Params,
2009 ClassTemplateDecl *SpecializedTemplate,
2010 ArrayRef<TemplateArgument> Args,
2011 const TemplateArgumentListInfo &ArgInfos,
2012 QualType CanonInjectedType,
2013 ClassTemplatePartialSpecializationDecl *PrevDecl);
2014
2015 static ClassTemplatePartialSpecializationDecl *
2016 CreateDeserialized(ASTContext &C, unsigned ID);
2017
2018 ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
2019 return cast<ClassTemplatePartialSpecializationDecl>(
2020 static_cast<ClassTemplateSpecializationDecl *>(
2021 this)->getMostRecentDecl());
2022 }
2023
2024 /// Get the list of template parameters
2025 TemplateParameterList *getTemplateParameters() const {
2026 return TemplateParams;
2027 }
2028
2029 /// Get the template arguments as written.
2030 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
2031 return ArgsAsWritten;
2032 }
2033
2034 /// Retrieve the member class template partial specialization from
2035 /// which this particular class template partial specialization was
2036 /// instantiated.
2037 ///
2038 /// \code
2039 /// template<typename T>
2040 /// struct Outer {
2041 /// template<typename U> struct Inner;
2042 /// template<typename U> struct Inner<U*> { }; // #1
2043 /// };
2044 ///
2045 /// Outer<float>::Inner<int*> ii;
2046 /// \endcode
2047 ///
2048 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
2049 /// end up instantiating the partial specialization
2050 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
2051 /// template partial specialization \c Outer<T>::Inner<U*>. Given
2052 /// \c Outer<float>::Inner<U*>, this function would return
2053 /// \c Outer<T>::Inner<U*>.
2054 ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
2055 const auto *First =
2056 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2057 return First->InstantiatedFromMember.getPointer();
2058 }
2059 ClassTemplatePartialSpecializationDecl *
2060 getInstantiatedFromMemberTemplate() const {
2061 return getInstantiatedFromMember();
2062 }
2063
2064 void setInstantiatedFromMember(
2065 ClassTemplatePartialSpecializationDecl *PartialSpec) {
2066 auto *First = cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2067 First->InstantiatedFromMember.setPointer(PartialSpec);
2068 }
2069
2070 /// Determines whether this class template partial specialization
2071 /// template was a specialization of a member partial specialization.
2072 ///
2073 /// In the following example, the member template partial specialization
2074 /// \c X<int>::Inner<T*> is a member specialization.
2075 ///
2076 /// \code
2077 /// template<typename T>
2078 /// struct X {
2079 /// template<typename U> struct Inner;
2080 /// template<typename U> struct Inner<U*>;
2081 /// };
2082 ///
2083 /// template<> template<typename T>
2084 /// struct X<int>::Inner<T*> { /* ... */ };
2085 /// \endcode
2086 bool isMemberSpecialization() {
2087 const auto *First =
2088 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2089 return First->InstantiatedFromMember.getInt();
2090 }
2091
2092 /// Note that this member template is a specialization.
2093 void setMemberSpecialization() {
2094 auto *First = cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2095 assert(First->InstantiatedFromMember.getPointer() &&((First->InstantiatedFromMember.getPointer() && "Only member templates can be member template specializations"
) ? static_cast<void> (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 2096, __PRETTY_FUNCTION__))
2096 "Only member templates can be member template specializations")((First->InstantiatedFromMember.getPointer() && "Only member templates can be member template specializations"
) ? static_cast<void> (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 2096, __PRETTY_FUNCTION__))
;
2097 return First->InstantiatedFromMember.setInt(true);
2098 }
2099
2100 /// Retrieves the injected specialization type for this partial
2101 /// specialization. This is not the same as the type-decl-type for
2102 /// this partial specialization, which is an InjectedClassNameType.
2103 QualType getInjectedSpecializationType() const {
2104 assert(getTypeForDecl() && "partial specialization has no type set!")((getTypeForDecl() && "partial specialization has no type set!"
) ? static_cast<void> (0) : __assert_fail ("getTypeForDecl() && \"partial specialization has no type set!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 2104, __PRETTY_FUNCTION__))
;
2105 return cast<InjectedClassNameType>(getTypeForDecl())
2106 ->getInjectedSpecializationType();
2107 }
2108
2109 // FIXME: Add Profile support!
2110
2111 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2112
2113 static bool classofKind(Kind K) {
2114 return K == ClassTemplatePartialSpecialization;
2115 }
2116};
2117
2118/// Declaration of a class template.
2119class ClassTemplateDecl : public RedeclarableTemplateDecl {
2120protected:
2121 /// Data that is common to all of the declarations of a given
2122 /// class template.
2123 struct Common : CommonBase {
2124 /// The class template specializations for this class
2125 /// template, including explicit specializations and instantiations.
2126 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
2127
2128 /// The class template partial specializations for this class
2129 /// template.
2130 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
2131 PartialSpecializations;
2132
2133 /// The injected-class-name type for this class template.
2134 QualType InjectedClassNameType;
2135
2136 Common() = default;
2137 };
2138
2139 /// Retrieve the set of specializations of this class template.
2140 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
2141 getSpecializations() const;
2142
2143 /// Retrieve the set of partial specializations of this class
2144 /// template.
2145 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
2146 getPartialSpecializations();
2147
2148 ClassTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, ASTContext &C,
2149 DeclContext *DC, SourceLocation L, DeclarationName Name,
2150 TemplateParameterList *Params, NamedDecl *Decl)
2151 : RedeclarableTemplateDecl(CTDI, ClassTemplate, C, DC, L, Name, Params,
2152 Decl) {}
2153
2154 ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2155 DeclarationName Name, TemplateParameterList *Params,
2156 NamedDecl *Decl)
2157 : ClassTemplateDecl(nullptr, C, DC, L, Name, Params, Decl) {}
2158
2159 CommonBase *newCommon(ASTContext &C) const override;
2160
2161 Common *getCommonPtr() const {
2162 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2163 }
2164
2165public:
2166 friend class ASTDeclReader;
2167 friend class ASTDeclWriter;
2168
2169 /// Load any lazily-loaded specializations from the external source.
2170 void LoadLazySpecializations() const;
2171
2172 /// Get the underlying class declarations of the template.
2173 CXXRecordDecl *getTemplatedDecl() const {
2174 return static_cast<CXXRecordDecl *>(TemplatedDecl);
2175 }
2176
2177 /// Returns whether this template declaration defines the primary
2178 /// class pattern.
2179 bool isThisDeclarationADefinition() const {
2180 return getTemplatedDecl()->isThisDeclarationADefinition();
2181 }
2182
2183 // FIXME: remove default argument for AssociatedConstraints
2184 /// Create a class template node.
2185 static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2186 SourceLocation L,
2187 DeclarationName Name,
2188 TemplateParameterList *Params,
2189 NamedDecl *Decl,
2190 Expr *AssociatedConstraints = nullptr);
2191
2192 /// Create an empty class template node.
2193 static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2194
2195 /// Return the specialization with the provided arguments if it exists,
2196 /// otherwise return the insertion point.
2197 ClassTemplateSpecializationDecl *
2198 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2199
2200 /// Insert the specified specialization knowing that it is not already
2201 /// in. InsertPos must be obtained from findSpecialization.
2202 void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
2203
2204 ClassTemplateDecl *getCanonicalDecl() override {
2205 return cast<ClassTemplateDecl>(
2206 RedeclarableTemplateDecl::getCanonicalDecl());
2207 }
2208 const ClassTemplateDecl *getCanonicalDecl() const {
2209 return cast<ClassTemplateDecl>(
2210 RedeclarableTemplateDecl::getCanonicalDecl());
2211 }
2212
2213 /// Retrieve the previous declaration of this class template, or
2214 /// nullptr if no such declaration exists.
2215 ClassTemplateDecl *getPreviousDecl() {
2216 return cast_or_null<ClassTemplateDecl>(
2217 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2218 }
2219 const ClassTemplateDecl *getPreviousDecl() const {
2220 return cast_or_null<ClassTemplateDecl>(
2221 static_cast<const RedeclarableTemplateDecl *>(
2222 this)->getPreviousDecl());
2223 }
2224
2225 ClassTemplateDecl *getMostRecentDecl() {
2226 return cast<ClassTemplateDecl>(
2227 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2228 }
2229 const ClassTemplateDecl *getMostRecentDecl() const {
2230 return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
2231 }
2232
2233 ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
2234 return cast_or_null<ClassTemplateDecl>(
2235 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2236 }
2237
2238 /// Return the partial specialization with the provided arguments if it
2239 /// exists, otherwise return the insertion point.
2240 ClassTemplatePartialSpecializationDecl *
2241 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2242
2243 /// Insert the specified partial specialization knowing that it is not
2244 /// already in. InsertPos must be obtained from findPartialSpecialization.
2245 void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
2246 void *InsertPos);
2247
2248 /// Retrieve the partial specializations as an ordered list.
2249 void getPartialSpecializations(
2250 SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
2251
2252 /// Find a class template partial specialization with the given
2253 /// type T.
2254 ///
2255 /// \param T a dependent type that names a specialization of this class
2256 /// template.
2257 ///
2258 /// \returns the class template partial specialization that exactly matches
2259 /// the type \p T, or nullptr if no such partial specialization exists.
2260 ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
2261
2262 /// Find a class template partial specialization which was instantiated
2263 /// from the given member partial specialization.
2264 ///
2265 /// \param D a member class template partial specialization.
2266 ///
2267 /// \returns the class template partial specialization which was instantiated
2268 /// from the given member partial specialization, or nullptr if no such
2269 /// partial specialization exists.
2270 ClassTemplatePartialSpecializationDecl *
2271 findPartialSpecInstantiatedFromMember(
2272 ClassTemplatePartialSpecializationDecl *D);
2273
2274 /// Retrieve the template specialization type of the
2275 /// injected-class-name for this class template.
2276 ///
2277 /// The injected-class-name for a class template \c X is \c
2278 /// X<template-args>, where \c template-args is formed from the
2279 /// template arguments that correspond to the template parameters of
2280 /// \c X. For example:
2281 ///
2282 /// \code
2283 /// template<typename T, int N>
2284 /// struct array {
2285 /// typedef array this_type; // "array" is equivalent to "array<T, N>"
2286 /// };
2287 /// \endcode
2288 QualType getInjectedClassNameSpecialization();
2289
2290 using spec_iterator = SpecIterator<ClassTemplateSpecializationDecl>;
2291 using spec_range = llvm::iterator_range<spec_iterator>;
2292
2293 spec_range specializations() const {
2294 return spec_range(spec_begin(), spec_end());
2295 }
2296
2297 spec_iterator spec_begin() const {
2298 return makeSpecIterator(getSpecializations(), false);
2299 }
2300
2301 spec_iterator spec_end() const {
2302 return makeSpecIterator(getSpecializations(), true);
2303 }
2304
2305 // Implement isa/cast/dyncast support
2306 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2307 static bool classofKind(Kind K) { return K == ClassTemplate; }
2308};
2309
2310/// Declaration of a friend template.
2311///
2312/// For example:
2313/// \code
2314/// template \<typename T> class A {
2315/// friend class MyVector<T>; // not a friend template
2316/// template \<typename U> friend class B; // not a friend template
2317/// template \<typename U> friend class Foo<T>::Nested; // friend template
2318/// };
2319/// \endcode
2320///
2321/// \note This class is not currently in use. All of the above
2322/// will yield a FriendDecl, not a FriendTemplateDecl.
2323class FriendTemplateDecl : public Decl {
2324 virtual void anchor();
2325
2326public:
2327 using FriendUnion = llvm::PointerUnion<NamedDecl *,TypeSourceInfo *>;
2328
2329private:
2330 // The number of template parameters; always non-zero.
2331 unsigned NumParams = 0;
2332
2333 // The parameter list.
2334 TemplateParameterList **Params = nullptr;
2335
2336 // The declaration that's a friend of this class.
2337 FriendUnion Friend;
2338
2339 // Location of the 'friend' specifier.
2340 SourceLocation FriendLoc;
2341
2342 FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
2343 MutableArrayRef<TemplateParameterList *> Params,
2344 FriendUnion Friend, SourceLocation FriendLoc)
2345 : Decl(Decl::FriendTemplate, DC, Loc), NumParams(Params.size()),
2346 Params(Params.data()), Friend(Friend), FriendLoc(FriendLoc) {}
2347
2348 FriendTemplateDecl(EmptyShell Empty) : Decl(Decl::FriendTemplate, Empty) {}
2349
2350public:
2351 friend class ASTDeclReader;
2352
2353 static FriendTemplateDecl *
2354 Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc,
2355 MutableArrayRef<TemplateParameterList *> Params, FriendUnion Friend,
2356 SourceLocation FriendLoc);
2357
2358 static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2359
2360 /// If this friend declaration names a templated type (or
2361 /// a dependent member type of a templated type), return that
2362 /// type; otherwise return null.
2363 TypeSourceInfo *getFriendType() const {
2364 return Friend.dyn_cast<TypeSourceInfo*>();
2365 }
2366
2367 /// If this friend declaration names a templated function (or
2368 /// a member function of a templated type), return that type;
2369 /// otherwise return null.
2370 NamedDecl *getFriendDecl() const {
2371 return Friend.dyn_cast<NamedDecl*>();
2372 }
2373
2374 /// Retrieves the location of the 'friend' keyword.
2375 SourceLocation getFriendLoc() const {
2376 return FriendLoc;
2377 }
2378
2379 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2380 assert(i <= NumParams)((i <= NumParams) ? static_cast<void> (0) : __assert_fail
("i <= NumParams", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 2380, __PRETTY_FUNCTION__))
;
2381 return Params[i];
2382 }
2383
2384 unsigned getNumTemplateParameters() const {
2385 return NumParams;
2386 }
2387
2388 // Implement isa/cast/dyncast/etc.
2389 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2390 static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
2391};
2392
2393/// Declaration of an alias template.
2394///
2395/// For example:
2396/// \code
2397/// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
2398/// \endcode
2399class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
2400protected:
2401 using Common = CommonBase;
2402
2403 TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2404 DeclarationName Name, TemplateParameterList *Params,
2405 NamedDecl *Decl)
2406 : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
2407 Decl) {}
2408
2409 CommonBase *newCommon(ASTContext &C) const override;
2410
2411 Common *getCommonPtr() {
2412 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2413 }
2414
2415public:
2416 friend class ASTDeclReader;
2417 friend class ASTDeclWriter;
2418
2419 /// Get the underlying function declaration of the template.
2420 TypeAliasDecl *getTemplatedDecl() const {
2421 return static_cast<TypeAliasDecl *>(TemplatedDecl);
2422 }
2423
2424
2425 TypeAliasTemplateDecl *getCanonicalDecl() override {
2426 return cast<TypeAliasTemplateDecl>(
2427 RedeclarableTemplateDecl::getCanonicalDecl());
2428 }
2429 const TypeAliasTemplateDecl *getCanonicalDecl() const {
2430 return cast<TypeAliasTemplateDecl>(
2431 RedeclarableTemplateDecl::getCanonicalDecl());
2432 }
2433
2434 /// Retrieve the previous declaration of this function template, or
2435 /// nullptr if no such declaration exists.
2436 TypeAliasTemplateDecl *getPreviousDecl() {
2437 return cast_or_null<TypeAliasTemplateDecl>(
2438 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2439 }
2440 const TypeAliasTemplateDecl *getPreviousDecl() const {
2441 return cast_or_null<TypeAliasTemplateDecl>(
2442 static_cast<const RedeclarableTemplateDecl *>(
2443 this)->getPreviousDecl());
2444 }
2445
2446 TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
2447 return cast_or_null<TypeAliasTemplateDecl>(
2448 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2449 }
2450
2451 /// Create a function template node.
2452 static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2453 SourceLocation L,
2454 DeclarationName Name,
2455 TemplateParameterList *Params,
2456 NamedDecl *Decl);
2457
2458 /// Create an empty alias template node.
2459 static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2460
2461 // Implement isa/cast/dyncast support
2462 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2463 static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
2464};
2465
2466/// Declaration of a function specialization at template class scope.
2467///
2468/// For example:
2469/// \code
2470/// template <class T>
2471/// class A {
2472/// template <class U> void foo(U a) { }
2473/// template<> void foo(int a) { }
2474/// }
2475/// \endcode
2476///
2477/// "template<> foo(int a)" will be saved in Specialization as a normal
2478/// CXXMethodDecl. Then during an instantiation of class A, it will be
2479/// transformed into an actual function specialization.
2480///
2481/// FIXME: This is redundant; we could store the same information directly on
2482/// the CXXMethodDecl as a DependentFunctionTemplateSpecializationInfo.
2483class ClassScopeFunctionSpecializationDecl : public Decl {
2484 CXXMethodDecl *Specialization;
2485 const ASTTemplateArgumentListInfo *TemplateArgs;
2486
2487 ClassScopeFunctionSpecializationDecl(
2488 DeclContext *DC, SourceLocation Loc, CXXMethodDecl *FD,
2489 const ASTTemplateArgumentListInfo *TemplArgs)
2490 : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
2491 Specialization(FD), TemplateArgs(TemplArgs) {}
2492
2493 ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
2494 : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
2495
2496 virtual void anchor();
2497
2498public:
2499 friend class ASTDeclReader;
2500 friend class ASTDeclWriter;
2501
2502 CXXMethodDecl *getSpecialization() const { return Specialization; }
2503 bool hasExplicitTemplateArgs() const { return TemplateArgs; }
2504 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
2505 return TemplateArgs;
2506 }
2507
2508 static ClassScopeFunctionSpecializationDecl *
2509 Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, CXXMethodDecl *FD,
2510 bool HasExplicitTemplateArgs,
2511 const TemplateArgumentListInfo &TemplateArgs) {
2512 return new (C, DC) ClassScopeFunctionSpecializationDecl(
2513 DC, Loc, FD,
2514 HasExplicitTemplateArgs
2515 ? ASTTemplateArgumentListInfo::Create(C, TemplateArgs)
2516 : nullptr);
2517 }
2518
2519 static ClassScopeFunctionSpecializationDecl *
2520 CreateDeserialized(ASTContext &Context, unsigned ID);
2521
2522 // Implement isa/cast/dyncast/etc.
2523 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2524
2525 static bool classofKind(Kind K) {
2526 return K == Decl::ClassScopeFunctionSpecialization;
2527 }
2528};
2529
2530/// Implementation of inline functions that require the template declarations
2531inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
2532 : Function(FTD) {}
2533
2534/// Represents a variable template specialization, which refers to
2535/// a variable template with a given set of template arguments.
2536///
2537/// Variable template specializations represent both explicit
2538/// specializations of variable templates, as in the example below, and
2539/// implicit instantiations of variable templates.
2540///
2541/// \code
2542/// template<typename T> constexpr T pi = T(3.1415926535897932385);
2543///
2544/// template<>
2545/// constexpr float pi<float>; // variable template specialization pi<float>
2546/// \endcode
2547class VarTemplateSpecializationDecl : public VarDecl,
2548 public llvm::FoldingSetNode {
2549
2550 /// Structure that stores information about a variable template
2551 /// specialization that was instantiated from a variable template partial
2552 /// specialization.
2553 struct SpecializedPartialSpecialization {
2554 /// The variable template partial specialization from which this
2555 /// variable template specialization was instantiated.
2556 VarTemplatePartialSpecializationDecl *PartialSpecialization;
2557
2558 /// The template argument list deduced for the variable template
2559 /// partial specialization itself.
2560 const TemplateArgumentList *TemplateArgs;
2561 };
2562
2563 /// The template that this specialization specializes.
2564 llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
2565 SpecializedTemplate;
2566
2567 /// Further info for explicit template specialization/instantiation.
2568 struct ExplicitSpecializationInfo {
2569 /// The type-as-written.
2570 TypeSourceInfo *TypeAsWritten = nullptr;
2571
2572 /// The location of the extern keyword.
2573 SourceLocation ExternLoc;
2574
2575 /// The location of the template keyword.
2576 SourceLocation TemplateKeywordLoc;
2577
2578 ExplicitSpecializationInfo() = default;
2579 };
2580
2581 /// Further info for explicit template specialization/instantiation.
2582 /// Does not apply to implicit specializations.
2583 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
2584
2585 /// The template arguments used to describe this specialization.
2586 const TemplateArgumentList *TemplateArgs;
2587 TemplateArgumentListInfo TemplateArgsInfo;
2588
2589 /// The point where this template was instantiated (if any).
2590 SourceLocation PointOfInstantiation;
2591
2592 /// The kind of specialization this declaration refers to.
2593 /// Really a value of type TemplateSpecializationKind.
2594 unsigned SpecializationKind : 3;
2595
2596 /// Whether this declaration is a complete definition of the
2597 /// variable template specialization. We can't otherwise tell apart
2598 /// an instantiated declaration from an instantiated definition with
2599 /// no initializer.
2600 unsigned IsCompleteDefinition : 1;
2601
2602protected:
2603 VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
2604 SourceLocation StartLoc, SourceLocation IdLoc,
2605 VarTemplateDecl *SpecializedTemplate,
2606 QualType T, TypeSourceInfo *TInfo,
2607 StorageClass S,
2608 ArrayRef<TemplateArgument> Args);
2609
2610 explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
2611
2612public:
2613 friend class ASTDeclReader;
2614 friend class ASTDeclWriter;
2615 friend class VarDecl;
2616
2617 static VarTemplateSpecializationDecl *
2618 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2619 SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
2620 TypeSourceInfo *TInfo, StorageClass S,
2621 ArrayRef<TemplateArgument> Args);
2622 static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
2623 unsigned ID);
2624
2625 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2626 bool Qualified) const override;
2627
2628 VarTemplateSpecializationDecl *getMostRecentDecl() {
2629 VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
2630 return cast<VarTemplateSpecializationDecl>(Recent);
2631 }
2632
2633 /// Retrieve the template that this specialization specializes.
2634 VarTemplateDecl *getSpecializedTemplate() const;
2635
2636 /// Retrieve the template arguments of the variable template
2637 /// specialization.
2638 const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
2639
2640 // TODO: Always set this when creating the new specialization?
2641 void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
2642
2643 const TemplateArgumentListInfo &getTemplateArgsInfo() const {
2644 return TemplateArgsInfo;
2645 }
2646
2647 /// Determine the kind of specialization that this
2648 /// declaration represents.
2649 TemplateSpecializationKind getSpecializationKind() const {
2650 return static_cast<TemplateSpecializationKind>(SpecializationKind);
2651 }
2652
2653 bool isExplicitSpecialization() const {
2654 return getSpecializationKind() == TSK_ExplicitSpecialization;
2655 }
2656
2657 bool isClassScopeExplicitSpecialization() const {
2658 return isExplicitSpecialization() &&
2659 isa<CXXRecordDecl>(getLexicalDeclContext());
2660 }
2661
2662 /// True if this declaration is an explicit specialization,
2663 /// explicit instantiation declaration, or explicit instantiation
2664 /// definition.
2665 bool isExplicitInstantiationOrSpecialization() const {
2666 return isTemplateExplicitInstantiationOrSpecialization(
2667 getTemplateSpecializationKind());
2668 }
2669
2670 void setSpecializationKind(TemplateSpecializationKind TSK) {
2671 SpecializationKind = TSK;
2672 }
2673
2674 /// Get the point of instantiation (if any), or null if none.
2675 SourceLocation getPointOfInstantiation() const {
2676 return PointOfInstantiation;
2677 }
2678
2679 void setPointOfInstantiation(SourceLocation Loc) {
2680 assert(Loc.isValid() && "point of instantiation must be valid!")((Loc.isValid() && "point of instantiation must be valid!"
) ? static_cast<void> (0) : __assert_fail ("Loc.isValid() && \"point of instantiation must be valid!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 2680, __PRETTY_FUNCTION__))
;
2681 PointOfInstantiation = Loc;
2682 }
2683
2684 void setCompleteDefinition() { IsCompleteDefinition = true; }
2685
2686 /// If this variable template specialization is an instantiation of
2687 /// a template (rather than an explicit specialization), return the
2688 /// variable template or variable template partial specialization from which
2689 /// it was instantiated.
2690 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2691 getInstantiatedFrom() const {
2692 if (!isTemplateInstantiation(getSpecializationKind()))
2693 return llvm::PointerUnion<VarTemplateDecl *,
2694 VarTemplatePartialSpecializationDecl *>();
2695
2696 return getSpecializedTemplateOrPartial();
2697 }
2698
2699 /// Retrieve the variable template or variable template partial
2700 /// specialization which was specialized by this.
2701 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2702 getSpecializedTemplateOrPartial() const {
2703 if (const auto *PartialSpec =
2704 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2705 return PartialSpec->PartialSpecialization;
2706
2707 return SpecializedTemplate.get<VarTemplateDecl *>();
2708 }
2709
2710 /// Retrieve the set of template arguments that should be used
2711 /// to instantiate the initializer of the variable template or variable
2712 /// template partial specialization from which this variable template
2713 /// specialization was instantiated.
2714 ///
2715 /// \returns For a variable template specialization instantiated from the
2716 /// primary template, this function will return the same template arguments
2717 /// as getTemplateArgs(). For a variable template specialization instantiated
2718 /// from a variable template partial specialization, this function will the
2719 /// return deduced template arguments for the variable template partial
2720 /// specialization itself.
2721 const TemplateArgumentList &getTemplateInstantiationArgs() const {
2722 if (const auto *PartialSpec =
2723 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2724 return *PartialSpec->TemplateArgs;
2725
2726 return getTemplateArgs();
2727 }
2728
2729 /// Note that this variable template specialization is actually an
2730 /// instantiation of the given variable template partial specialization whose
2731 /// template arguments have been deduced.
2732 void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
2733 const TemplateArgumentList *TemplateArgs) {
2734 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&((!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a variable template partial specialization!"
) ? static_cast<void> (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Already set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 2735, __PRETTY_FUNCTION__))
2735 "Already set to a variable template partial specialization!")((!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a variable template partial specialization!"
) ? static_cast<void> (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Already set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 2735, __PRETTY_FUNCTION__))
;
2736 auto *PS = new (getASTContext()) SpecializedPartialSpecialization();
2737 PS->PartialSpecialization = PartialSpec;
2738 PS->TemplateArgs = TemplateArgs;
2739 SpecializedTemplate = PS;
2740 }
2741
2742 /// Note that this variable template specialization is an instantiation
2743 /// of the given variable template.
2744 void setInstantiationOf(VarTemplateDecl *TemplDecl) {
2745 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&((!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a variable template partial specialization!"
) ? static_cast<void> (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Previously set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 2746, __PRETTY_FUNCTION__))
2746 "Previously set to a variable template partial specialization!")((!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a variable template partial specialization!"
) ? static_cast<void> (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Previously set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include/clang/AST/DeclTemplate.h"
, 2746, __PRETTY_FUNCTION__))
;
2747 SpecializedTemplate = TemplDecl;
2748 }
2749
2750 /// Sets the type of this specialization as it was written by
2751 /// the user.
2752 void setTypeAsWritten(TypeSourceInfo *T) {
2753 if (!ExplicitInfo)