Bug Summary

File:tools/clang/include/clang/AST/DeclTemplate.h
Warning:line 1824, 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 -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-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/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/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.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-8~svn345461/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -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-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include/clang/AST/DeclTemplate.h

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