Bug Summary

File:clang/lib/Sema/TreeTransform.h
Warning:line 5615, column 24
Forming reference to null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/Sema/TreeTransform.h

1//===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements a semantic tree transformation that takes a given
9// AST and rebuilds it, possibly transforming some nodes in the process.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14#define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15
16#include "CoroutineStmtBuilder.h"
17#include "TypeLocBuilder.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprConcepts.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprOpenMP.h"
26#include "clang/AST/OpenMPClause.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/StmtObjC.h"
30#include "clang/AST/StmtOpenMP.h"
31#include "clang/Basic/DiagnosticParse.h"
32#include "clang/Basic/OpenMPKinds.h"
33#include "clang/Sema/Designator.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Ownership.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "clang/Sema/SemaDiagnostic.h"
39#include "clang/Sema/SemaInternal.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/Support/ErrorHandling.h"
42#include <algorithm>
43
44using namespace llvm::omp;
45
46namespace clang {
47using namespace sema;
48
49/// A semantic tree transformation that allows one to transform one
50/// abstract syntax tree into another.
51///
52/// A new tree transformation is defined by creating a new subclass \c X of
53/// \c TreeTransform<X> and then overriding certain operations to provide
54/// behavior specific to that transformation. For example, template
55/// instantiation is implemented as a tree transformation where the
56/// transformation of TemplateTypeParmType nodes involves substituting the
57/// template arguments for their corresponding template parameters; a similar
58/// transformation is performed for non-type template parameters and
59/// template template parameters.
60///
61/// This tree-transformation template uses static polymorphism to allow
62/// subclasses to customize any of its operations. Thus, a subclass can
63/// override any of the transformation or rebuild operators by providing an
64/// operation with the same signature as the default implementation. The
65/// overriding function should not be virtual.
66///
67/// Semantic tree transformations are split into two stages, either of which
68/// can be replaced by a subclass. The "transform" step transforms an AST node
69/// or the parts of an AST node using the various transformation functions,
70/// then passes the pieces on to the "rebuild" step, which constructs a new AST
71/// node of the appropriate kind from the pieces. The default transformation
72/// routines recursively transform the operands to composite AST nodes (e.g.,
73/// the pointee type of a PointerType node) and, if any of those operand nodes
74/// were changed by the transformation, invokes the rebuild operation to create
75/// a new AST node.
76///
77/// Subclasses can customize the transformation at various levels. The
78/// most coarse-grained transformations involve replacing TransformType(),
79/// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
80/// TransformTemplateName(), or TransformTemplateArgument() with entirely
81/// new implementations.
82///
83/// For more fine-grained transformations, subclasses can replace any of the
84/// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
85/// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
86/// replacing TransformTemplateTypeParmType() allows template instantiation
87/// to substitute template arguments for their corresponding template
88/// parameters. Additionally, subclasses can override the \c RebuildXXX
89/// functions to control how AST nodes are rebuilt when their operands change.
90/// By default, \c TreeTransform will invoke semantic analysis to rebuild
91/// AST nodes. However, certain other tree transformations (e.g, cloning) may
92/// be able to use more efficient rebuild steps.
93///
94/// There are a handful of other functions that can be overridden, allowing one
95/// to avoid traversing nodes that don't need any transformation
96/// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
97/// operands have not changed (\c AlwaysRebuild()), and customize the
98/// default locations and entity names used for type-checking
99/// (\c getBaseLocation(), \c getBaseEntity()).
100template<typename Derived>
101class TreeTransform {
102 /// Private RAII object that helps us forget and then re-remember
103 /// the template argument corresponding to a partially-substituted parameter
104 /// pack.
105 class ForgetPartiallySubstitutedPackRAII {
106 Derived &Self;
107 TemplateArgument Old;
108
109 public:
110 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
111 Old = Self.ForgetPartiallySubstitutedPack();
112 }
113
114 ~ForgetPartiallySubstitutedPackRAII() {
115 Self.RememberPartiallySubstitutedPack(Old);
116 }
117 };
118
119protected:
120 Sema &SemaRef;
121
122 /// The set of local declarations that have been transformed, for
123 /// cases where we are forced to build new declarations within the transformer
124 /// rather than in the subclass (e.g., lambda closure types).
125 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
126
127public:
128 /// Initializes a new tree transformer.
129 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
130
131 /// Retrieves a reference to the derived class.
132 Derived &getDerived() { return static_cast<Derived&>(*this); }
133
134 /// Retrieves a reference to the derived class.
135 const Derived &getDerived() const {
136 return static_cast<const Derived&>(*this);
137 }
138
139 static inline ExprResult Owned(Expr *E) { return E; }
140 static inline StmtResult Owned(Stmt *S) { return S; }
141
142 /// Retrieves a reference to the semantic analysis object used for
143 /// this tree transform.
144 Sema &getSema() const { return SemaRef; }
145
146 /// Whether the transformation should always rebuild AST nodes, even
147 /// if none of the children have changed.
148 ///
149 /// Subclasses may override this function to specify when the transformation
150 /// should rebuild all AST nodes.
151 ///
152 /// We must always rebuild all AST nodes when performing variadic template
153 /// pack expansion, in order to avoid violating the AST invariant that each
154 /// statement node appears at most once in its containing declaration.
155 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
156
157 /// Whether the transformation is forming an expression or statement that
158 /// replaces the original. In this case, we'll reuse mangling numbers from
159 /// existing lambdas.
160 bool ReplacingOriginal() { return false; }
161
162 /// Wether CXXConstructExpr can be skipped when they are implicit.
163 /// They will be reconstructed when used if needed.
164 /// This is usefull when the user that cause rebuilding of the
165 /// CXXConstructExpr is outside of the expression at which the TreeTransform
166 /// started.
167 bool AllowSkippingCXXConstructExpr() { return true; }
168
169 /// Returns the location of the entity being transformed, if that
170 /// information was not available elsewhere in the AST.
171 ///
172 /// By default, returns no source-location information. Subclasses can
173 /// provide an alternative implementation that provides better location
174 /// information.
175 SourceLocation getBaseLocation() { return SourceLocation(); }
176
177 /// Returns the name of the entity being transformed, if that
178 /// information was not available elsewhere in the AST.
179 ///
180 /// By default, returns an empty name. Subclasses can provide an alternative
181 /// implementation with a more precise name.
182 DeclarationName getBaseEntity() { return DeclarationName(); }
183
184 /// Sets the "base" location and entity when that
185 /// information is known based on another transformation.
186 ///
187 /// By default, the source location and entity are ignored. Subclasses can
188 /// override this function to provide a customized implementation.
189 void setBase(SourceLocation Loc, DeclarationName Entity) { }
190
191 /// RAII object that temporarily sets the base location and entity
192 /// used for reporting diagnostics in types.
193 class TemporaryBase {
194 TreeTransform &Self;
195 SourceLocation OldLocation;
196 DeclarationName OldEntity;
197
198 public:
199 TemporaryBase(TreeTransform &Self, SourceLocation Location,
200 DeclarationName Entity) : Self(Self) {
201 OldLocation = Self.getDerived().getBaseLocation();
202 OldEntity = Self.getDerived().getBaseEntity();
203
204 if (Location.isValid())
205 Self.getDerived().setBase(Location, Entity);
206 }
207
208 ~TemporaryBase() {
209 Self.getDerived().setBase(OldLocation, OldEntity);
210 }
211 };
212
213 /// Determine whether the given type \p T has already been
214 /// transformed.
215 ///
216 /// Subclasses can provide an alternative implementation of this routine
217 /// to short-circuit evaluation when it is known that a given type will
218 /// not change. For example, template instantiation need not traverse
219 /// non-dependent types.
220 bool AlreadyTransformed(QualType T) {
221 return T.isNull();
222 }
223
224 /// Transform a template parameter depth level.
225 ///
226 /// During a transformation that transforms template parameters, this maps
227 /// an old template parameter depth to a new depth.
228 unsigned TransformTemplateDepth(unsigned Depth) {
229 return Depth;
230 }
231
232 /// Determine whether the given call argument should be dropped, e.g.,
233 /// because it is a default argument.
234 ///
235 /// Subclasses can provide an alternative implementation of this routine to
236 /// determine which kinds of call arguments get dropped. By default,
237 /// CXXDefaultArgument nodes are dropped (prior to transformation).
238 bool DropCallArgument(Expr *E) {
239 return E->isDefaultArgument();
240 }
241
242 /// Determine whether we should expand a pack expansion with the
243 /// given set of parameter packs into separate arguments by repeatedly
244 /// transforming the pattern.
245 ///
246 /// By default, the transformer never tries to expand pack expansions.
247 /// Subclasses can override this routine to provide different behavior.
248 ///
249 /// \param EllipsisLoc The location of the ellipsis that identifies the
250 /// pack expansion.
251 ///
252 /// \param PatternRange The source range that covers the entire pattern of
253 /// the pack expansion.
254 ///
255 /// \param Unexpanded The set of unexpanded parameter packs within the
256 /// pattern.
257 ///
258 /// \param ShouldExpand Will be set to \c true if the transformer should
259 /// expand the corresponding pack expansions into separate arguments. When
260 /// set, \c NumExpansions must also be set.
261 ///
262 /// \param RetainExpansion Whether the caller should add an unexpanded
263 /// pack expansion after all of the expanded arguments. This is used
264 /// when extending explicitly-specified template argument packs per
265 /// C++0x [temp.arg.explicit]p9.
266 ///
267 /// \param NumExpansions The number of separate arguments that will be in
268 /// the expanded form of the corresponding pack expansion. This is both an
269 /// input and an output parameter, which can be set by the caller if the
270 /// number of expansions is known a priori (e.g., due to a prior substitution)
271 /// and will be set by the callee when the number of expansions is known.
272 /// The callee must set this value when \c ShouldExpand is \c true; it may
273 /// set this value in other cases.
274 ///
275 /// \returns true if an error occurred (e.g., because the parameter packs
276 /// are to be instantiated with arguments of different lengths), false
277 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
278 /// must be set.
279 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
280 SourceRange PatternRange,
281 ArrayRef<UnexpandedParameterPack> Unexpanded,
282 bool &ShouldExpand,
283 bool &RetainExpansion,
284 Optional<unsigned> &NumExpansions) {
285 ShouldExpand = false;
286 return false;
287 }
288
289 /// "Forget" about the partially-substituted pack template argument,
290 /// when performing an instantiation that must preserve the parameter pack
291 /// use.
292 ///
293 /// This routine is meant to be overridden by the template instantiator.
294 TemplateArgument ForgetPartiallySubstitutedPack() {
295 return TemplateArgument();
296 }
297
298 /// "Remember" the partially-substituted pack template argument
299 /// after performing an instantiation that must preserve the parameter pack
300 /// use.
301 ///
302 /// This routine is meant to be overridden by the template instantiator.
303 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
304
305 /// Note to the derived class when a function parameter pack is
306 /// being expanded.
307 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
308
309 /// Transforms the given type into another type.
310 ///
311 /// By default, this routine transforms a type by creating a
312 /// TypeSourceInfo for it and delegating to the appropriate
313 /// function. This is expensive, but we don't mind, because
314 /// this method is deprecated anyway; all users should be
315 /// switched to storing TypeSourceInfos.
316 ///
317 /// \returns the transformed type.
318 QualType TransformType(QualType T);
319
320 /// Transforms the given type-with-location into a new
321 /// type-with-location.
322 ///
323 /// By default, this routine transforms a type by delegating to the
324 /// appropriate TransformXXXType to build a new type. Subclasses
325 /// may override this function (to take over all type
326 /// transformations) or some set of the TransformXXXType functions
327 /// to alter the transformation.
328 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
329
330 /// Transform the given type-with-location into a new
331 /// type, collecting location information in the given builder
332 /// as necessary.
333 ///
334 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
335
336 /// Transform a type that is permitted to produce a
337 /// DeducedTemplateSpecializationType.
338 ///
339 /// This is used in the (relatively rare) contexts where it is acceptable
340 /// for transformation to produce a class template type with deduced
341 /// template arguments.
342 /// @{
343 QualType TransformTypeWithDeducedTST(QualType T);
344 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
345 /// @}
346
347 /// The reason why the value of a statement is not discarded, if any.
348 enum StmtDiscardKind {
349 SDK_Discarded,
350 SDK_NotDiscarded,
351 SDK_StmtExprResult,
352 };
353
354 /// Transform the given statement.
355 ///
356 /// By default, this routine transforms a statement by delegating to the
357 /// appropriate TransformXXXStmt function to transform a specific kind of
358 /// statement or the TransformExpr() function to transform an expression.
359 /// Subclasses may override this function to transform statements using some
360 /// other mechanism.
361 ///
362 /// \returns the transformed statement.
363 StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
364
365 /// Transform the given statement.
366 ///
367 /// By default, this routine transforms a statement by delegating to the
368 /// appropriate TransformOMPXXXClause function to transform a specific kind
369 /// of clause. Subclasses may override this function to transform statements
370 /// using some other mechanism.
371 ///
372 /// \returns the transformed OpenMP clause.
373 OMPClause *TransformOMPClause(OMPClause *S);
374
375 /// Transform the given attribute.
376 ///
377 /// By default, this routine transforms a statement by delegating to the
378 /// appropriate TransformXXXAttr function to transform a specific kind
379 /// of attribute. Subclasses may override this function to transform
380 /// attributed statements using some other mechanism.
381 ///
382 /// \returns the transformed attribute
383 const Attr *TransformAttr(const Attr *S);
384
385/// Transform the specified attribute.
386///
387/// Subclasses should override the transformation of attributes with a pragma
388/// spelling to transform expressions stored within the attribute.
389///
390/// \returns the transformed attribute.
391#define ATTR(X)
392#define PRAGMA_SPELLING_ATTR(X) \
393 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
394#include "clang/Basic/AttrList.inc"
395
396 /// Transform the given expression.
397 ///
398 /// By default, this routine transforms an expression by delegating to the
399 /// appropriate TransformXXXExpr function to build a new expression.
400 /// Subclasses may override this function to transform expressions using some
401 /// other mechanism.
402 ///
403 /// \returns the transformed expression.
404 ExprResult TransformExpr(Expr *E);
405
406 /// Transform the given initializer.
407 ///
408 /// By default, this routine transforms an initializer by stripping off the
409 /// semantic nodes added by initialization, then passing the result to
410 /// TransformExpr or TransformExprs.
411 ///
412 /// \returns the transformed initializer.
413 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
414
415 /// Transform the given list of expressions.
416 ///
417 /// This routine transforms a list of expressions by invoking
418 /// \c TransformExpr() for each subexpression. However, it also provides
419 /// support for variadic templates by expanding any pack expansions (if the
420 /// derived class permits such expansion) along the way. When pack expansions
421 /// are present, the number of outputs may not equal the number of inputs.
422 ///
423 /// \param Inputs The set of expressions to be transformed.
424 ///
425 /// \param NumInputs The number of expressions in \c Inputs.
426 ///
427 /// \param IsCall If \c true, then this transform is being performed on
428 /// function-call arguments, and any arguments that should be dropped, will
429 /// be.
430 ///
431 /// \param Outputs The transformed input expressions will be added to this
432 /// vector.
433 ///
434 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
435 /// due to transformation.
436 ///
437 /// \returns true if an error occurred, false otherwise.
438 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
439 SmallVectorImpl<Expr *> &Outputs,
440 bool *ArgChanged = nullptr);
441
442 /// Transform the given declaration, which is referenced from a type
443 /// or expression.
444 ///
445 /// By default, acts as the identity function on declarations, unless the
446 /// transformer has had to transform the declaration itself. Subclasses
447 /// may override this function to provide alternate behavior.
448 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
449 llvm::DenseMap<Decl *, Decl *>::iterator Known
450 = TransformedLocalDecls.find(D);
451 if (Known != TransformedLocalDecls.end())
452 return Known->second;
453
454 return D;
455 }
456
457 /// Transform the specified condition.
458 ///
459 /// By default, this transforms the variable and expression and rebuilds
460 /// the condition.
461 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
462 Expr *Expr,
463 Sema::ConditionKind Kind);
464
465 /// Transform the attributes associated with the given declaration and
466 /// place them on the new declaration.
467 ///
468 /// By default, this operation does nothing. Subclasses may override this
469 /// behavior to transform attributes.
470 void transformAttrs(Decl *Old, Decl *New) { }
471
472 /// Note that a local declaration has been transformed by this
473 /// transformer.
474 ///
475 /// Local declarations are typically transformed via a call to
476 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
477 /// the transformer itself has to transform the declarations. This routine
478 /// can be overridden by a subclass that keeps track of such mappings.
479 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
480 assert(New.size() == 1 &&((New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? static_cast<void> (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/Sema/TreeTransform.h"
, 481, __PRETTY_FUNCTION__))
481 "must override transformedLocalDecl if performing pack expansion")((New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? static_cast<void> (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/Sema/TreeTransform.h"
, 481, __PRETTY_FUNCTION__))
;
482 TransformedLocalDecls[Old] = New.front();
483 }
484
485 /// Transform the definition of the given declaration.
486 ///
487 /// By default, invokes TransformDecl() to transform the declaration.
488 /// Subclasses may override this function to provide alternate behavior.
489 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
490 return getDerived().TransformDecl(Loc, D);
491 }
492
493 /// Transform the given declaration, which was the first part of a
494 /// nested-name-specifier in a member access expression.
495 ///
496 /// This specific declaration transformation only applies to the first
497 /// identifier in a nested-name-specifier of a member access expression, e.g.,
498 /// the \c T in \c x->T::member
499 ///
500 /// By default, invokes TransformDecl() to transform the declaration.
501 /// Subclasses may override this function to provide alternate behavior.
502 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
503 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
504 }
505
506 /// Transform the set of declarations in an OverloadExpr.
507 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
508 LookupResult &R);
509
510 /// Transform the given nested-name-specifier with source-location
511 /// information.
512 ///
513 /// By default, transforms all of the types and declarations within the
514 /// nested-name-specifier. Subclasses may override this function to provide
515 /// alternate behavior.
516 NestedNameSpecifierLoc
517 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
518 QualType ObjectType = QualType(),
519 NamedDecl *FirstQualifierInScope = nullptr);
520
521 /// Transform the given declaration name.
522 ///
523 /// By default, transforms the types of conversion function, constructor,
524 /// and destructor names and then (if needed) rebuilds the declaration name.
525 /// Identifiers and selectors are returned unmodified. Sublcasses may
526 /// override this function to provide alternate behavior.
527 DeclarationNameInfo
528 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
529
530 bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
531 llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
532 concepts::TypeRequirement *
533 TransformTypeRequirement(concepts::TypeRequirement *Req);
534 concepts::ExprRequirement *
535 TransformExprRequirement(concepts::ExprRequirement *Req);
536 concepts::NestedRequirement *
537 TransformNestedRequirement(concepts::NestedRequirement *Req);
538
539 /// Transform the given template name.
540 ///
541 /// \param SS The nested-name-specifier that qualifies the template
542 /// name. This nested-name-specifier must already have been transformed.
543 ///
544 /// \param Name The template name to transform.
545 ///
546 /// \param NameLoc The source location of the template name.
547 ///
548 /// \param ObjectType If we're translating a template name within a member
549 /// access expression, this is the type of the object whose member template
550 /// is being referenced.
551 ///
552 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
553 /// also refers to a name within the current (lexical) scope, this is the
554 /// declaration it refers to.
555 ///
556 /// By default, transforms the template name by transforming the declarations
557 /// and nested-name-specifiers that occur within the template name.
558 /// Subclasses may override this function to provide alternate behavior.
559 TemplateName
560 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
561 SourceLocation NameLoc,
562 QualType ObjectType = QualType(),
563 NamedDecl *FirstQualifierInScope = nullptr,
564 bool AllowInjectedClassName = false);
565
566 /// Transform the given template argument.
567 ///
568 /// By default, this operation transforms the type, expression, or
569 /// declaration stored within the template argument and constructs a
570 /// new template argument from the transformed result. Subclasses may
571 /// override this function to provide alternate behavior.
572 ///
573 /// Returns true if there was an error.
574 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
575 TemplateArgumentLoc &Output,
576 bool Uneval = false);
577
578 /// Transform the given set of template arguments.
579 ///
580 /// By default, this operation transforms all of the template arguments
581 /// in the input set using \c TransformTemplateArgument(), and appends
582 /// the transformed arguments to the output list.
583 ///
584 /// Note that this overload of \c TransformTemplateArguments() is merely
585 /// a convenience function. Subclasses that wish to override this behavior
586 /// should override the iterator-based member template version.
587 ///
588 /// \param Inputs The set of template arguments to be transformed.
589 ///
590 /// \param NumInputs The number of template arguments in \p Inputs.
591 ///
592 /// \param Outputs The set of transformed template arguments output by this
593 /// routine.
594 ///
595 /// Returns true if an error occurred.
596 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
597 unsigned NumInputs,
598 TemplateArgumentListInfo &Outputs,
599 bool Uneval = false) {
600 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
601 Uneval);
602 }
603
604 /// Transform the given set of template arguments.
605 ///
606 /// By default, this operation transforms all of the template arguments
607 /// in the input set using \c TransformTemplateArgument(), and appends
608 /// the transformed arguments to the output list.
609 ///
610 /// \param First An iterator to the first template argument.
611 ///
612 /// \param Last An iterator one step past the last template argument.
613 ///
614 /// \param Outputs The set of transformed template arguments output by this
615 /// routine.
616 ///
617 /// Returns true if an error occurred.
618 template<typename InputIterator>
619 bool TransformTemplateArguments(InputIterator First,
620 InputIterator Last,
621 TemplateArgumentListInfo &Outputs,
622 bool Uneval = false);
623
624 /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
625 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
626 TemplateArgumentLoc &ArgLoc);
627
628 /// Fakes up a TypeSourceInfo for a type.
629 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
630 return SemaRef.Context.getTrivialTypeSourceInfo(T,
631 getDerived().getBaseLocation());
632 }
633
634#define ABSTRACT_TYPELOC(CLASS, PARENT)
635#define TYPELOC(CLASS, PARENT) \
636 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
637#include "clang/AST/TypeLocNodes.def"
638
639 template<typename Fn>
640 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
641 FunctionProtoTypeLoc TL,
642 CXXRecordDecl *ThisContext,
643 Qualifiers ThisTypeQuals,
644 Fn TransformExceptionSpec);
645
646 bool TransformExceptionSpec(SourceLocation Loc,
647 FunctionProtoType::ExceptionSpecInfo &ESI,
648 SmallVectorImpl<QualType> &Exceptions,
649 bool &Changed);
650
651 StmtResult TransformSEHHandler(Stmt *Handler);
652
653 QualType
654 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
655 TemplateSpecializationTypeLoc TL,
656 TemplateName Template);
657
658 QualType
659 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
660 DependentTemplateSpecializationTypeLoc TL,
661 TemplateName Template,
662 CXXScopeSpec &SS);
663
664 QualType TransformDependentTemplateSpecializationType(
665 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
666 NestedNameSpecifierLoc QualifierLoc);
667
668 /// Transforms the parameters of a function type into the
669 /// given vectors.
670 ///
671 /// The result vectors should be kept in sync; null entries in the
672 /// variables vector are acceptable.
673 ///
674 /// Return true on error.
675 bool TransformFunctionTypeParams(
676 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
677 const QualType *ParamTypes,
678 const FunctionProtoType::ExtParameterInfo *ParamInfos,
679 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
680 Sema::ExtParameterInfoBuilder &PInfos);
681
682 /// Transforms a single function-type parameter. Return null
683 /// on error.
684 ///
685 /// \param indexAdjustment - A number to add to the parameter's
686 /// scope index; can be negative
687 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
688 int indexAdjustment,
689 Optional<unsigned> NumExpansions,
690 bool ExpectParameterPack);
691
692 /// Transform the body of a lambda-expression.
693 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
694 /// Alternative implementation of TransformLambdaBody that skips transforming
695 /// the body.
696 StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
697
698 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
699
700 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
701 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
702
703 TemplateParameterList *TransformTemplateParameterList(
704 TemplateParameterList *TPL) {
705 return TPL;
706 }
707
708 ExprResult TransformAddressOfOperand(Expr *E);
709
710 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
711 bool IsAddressOfOperand,
712 TypeSourceInfo **RecoveryTSI);
713
714 ExprResult TransformParenDependentScopeDeclRefExpr(
715 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
716 TypeSourceInfo **RecoveryTSI);
717
718 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
719
720// FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
721// amount of stack usage with clang.
722#define STMT(Node, Parent) \
723 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
724 StmtResult Transform##Node(Node *S);
725#define VALUESTMT(Node, Parent) \
726 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
727 StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
728#define EXPR(Node, Parent) \
729 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
730 ExprResult Transform##Node(Node *E);
731#define ABSTRACT_STMT(Stmt)
732#include "clang/AST/StmtNodes.inc"
733
734#define OMP_CLAUSE_CLASS(Enum, Str, Class) \
735 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
736 OMPClause *Transform ## Class(Class *S);
737#include "llvm/Frontend/OpenMP/OMPKinds.def"
738
739 /// Build a new qualified type given its unqualified type and type location.
740 ///
741 /// By default, this routine adds type qualifiers only to types that can
742 /// have qualifiers, and silently suppresses those qualifiers that are not
743 /// permitted. Subclasses may override this routine to provide different
744 /// behavior.
745 QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
746
747 /// Build a new pointer type given its pointee type.
748 ///
749 /// By default, performs semantic analysis when building the pointer type.
750 /// Subclasses may override this routine to provide different behavior.
751 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
752
753 /// Build a new block pointer type given its pointee type.
754 ///
755 /// By default, performs semantic analysis when building the block pointer
756 /// type. Subclasses may override this routine to provide different behavior.
757 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
758
759 /// Build a new reference type given the type it references.
760 ///
761 /// By default, performs semantic analysis when building the
762 /// reference type. Subclasses may override this routine to provide
763 /// different behavior.
764 ///
765 /// \param LValue whether the type was written with an lvalue sigil
766 /// or an rvalue sigil.
767 QualType RebuildReferenceType(QualType ReferentType,
768 bool LValue,
769 SourceLocation Sigil);
770
771 /// Build a new member pointer type given the pointee type and the
772 /// class type it refers into.
773 ///
774 /// By default, performs semantic analysis when building the member pointer
775 /// type. Subclasses may override this routine to provide different behavior.
776 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
777 SourceLocation Sigil);
778
779 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
780 SourceLocation ProtocolLAngleLoc,
781 ArrayRef<ObjCProtocolDecl *> Protocols,
782 ArrayRef<SourceLocation> ProtocolLocs,
783 SourceLocation ProtocolRAngleLoc);
784
785 /// Build an Objective-C object type.
786 ///
787 /// By default, performs semantic analysis when building the object type.
788 /// Subclasses may override this routine to provide different behavior.
789 QualType RebuildObjCObjectType(QualType BaseType,
790 SourceLocation Loc,
791 SourceLocation TypeArgsLAngleLoc,
792 ArrayRef<TypeSourceInfo *> TypeArgs,
793 SourceLocation TypeArgsRAngleLoc,
794 SourceLocation ProtocolLAngleLoc,
795 ArrayRef<ObjCProtocolDecl *> Protocols,
796 ArrayRef<SourceLocation> ProtocolLocs,
797 SourceLocation ProtocolRAngleLoc);
798
799 /// Build a new Objective-C object pointer type given the pointee type.
800 ///
801 /// By default, directly builds the pointer type, with no additional semantic
802 /// analysis.
803 QualType RebuildObjCObjectPointerType(QualType PointeeType,
804 SourceLocation Star);
805
806 /// Build a new array type given the element type, size
807 /// modifier, size of the array (if known), size expression, and index type
808 /// qualifiers.
809 ///
810 /// By default, performs semantic analysis when building the array type.
811 /// Subclasses may override this routine to provide different behavior.
812 /// Also by default, all of the other Rebuild*Array
813 QualType RebuildArrayType(QualType ElementType,
814 ArrayType::ArraySizeModifier SizeMod,
815 const llvm::APInt *Size,
816 Expr *SizeExpr,
817 unsigned IndexTypeQuals,
818 SourceRange BracketsRange);
819
820 /// Build a new constant array type given the element type, size
821 /// modifier, (known) size of the array, and index type qualifiers.
822 ///
823 /// By default, performs semantic analysis when building the array type.
824 /// Subclasses may override this routine to provide different behavior.
825 QualType RebuildConstantArrayType(QualType ElementType,
826 ArrayType::ArraySizeModifier SizeMod,
827 const llvm::APInt &Size,
828 Expr *SizeExpr,
829 unsigned IndexTypeQuals,
830 SourceRange BracketsRange);
831
832 /// Build a new incomplete array type given the element type, size
833 /// modifier, and index type qualifiers.
834 ///
835 /// By default, performs semantic analysis when building the array type.
836 /// Subclasses may override this routine to provide different behavior.
837 QualType RebuildIncompleteArrayType(QualType ElementType,
838 ArrayType::ArraySizeModifier SizeMod,
839 unsigned IndexTypeQuals,
840 SourceRange BracketsRange);
841
842 /// Build a new variable-length array type given the element type,
843 /// size modifier, size expression, and index type qualifiers.
844 ///
845 /// By default, performs semantic analysis when building the array type.
846 /// Subclasses may override this routine to provide different behavior.
847 QualType RebuildVariableArrayType(QualType ElementType,
848 ArrayType::ArraySizeModifier SizeMod,
849 Expr *SizeExpr,
850 unsigned IndexTypeQuals,
851 SourceRange BracketsRange);
852
853 /// Build a new dependent-sized array type given the element type,
854 /// size modifier, size expression, and index type qualifiers.
855 ///
856 /// By default, performs semantic analysis when building the array type.
857 /// Subclasses may override this routine to provide different behavior.
858 QualType RebuildDependentSizedArrayType(QualType ElementType,
859 ArrayType::ArraySizeModifier SizeMod,
860 Expr *SizeExpr,
861 unsigned IndexTypeQuals,
862 SourceRange BracketsRange);
863
864 /// Build a new vector type given the element type and
865 /// number of elements.
866 ///
867 /// By default, performs semantic analysis when building the vector type.
868 /// Subclasses may override this routine to provide different behavior.
869 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
870 VectorType::VectorKind VecKind);
871
872 /// Build a new potentially dependently-sized extended vector type
873 /// given the element type and number of elements.
874 ///
875 /// By default, performs semantic analysis when building the vector type.
876 /// Subclasses may override this routine to provide different behavior.
877 QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
878 SourceLocation AttributeLoc,
879 VectorType::VectorKind);
880
881 /// Build a new extended vector type given the element type and
882 /// number of elements.
883 ///
884 /// By default, performs semantic analysis when building the vector type.
885 /// Subclasses may override this routine to provide different behavior.
886 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
887 SourceLocation AttributeLoc);
888
889 /// Build a new potentially dependently-sized extended vector type
890 /// given the element type and number of elements.
891 ///
892 /// By default, performs semantic analysis when building the vector type.
893 /// Subclasses may override this routine to provide different behavior.
894 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
895 Expr *SizeExpr,
896 SourceLocation AttributeLoc);
897
898 /// Build a new matrix type given the element type and dimensions.
899 QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
900 unsigned NumColumns);
901
902 /// Build a new matrix type given the type and dependently-defined
903 /// dimensions.
904 QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
905 Expr *ColumnExpr,
906 SourceLocation AttributeLoc);
907
908 /// Build a new DependentAddressSpaceType or return the pointee
909 /// type variable with the correct address space (retrieved from
910 /// AddrSpaceExpr) applied to it. The former will be returned in cases
911 /// where the address space remains dependent.
912 ///
913 /// By default, performs semantic analysis when building the type with address
914 /// space applied. Subclasses may override this routine to provide different
915 /// behavior.
916 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
917 Expr *AddrSpaceExpr,
918 SourceLocation AttributeLoc);
919
920 /// Build a new function type.
921 ///
922 /// By default, performs semantic analysis when building the function type.
923 /// Subclasses may override this routine to provide different behavior.
924 QualType RebuildFunctionProtoType(QualType T,
925 MutableArrayRef<QualType> ParamTypes,
926 const FunctionProtoType::ExtProtoInfo &EPI);
927
928 /// Build a new unprototyped function type.
929 QualType RebuildFunctionNoProtoType(QualType ResultType);
930
931 /// Rebuild an unresolved typename type, given the decl that
932 /// the UnresolvedUsingTypenameDecl was transformed to.
933 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
934
935 /// Build a new typedef type.
936 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
937 return SemaRef.Context.getTypeDeclType(Typedef);
938 }
939
940 /// Build a new MacroDefined type.
941 QualType RebuildMacroQualifiedType(QualType T,
942 const IdentifierInfo *MacroII) {
943 return SemaRef.Context.getMacroQualifiedType(T, MacroII);
944 }
945
946 /// Build a new class/struct/union type.
947 QualType RebuildRecordType(RecordDecl *Record) {
948 return SemaRef.Context.getTypeDeclType(Record);
949 }
950
951 /// Build a new Enum type.
952 QualType RebuildEnumType(EnumDecl *Enum) {
953 return SemaRef.Context.getTypeDeclType(Enum);
954 }
955
956 /// Build a new typeof(expr) type.
957 ///
958 /// By default, performs semantic analysis when building the typeof type.
959 /// Subclasses may override this routine to provide different behavior.
960 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
961
962 /// Build a new typeof(type) type.
963 ///
964 /// By default, builds a new TypeOfType with the given underlying type.
965 QualType RebuildTypeOfType(QualType Underlying);
966
967 /// Build a new unary transform type.
968 QualType RebuildUnaryTransformType(QualType BaseType,
969 UnaryTransformType::UTTKind UKind,
970 SourceLocation Loc);
971
972 /// Build a new C++11 decltype type.
973 ///
974 /// By default, performs semantic analysis when building the decltype type.
975 /// Subclasses may override this routine to provide different behavior.
976 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
977
978 /// Build a new C++11 auto type.
979 ///
980 /// By default, builds a new AutoType with the given deduced type.
981 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
982 ConceptDecl *TypeConstraintConcept,
983 ArrayRef<TemplateArgument> TypeConstraintArgs) {
984 // Note, IsDependent is always false here: we implicitly convert an 'auto'
985 // which has been deduced to a dependent type into an undeduced 'auto', so
986 // that we'll retry deduction after the transformation.
987 return SemaRef.Context.getAutoType(Deduced, Keyword,
988 /*IsDependent*/ false, /*IsPack=*/false,
989 TypeConstraintConcept,
990 TypeConstraintArgs);
991 }
992
993 /// By default, builds a new DeducedTemplateSpecializationType with the given
994 /// deduced type.
995 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
996 QualType Deduced) {
997 return SemaRef.Context.getDeducedTemplateSpecializationType(
998 Template, Deduced, /*IsDependent*/ false);
999 }
1000
1001 /// Build a new template specialization type.
1002 ///
1003 /// By default, performs semantic analysis when building the template
1004 /// specialization type. Subclasses may override this routine to provide
1005 /// different behavior.
1006 QualType RebuildTemplateSpecializationType(TemplateName Template,
1007 SourceLocation TemplateLoc,
1008 TemplateArgumentListInfo &Args);
1009
1010 /// Build a new parenthesized type.
1011 ///
1012 /// By default, builds a new ParenType type from the inner type.
1013 /// Subclasses may override this routine to provide different behavior.
1014 QualType RebuildParenType(QualType InnerType) {
1015 return SemaRef.BuildParenType(InnerType);
1016 }
1017
1018 /// Build a new qualified name type.
1019 ///
1020 /// By default, builds a new ElaboratedType type from the keyword,
1021 /// the nested-name-specifier and the named type.
1022 /// Subclasses may override this routine to provide different behavior.
1023 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1024 ElaboratedTypeKeyword Keyword,
1025 NestedNameSpecifierLoc QualifierLoc,
1026 QualType Named) {
1027 return SemaRef.Context.getElaboratedType(Keyword,
1028 QualifierLoc.getNestedNameSpecifier(),
1029 Named);
1030 }
1031
1032 /// Build a new typename type that refers to a template-id.
1033 ///
1034 /// By default, builds a new DependentNameType type from the
1035 /// nested-name-specifier and the given type. Subclasses may override
1036 /// this routine to provide different behavior.
1037 QualType RebuildDependentTemplateSpecializationType(
1038 ElaboratedTypeKeyword Keyword,
1039 NestedNameSpecifierLoc QualifierLoc,
1040 SourceLocation TemplateKWLoc,
1041 const IdentifierInfo *Name,
1042 SourceLocation NameLoc,
1043 TemplateArgumentListInfo &Args,
1044 bool AllowInjectedClassName) {
1045 // Rebuild the template name.
1046 // TODO: avoid TemplateName abstraction
1047 CXXScopeSpec SS;
1048 SS.Adopt(QualifierLoc);
1049 TemplateName InstName = getDerived().RebuildTemplateName(
1050 SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1051 AllowInjectedClassName);
1052
1053 if (InstName.isNull())
1054 return QualType();
1055
1056 // If it's still dependent, make a dependent specialization.
1057 if (InstName.getAsDependentTemplateName())
1058 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1059 QualifierLoc.getNestedNameSpecifier(),
1060 Name,
1061 Args);
1062
1063 // Otherwise, make an elaborated type wrapping a non-dependent
1064 // specialization.
1065 QualType T =
1066 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1067 if (T.isNull()) return QualType();
1068
1069 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1070 return T;
1071
1072 return SemaRef.Context.getElaboratedType(Keyword,
1073 QualifierLoc.getNestedNameSpecifier(),
1074 T);
1075 }
1076
1077 /// Build a new typename type that refers to an identifier.
1078 ///
1079 /// By default, performs semantic analysis when building the typename type
1080 /// (or elaborated type). Subclasses may override this routine to provide
1081 /// different behavior.
1082 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1083 SourceLocation KeywordLoc,
1084 NestedNameSpecifierLoc QualifierLoc,
1085 const IdentifierInfo *Id,
1086 SourceLocation IdLoc,
1087 bool DeducedTSTContext) {
1088 CXXScopeSpec SS;
1089 SS.Adopt(QualifierLoc);
1090
1091 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1092 // If the name is still dependent, just build a new dependent name type.
1093 if (!SemaRef.computeDeclContext(SS))
1094 return SemaRef.Context.getDependentNameType(Keyword,
1095 QualifierLoc.getNestedNameSpecifier(),
1096 Id);
1097 }
1098
1099 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1100 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1101 *Id, IdLoc, DeducedTSTContext);
1102 }
1103
1104 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1105
1106 // We had a dependent elaborated-type-specifier that has been transformed
1107 // into a non-dependent elaborated-type-specifier. Find the tag we're
1108 // referring to.
1109 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1110 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1111 if (!DC)
1112 return QualType();
1113
1114 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1115 return QualType();
1116
1117 TagDecl *Tag = nullptr;
1118 SemaRef.LookupQualifiedName(Result, DC);
1119 switch (Result.getResultKind()) {
1120 case LookupResult::NotFound:
1121 case LookupResult::NotFoundInCurrentInstantiation:
1122 break;
1123
1124 case LookupResult::Found:
1125 Tag = Result.getAsSingle<TagDecl>();
1126 break;
1127
1128 case LookupResult::FoundOverloaded:
1129 case LookupResult::FoundUnresolvedValue:
1130 llvm_unreachable("Tag lookup cannot find non-tags")::llvm::llvm_unreachable_internal("Tag lookup cannot find non-tags"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/Sema/TreeTransform.h"
, 1130)
;
1131
1132 case LookupResult::Ambiguous:
1133 // Let the LookupResult structure handle ambiguities.
1134 return QualType();
1135 }
1136
1137 if (!Tag) {
1138 // Check where the name exists but isn't a tag type and use that to emit
1139 // better diagnostics.
1140 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1141 SemaRef.LookupQualifiedName(Result, DC);
1142 switch (Result.getResultKind()) {
1143 case LookupResult::Found:
1144 case LookupResult::FoundOverloaded:
1145 case LookupResult::FoundUnresolvedValue: {
1146 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1147 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1148 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1149 << NTK << Kind;
1150 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1151 break;
1152 }
1153 default:
1154 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1155 << Kind << Id << DC << QualifierLoc.getSourceRange();
1156 break;
1157 }
1158 return QualType();
1159 }
1160
1161 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1162 IdLoc, Id)) {
1163 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1164 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1165 return QualType();
1166 }
1167
1168 // Build the elaborated-type-specifier type.
1169 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1170 return SemaRef.Context.getElaboratedType(Keyword,
1171 QualifierLoc.getNestedNameSpecifier(),
1172 T);
1173 }
1174
1175 /// Build a new pack expansion type.
1176 ///
1177 /// By default, builds a new PackExpansionType type from the given pattern.
1178 /// Subclasses may override this routine to provide different behavior.
1179 QualType RebuildPackExpansionType(QualType Pattern,
1180 SourceRange PatternRange,
1181 SourceLocation EllipsisLoc,
1182 Optional<unsigned> NumExpansions) {
1183 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1184 NumExpansions);
1185 }
1186
1187 /// Build a new atomic type given its value type.
1188 ///
1189 /// By default, performs semantic analysis when building the atomic type.
1190 /// Subclasses may override this routine to provide different behavior.
1191 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1192
1193 /// Build a new pipe type given its value type.
1194 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1195 bool isReadPipe);
1196
1197 /// Build an extended int given its value type.
1198 QualType RebuildExtIntType(bool IsUnsigned, unsigned NumBits,
1199 SourceLocation Loc);
1200
1201 /// Build a dependent extended int given its value type.
1202 QualType RebuildDependentExtIntType(bool IsUnsigned, Expr *NumBitsExpr,
1203 SourceLocation Loc);
1204
1205 /// Build a new template name given a nested name specifier, a flag
1206 /// indicating whether the "template" keyword was provided, and the template
1207 /// that the template name refers to.
1208 ///
1209 /// By default, builds the new template name directly. Subclasses may override
1210 /// this routine to provide different behavior.
1211 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1212 bool TemplateKW,
1213 TemplateDecl *Template);
1214
1215 /// Build a new template name given a nested name specifier and the
1216 /// name that is referred to as a template.
1217 ///
1218 /// By default, performs semantic analysis to determine whether the name can
1219 /// be resolved to a specific template, then builds the appropriate kind of
1220 /// template name. Subclasses may override this routine to provide different
1221 /// behavior.
1222 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1223 SourceLocation TemplateKWLoc,
1224 const IdentifierInfo &Name,
1225 SourceLocation NameLoc, QualType ObjectType,
1226 NamedDecl *FirstQualifierInScope,
1227 bool AllowInjectedClassName);
1228
1229 /// Build a new template name given a nested name specifier and the
1230 /// overloaded operator name that is referred to as a template.
1231 ///
1232 /// By default, performs semantic analysis to determine whether the name can
1233 /// be resolved to a specific template, then builds the appropriate kind of
1234 /// template name. Subclasses may override this routine to provide different
1235 /// behavior.
1236 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1237 SourceLocation TemplateKWLoc,
1238 OverloadedOperatorKind Operator,
1239 SourceLocation NameLoc, QualType ObjectType,
1240 bool AllowInjectedClassName);
1241
1242 /// Build a new template name given a template template parameter pack
1243 /// and the
1244 ///
1245 /// By default, performs semantic analysis to determine whether the name can
1246 /// be resolved to a specific template, then builds the appropriate kind of
1247 /// template name. Subclasses may override this routine to provide different
1248 /// behavior.
1249 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1250 const TemplateArgument &ArgPack) {
1251 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1252 }
1253
1254 /// Build a new compound statement.
1255 ///
1256 /// By default, performs semantic analysis to build the new statement.
1257 /// Subclasses may override this routine to provide different behavior.
1258 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1259 MultiStmtArg Statements,
1260 SourceLocation RBraceLoc,
1261 bool IsStmtExpr) {
1262 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1263 IsStmtExpr);
1264 }
1265
1266 /// Build a new case statement.
1267 ///
1268 /// By default, performs semantic analysis to build the new statement.
1269 /// Subclasses may override this routine to provide different behavior.
1270 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1271 Expr *LHS,
1272 SourceLocation EllipsisLoc,
1273 Expr *RHS,
1274 SourceLocation ColonLoc) {
1275 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1276 ColonLoc);
1277 }
1278
1279 /// Attach the body to a new case statement.
1280 ///
1281 /// By default, performs semantic analysis to build the new statement.
1282 /// Subclasses may override this routine to provide different behavior.
1283 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1284 getSema().ActOnCaseStmtBody(S, Body);
1285 return S;
1286 }
1287
1288 /// Build a new default statement.
1289 ///
1290 /// By default, performs semantic analysis to build the new statement.
1291 /// Subclasses may override this routine to provide different behavior.
1292 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1293 SourceLocation ColonLoc,
1294 Stmt *SubStmt) {
1295 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1296 /*CurScope=*/nullptr);
1297 }
1298
1299 /// Build a new label statement.
1300 ///
1301 /// By default, performs semantic analysis to build the new statement.
1302 /// Subclasses may override this routine to provide different behavior.
1303 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1304 SourceLocation ColonLoc, Stmt *SubStmt) {
1305 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1306 }
1307
1308 /// Build a new attributed statement.
1309 ///
1310 /// By default, performs semantic analysis to build the new statement.
1311 /// Subclasses may override this routine to provide different behavior.
1312 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1313 ArrayRef<const Attr*> Attrs,
1314 Stmt *SubStmt) {
1315 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1316 }
1317
1318 /// Build a new "if" statement.
1319 ///
1320 /// By default, performs semantic analysis to build the new statement.
1321 /// Subclasses may override this routine to provide different behavior.
1322 StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1323 SourceLocation LParenLoc, Sema::ConditionResult Cond,
1324 SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1325 SourceLocation ElseLoc, Stmt *Else) {
1326 return getSema().ActOnIfStmt(IfLoc, IsConstexpr, LParenLoc, Init, Cond,
1327 RParenLoc, Then, ElseLoc, Else);
1328 }
1329
1330 /// Start building a new switch statement.
1331 ///
1332 /// By default, performs semantic analysis to build the new statement.
1333 /// Subclasses may override this routine to provide different behavior.
1334 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1335 SourceLocation LParenLoc, Stmt *Init,
1336 Sema::ConditionResult Cond,
1337 SourceLocation RParenLoc) {
1338 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1339 RParenLoc);
1340 }
1341
1342 /// Attach the body to the switch statement.
1343 ///
1344 /// By default, performs semantic analysis to build the new statement.
1345 /// Subclasses may override this routine to provide different behavior.
1346 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1347 Stmt *Switch, Stmt *Body) {
1348 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1349 }
1350
1351 /// Build a new while statement.
1352 ///
1353 /// By default, performs semantic analysis to build the new statement.
1354 /// Subclasses may override this routine to provide different behavior.
1355 StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1356 Sema::ConditionResult Cond,
1357 SourceLocation RParenLoc, Stmt *Body) {
1358 return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1359 }
1360
1361 /// Build a new do-while statement.
1362 ///
1363 /// By default, performs semantic analysis to build the new statement.
1364 /// Subclasses may override this routine to provide different behavior.
1365 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1366 SourceLocation WhileLoc, SourceLocation LParenLoc,
1367 Expr *Cond, SourceLocation RParenLoc) {
1368 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1369 Cond, RParenLoc);
1370 }
1371
1372 /// Build a new for statement.
1373 ///
1374 /// By default, performs semantic analysis to build the new statement.
1375 /// Subclasses may override this routine to provide different behavior.
1376 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1377 Stmt *Init, Sema::ConditionResult Cond,
1378 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1379 Stmt *Body) {
1380 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1381 Inc, RParenLoc, Body);
1382 }
1383
1384 /// Build a new goto statement.
1385 ///
1386 /// By default, performs semantic analysis to build the new statement.
1387 /// Subclasses may override this routine to provide different behavior.
1388 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1389 LabelDecl *Label) {
1390 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1391 }
1392
1393 /// Build a new indirect goto statement.
1394 ///
1395 /// By default, performs semantic analysis to build the new statement.
1396 /// Subclasses may override this routine to provide different behavior.
1397 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1398 SourceLocation StarLoc,
1399 Expr *Target) {
1400 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1401 }
1402
1403 /// Build a new return statement.
1404 ///
1405 /// By default, performs semantic analysis to build the new statement.
1406 /// Subclasses may override this routine to provide different behavior.
1407 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1408 return getSema().BuildReturnStmt(ReturnLoc, Result);
1409 }
1410
1411 /// Build a new declaration statement.
1412 ///
1413 /// By default, performs semantic analysis to build the new statement.
1414 /// Subclasses may override this routine to provide different behavior.
1415 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1416 SourceLocation StartLoc, SourceLocation EndLoc) {
1417 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1418 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1419 }
1420
1421 /// Build a new inline asm statement.
1422 ///
1423 /// By default, performs semantic analysis to build the new statement.
1424 /// Subclasses may override this routine to provide different behavior.
1425 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1426 bool IsVolatile, unsigned NumOutputs,
1427 unsigned NumInputs, IdentifierInfo **Names,
1428 MultiExprArg Constraints, MultiExprArg Exprs,
1429 Expr *AsmString, MultiExprArg Clobbers,
1430 unsigned NumLabels,
1431 SourceLocation RParenLoc) {
1432 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1433 NumInputs, Names, Constraints, Exprs,
1434 AsmString, Clobbers, NumLabels, RParenLoc);
1435 }
1436
1437 /// Build a new MS style inline asm statement.
1438 ///
1439 /// By default, performs semantic analysis to build the new statement.
1440 /// Subclasses may override this routine to provide different behavior.
1441 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1442 ArrayRef<Token> AsmToks,
1443 StringRef AsmString,
1444 unsigned NumOutputs, unsigned NumInputs,
1445 ArrayRef<StringRef> Constraints,
1446 ArrayRef<StringRef> Clobbers,
1447 ArrayRef<Expr*> Exprs,
1448 SourceLocation EndLoc) {
1449 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1450 NumOutputs, NumInputs,
1451 Constraints, Clobbers, Exprs, EndLoc);
1452 }
1453
1454 /// Build a new co_return statement.
1455 ///
1456 /// By default, performs semantic analysis to build the new statement.
1457 /// Subclasses may override this routine to provide different behavior.
1458 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1459 bool IsImplicit) {
1460 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1461 }
1462
1463 /// Build a new co_await expression.
1464 ///
1465 /// By default, performs semantic analysis to build the new expression.
1466 /// Subclasses may override this routine to provide different behavior.
1467 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1468 bool IsImplicit) {
1469 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1470 }
1471
1472 /// Build a new co_await expression.
1473 ///
1474 /// By default, performs semantic analysis to build the new expression.
1475 /// Subclasses may override this routine to provide different behavior.
1476 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1477 Expr *Result,
1478 UnresolvedLookupExpr *Lookup) {
1479 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1480 }
1481
1482 /// Build a new co_yield expression.
1483 ///
1484 /// By default, performs semantic analysis to build the new expression.
1485 /// Subclasses may override this routine to provide different behavior.
1486 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1487 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1488 }
1489
1490 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1491 return getSema().BuildCoroutineBodyStmt(Args);
1492 }
1493
1494 /// Build a new Objective-C \@try statement.
1495 ///
1496 /// By default, performs semantic analysis to build the new statement.
1497 /// Subclasses may override this routine to provide different behavior.
1498 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1499 Stmt *TryBody,
1500 MultiStmtArg CatchStmts,
1501 Stmt *Finally) {
1502 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1503 Finally);
1504 }
1505
1506 /// Rebuild an Objective-C exception declaration.
1507 ///
1508 /// By default, performs semantic analysis to build the new declaration.
1509 /// Subclasses may override this routine to provide different behavior.
1510 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1511 TypeSourceInfo *TInfo, QualType T) {
1512 return getSema().BuildObjCExceptionDecl(TInfo, T,
1513 ExceptionDecl->getInnerLocStart(),
1514 ExceptionDecl->getLocation(),
1515 ExceptionDecl->getIdentifier());
1516 }
1517
1518 /// Build a new Objective-C \@catch statement.
1519 ///
1520 /// By default, performs semantic analysis to build the new statement.
1521 /// Subclasses may override this routine to provide different behavior.
1522 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1523 SourceLocation RParenLoc,
1524 VarDecl *Var,
1525 Stmt *Body) {
1526 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1527 Var, Body);
1528 }
1529
1530 /// Build a new Objective-C \@finally statement.
1531 ///
1532 /// By default, performs semantic analysis to build the new statement.
1533 /// Subclasses may override this routine to provide different behavior.
1534 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1535 Stmt *Body) {
1536 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1537 }
1538
1539 /// Build a new Objective-C \@throw statement.
1540 ///
1541 /// By default, performs semantic analysis to build the new statement.
1542 /// Subclasses may override this routine to provide different behavior.
1543 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1544 Expr *Operand) {
1545 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1546 }
1547
1548 /// Build a new OpenMP executable directive.
1549 ///
1550 /// By default, performs semantic analysis to build the new statement.
1551 /// Subclasses may override this routine to provide different behavior.
1552 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1553 DeclarationNameInfo DirName,
1554 OpenMPDirectiveKind CancelRegion,
1555 ArrayRef<OMPClause *> Clauses,
1556 Stmt *AStmt, SourceLocation StartLoc,
1557 SourceLocation EndLoc) {
1558 return getSema().ActOnOpenMPExecutableDirective(
1559 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1560 }
1561
1562 /// Build a new OpenMP 'if' clause.
1563 ///
1564 /// By default, performs semantic analysis to build the new OpenMP clause.
1565 /// Subclasses may override this routine to provide different behavior.
1566 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1567 Expr *Condition, SourceLocation StartLoc,
1568 SourceLocation LParenLoc,
1569 SourceLocation NameModifierLoc,
1570 SourceLocation ColonLoc,
1571 SourceLocation EndLoc) {
1572 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1573 LParenLoc, NameModifierLoc, ColonLoc,
1574 EndLoc);
1575 }
1576
1577 /// Build a new OpenMP 'final' clause.
1578 ///
1579 /// By default, performs semantic analysis to build the new OpenMP clause.
1580 /// Subclasses may override this routine to provide different behavior.
1581 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1582 SourceLocation LParenLoc,
1583 SourceLocation EndLoc) {
1584 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1585 EndLoc);
1586 }
1587
1588 /// Build a new OpenMP 'num_threads' clause.
1589 ///
1590 /// By default, performs semantic analysis to build the new OpenMP clause.
1591 /// Subclasses may override this routine to provide different behavior.
1592 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1593 SourceLocation StartLoc,
1594 SourceLocation LParenLoc,
1595 SourceLocation EndLoc) {
1596 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1597 LParenLoc, EndLoc);
1598 }
1599
1600 /// Build a new OpenMP 'safelen' clause.
1601 ///
1602 /// By default, performs semantic analysis to build the new OpenMP clause.
1603 /// Subclasses may override this routine to provide different behavior.
1604 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1605 SourceLocation LParenLoc,
1606 SourceLocation EndLoc) {
1607 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1608 }
1609
1610 /// Build a new OpenMP 'simdlen' clause.
1611 ///
1612 /// By default, performs semantic analysis to build the new OpenMP clause.
1613 /// Subclasses may override this routine to provide different behavior.
1614 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1615 SourceLocation LParenLoc,
1616 SourceLocation EndLoc) {
1617 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1618 }
1619
1620 /// Build a new OpenMP 'allocator' clause.
1621 ///
1622 /// By default, performs semantic analysis to build the new OpenMP clause.
1623 /// Subclasses may override this routine to provide different behavior.
1624 OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1625 SourceLocation LParenLoc,
1626 SourceLocation EndLoc) {
1627 return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1628 }
1629
1630 /// Build a new OpenMP 'collapse' clause.
1631 ///
1632 /// By default, performs semantic analysis to build the new OpenMP clause.
1633 /// Subclasses may override this routine to provide different behavior.
1634 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1635 SourceLocation LParenLoc,
1636 SourceLocation EndLoc) {
1637 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1638 EndLoc);
1639 }
1640
1641 /// Build a new OpenMP 'default' clause.
1642 ///
1643 /// By default, performs semantic analysis to build the new OpenMP clause.
1644 /// Subclasses may override this routine to provide different behavior.
1645 OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1646 SourceLocation StartLoc,
1647 SourceLocation LParenLoc,
1648 SourceLocation EndLoc) {
1649 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1650 StartLoc, LParenLoc, EndLoc);
1651 }
1652
1653 /// Build a new OpenMP 'proc_bind' clause.
1654 ///
1655 /// By default, performs semantic analysis to build the new OpenMP clause.
1656 /// Subclasses may override this routine to provide different behavior.
1657 OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1658 SourceLocation KindKwLoc,
1659 SourceLocation StartLoc,
1660 SourceLocation LParenLoc,
1661 SourceLocation EndLoc) {
1662 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1663 StartLoc, LParenLoc, EndLoc);
1664 }
1665
1666 /// Build a new OpenMP 'schedule' clause.
1667 ///
1668 /// By default, performs semantic analysis to build the new OpenMP clause.
1669 /// Subclasses may override this routine to provide different behavior.
1670 OMPClause *RebuildOMPScheduleClause(
1671 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1672 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1673 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1674 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1675 return getSema().ActOnOpenMPScheduleClause(
1676 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1677 CommaLoc, EndLoc);
1678 }
1679
1680 /// Build a new OpenMP 'ordered' clause.
1681 ///
1682 /// By default, performs semantic analysis to build the new OpenMP clause.
1683 /// Subclasses may override this routine to provide different behavior.
1684 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1685 SourceLocation EndLoc,
1686 SourceLocation LParenLoc, Expr *Num) {
1687 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1688 }
1689
1690 /// Build a new OpenMP 'private' clause.
1691 ///
1692 /// By default, performs semantic analysis to build the new OpenMP clause.
1693 /// Subclasses may override this routine to provide different behavior.
1694 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1695 SourceLocation StartLoc,
1696 SourceLocation LParenLoc,
1697 SourceLocation EndLoc) {
1698 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1699 EndLoc);
1700 }
1701
1702 /// Build a new OpenMP 'firstprivate' clause.
1703 ///
1704 /// By default, performs semantic analysis to build the new OpenMP clause.
1705 /// Subclasses may override this routine to provide different behavior.
1706 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1707 SourceLocation StartLoc,
1708 SourceLocation LParenLoc,
1709 SourceLocation EndLoc) {
1710 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1711 EndLoc);
1712 }
1713
1714 /// Build a new OpenMP 'lastprivate' clause.
1715 ///
1716 /// By default, performs semantic analysis to build the new OpenMP clause.
1717 /// Subclasses may override this routine to provide different behavior.
1718 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1719 OpenMPLastprivateModifier LPKind,
1720 SourceLocation LPKindLoc,
1721 SourceLocation ColonLoc,
1722 SourceLocation StartLoc,
1723 SourceLocation LParenLoc,
1724 SourceLocation EndLoc) {
1725 return getSema().ActOnOpenMPLastprivateClause(
1726 VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1727 }
1728
1729 /// Build a new OpenMP 'shared' clause.
1730 ///
1731 /// By default, performs semantic analysis to build the new OpenMP clause.
1732 /// Subclasses may override this routine to provide different behavior.
1733 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1734 SourceLocation StartLoc,
1735 SourceLocation LParenLoc,
1736 SourceLocation EndLoc) {
1737 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1738 EndLoc);
1739 }
1740
1741 /// Build a new OpenMP 'reduction' clause.
1742 ///
1743 /// By default, performs semantic analysis to build the new statement.
1744 /// Subclasses may override this routine to provide different behavior.
1745 OMPClause *RebuildOMPReductionClause(
1746 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1747 SourceLocation StartLoc, SourceLocation LParenLoc,
1748 SourceLocation ModifierLoc, SourceLocation ColonLoc,
1749 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1750 const DeclarationNameInfo &ReductionId,
1751 ArrayRef<Expr *> UnresolvedReductions) {
1752 return getSema().ActOnOpenMPReductionClause(
1753 VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1754 ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1755 }
1756
1757 /// Build a new OpenMP 'task_reduction' clause.
1758 ///
1759 /// By default, performs semantic analysis to build the new statement.
1760 /// Subclasses may override this routine to provide different behavior.
1761 OMPClause *RebuildOMPTaskReductionClause(
1762 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1763 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1764 CXXScopeSpec &ReductionIdScopeSpec,
1765 const DeclarationNameInfo &ReductionId,
1766 ArrayRef<Expr *> UnresolvedReductions) {
1767 return getSema().ActOnOpenMPTaskReductionClause(
1768 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1769 ReductionId, UnresolvedReductions);
1770 }
1771
1772 /// Build a new OpenMP 'in_reduction' clause.
1773 ///
1774 /// By default, performs semantic analysis to build the new statement.
1775 /// Subclasses may override this routine to provide different behavior.
1776 OMPClause *
1777 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1778 SourceLocation LParenLoc, SourceLocation ColonLoc,
1779 SourceLocation EndLoc,
1780 CXXScopeSpec &ReductionIdScopeSpec,
1781 const DeclarationNameInfo &ReductionId,
1782 ArrayRef<Expr *> UnresolvedReductions) {
1783 return getSema().ActOnOpenMPInReductionClause(
1784 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1785 ReductionId, UnresolvedReductions);
1786 }
1787
1788 /// Build a new OpenMP 'linear' clause.
1789 ///
1790 /// By default, performs semantic analysis to build the new OpenMP clause.
1791 /// Subclasses may override this routine to provide different behavior.
1792 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1793 SourceLocation StartLoc,
1794 SourceLocation LParenLoc,
1795 OpenMPLinearClauseKind Modifier,
1796 SourceLocation ModifierLoc,
1797 SourceLocation ColonLoc,
1798 SourceLocation EndLoc) {
1799 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1800 Modifier, ModifierLoc, ColonLoc,
1801 EndLoc);
1802 }
1803
1804 /// Build a new OpenMP 'aligned' clause.
1805 ///
1806 /// By default, performs semantic analysis to build the new OpenMP clause.
1807 /// Subclasses may override this routine to provide different behavior.
1808 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1809 SourceLocation StartLoc,
1810 SourceLocation LParenLoc,
1811 SourceLocation ColonLoc,
1812 SourceLocation EndLoc) {
1813 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1814 LParenLoc, ColonLoc, EndLoc);
1815 }
1816
1817 /// Build a new OpenMP 'copyin' clause.
1818 ///
1819 /// By default, performs semantic analysis to build the new OpenMP clause.
1820 /// Subclasses may override this routine to provide different behavior.
1821 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1822 SourceLocation StartLoc,
1823 SourceLocation LParenLoc,
1824 SourceLocation EndLoc) {
1825 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1826 EndLoc);
1827 }
1828
1829 /// Build a new OpenMP 'copyprivate' clause.
1830 ///
1831 /// By default, performs semantic analysis to build the new OpenMP clause.
1832 /// Subclasses may override this routine to provide different behavior.
1833 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1834 SourceLocation StartLoc,
1835 SourceLocation LParenLoc,
1836 SourceLocation EndLoc) {
1837 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1838 EndLoc);
1839 }
1840
1841 /// Build a new OpenMP 'flush' pseudo clause.
1842 ///
1843 /// By default, performs semantic analysis to build the new OpenMP clause.
1844 /// Subclasses may override this routine to provide different behavior.
1845 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1846 SourceLocation StartLoc,
1847 SourceLocation LParenLoc,
1848 SourceLocation EndLoc) {
1849 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1850 EndLoc);
1851 }
1852
1853 /// Build a new OpenMP 'depobj' pseudo clause.
1854 ///
1855 /// By default, performs semantic analysis to build the new OpenMP clause.
1856 /// Subclasses may override this routine to provide different behavior.
1857 OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1858 SourceLocation LParenLoc,
1859 SourceLocation EndLoc) {
1860 return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1861 EndLoc);
1862 }
1863
1864 /// Build a new OpenMP 'depend' pseudo clause.
1865 ///
1866 /// By default, performs semantic analysis to build the new OpenMP clause.
1867 /// Subclasses may override this routine to provide different behavior.
1868 OMPClause *
1869 RebuildOMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
1870 SourceLocation DepLoc, SourceLocation ColonLoc,
1871 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1872 SourceLocation LParenLoc, SourceLocation EndLoc) {
1873 return getSema().ActOnOpenMPDependClause(DepModifier, DepKind, DepLoc,
1874 ColonLoc, VarList, StartLoc,
1875 LParenLoc, EndLoc);
1876 }
1877
1878 /// Build a new OpenMP 'device' clause.
1879 ///
1880 /// By default, performs semantic analysis to build the new statement.
1881 /// Subclasses may override this routine to provide different behavior.
1882 OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1883 Expr *Device, SourceLocation StartLoc,
1884 SourceLocation LParenLoc,
1885 SourceLocation ModifierLoc,
1886 SourceLocation EndLoc) {
1887 return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
1888 LParenLoc, ModifierLoc, EndLoc);
1889 }
1890
1891 /// Build a new OpenMP 'map' clause.
1892 ///
1893 /// By default, performs semantic analysis to build the new OpenMP clause.
1894 /// Subclasses may override this routine to provide different behavior.
1895 OMPClause *RebuildOMPMapClause(
1896 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1897 ArrayRef<SourceLocation> MapTypeModifiersLoc,
1898 CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1899 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1900 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1901 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1902 return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1903 MapperIdScopeSpec, MapperId, MapType,
1904 IsMapTypeImplicit, MapLoc, ColonLoc,
1905 VarList, Locs, UnresolvedMappers);
1906 }
1907
1908 /// Build a new OpenMP 'allocate' clause.
1909 ///
1910 /// By default, performs semantic analysis to build the new OpenMP clause.
1911 /// Subclasses may override this routine to provide different behavior.
1912 OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1913 SourceLocation StartLoc,
1914 SourceLocation LParenLoc,
1915 SourceLocation ColonLoc,
1916 SourceLocation EndLoc) {
1917 return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1918 LParenLoc, ColonLoc, EndLoc);
1919 }
1920
1921 /// Build a new OpenMP 'num_teams' clause.
1922 ///
1923 /// By default, performs semantic analysis to build the new statement.
1924 /// Subclasses may override this routine to provide different behavior.
1925 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1926 SourceLocation LParenLoc,
1927 SourceLocation EndLoc) {
1928 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1929 EndLoc);
1930 }
1931
1932 /// Build a new OpenMP 'thread_limit' clause.
1933 ///
1934 /// By default, performs semantic analysis to build the new statement.
1935 /// Subclasses may override this routine to provide different behavior.
1936 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1937 SourceLocation StartLoc,
1938 SourceLocation LParenLoc,
1939 SourceLocation EndLoc) {
1940 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1941 LParenLoc, EndLoc);
1942 }
1943
1944 /// Build a new OpenMP 'priority' clause.
1945 ///
1946 /// By default, performs semantic analysis to build the new statement.
1947 /// Subclasses may override this routine to provide different behavior.
1948 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1949 SourceLocation LParenLoc,
1950 SourceLocation EndLoc) {
1951 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1952 EndLoc);
1953 }
1954
1955 /// Build a new OpenMP 'grainsize' clause.
1956 ///
1957 /// By default, performs semantic analysis to build the new statement.
1958 /// Subclasses may override this routine to provide different behavior.
1959 OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1960 SourceLocation LParenLoc,
1961 SourceLocation EndLoc) {
1962 return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1963 EndLoc);
1964 }
1965
1966 /// Build a new OpenMP 'num_tasks' clause.
1967 ///
1968 /// By default, performs semantic analysis to build the new statement.
1969 /// Subclasses may override this routine to provide different behavior.
1970 OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1971 SourceLocation LParenLoc,
1972 SourceLocation EndLoc) {
1973 return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1974 EndLoc);
1975 }
1976
1977 /// Build a new OpenMP 'hint' clause.
1978 ///
1979 /// By default, performs semantic analysis to build the new statement.
1980 /// Subclasses may override this routine to provide different behavior.
1981 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1982 SourceLocation LParenLoc,
1983 SourceLocation EndLoc) {
1984 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1985 }
1986
1987 /// Build a new OpenMP 'detach' clause.
1988 ///
1989 /// By default, performs semantic analysis to build the new statement.
1990 /// Subclasses may override this routine to provide different behavior.
1991 OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
1992 SourceLocation LParenLoc,
1993 SourceLocation EndLoc) {
1994 return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
1995 }
1996
1997 /// Build a new OpenMP 'dist_schedule' clause.
1998 ///
1999 /// By default, performs semantic analysis to build the new OpenMP clause.
2000 /// Subclasses may override this routine to provide different behavior.
2001 OMPClause *
2002 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2003 Expr *ChunkSize, SourceLocation StartLoc,
2004 SourceLocation LParenLoc, SourceLocation KindLoc,
2005 SourceLocation CommaLoc, SourceLocation EndLoc) {
2006 return getSema().ActOnOpenMPDistScheduleClause(
2007 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2008 }
2009
2010 /// Build a new OpenMP 'to' clause.
2011 ///
2012 /// By default, performs semantic analysis to build the new statement.
2013 /// Subclasses may override this routine to provide different behavior.
2014 OMPClause *
2015 RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2016 ArrayRef<SourceLocation> MotionModifiersLoc,
2017 CXXScopeSpec &MapperIdScopeSpec,
2018 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2019 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2020 ArrayRef<Expr *> UnresolvedMappers) {
2021 return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2022 MapperIdScopeSpec, MapperId, ColonLoc,
2023 VarList, Locs, UnresolvedMappers);
2024 }
2025
2026 /// Build a new OpenMP 'from' clause.
2027 ///
2028 /// By default, performs semantic analysis to build the new statement.
2029 /// Subclasses may override this routine to provide different behavior.
2030 OMPClause *
2031 RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2032 ArrayRef<SourceLocation> MotionModifiersLoc,
2033 CXXScopeSpec &MapperIdScopeSpec,
2034 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2035 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2036 ArrayRef<Expr *> UnresolvedMappers) {
2037 return getSema().ActOnOpenMPFromClause(
2038 MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2039 ColonLoc, VarList, Locs, UnresolvedMappers);
2040 }
2041
2042 /// Build a new OpenMP 'use_device_ptr' clause.
2043 ///
2044 /// By default, performs semantic analysis to build the new OpenMP clause.
2045 /// Subclasses may override this routine to provide different behavior.
2046 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2047 const OMPVarListLocTy &Locs) {
2048 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2049 }
2050
2051 /// Build a new OpenMP 'use_device_addr' clause.
2052 ///
2053 /// By default, performs semantic analysis to build the new OpenMP clause.
2054 /// Subclasses may override this routine to provide different behavior.
2055 OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2056 const OMPVarListLocTy &Locs) {
2057 return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2058 }
2059
2060 /// Build a new OpenMP 'is_device_ptr' clause.
2061 ///
2062 /// By default, performs semantic analysis to build the new OpenMP clause.
2063 /// Subclasses may override this routine to provide different behavior.
2064 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2065 const OMPVarListLocTy &Locs) {
2066 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2067 }
2068
2069 /// Build a new OpenMP 'defaultmap' clause.
2070 ///
2071 /// By default, performs semantic analysis to build the new OpenMP clause.
2072 /// Subclasses may override this routine to provide different behavior.
2073 OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2074 OpenMPDefaultmapClauseKind Kind,
2075 SourceLocation StartLoc,
2076 SourceLocation LParenLoc,
2077 SourceLocation MLoc,
2078 SourceLocation KindLoc,
2079 SourceLocation EndLoc) {
2080 return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2081 MLoc, KindLoc, EndLoc);
2082 }
2083
2084 /// Build a new OpenMP 'nontemporal' clause.
2085 ///
2086 /// By default, performs semantic analysis to build the new OpenMP clause.
2087 /// Subclasses may override this routine to provide different behavior.
2088 OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2089 SourceLocation StartLoc,
2090 SourceLocation LParenLoc,
2091 SourceLocation EndLoc) {
2092 return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2093 EndLoc);
2094 }
2095
2096 /// Build a new OpenMP 'inclusive' clause.
2097 ///
2098 /// By default, performs semantic analysis to build the new OpenMP clause.
2099 /// Subclasses may override this routine to provide different behavior.
2100 OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2101 SourceLocation StartLoc,
2102 SourceLocation LParenLoc,
2103 SourceLocation EndLoc) {
2104 return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2105 EndLoc);
2106 }
2107
2108 /// Build a new OpenMP 'exclusive' clause.
2109 ///
2110 /// By default, performs semantic analysis to build the new OpenMP clause.
2111 /// Subclasses may override this routine to provide different behavior.
2112 OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2113 SourceLocation StartLoc,
2114 SourceLocation LParenLoc,
2115 SourceLocation EndLoc) {
2116 return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2117 EndLoc);
2118 }
2119
2120 /// Build a new OpenMP 'uses_allocators' clause.
2121 ///
2122 /// By default, performs semantic analysis to build the new OpenMP clause.
2123 /// Subclasses may override this routine to provide different behavior.
2124 OMPClause *RebuildOMPUsesAllocatorsClause(
2125 ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2126 SourceLocation LParenLoc, SourceLocation EndLoc) {
2127 return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2128 Data);
2129 }
2130
2131 /// Build a new OpenMP 'affinity' clause.
2132 ///
2133 /// By default, performs semantic analysis to build the new OpenMP clause.
2134 /// Subclasses may override this routine to provide different behavior.
2135 OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2136 SourceLocation LParenLoc,
2137 SourceLocation ColonLoc,
2138 SourceLocation EndLoc, Expr *Modifier,
2139 ArrayRef<Expr *> Locators) {
2140 return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2141 EndLoc, Modifier, Locators);
2142 }
2143
2144 /// Build a new OpenMP 'order' clause.
2145 ///
2146 /// By default, performs semantic analysis to build the new OpenMP clause.
2147 /// Subclasses may override this routine to provide different behavior.
2148 OMPClause *RebuildOMPOrderClause(OpenMPOrderClauseKind Kind,
2149 SourceLocation KindKwLoc,
2150 SourceLocation StartLoc,
2151 SourceLocation LParenLoc,
2152 SourceLocation EndLoc) {
2153 return getSema().ActOnOpenMPOrderClause(Kind, KindKwLoc, StartLoc,
2154 LParenLoc, EndLoc);
2155 }
2156
2157 /// Rebuild the operand to an Objective-C \@synchronized statement.
2158 ///
2159 /// By default, performs semantic analysis to build the new statement.
2160 /// Subclasses may override this routine to provide different behavior.
2161 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2162 Expr *object) {
2163 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2164 }
2165
2166 /// Build a new Objective-C \@synchronized statement.
2167 ///
2168 /// By default, performs semantic analysis to build the new statement.
2169 /// Subclasses may override this routine to provide different behavior.
2170 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2171 Expr *Object, Stmt *Body) {
2172 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2173 }
2174
2175 /// Build a new Objective-C \@autoreleasepool statement.
2176 ///
2177 /// By default, performs semantic analysis to build the new statement.
2178 /// Subclasses may override this routine to provide different behavior.
2179 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2180 Stmt *Body) {
2181 return getSema().ActOn