Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

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

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

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/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/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExprOpenMP.h"
25#include "clang/AST/OpenMPClause.h"
26#include "clang/AST/Stmt.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/AST/StmtObjC.h"
29#include "clang/AST/StmtOpenMP.h"
30#include "clang/Sema/Designator.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Ownership.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/SemaDiagnostic.h"
36#include "clang/Sema/SemaInternal.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/Support/ErrorHandling.h"
39#include <algorithm>
40
41using namespace llvm::omp;
42
43namespace clang {
44using namespace sema;
45
46/// A semantic tree transformation that allows one to transform one
47/// abstract syntax tree into another.
48///
49/// A new tree transformation is defined by creating a new subclass \c X of
50/// \c TreeTransform<X> and then overriding certain operations to provide
51/// behavior specific to that transformation. For example, template
52/// instantiation is implemented as a tree transformation where the
53/// transformation of TemplateTypeParmType nodes involves substituting the
54/// template arguments for their corresponding template parameters; a similar
55/// transformation is performed for non-type template parameters and
56/// template template parameters.
57///
58/// This tree-transformation template uses static polymorphism to allow
59/// subclasses to customize any of its operations. Thus, a subclass can
60/// override any of the transformation or rebuild operators by providing an
61/// operation with the same signature as the default implementation. The
62/// overriding function should not be virtual.
63///
64/// Semantic tree transformations are split into two stages, either of which
65/// can be replaced by a subclass. The "transform" step transforms an AST node
66/// or the parts of an AST node using the various transformation functions,
67/// then passes the pieces on to the "rebuild" step, which constructs a new AST
68/// node of the appropriate kind from the pieces. The default transformation
69/// routines recursively transform the operands to composite AST nodes (e.g.,
70/// the pointee type of a PointerType node) and, if any of those operand nodes
71/// were changed by the transformation, invokes the rebuild operation to create
72/// a new AST node.
73///
74/// Subclasses can customize the transformation at various levels. The
75/// most coarse-grained transformations involve replacing TransformType(),
76/// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
77/// TransformTemplateName(), or TransformTemplateArgument() with entirely
78/// new implementations.
79///
80/// For more fine-grained transformations, subclasses can replace any of the
81/// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
82/// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
83/// replacing TransformTemplateTypeParmType() allows template instantiation
84/// to substitute template arguments for their corresponding template
85/// parameters. Additionally, subclasses can override the \c RebuildXXX
86/// functions to control how AST nodes are rebuilt when their operands change.
87/// By default, \c TreeTransform will invoke semantic analysis to rebuild
88/// AST nodes. However, certain other tree transformations (e.g, cloning) may
89/// be able to use more efficient rebuild steps.
90///
91/// There are a handful of other functions that can be overridden, allowing one
92/// to avoid traversing nodes that don't need any transformation
93/// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
94/// operands have not changed (\c AlwaysRebuild()), and customize the
95/// default locations and entity names used for type-checking
96/// (\c getBaseLocation(), \c getBaseEntity()).
97template<typename Derived>
98class TreeTransform {
99 /// Private RAII object that helps us forget and then re-remember
100 /// the template argument corresponding to a partially-substituted parameter
101 /// pack.
102 class ForgetPartiallySubstitutedPackRAII {
103 Derived &Self;
104 TemplateArgument Old;
105
106 public:
107 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
108 Old = Self.ForgetPartiallySubstitutedPack();
109 }
110
111 ~ForgetPartiallySubstitutedPackRAII() {
112 Self.RememberPartiallySubstitutedPack(Old);
113 }
114 };
115
116protected:
117 Sema &SemaRef;
118
119 /// The set of local declarations that have been transformed, for
120 /// cases where we are forced to build new declarations within the transformer
121 /// rather than in the subclass (e.g., lambda closure types).
122 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
123
124public:
125 /// Initializes a new tree transformer.
126 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
127
128 /// Retrieves a reference to the derived class.
129 Derived &getDerived() { return static_cast<Derived&>(*this); }
130
131 /// Retrieves a reference to the derived class.
132 const Derived &getDerived() const {
133 return static_cast<const Derived&>(*this);
134 }
135
136 static inline ExprResult Owned(Expr *E) { return E; }
137 static inline StmtResult Owned(Stmt *S) { return S; }
138
139 /// Retrieves a reference to the semantic analysis object used for
140 /// this tree transform.
141 Sema &getSema() const { return SemaRef; }
142
143 /// Whether the transformation should always rebuild AST nodes, even
144 /// if none of the children have changed.
145 ///
146 /// Subclasses may override this function to specify when the transformation
147 /// should rebuild all AST nodes.
148 ///
149 /// We must always rebuild all AST nodes when performing variadic template
150 /// pack expansion, in order to avoid violating the AST invariant that each
151 /// statement node appears at most once in its containing declaration.
152 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
153
154 /// Whether the transformation is forming an expression or statement that
155 /// replaces the original. In this case, we'll reuse mangling numbers from
156 /// existing lambdas.
157 bool ReplacingOriginal() { return false; }
158
159 /// Returns the location of the entity being transformed, if that
160 /// information was not available elsewhere in the AST.
161 ///
162 /// By default, returns no source-location information. Subclasses can
163 /// provide an alternative implementation that provides better location
164 /// information.
165 SourceLocation getBaseLocation() { return SourceLocation(); }
166
167 /// Returns the name of the entity being transformed, if that
168 /// information was not available elsewhere in the AST.
169 ///
170 /// By default, returns an empty name. Subclasses can provide an alternative
171 /// implementation with a more precise name.
172 DeclarationName getBaseEntity() { return DeclarationName(); }
173
174 /// Sets the "base" location and entity when that
175 /// information is known based on another transformation.
176 ///
177 /// By default, the source location and entity are ignored. Subclasses can
178 /// override this function to provide a customized implementation.
179 void setBase(SourceLocation Loc, DeclarationName Entity) { }
180
181 /// RAII object that temporarily sets the base location and entity
182 /// used for reporting diagnostics in types.
183 class TemporaryBase {
184 TreeTransform &Self;
185 SourceLocation OldLocation;
186 DeclarationName OldEntity;
187
188 public:
189 TemporaryBase(TreeTransform &Self, SourceLocation Location,
190 DeclarationName Entity) : Self(Self) {
191 OldLocation = Self.getDerived().getBaseLocation();
192 OldEntity = Self.getDerived().getBaseEntity();
193
194 if (Location.isValid())
195 Self.getDerived().setBase(Location, Entity);
196 }
197
198 ~TemporaryBase() {
199 Self.getDerived().setBase(OldLocation, OldEntity);
200 }
201 };
202
203 /// Determine whether the given type \p T has already been
204 /// transformed.
205 ///
206 /// Subclasses can provide an alternative implementation of this routine
207 /// to short-circuit evaluation when it is known that a given type will
208 /// not change. For example, template instantiation need not traverse
209 /// non-dependent types.
210 bool AlreadyTransformed(QualType T) {
211 return T.isNull();
212 }
213
214 /// Determine whether the given call argument should be dropped, e.g.,
215 /// because it is a default argument.
216 ///
217 /// Subclasses can provide an alternative implementation of this routine to
218 /// determine which kinds of call arguments get dropped. By default,
219 /// CXXDefaultArgument nodes are dropped (prior to transformation).
220 bool DropCallArgument(Expr *E) {
221 return E->isDefaultArgument();
222 }
223
224 /// Determine whether we should expand a pack expansion with the
225 /// given set of parameter packs into separate arguments by repeatedly
226 /// transforming the pattern.
227 ///
228 /// By default, the transformer never tries to expand pack expansions.
229 /// Subclasses can override this routine to provide different behavior.
230 ///
231 /// \param EllipsisLoc The location of the ellipsis that identifies the
232 /// pack expansion.
233 ///
234 /// \param PatternRange The source range that covers the entire pattern of
235 /// the pack expansion.
236 ///
237 /// \param Unexpanded The set of unexpanded parameter packs within the
238 /// pattern.
239 ///
240 /// \param ShouldExpand Will be set to \c true if the transformer should
241 /// expand the corresponding pack expansions into separate arguments. When
242 /// set, \c NumExpansions must also be set.
243 ///
244 /// \param RetainExpansion Whether the caller should add an unexpanded
245 /// pack expansion after all of the expanded arguments. This is used
246 /// when extending explicitly-specified template argument packs per
247 /// C++0x [temp.arg.explicit]p9.
248 ///
249 /// \param NumExpansions The number of separate arguments that will be in
250 /// the expanded form of the corresponding pack expansion. This is both an
251 /// input and an output parameter, which can be set by the caller if the
252 /// number of expansions is known a priori (e.g., due to a prior substitution)
253 /// and will be set by the callee when the number of expansions is known.
254 /// The callee must set this value when \c ShouldExpand is \c true; it may
255 /// set this value in other cases.
256 ///
257 /// \returns true if an error occurred (e.g., because the parameter packs
258 /// are to be instantiated with arguments of different lengths), false
259 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
260 /// must be set.
261 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
262 SourceRange PatternRange,
263 ArrayRef<UnexpandedParameterPack> Unexpanded,
264 bool &ShouldExpand,
265 bool &RetainExpansion,
266 Optional<unsigned> &NumExpansions) {
267 ShouldExpand = false;
268 return false;
269 }
270
271 /// "Forget" about the partially-substituted pack template argument,
272 /// when performing an instantiation that must preserve the parameter pack
273 /// use.
274 ///
275 /// This routine is meant to be overridden by the template instantiator.
276 TemplateArgument ForgetPartiallySubstitutedPack() {
277 return TemplateArgument();
278 }
279
280 /// "Remember" the partially-substituted pack template argument
281 /// after performing an instantiation that must preserve the parameter pack
282 /// use.
283 ///
284 /// This routine is meant to be overridden by the template instantiator.
285 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
286
287 /// Note to the derived class when a function parameter pack is
288 /// being expanded.
289 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
290
291 /// Transforms the given type into another type.
292 ///
293 /// By default, this routine transforms a type by creating a
294 /// TypeSourceInfo for it and delegating to the appropriate
295 /// function. This is expensive, but we don't mind, because
296 /// this method is deprecated anyway; all users should be
297 /// switched to storing TypeSourceInfos.
298 ///
299 /// \returns the transformed type.
300 QualType TransformType(QualType T);
301
302 /// Transforms the given type-with-location into a new
303 /// type-with-location.
304 ///
305 /// By default, this routine transforms a type by delegating to the
306 /// appropriate TransformXXXType to build a new type. Subclasses
307 /// may override this function (to take over all type
308 /// transformations) or some set of the TransformXXXType functions
309 /// to alter the transformation.
310 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
311
312 /// Transform the given type-with-location into a new
313 /// type, collecting location information in the given builder
314 /// as necessary.
315 ///
316 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
317
318 /// Transform a type that is permitted to produce a
319 /// DeducedTemplateSpecializationType.
320 ///
321 /// This is used in the (relatively rare) contexts where it is acceptable
322 /// for transformation to produce a class template type with deduced
323 /// template arguments.
324 /// @{
325 QualType TransformTypeWithDeducedTST(QualType T);
326 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
327 /// @}
328
329 /// The reason why the value of a statement is not discarded, if any.
330 enum StmtDiscardKind {
331 SDK_Discarded,
332 SDK_NotDiscarded,
333 SDK_StmtExprResult,
334 };
335
336 /// Transform the given statement.
337 ///
338 /// By default, this routine transforms a statement by delegating to the
339 /// appropriate TransformXXXStmt function to transform a specific kind of
340 /// statement or the TransformExpr() function to transform an expression.
341 /// Subclasses may override this function to transform statements using some
342 /// other mechanism.
343 ///
344 /// \returns the transformed statement.
345 StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
346
347 /// Transform the given statement.
348 ///
349 /// By default, this routine transforms a statement by delegating to the
350 /// appropriate TransformOMPXXXClause function to transform a specific kind
351 /// of clause. Subclasses may override this function to transform statements
352 /// using some other mechanism.
353 ///
354 /// \returns the transformed OpenMP clause.
355 OMPClause *TransformOMPClause(OMPClause *S);
356
357 /// Transform the given attribute.
358 ///
359 /// By default, this routine transforms a statement by delegating to the
360 /// appropriate TransformXXXAttr function to transform a specific kind
361 /// of attribute. Subclasses may override this function to transform
362 /// attributed statements using some other mechanism.
363 ///
364 /// \returns the transformed attribute
365 const Attr *TransformAttr(const Attr *S);
366
367/// Transform the specified attribute.
368///
369/// Subclasses should override the transformation of attributes with a pragma
370/// spelling to transform expressions stored within the attribute.
371///
372/// \returns the transformed attribute.
373#define ATTR(X)
374#define PRAGMA_SPELLING_ATTR(X) \
375 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
376#include "clang/Basic/AttrList.inc"
377
378 /// Transform the given expression.
379 ///
380 /// By default, this routine transforms an expression by delegating to the
381 /// appropriate TransformXXXExpr function to build a new expression.
382 /// Subclasses may override this function to transform expressions using some
383 /// other mechanism.
384 ///
385 /// \returns the transformed expression.
386 ExprResult TransformExpr(Expr *E);
387
388 /// Transform the given initializer.
389 ///
390 /// By default, this routine transforms an initializer by stripping off the
391 /// semantic nodes added by initialization, then passing the result to
392 /// TransformExpr or TransformExprs.
393 ///
394 /// \returns the transformed initializer.
395 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
396
397 /// Transform the given list of expressions.
398 ///
399 /// This routine transforms a list of expressions by invoking
400 /// \c TransformExpr() for each subexpression. However, it also provides
401 /// support for variadic templates by expanding any pack expansions (if the
402 /// derived class permits such expansion) along the way. When pack expansions
403 /// are present, the number of outputs may not equal the number of inputs.
404 ///
405 /// \param Inputs The set of expressions to be transformed.
406 ///
407 /// \param NumInputs The number of expressions in \c Inputs.
408 ///
409 /// \param IsCall If \c true, then this transform is being performed on
410 /// function-call arguments, and any arguments that should be dropped, will
411 /// be.
412 ///
413 /// \param Outputs The transformed input expressions will be added to this
414 /// vector.
415 ///
416 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
417 /// due to transformation.
418 ///
419 /// \returns true if an error occurred, false otherwise.
420 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
421 SmallVectorImpl<Expr *> &Outputs,
422 bool *ArgChanged = nullptr);
423
424 /// Transform the given declaration, which is referenced from a type
425 /// or expression.
426 ///
427 /// By default, acts as the identity function on declarations, unless the
428 /// transformer has had to transform the declaration itself. Subclasses
429 /// may override this function to provide alternate behavior.
430 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
431 llvm::DenseMap<Decl *, Decl *>::iterator Known
432 = TransformedLocalDecls.find(D);
433 if (Known != TransformedLocalDecls.end())
434 return Known->second;
435
436 return D;
437 }
438
439 /// Transform the specified condition.
440 ///
441 /// By default, this transforms the variable and expression and rebuilds
442 /// the condition.
443 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
444 Expr *Expr,
445 Sema::ConditionKind Kind);
446
447 /// Transform the attributes associated with the given declaration and
448 /// place them on the new declaration.
449 ///
450 /// By default, this operation does nothing. Subclasses may override this
451 /// behavior to transform attributes.
452 void transformAttrs(Decl *Old, Decl *New) { }
453
454 /// Note that a local declaration has been transformed by this
455 /// transformer.
456 ///
457 /// Local declarations are typically transformed via a call to
458 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
459 /// the transformer itself has to transform the declarations. This routine
460 /// can be overridden by a subclass that keeps track of such mappings.
461 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
462 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/TreeTransform.h"
, 463, __PRETTY_FUNCTION__))
463 "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/TreeTransform.h"
, 463, __PRETTY_FUNCTION__))
;
464 TransformedLocalDecls[Old] = New.front();
465 }
466
467 /// Transform the definition of the given declaration.
468 ///
469 /// By default, invokes TransformDecl() to transform the declaration.
470 /// Subclasses may override this function to provide alternate behavior.
471 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
472 return getDerived().TransformDecl(Loc, D);
473 }
474
475 /// Transform the given declaration, which was the first part of a
476 /// nested-name-specifier in a member access expression.
477 ///
478 /// This specific declaration transformation only applies to the first
479 /// identifier in a nested-name-specifier of a member access expression, e.g.,
480 /// the \c T in \c x->T::member
481 ///
482 /// By default, invokes TransformDecl() to transform the declaration.
483 /// Subclasses may override this function to provide alternate behavior.
484 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
485 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
486 }
487
488 /// Transform the set of declarations in an OverloadExpr.
489 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
490 LookupResult &R);
491
492 /// Transform the given nested-name-specifier with source-location
493 /// information.
494 ///
495 /// By default, transforms all of the types and declarations within the
496 /// nested-name-specifier. Subclasses may override this function to provide
497 /// alternate behavior.
498 NestedNameSpecifierLoc
499 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
500 QualType ObjectType = QualType(),
501 NamedDecl *FirstQualifierInScope = nullptr);
502
503 /// Transform the given declaration name.
504 ///
505 /// By default, transforms the types of conversion function, constructor,
506 /// and destructor names and then (if needed) rebuilds the declaration name.
507 /// Identifiers and selectors are returned unmodified. Sublcasses may
508 /// override this function to provide alternate behavior.
509 DeclarationNameInfo
510 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
511
512 /// Transform the given template name.
513 ///
514 /// \param SS The nested-name-specifier that qualifies the template
515 /// name. This nested-name-specifier must already have been transformed.
516 ///
517 /// \param Name The template name to transform.
518 ///
519 /// \param NameLoc The source location of the template name.
520 ///
521 /// \param ObjectType If we're translating a template name within a member
522 /// access expression, this is the type of the object whose member template
523 /// is being referenced.
524 ///
525 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
526 /// also refers to a name within the current (lexical) scope, this is the
527 /// declaration it refers to.
528 ///
529 /// By default, transforms the template name by transforming the declarations
530 /// and nested-name-specifiers that occur within the template name.
531 /// Subclasses may override this function to provide alternate behavior.
532 TemplateName
533 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
534 SourceLocation NameLoc,
535 QualType ObjectType = QualType(),
536 NamedDecl *FirstQualifierInScope = nullptr,
537 bool AllowInjectedClassName = false);
538
539 /// Transform the given template argument.
540 ///
541 /// By default, this operation transforms the type, expression, or
542 /// declaration stored within the template argument and constructs a
543 /// new template argument from the transformed result. Subclasses may
544 /// override this function to provide alternate behavior.
545 ///
546 /// Returns true if there was an error.
547 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
548 TemplateArgumentLoc &Output,
549 bool Uneval = false);
550
551 /// Transform the given set of template arguments.
552 ///
553 /// By default, this operation transforms all of the template arguments
554 /// in the input set using \c TransformTemplateArgument(), and appends
555 /// the transformed arguments to the output list.
556 ///
557 /// Note that this overload of \c TransformTemplateArguments() is merely
558 /// a convenience function. Subclasses that wish to override this behavior
559 /// should override the iterator-based member template version.
560 ///
561 /// \param Inputs The set of template arguments to be transformed.
562 ///
563 /// \param NumInputs The number of template arguments in \p Inputs.
564 ///
565 /// \param Outputs The set of transformed template arguments output by this
566 /// routine.
567 ///
568 /// Returns true if an error occurred.
569 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
570 unsigned NumInputs,
571 TemplateArgumentListInfo &Outputs,
572 bool Uneval = false) {
573 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
574 Uneval);
575 }
576
577 /// Transform the given set of template arguments.
578 ///
579 /// By default, this operation transforms all of the template arguments
580 /// in the input set using \c TransformTemplateArgument(), and appends
581 /// the transformed arguments to the output list.
582 ///
583 /// \param First An iterator to the first template argument.
584 ///
585 /// \param Last An iterator one step past the last template argument.
586 ///
587 /// \param Outputs The set of transformed template arguments output by this
588 /// routine.
589 ///
590 /// Returns true if an error occurred.
591 template<typename InputIterator>
592 bool TransformTemplateArguments(InputIterator First,
593 InputIterator Last,
594 TemplateArgumentListInfo &Outputs,
595 bool Uneval = false);
596
597 /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
598 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
599 TemplateArgumentLoc &ArgLoc);
600
601 /// Fakes up a TypeSourceInfo for a type.
602 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
603 return SemaRef.Context.getTrivialTypeSourceInfo(T,
604 getDerived().getBaseLocation());
605 }
606
607#define ABSTRACT_TYPELOC(CLASS, PARENT)
608#define TYPELOC(CLASS, PARENT) \
609 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
610#include "clang/AST/TypeLocNodes.def"
611
612 template<typename Fn>
613 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
614 FunctionProtoTypeLoc TL,
615 CXXRecordDecl *ThisContext,
616 Qualifiers ThisTypeQuals,
617 Fn TransformExceptionSpec);
618
619 bool TransformExceptionSpec(SourceLocation Loc,
620 FunctionProtoType::ExceptionSpecInfo &ESI,
621 SmallVectorImpl<QualType> &Exceptions,
622 bool &Changed);
623
624 StmtResult TransformSEHHandler(Stmt *Handler);
625
626 QualType
627 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
628 TemplateSpecializationTypeLoc TL,
629 TemplateName Template);
630
631 QualType
632 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
633 DependentTemplateSpecializationTypeLoc TL,
634 TemplateName Template,
635 CXXScopeSpec &SS);
636
637 QualType TransformDependentTemplateSpecializationType(
638 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
639 NestedNameSpecifierLoc QualifierLoc);
640
641 /// Transforms the parameters of a function type into the
642 /// given vectors.
643 ///
644 /// The result vectors should be kept in sync; null entries in the
645 /// variables vector are acceptable.
646 ///
647 /// Return true on error.
648 bool TransformFunctionTypeParams(
649 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
650 const QualType *ParamTypes,
651 const FunctionProtoType::ExtParameterInfo *ParamInfos,
652 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
653 Sema::ExtParameterInfoBuilder &PInfos);
654
655 /// Transforms a single function-type parameter. Return null
656 /// on error.
657 ///
658 /// \param indexAdjustment - A number to add to the parameter's
659 /// scope index; can be negative
660 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
661 int indexAdjustment,
662 Optional<unsigned> NumExpansions,
663 bool ExpectParameterPack);
664
665 /// Transform the body of a lambda-expression.
666 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
667 /// Alternative implementation of TransformLambdaBody that skips transforming
668 /// the body.
669 StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
670
671 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
672
673 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
674 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
675
676 TemplateParameterList *TransformTemplateParameterList(
677 TemplateParameterList *TPL) {
678 return TPL;
679 }
680
681 ExprResult TransformAddressOfOperand(Expr *E);
682
683 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
684 bool IsAddressOfOperand,
685 TypeSourceInfo **RecoveryTSI);
686
687 ExprResult TransformParenDependentScopeDeclRefExpr(
688 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
689 TypeSourceInfo **RecoveryTSI);
690
691 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
692
693// FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
694// amount of stack usage with clang.
695#define STMT(Node, Parent) \
696 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
697 StmtResult Transform##Node(Node *S);
698#define VALUESTMT(Node, Parent) \
699 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
700 StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
701#define EXPR(Node, Parent) \
702 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
703 ExprResult Transform##Node(Node *E);
704#define ABSTRACT_STMT(Stmt)
705#include "clang/AST/StmtNodes.inc"
706
707#define OPENMP_CLAUSE(Name, Class) \
708 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
709 OMPClause *Transform ## Class(Class *S);
710#include "clang/Basic/OpenMPKinds.def"
711
712 /// Build a new qualified type given its unqualified type and type location.
713 ///
714 /// By default, this routine adds type qualifiers only to types that can
715 /// have qualifiers, and silently suppresses those qualifiers that are not
716 /// permitted. Subclasses may override this routine to provide different
717 /// behavior.
718 QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
719
720 /// Build a new pointer type given its pointee type.
721 ///
722 /// By default, performs semantic analysis when building the pointer type.
723 /// Subclasses may override this routine to provide different behavior.
724 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
725
726 /// Build a new block pointer type given its pointee type.
727 ///
728 /// By default, performs semantic analysis when building the block pointer
729 /// type. Subclasses may override this routine to provide different behavior.
730 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
731
732 /// Build a new reference type given the type it references.
733 ///
734 /// By default, performs semantic analysis when building the
735 /// reference type. Subclasses may override this routine to provide
736 /// different behavior.
737 ///
738 /// \param LValue whether the type was written with an lvalue sigil
739 /// or an rvalue sigil.
740 QualType RebuildReferenceType(QualType ReferentType,
741 bool LValue,
742 SourceLocation Sigil);
743
744 /// Build a new member pointer type given the pointee type and the
745 /// class type it refers into.
746 ///
747 /// By default, performs semantic analysis when building the member pointer
748 /// type. Subclasses may override this routine to provide different behavior.
749 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
750 SourceLocation Sigil);
751
752 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
753 SourceLocation ProtocolLAngleLoc,
754 ArrayRef<ObjCProtocolDecl *> Protocols,
755 ArrayRef<SourceLocation> ProtocolLocs,
756 SourceLocation ProtocolRAngleLoc);
757
758 /// Build an Objective-C object type.
759 ///
760 /// By default, performs semantic analysis when building the object type.
761 /// Subclasses may override this routine to provide different behavior.
762 QualType RebuildObjCObjectType(QualType BaseType,
763 SourceLocation Loc,
764 SourceLocation TypeArgsLAngleLoc,
765 ArrayRef<TypeSourceInfo *> TypeArgs,
766 SourceLocation TypeArgsRAngleLoc,
767 SourceLocation ProtocolLAngleLoc,
768 ArrayRef<ObjCProtocolDecl *> Protocols,
769 ArrayRef<SourceLocation> ProtocolLocs,
770 SourceLocation ProtocolRAngleLoc);
771
772 /// Build a new Objective-C object pointer type given the pointee type.
773 ///
774 /// By default, directly builds the pointer type, with no additional semantic
775 /// analysis.
776 QualType RebuildObjCObjectPointerType(QualType PointeeType,
777 SourceLocation Star);
778
779 /// Build a new array type given the element type, size
780 /// modifier, size of the array (if known), size expression, and index type
781 /// qualifiers.
782 ///
783 /// By default, performs semantic analysis when building the array type.
784 /// Subclasses may override this routine to provide different behavior.
785 /// Also by default, all of the other Rebuild*Array
786 QualType RebuildArrayType(QualType ElementType,
787 ArrayType::ArraySizeModifier SizeMod,
788 const llvm::APInt *Size,
789 Expr *SizeExpr,
790 unsigned IndexTypeQuals,
791 SourceRange BracketsRange);
792
793 /// Build a new constant array type given the element type, size
794 /// modifier, (known) size of the array, and index type qualifiers.
795 ///
796 /// By default, performs semantic analysis when building the array type.
797 /// Subclasses may override this routine to provide different behavior.
798 QualType RebuildConstantArrayType(QualType ElementType,
799 ArrayType::ArraySizeModifier SizeMod,
800 const llvm::APInt &Size,
801 Expr *SizeExpr,
802 unsigned IndexTypeQuals,
803 SourceRange BracketsRange);
804
805 /// Build a new incomplete array type given the element type, size
806 /// modifier, and index type qualifiers.
807 ///
808 /// By default, performs semantic analysis when building the array type.
809 /// Subclasses may override this routine to provide different behavior.
810 QualType RebuildIncompleteArrayType(QualType ElementType,
811 ArrayType::ArraySizeModifier SizeMod,
812 unsigned IndexTypeQuals,
813 SourceRange BracketsRange);
814
815 /// Build a new variable-length array type given the element type,
816 /// size modifier, size expression, and index type qualifiers.
817 ///
818 /// By default, performs semantic analysis when building the array type.
819 /// Subclasses may override this routine to provide different behavior.
820 QualType RebuildVariableArrayType(QualType ElementType,
821 ArrayType::ArraySizeModifier SizeMod,
822 Expr *SizeExpr,
823 unsigned IndexTypeQuals,
824 SourceRange BracketsRange);
825
826 /// Build a new dependent-sized array type given the element type,
827 /// size modifier, size expression, and index type qualifiers.
828 ///
829 /// By default, performs semantic analysis when building the array type.
830 /// Subclasses may override this routine to provide different behavior.
831 QualType RebuildDependentSizedArrayType(QualType ElementType,
832 ArrayType::ArraySizeModifier SizeMod,
833 Expr *SizeExpr,
834 unsigned IndexTypeQuals,
835 SourceRange BracketsRange);
836
837 /// Build a new vector type given the element type and
838 /// number of elements.
839 ///
840 /// By default, performs semantic analysis when building the vector type.
841 /// Subclasses may override this routine to provide different behavior.
842 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
843 VectorType::VectorKind VecKind);
844
845 /// Build a new potentially dependently-sized extended vector type
846 /// given the element type and number of elements.
847 ///
848 /// By default, performs semantic analysis when building the vector type.
849 /// Subclasses may override this routine to provide different behavior.
850 QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
851 SourceLocation AttributeLoc,
852 VectorType::VectorKind);
853
854 /// Build a new extended vector type given the element type and
855 /// number of elements.
856 ///
857 /// By default, performs semantic analysis when building the vector type.
858 /// Subclasses may override this routine to provide different behavior.
859 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
860 SourceLocation AttributeLoc);
861
862 /// Build a new potentially dependently-sized extended vector type
863 /// given the element type and number of elements.
864 ///
865 /// By default, performs semantic analysis when building the vector type.
866 /// Subclasses may override this routine to provide different behavior.
867 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
868 Expr *SizeExpr,
869 SourceLocation AttributeLoc);
870
871 /// Build a new DependentAddressSpaceType or return the pointee
872 /// type variable with the correct address space (retrieved from
873 /// AddrSpaceExpr) applied to it. The former will be returned in cases
874 /// where the address space remains dependent.
875 ///
876 /// By default, performs semantic analysis when building the type with address
877 /// space applied. Subclasses may override this routine to provide different
878 /// behavior.
879 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
880 Expr *AddrSpaceExpr,
881 SourceLocation AttributeLoc);
882
883 /// Build a new function type.
884 ///
885 /// By default, performs semantic analysis when building the function type.
886 /// Subclasses may override this routine to provide different behavior.
887 QualType RebuildFunctionProtoType(QualType T,
888 MutableArrayRef<QualType> ParamTypes,
889 const FunctionProtoType::ExtProtoInfo &EPI);
890
891 /// Build a new unprototyped function type.
892 QualType RebuildFunctionNoProtoType(QualType ResultType);
893
894 /// Rebuild an unresolved typename type, given the decl that
895 /// the UnresolvedUsingTypenameDecl was transformed to.
896 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
897
898 /// Build a new typedef type.
899 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
900 return SemaRef.Context.getTypeDeclType(Typedef);
901 }
902
903 /// Build a new MacroDefined type.
904 QualType RebuildMacroQualifiedType(QualType T,
905 const IdentifierInfo *MacroII) {
906 return SemaRef.Context.getMacroQualifiedType(T, MacroII);
907 }
908
909 /// Build a new class/struct/union type.
910 QualType RebuildRecordType(RecordDecl *Record) {
911 return SemaRef.Context.getTypeDeclType(Record);
912 }
913
914 /// Build a new Enum type.
915 QualType RebuildEnumType(EnumDecl *Enum) {
916 return SemaRef.Context.getTypeDeclType(Enum);
917 }
918
919 /// Build a new typeof(expr) type.
920 ///
921 /// By default, performs semantic analysis when building the typeof type.
922 /// Subclasses may override this routine to provide different behavior.
923 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
924
925 /// Build a new typeof(type) type.
926 ///
927 /// By default, builds a new TypeOfType with the given underlying type.
928 QualType RebuildTypeOfType(QualType Underlying);
929
930 /// Build a new unary transform type.
931 QualType RebuildUnaryTransformType(QualType BaseType,
932 UnaryTransformType::UTTKind UKind,
933 SourceLocation Loc);
934
935 /// Build a new C++11 decltype type.
936 ///
937 /// By default, performs semantic analysis when building the decltype type.
938 /// Subclasses may override this routine to provide different behavior.
939 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
940
941 /// Build a new C++11 auto type.
942 ///
943 /// By default, builds a new AutoType with the given deduced type.
944 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
945 // Note, IsDependent is always false here: we implicitly convert an 'auto'
946 // which has been deduced to a dependent type into an undeduced 'auto', so
947 // that we'll retry deduction after the transformation.
948 return SemaRef.Context.getAutoType(Deduced, Keyword,
949 /*IsDependent*/ false);
950 }
951
952 /// By default, builds a new DeducedTemplateSpecializationType with the given
953 /// deduced type.
954 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
955 QualType Deduced) {
956 return SemaRef.Context.getDeducedTemplateSpecializationType(
957 Template, Deduced, /*IsDependent*/ false);
958 }
959
960 /// Build a new template specialization type.
961 ///
962 /// By default, performs semantic analysis when building the template
963 /// specialization type. Subclasses may override this routine to provide
964 /// different behavior.
965 QualType RebuildTemplateSpecializationType(TemplateName Template,
966 SourceLocation TemplateLoc,
967 TemplateArgumentListInfo &Args);
968
969 /// Build a new parenthesized type.
970 ///
971 /// By default, builds a new ParenType type from the inner type.
972 /// Subclasses may override this routine to provide different behavior.
973 QualType RebuildParenType(QualType InnerType) {
974 return SemaRef.BuildParenType(InnerType);
975 }
976
977 /// Build a new qualified name type.
978 ///
979 /// By default, builds a new ElaboratedType type from the keyword,
980 /// the nested-name-specifier and the named type.
981 /// Subclasses may override this routine to provide different behavior.
982 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
983 ElaboratedTypeKeyword Keyword,
984 NestedNameSpecifierLoc QualifierLoc,
985 QualType Named) {
986 return SemaRef.Context.getElaboratedType(Keyword,
987 QualifierLoc.getNestedNameSpecifier(),
988 Named);
989 }
990
991 /// Build a new typename type that refers to a template-id.
992 ///
993 /// By default, builds a new DependentNameType type from the
994 /// nested-name-specifier and the given type. Subclasses may override
995 /// this routine to provide different behavior.
996 QualType RebuildDependentTemplateSpecializationType(
997 ElaboratedTypeKeyword Keyword,
998 NestedNameSpecifierLoc QualifierLoc,
999 SourceLocation TemplateKWLoc,
1000 const IdentifierInfo *Name,
1001 SourceLocation NameLoc,
1002 TemplateArgumentListInfo &Args,
1003 bool AllowInjectedClassName) {
1004 // Rebuild the template name.
1005 // TODO: avoid TemplateName abstraction
1006 CXXScopeSpec SS;
1007 SS.Adopt(QualifierLoc);
1008 TemplateName InstName = getDerived().RebuildTemplateName(
1009 SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1010 AllowInjectedClassName);
1011
1012 if (InstName.isNull())
1013 return QualType();
1014
1015 // If it's still dependent, make a dependent specialization.
1016 if (InstName.getAsDependentTemplateName())
1017 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1018 QualifierLoc.getNestedNameSpecifier(),
1019 Name,
1020 Args);
1021
1022 // Otherwise, make an elaborated type wrapping a non-dependent
1023 // specialization.
1024 QualType T =
1025 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1026 if (T.isNull()) return QualType();
1027
1028 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1029 return T;
1030
1031 return SemaRef.Context.getElaboratedType(Keyword,
1032 QualifierLoc.getNestedNameSpecifier(),
1033 T);
1034 }
1035
1036 /// Build a new typename type that refers to an identifier.
1037 ///
1038 /// By default, performs semantic analysis when building the typename type
1039 /// (or elaborated type). Subclasses may override this routine to provide
1040 /// different behavior.
1041 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1042 SourceLocation KeywordLoc,
1043 NestedNameSpecifierLoc QualifierLoc,
1044 const IdentifierInfo *Id,
1045 SourceLocation IdLoc,
1046 bool DeducedTSTContext) {
1047 CXXScopeSpec SS;
1048 SS.Adopt(QualifierLoc);
1049
1050 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1051 // If the name is still dependent, just build a new dependent name type.
1052 if (!SemaRef.computeDeclContext(SS))
1053 return SemaRef.Context.getDependentNameType(Keyword,
1054 QualifierLoc.getNestedNameSpecifier(),
1055 Id);
1056 }
1057
1058 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1059 QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1060 *Id, IdLoc);
1061 // If a dependent name resolves to a deduced template specialization type,
1062 // check that we're in one of the syntactic contexts permitting it.
1063 if (!DeducedTSTContext) {
1064 if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1065 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1066 SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1067 << (int)SemaRef.getTemplateNameKindForDiagnostics(
1068 Deduced->getTemplateName())
1069 << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1070 if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1071 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1072 return QualType();
1073 }
1074 }
1075 return T;
1076 }
1077
1078 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1079
1080 // We had a dependent elaborated-type-specifier that has been transformed
1081 // into a non-dependent elaborated-type-specifier. Find the tag we're
1082 // referring to.
1083 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1084 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1085 if (!DC)
1086 return QualType();
1087
1088 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1089 return QualType();
1090
1091 TagDecl *Tag = nullptr;
1092 SemaRef.LookupQualifiedName(Result, DC);
1093 switch (Result.getResultKind()) {
1094 case LookupResult::NotFound:
1095 case LookupResult::NotFoundInCurrentInstantiation:
1096 break;
1097
1098 case LookupResult::Found:
1099 Tag = Result.getAsSingle<TagDecl>();
1100 break;
1101
1102 case LookupResult::FoundOverloaded:
1103 case LookupResult::FoundUnresolvedValue:
1104 llvm_unreachable("Tag lookup cannot find non-tags")::llvm::llvm_unreachable_internal("Tag lookup cannot find non-tags"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/TreeTransform.h"
, 1104)
;
1105
1106 case LookupResult::Ambiguous:
1107 // Let the LookupResult structure handle ambiguities.
1108 return QualType();
1109 }
1110
1111 if (!Tag) {
1112 // Check where the name exists but isn't a tag type and use that to emit
1113 // better diagnostics.
1114 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1115 SemaRef.LookupQualifiedName(Result, DC);
1116 switch (Result.getResultKind()) {
1117 case LookupResult::Found:
1118 case LookupResult::FoundOverloaded:
1119 case LookupResult::FoundUnresolvedValue: {
1120 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1121 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1122 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1123 << NTK << Kind;
1124 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1125 break;
1126 }
1127 default:
1128 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1129 << Kind << Id << DC << QualifierLoc.getSourceRange();
1130 break;
1131 }
1132 return QualType();
1133 }
1134
1135 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1136 IdLoc, Id)) {
1137 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1138 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1139 return QualType();
1140 }
1141
1142 // Build the elaborated-type-specifier type.
1143 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1144 return SemaRef.Context.getElaboratedType(Keyword,
1145 QualifierLoc.getNestedNameSpecifier(),
1146 T);
1147 }
1148
1149 /// Build a new pack expansion type.
1150 ///
1151 /// By default, builds a new PackExpansionType type from the given pattern.
1152 /// Subclasses may override this routine to provide different behavior.
1153 QualType RebuildPackExpansionType(QualType Pattern,
1154 SourceRange PatternRange,
1155 SourceLocation EllipsisLoc,
1156 Optional<unsigned> NumExpansions) {
1157 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1158 NumExpansions);
1159 }
1160
1161 /// Build a new atomic type given its value type.
1162 ///
1163 /// By default, performs semantic analysis when building the atomic type.
1164 /// Subclasses may override this routine to provide different behavior.
1165 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1166
1167 /// Build a new pipe type given its value type.
1168 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1169 bool isReadPipe);
1170
1171 /// Build a new template name given a nested name specifier, a flag
1172 /// indicating whether the "template" keyword was provided, and the template
1173 /// that the template name refers to.
1174 ///
1175 /// By default, builds the new template name directly. Subclasses may override
1176 /// this routine to provide different behavior.
1177 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1178 bool TemplateKW,
1179 TemplateDecl *Template);
1180
1181 /// Build a new template name given a nested name specifier and the
1182 /// name that is referred to as a template.
1183 ///
1184 /// By default, performs semantic analysis to determine whether the name can
1185 /// be resolved to a specific template, then builds the appropriate kind of
1186 /// template name. Subclasses may override this routine to provide different
1187 /// behavior.
1188 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1189 SourceLocation TemplateKWLoc,
1190 const IdentifierInfo &Name,
1191 SourceLocation NameLoc, QualType ObjectType,
1192 NamedDecl *FirstQualifierInScope,
1193 bool AllowInjectedClassName);
1194
1195 /// Build a new template name given a nested name specifier and the
1196 /// overloaded operator name that is referred to as a template.
1197 ///
1198 /// By default, performs semantic analysis to determine whether the name can
1199 /// be resolved to a specific template, then builds the appropriate kind of
1200 /// template name. Subclasses may override this routine to provide different
1201 /// behavior.
1202 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1203 SourceLocation TemplateKWLoc,
1204 OverloadedOperatorKind Operator,
1205 SourceLocation NameLoc, QualType ObjectType,
1206 bool AllowInjectedClassName);
1207
1208 /// Build a new template name given a template template parameter pack
1209 /// and the
1210 ///
1211 /// By default, performs semantic analysis to determine whether the name can
1212 /// be resolved to a specific template, then builds the appropriate kind of
1213 /// template name. Subclasses may override this routine to provide different
1214 /// behavior.
1215 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1216 const TemplateArgument &ArgPack) {
1217 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1218 }
1219
1220 /// Build a new compound statement.
1221 ///
1222 /// By default, performs semantic analysis to build the new statement.
1223 /// Subclasses may override this routine to provide different behavior.
1224 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1225 MultiStmtArg Statements,
1226 SourceLocation RBraceLoc,
1227 bool IsStmtExpr) {
1228 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1229 IsStmtExpr);
1230 }
1231
1232 /// Build a new case statement.
1233 ///
1234 /// By default, performs semantic analysis to build the new statement.
1235 /// Subclasses may override this routine to provide different behavior.
1236 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1237 Expr *LHS,
1238 SourceLocation EllipsisLoc,
1239 Expr *RHS,
1240 SourceLocation ColonLoc) {
1241 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1242 ColonLoc);
1243 }
1244
1245 /// Attach the body to a new case statement.
1246 ///
1247 /// By default, performs semantic analysis to build the new statement.
1248 /// Subclasses may override this routine to provide different behavior.
1249 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1250 getSema().ActOnCaseStmtBody(S, Body);
1251 return S;
1252 }
1253
1254 /// Build a new default 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 RebuildDefaultStmt(SourceLocation DefaultLoc,
1259 SourceLocation ColonLoc,
1260 Stmt *SubStmt) {
1261 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1262 /*CurScope=*/nullptr);
1263 }
1264
1265 /// Build a new label statement.
1266 ///
1267 /// By default, performs semantic analysis to build the new statement.
1268 /// Subclasses may override this routine to provide different behavior.
1269 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1270 SourceLocation ColonLoc, Stmt *SubStmt) {
1271 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1272 }
1273
1274 /// Build a new label statement.
1275 ///
1276 /// By default, performs semantic analysis to build the new statement.
1277 /// Subclasses may override this routine to provide different behavior.
1278 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1279 ArrayRef<const Attr*> Attrs,
1280 Stmt *SubStmt) {
1281 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1282 }
1283
1284 /// Build a new "if" statement.
1285 ///
1286 /// By default, performs semantic analysis to build the new statement.
1287 /// Subclasses may override this routine to provide different behavior.
1288 StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1289 Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1290 SourceLocation ElseLoc, Stmt *Else) {
1291 return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1292 ElseLoc, Else);
1293 }
1294
1295 /// Start building a new switch statement.
1296 ///
1297 /// By default, performs semantic analysis to build the new statement.
1298 /// Subclasses may override this routine to provide different behavior.
1299 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1300 Sema::ConditionResult Cond) {
1301 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1302 }
1303
1304 /// Attach the body to the switch statement.
1305 ///
1306 /// By default, performs semantic analysis to build the new statement.
1307 /// Subclasses may override this routine to provide different behavior.
1308 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1309 Stmt *Switch, Stmt *Body) {
1310 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1311 }
1312
1313 /// Build a new while statement.
1314 ///
1315 /// By default, performs semantic analysis to build the new statement.
1316 /// Subclasses may override this routine to provide different behavior.
1317 StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1318 Sema::ConditionResult Cond, Stmt *Body) {
1319 return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1320 }
1321
1322 /// Build a new do-while statement.
1323 ///
1324 /// By default, performs semantic analysis to build the new statement.
1325 /// Subclasses may override this routine to provide different behavior.
1326 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1327 SourceLocation WhileLoc, SourceLocation LParenLoc,
1328 Expr *Cond, SourceLocation RParenLoc) {
1329 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1330 Cond, RParenLoc);
1331 }
1332
1333 /// Build a new for statement.
1334 ///
1335 /// By default, performs semantic analysis to build the new statement.
1336 /// Subclasses may override this routine to provide different behavior.
1337 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1338 Stmt *Init, Sema::ConditionResult Cond,
1339 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1340 Stmt *Body) {
1341 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1342 Inc, RParenLoc, Body);
1343 }
1344
1345 /// Build a new goto statement.
1346 ///
1347 /// By default, performs semantic analysis to build the new statement.
1348 /// Subclasses may override this routine to provide different behavior.
1349 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1350 LabelDecl *Label) {
1351 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1352 }
1353
1354 /// Build a new indirect goto statement.
1355 ///
1356 /// By default, performs semantic analysis to build the new statement.
1357 /// Subclasses may override this routine to provide different behavior.
1358 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1359 SourceLocation StarLoc,
1360 Expr *Target) {
1361 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1362 }
1363
1364 /// Build a new return statement.
1365 ///
1366 /// By default, performs semantic analysis to build the new statement.
1367 /// Subclasses may override this routine to provide different behavior.
1368 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1369 return getSema().BuildReturnStmt(ReturnLoc, Result);
1370 }
1371
1372 /// Build a new declaration 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 RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1377 SourceLocation StartLoc, SourceLocation EndLoc) {
1378 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1379 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1380 }
1381
1382 /// Build a new inline asm statement.
1383 ///
1384 /// By default, performs semantic analysis to build the new statement.
1385 /// Subclasses may override this routine to provide different behavior.
1386 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1387 bool IsVolatile, unsigned NumOutputs,
1388 unsigned NumInputs, IdentifierInfo **Names,
1389 MultiExprArg Constraints, MultiExprArg Exprs,
1390 Expr *AsmString, MultiExprArg Clobbers,
1391 unsigned NumLabels,
1392 SourceLocation RParenLoc) {
1393 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1394 NumInputs, Names, Constraints, Exprs,
1395 AsmString, Clobbers, NumLabels, RParenLoc);
1396 }
1397
1398 /// Build a new MS style inline asm statement.
1399 ///
1400 /// By default, performs semantic analysis to build the new statement.
1401 /// Subclasses may override this routine to provide different behavior.
1402 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1403 ArrayRef<Token> AsmToks,
1404 StringRef AsmString,
1405 unsigned NumOutputs, unsigned NumInputs,
1406 ArrayRef<StringRef> Constraints,
1407 ArrayRef<StringRef> Clobbers,
1408 ArrayRef<Expr*> Exprs,
1409 SourceLocation EndLoc) {
1410 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1411 NumOutputs, NumInputs,
1412 Constraints, Clobbers, Exprs, EndLoc);
1413 }
1414
1415 /// Build a new co_return statement.
1416 ///
1417 /// By default, performs semantic analysis to build the new statement.
1418 /// Subclasses may override this routine to provide different behavior.
1419 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1420 bool IsImplicit) {
1421 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1422 }
1423
1424 /// Build a new co_await expression.
1425 ///
1426 /// By default, performs semantic analysis to build the new expression.
1427 /// Subclasses may override this routine to provide different behavior.
1428 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1429 bool IsImplicit) {
1430 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1431 }
1432
1433 /// Build a new co_await expression.
1434 ///
1435 /// By default, performs semantic analysis to build the new expression.
1436 /// Subclasses may override this routine to provide different behavior.
1437 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1438 Expr *Result,
1439 UnresolvedLookupExpr *Lookup) {
1440 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1441 }
1442
1443 /// Build a new co_yield expression.
1444 ///
1445 /// By default, performs semantic analysis to build the new expression.
1446 /// Subclasses may override this routine to provide different behavior.
1447 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1448 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1449 }
1450
1451 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1452 return getSema().BuildCoroutineBodyStmt(Args);
1453 }
1454
1455 /// Build a new Objective-C \@try statement.
1456 ///
1457 /// By default, performs semantic analysis to build the new statement.
1458 /// Subclasses may override this routine to provide different behavior.
1459 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1460 Stmt *TryBody,
1461 MultiStmtArg CatchStmts,
1462 Stmt *Finally) {
1463 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1464 Finally);
1465 }
1466
1467 /// Rebuild an Objective-C exception declaration.
1468 ///
1469 /// By default, performs semantic analysis to build the new declaration.
1470 /// Subclasses may override this routine to provide different behavior.
1471 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1472 TypeSourceInfo *TInfo, QualType T) {
1473 return getSema().BuildObjCExceptionDecl(TInfo, T,
1474 ExceptionDecl->getInnerLocStart(),
1475 ExceptionDecl->getLocation(),
1476 ExceptionDecl->getIdentifier());
1477 }
1478
1479 /// Build a new Objective-C \@catch statement.
1480 ///
1481 /// By default, performs semantic analysis to build the new statement.
1482 /// Subclasses may override this routine to provide different behavior.
1483 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1484 SourceLocation RParenLoc,
1485 VarDecl *Var,
1486 Stmt *Body) {
1487 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1488 Var, Body);
1489 }
1490
1491 /// Build a new Objective-C \@finally statement.
1492 ///
1493 /// By default, performs semantic analysis to build the new statement.
1494 /// Subclasses may override this routine to provide different behavior.
1495 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1496 Stmt *Body) {
1497 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1498 }
1499
1500 /// Build a new Objective-C \@throw statement.
1501 ///
1502 /// By default, performs semantic analysis to build the new statement.
1503 /// Subclasses may override this routine to provide different behavior.
1504 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1505 Expr *Operand) {
1506 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1507 }
1508
1509 /// Build a new OpenMP executable directive.
1510 ///
1511 /// By default, performs semantic analysis to build the new statement.
1512 /// Subclasses may override this routine to provide different behavior.
1513 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1514 DeclarationNameInfo DirName,
1515 OpenMPDirectiveKind CancelRegion,
1516 ArrayRef<OMPClause *> Clauses,
1517 Stmt *AStmt, SourceLocation StartLoc,
1518 SourceLocation EndLoc) {
1519 return getSema().ActOnOpenMPExecutableDirective(
1520 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1521 }
1522
1523 /// Build a new OpenMP 'if' clause.
1524 ///
1525 /// By default, performs semantic analysis to build the new OpenMP clause.
1526 /// Subclasses may override this routine to provide different behavior.
1527 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1528 Expr *Condition, SourceLocation StartLoc,
1529 SourceLocation LParenLoc,
1530 SourceLocation NameModifierLoc,
1531 SourceLocation ColonLoc,
1532 SourceLocation EndLoc) {
1533 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1534 LParenLoc, NameModifierLoc, ColonLoc,
1535 EndLoc);
1536 }
1537
1538 /// Build a new OpenMP 'final' clause.
1539 ///
1540 /// By default, performs semantic analysis to build the new OpenMP clause.
1541 /// Subclasses may override this routine to provide different behavior.
1542 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1543 SourceLocation LParenLoc,
1544 SourceLocation EndLoc) {
1545 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1546 EndLoc);
1547 }
1548
1549 /// Build a new OpenMP 'num_threads' clause.
1550 ///
1551 /// By default, performs semantic analysis to build the new OpenMP clause.
1552 /// Subclasses may override this routine to provide different behavior.
1553 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1554 SourceLocation StartLoc,
1555 SourceLocation LParenLoc,
1556 SourceLocation EndLoc) {
1557 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1558 LParenLoc, EndLoc);
1559 }
1560
1561 /// Build a new OpenMP 'safelen' clause.
1562 ///
1563 /// By default, performs semantic analysis to build the new OpenMP clause.
1564 /// Subclasses may override this routine to provide different behavior.
1565 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1566 SourceLocation LParenLoc,
1567 SourceLocation EndLoc) {
1568 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1569 }
1570
1571 /// Build a new OpenMP 'simdlen' clause.
1572 ///
1573 /// By default, performs semantic analysis to build the new OpenMP clause.
1574 /// Subclasses may override this routine to provide different behavior.
1575 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1576 SourceLocation LParenLoc,
1577 SourceLocation EndLoc) {
1578 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1579 }
1580
1581 /// Build a new OpenMP 'allocator' clause.
1582 ///
1583 /// By default, performs semantic analysis to build the new OpenMP clause.
1584 /// Subclasses may override this routine to provide different behavior.
1585 OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1586 SourceLocation LParenLoc,
1587 SourceLocation EndLoc) {
1588 return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1589 }
1590
1591 /// Build a new OpenMP 'collapse' clause.
1592 ///
1593 /// By default, performs semantic analysis to build the new OpenMP clause.
1594 /// Subclasses may override this routine to provide different behavior.
1595 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1596 SourceLocation LParenLoc,
1597 SourceLocation EndLoc) {
1598 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1599 EndLoc);
1600 }
1601
1602 /// Build a new OpenMP 'default' clause.
1603 ///
1604 /// By default, performs semantic analysis to build the new OpenMP clause.
1605 /// Subclasses may override this routine to provide different behavior.
1606 OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1607 SourceLocation KindKwLoc,
1608 SourceLocation StartLoc,
1609 SourceLocation LParenLoc,
1610 SourceLocation EndLoc) {
1611 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1612 StartLoc, LParenLoc, EndLoc);
1613 }
1614
1615 /// Build a new OpenMP 'proc_bind' clause.
1616 ///
1617 /// By default, performs semantic analysis to build the new OpenMP clause.
1618 /// Subclasses may override this routine to provide different behavior.
1619 OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1620 SourceLocation KindKwLoc,
1621 SourceLocation StartLoc,
1622 SourceLocation LParenLoc,
1623 SourceLocation EndLoc) {
1624 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1625 StartLoc, LParenLoc, EndLoc);
1626 }
1627
1628 /// Build a new OpenMP 'schedule' clause.
1629 ///
1630 /// By default, performs semantic analysis to build the new OpenMP clause.
1631 /// Subclasses may override this routine to provide different behavior.
1632 OMPClause *RebuildOMPScheduleClause(
1633 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1634 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1635 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1636 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1637 return getSema().ActOnOpenMPScheduleClause(
1638 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1639 CommaLoc, EndLoc);
1640 }
1641
1642 /// Build a new OpenMP 'ordered' clause.
1643 ///
1644 /// By default, performs semantic analysis to build the new OpenMP clause.
1645 /// Subclasses may override this routine to provide different behavior.
1646 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1647 SourceLocation EndLoc,
1648 SourceLocation LParenLoc, Expr *Num) {
1649 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1650 }
1651
1652 /// Build a new OpenMP 'private' clause.
1653 ///
1654 /// By default, performs semantic analysis to build the new OpenMP clause.
1655 /// Subclasses may override this routine to provide different behavior.
1656 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1657 SourceLocation StartLoc,
1658 SourceLocation LParenLoc,
1659 SourceLocation EndLoc) {
1660 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1661 EndLoc);
1662 }
1663
1664 /// Build a new OpenMP 'firstprivate' clause.
1665 ///
1666 /// By default, performs semantic analysis to build the new OpenMP clause.
1667 /// Subclasses may override this routine to provide different behavior.
1668 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1669 SourceLocation StartLoc,
1670 SourceLocation LParenLoc,
1671 SourceLocation EndLoc) {
1672 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1673 EndLoc);
1674 }
1675
1676 /// Build a new OpenMP 'lastprivate' clause.
1677 ///
1678 /// By default, performs semantic analysis to build the new OpenMP clause.
1679 /// Subclasses may override this routine to provide different behavior.
1680 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1681 OpenMPLastprivateModifier LPKind,
1682 SourceLocation LPKindLoc,
1683 SourceLocation ColonLoc,
1684 SourceLocation StartLoc,
1685 SourceLocation LParenLoc,
1686 SourceLocation EndLoc) {
1687 return getSema().ActOnOpenMPLastprivateClause(
1688 VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1689 }
1690
1691 /// Build a new OpenMP 'shared' clause.
1692 ///
1693 /// By default, performs semantic analysis to build the new OpenMP clause.
1694 /// Subclasses may override this routine to provide different behavior.
1695 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1696 SourceLocation StartLoc,
1697 SourceLocation LParenLoc,
1698 SourceLocation EndLoc) {
1699 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1700 EndLoc);
1701 }
1702
1703 /// Build a new OpenMP 'reduction' clause.
1704 ///
1705 /// By default, performs semantic analysis to build the new statement.
1706 /// Subclasses may override this routine to provide different behavior.
1707 OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1708 SourceLocation StartLoc,
1709 SourceLocation LParenLoc,
1710 SourceLocation ColonLoc,
1711 SourceLocation EndLoc,
1712 CXXScopeSpec &ReductionIdScopeSpec,
1713 const DeclarationNameInfo &ReductionId,
1714 ArrayRef<Expr *> UnresolvedReductions) {
1715 return getSema().ActOnOpenMPReductionClause(
1716 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1717 ReductionId, UnresolvedReductions);
1718 }
1719
1720 /// Build a new OpenMP 'task_reduction' clause.
1721 ///
1722 /// By default, performs semantic analysis to build the new statement.
1723 /// Subclasses may override this routine to provide different behavior.
1724 OMPClause *RebuildOMPTaskReductionClause(
1725 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1726 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1727 CXXScopeSpec &ReductionIdScopeSpec,
1728 const DeclarationNameInfo &ReductionId,
1729 ArrayRef<Expr *> UnresolvedReductions) {
1730 return getSema().ActOnOpenMPTaskReductionClause(
1731 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1732 ReductionId, UnresolvedReductions);
1733 }
1734
1735 /// Build a new OpenMP 'in_reduction' clause.
1736 ///
1737 /// By default, performs semantic analysis to build the new statement.
1738 /// Subclasses may override this routine to provide different behavior.
1739 OMPClause *
1740 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1741 SourceLocation LParenLoc, SourceLocation ColonLoc,
1742 SourceLocation EndLoc,
1743 CXXScopeSpec &ReductionIdScopeSpec,
1744 const DeclarationNameInfo &ReductionId,
1745 ArrayRef<Expr *> UnresolvedReductions) {
1746 return getSema().ActOnOpenMPInReductionClause(
1747 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1748 ReductionId, UnresolvedReductions);
1749 }
1750
1751 /// Build a new OpenMP 'linear' clause.
1752 ///
1753 /// By default, performs semantic analysis to build the new OpenMP clause.
1754 /// Subclasses may override this routine to provide different behavior.
1755 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1756 SourceLocation StartLoc,
1757 SourceLocation LParenLoc,
1758 OpenMPLinearClauseKind Modifier,
1759 SourceLocation ModifierLoc,
1760 SourceLocation ColonLoc,
1761 SourceLocation EndLoc) {
1762 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1763 Modifier, ModifierLoc, ColonLoc,
1764 EndLoc);
1765 }
1766
1767 /// Build a new OpenMP 'aligned' clause.
1768 ///
1769 /// By default, performs semantic analysis to build the new OpenMP clause.
1770 /// Subclasses may override this routine to provide different behavior.
1771 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1772 SourceLocation StartLoc,
1773 SourceLocation LParenLoc,
1774 SourceLocation ColonLoc,
1775 SourceLocation EndLoc) {
1776 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1777 LParenLoc, ColonLoc, EndLoc);
1778 }
1779
1780 /// Build a new OpenMP 'copyin' clause.
1781 ///
1782 /// By default, performs semantic analysis to build the new OpenMP clause.
1783 /// Subclasses may override this routine to provide different behavior.
1784 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1785 SourceLocation StartLoc,
1786 SourceLocation LParenLoc,
1787 SourceLocation EndLoc) {
1788 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1789 EndLoc);
1790 }
1791
1792 /// Build a new OpenMP 'copyprivate' clause.
1793 ///
1794 /// By default, performs semantic analysis to build the new OpenMP clause.
1795 /// Subclasses may override this routine to provide different behavior.
1796 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1797 SourceLocation StartLoc,
1798 SourceLocation LParenLoc,
1799 SourceLocation EndLoc) {
1800 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1801 EndLoc);
1802 }
1803
1804 /// Build a new OpenMP 'flush' pseudo 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 *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1809 SourceLocation StartLoc,
1810 SourceLocation LParenLoc,
1811 SourceLocation EndLoc) {
1812 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1813 EndLoc);
1814 }
1815
1816 /// Build a new OpenMP 'depend' pseudo clause.
1817 ///
1818 /// By default, performs semantic analysis to build the new OpenMP clause.
1819 /// Subclasses may override this routine to provide different behavior.
1820 OMPClause *
1821 RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1822 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1823 SourceLocation StartLoc, SourceLocation LParenLoc,
1824 SourceLocation EndLoc) {
1825 return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1826 StartLoc, LParenLoc, EndLoc);
1827 }
1828
1829 /// Build a new OpenMP 'device' clause.
1830 ///
1831 /// By default, performs semantic analysis to build the new statement.
1832 /// Subclasses may override this routine to provide different behavior.
1833 OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1834 SourceLocation LParenLoc,
1835 SourceLocation EndLoc) {
1836 return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1837 EndLoc);
1838 }
1839
1840 /// Build a new OpenMP 'map' clause.
1841 ///
1842 /// By default, performs semantic analysis to build the new OpenMP clause.
1843 /// Subclasses may override this routine to provide different behavior.
1844 OMPClause *RebuildOMPMapClause(
1845 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1846 ArrayRef<SourceLocation> MapTypeModifiersLoc,
1847 CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1848 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1849 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1850 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1851 return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1852 MapperIdScopeSpec, MapperId, MapType,
1853 IsMapTypeImplicit, MapLoc, ColonLoc,
1854 VarList, Locs, UnresolvedMappers);
1855 }
1856
1857 /// Build a new OpenMP 'allocate' clause.
1858 ///
1859 /// By default, performs semantic analysis to build the new OpenMP clause.
1860 /// Subclasses may override this routine to provide different behavior.
1861 OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1862 SourceLocation StartLoc,
1863 SourceLocation LParenLoc,
1864 SourceLocation ColonLoc,
1865 SourceLocation EndLoc) {
1866 return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1867 LParenLoc, ColonLoc, EndLoc);
1868 }
1869
1870 /// Build a new OpenMP 'num_teams' clause.
1871 ///
1872 /// By default, performs semantic analysis to build the new statement.
1873 /// Subclasses may override this routine to provide different behavior.
1874 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1875 SourceLocation LParenLoc,
1876 SourceLocation EndLoc) {
1877 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1878 EndLoc);
1879 }
1880
1881 /// Build a new OpenMP 'thread_limit' clause.
1882 ///
1883 /// By default, performs semantic analysis to build the new statement.
1884 /// Subclasses may override this routine to provide different behavior.
1885 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1886 SourceLocation StartLoc,
1887 SourceLocation LParenLoc,
1888 SourceLocation EndLoc) {
1889 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1890 LParenLoc, EndLoc);
1891 }
1892
1893 /// Build a new OpenMP 'priority' clause.
1894 ///
1895 /// By default, performs semantic analysis to build the new statement.
1896 /// Subclasses may override this routine to provide different behavior.
1897 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1898 SourceLocation LParenLoc,
1899 SourceLocation EndLoc) {
1900 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1901 EndLoc);
1902 }
1903
1904 /// Build a new OpenMP 'grainsize' clause.
1905 ///
1906 /// By default, performs semantic analysis to build the new statement.
1907 /// Subclasses may override this routine to provide different behavior.
1908 OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1909 SourceLocation LParenLoc,
1910 SourceLocation EndLoc) {
1911 return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1912 EndLoc);
1913 }
1914
1915 /// Build a new OpenMP 'num_tasks' clause.
1916 ///
1917 /// By default, performs semantic analysis to build the new statement.
1918 /// Subclasses may override this routine to provide different behavior.
1919 OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1920 SourceLocation LParenLoc,
1921 SourceLocation EndLoc) {
1922 return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1923 EndLoc);
1924 }
1925
1926 /// Build a new OpenMP 'hint' clause.
1927 ///
1928 /// By default, performs semantic analysis to build the new statement.
1929 /// Subclasses may override this routine to provide different behavior.
1930 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1931 SourceLocation LParenLoc,
1932 SourceLocation EndLoc) {
1933 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1934 }
1935
1936 /// Build a new OpenMP 'dist_schedule' clause.
1937 ///
1938 /// By default, performs semantic analysis to build the new OpenMP clause.
1939 /// Subclasses may override this routine to provide different behavior.
1940 OMPClause *
1941 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1942 Expr *ChunkSize, SourceLocation StartLoc,
1943 SourceLocation LParenLoc, SourceLocation KindLoc,
1944 SourceLocation CommaLoc, SourceLocation EndLoc) {
1945 return getSema().ActOnOpenMPDistScheduleClause(
1946 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1947 }
1948
1949 /// Build a new OpenMP 'to' clause.
1950 ///
1951 /// By default, performs semantic analysis to build the new statement.
1952 /// Subclasses may override this routine to provide different behavior.
1953 OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1954 CXXScopeSpec &MapperIdScopeSpec,
1955 DeclarationNameInfo &MapperId,
1956 const OMPVarListLocTy &Locs,
1957 ArrayRef<Expr *> UnresolvedMappers) {
1958 return getSema().ActOnOpenMPToClause(VarList, MapperIdScopeSpec, MapperId,
1959 Locs, UnresolvedMappers);
1960 }
1961
1962 /// Build a new OpenMP 'from' clause.
1963 ///
1964 /// By default, performs semantic analysis to build the new statement.
1965 /// Subclasses may override this routine to provide different behavior.
1966 OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1967 CXXScopeSpec &MapperIdScopeSpec,
1968 DeclarationNameInfo &MapperId,
1969 const OMPVarListLocTy &Locs,
1970 ArrayRef<Expr *> UnresolvedMappers) {
1971 return getSema().ActOnOpenMPFromClause(VarList, MapperIdScopeSpec, MapperId,
1972 Locs, UnresolvedMappers);
1973 }
1974
1975 /// Build a new OpenMP 'use_device_ptr' clause.
1976 ///
1977 /// By default, performs semantic analysis to build the new OpenMP clause.
1978 /// Subclasses may override this routine to provide different behavior.
1979 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1980 const OMPVarListLocTy &Locs) {
1981 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
1982 }
1983
1984 /// Build a new OpenMP 'is_device_ptr' clause.
1985 ///
1986 /// By default, performs semantic analysis to build the new OpenMP clause.
1987 /// Subclasses may override this routine to provide different behavior.
1988 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1989 const OMPVarListLocTy &Locs) {
1990 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
1991 }
1992
1993 /// Build a new OpenMP 'defaultmap' clause.
1994 ///
1995 /// By default, performs semantic analysis to build the new OpenMP clause.
1996 /// Subclasses may override this routine to provide different behavior.
1997 OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
1998 OpenMPDefaultmapClauseKind Kind,
1999 SourceLocation StartLoc,
2000 SourceLocation LParenLoc,
2001 SourceLocation MLoc,
2002 SourceLocation KindLoc,
2003 SourceLocation EndLoc) {
2004 return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2005 MLoc, KindLoc, EndLoc);
2006 }
2007
2008 /// Build a new OpenMP 'nontemporal' clause.
2009 ///
2010 /// By default, performs semantic analysis to build the new OpenMP clause.
2011 /// Subclasses may override this routine to provide different behavior.
2012 OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2013 SourceLocation StartLoc,
2014 SourceLocation LParenLoc,
2015 SourceLocation EndLoc) {
2016 return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2017 EndLoc);
2018 }
2019
2020 /// Rebuild the operand to an Objective-C \@synchronized statement.
2021 ///
2022 /// By default, performs semantic analysis to build the new statement.
2023 /// Subclasses may override this routine to provide different behavior.
2024 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2025 Expr *object) {
2026 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2027 }
2028
2029 /// Build a new Objective-C \@synchronized statement.
2030 ///
2031 /// By default, performs semantic analysis to build the new statement.
2032 /// Subclasses may override this routine to provide different behavior.
2033 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2034 Expr *Object, Stmt *Body) {
2035 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2036 }
2037
2038 /// Build a new Objective-C \@autoreleasepool statement.
2039 ///
2040 /// By default, performs semantic analysis to build the new statement.
2041 /// Subclasses may override this routine to provide different behavior.
2042 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2043 Stmt *Body) {
2044 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2045 }
2046
2047 /// Build a new Objective-C fast enumeration statement.
2048 ///
2049 /// By default, performs semantic analysis to build the new statement.
2050 /// Subclasses may override this routine to provide different behavior.
2051 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2052 Stmt *Element,
2053 Expr *Collection,
2054 SourceLocation RParenLoc,
2055 Stmt *Body) {
2056 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2057 Element,
2058 Collection,
2059 RParenLoc);
2060 if (ForEachStmt.isInvalid())
2061 return StmtError();
2062
2063 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2064 }
2065
2066 /// Build a new C++ exception declaration.
2067 ///
2068 /// By default, performs semantic analysis to build the new decaration.
2069 /// Subclasses may override this routine to provide different behavior.
2070 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2071 TypeSourceInfo *Declarator,
2072 SourceLocation StartLoc,
2073 SourceLocation IdLoc,
2074 IdentifierInfo *Id) {
2075 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2076 StartLoc, IdLoc, Id);
2077 if (Var)
2078 getSema().CurContext->addDecl(Var);
2079 return Var;
2080 }
2081
2082 /// Build a new C++ catch statement.
2083 ///
2084 /// By default, performs semantic analysis to build the new statement.
2085 /// Subclasses may override this routine to provide different behavior.
2086 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2087 VarDecl *ExceptionDecl,
2088 Stmt *Handler) {
2089 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2090 Handler));
2091 }
2092
2093 /// Build a new C++ try statement.
2094 ///
2095 /// By default, performs semantic analysis to build the new statement.
2096 /// Subclasses may override this routine to provide different behavior.
2097 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2098 ArrayRef<Stmt *> Handlers) {
2099 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2100 }
2101
2102 /// Build a new C++0x range-based for statement.
2103 ///
2104 /// By default, performs semantic analysis to build the new statement.
2105 /// Subclasses may override this routine to provide different behavior.
2106 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2107 SourceLocation CoawaitLoc, Stmt *Init,
2108 SourceLocation ColonLoc, Stmt *Range,
2109 Stmt *Begin, Stmt *End, Expr *Cond,
2110 Expr *Inc, Stmt *LoopVar,
2111 SourceLocation RParenLoc) {
2112 // If we've just learned that the range is actually an Objective-C
2113 // collection, treat this as an Objective-C fast enumeration loop.
2114 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2115 if (RangeStmt->isSingleDecl()) {
2116 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2117 if (RangeVar->isInvalidDecl())
2118 return StmtError();
2119
2120 Expr *RangeExpr = RangeVar->getInit();
2121 if (!RangeExpr->isTypeDependent() &&
2122 RangeExpr->getType()->isObjCObjectPointerType()) {
2123 // FIXME: Support init-statements in Objective-C++20 ranged for
2124 // statement.
2125 if (Init) {
2126 return SemaRef.Diag(Init->getBeginLoc(),
2127 diag::err_objc_for_range_init_stmt)
2128 << Init->getSourceRange();
2129 }
2130 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2131 RangeExpr, RParenLoc);
2132 }
2133 }
2134 }
2135 }
2136
2137 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2138 Range, Begin, End, Cond, Inc, LoopVar,
2139 RParenLoc, Sema::BFRK_Rebuild);
2140 }
2141
2142 /// Build a new C++0x range-based for statement.
2143 ///
2144 /// By default, performs semantic analysis to build the new statement.
2145 /// Subclasses may override this routine to provide different behavior.
2146 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2147 bool IsIfExists,
2148 NestedNameSpecifierLoc QualifierLoc,
2149 DeclarationNameInfo NameInfo,
2150 Stmt *Nested) {
2151 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2152 QualifierLoc, NameInfo, Nested);
2153 }
2154
2155 /// Attach body to a C++0x range-based for statement.
2156 ///
2157 /// By default, performs semantic analysis to finish the new statement.
2158 /// Subclasses may override this routine to provide different behavior.
2159 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2160 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2161 }
2162
2163 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2164 Stmt *TryBlock, Stmt *Handler) {
2165 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2166 }
2167
2168 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2169 Stmt *Block) {
2170 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2171 }
2172
2173 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2174 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2175 }
2176
2177 /// Build a new predefined expression.
2178 ///
2179 /// By default, performs semantic analysis to build the new expression.
2180 /// Subclasses may override this routine to provide different behavior.
2181 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2182 PredefinedExpr::IdentKind IK) {
2183 return getSema().BuildPredefinedExpr(Loc, IK);
2184 }
2185
2186 /// Build a new expression that references a declaration.
2187 ///
2188 /// By default, performs semantic analysis to build the new expression.
2189 /// Subclasses may override this routine to provide different behavior.
2190 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2191 LookupResult &R,
2192 bool RequiresADL) {
2193 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2194 }
2195
2196
2197 /// Build a new expression that references a declaration.
2198 ///
2199 /// By default, performs semantic analysis to build the new expression.
2200 /// Subclasses may override this routine to provide different behavior.
2201 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2202 ValueDecl *VD,
2203 const DeclarationNameInfo &NameInfo,
2204 NamedDecl *Found,
2205 TemplateArgumentListInfo *TemplateArgs) {
2206 CXXScopeSpec SS;
2207 SS.Adopt(QualifierLoc);
2208 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2209 TemplateArgs);
2210 }
2211
2212 /// Build a new expression in parentheses.
2213 ///
2214 /// By default, performs semantic analysis to build the new expression.
2215 /// Subclasses may override this routine to provide different behavior.
2216 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2217 SourceLocation RParen) {
2218 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2219 }
2220
2221 /// Build a new pseudo-destructor expression.
2222 ///
2223 /// By default, performs semantic analysis to build the new expression.
2224 /// Subclasses may override this routine to provide different behavior.
2225 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2226 SourceLocation OperatorLoc,
2227 bool isArrow,
2228 CXXScopeSpec &SS,
2229 TypeSourceInfo *ScopeType,
2230 SourceLocation CCLoc,
2231 SourceLocation TildeLoc,
2232 PseudoDestructorTypeStorage Destroyed);
2233
2234 /// Build a new unary operator expression.
2235 ///
2236 /// By default, performs semantic analysis to build the new expression.
2237 /// Subclasses may override this routine to provide different behavior.
2238 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2239 UnaryOperatorKind Opc,
2240 Expr *SubExpr) {
2241 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2242 }
2243
2244 /// Build a new builtin offsetof expression.
2245 ///
2246 /// By default, performs semantic analysis to build the new expression.
2247 /// Subclasses may override this routine to provide different behavior.
2248 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2249 TypeSourceInfo *Type,
2250 ArrayRef<Sema::OffsetOfComponent> Components,
2251 SourceLocation RParenLoc) {
2252 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2253 RParenLoc);
2254 }
2255
2256 /// Build a new sizeof, alignof or vec_step expression with a
2257 /// type argument.
2258 ///
2259 /// By default, performs semantic analysis to build the new expression.
2260 /// Subclasses may override this routine to provide different behavior.
2261 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2262 SourceLocation OpLoc,
2263 UnaryExprOrTypeTrait ExprKind,
2264 SourceRange R) {
2265 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2266 }
2267
2268 /// Build a new sizeof, alignof or vec step expression with an
2269 /// expression argument.
2270 ///
2271 /// By default, performs semantic analysis to build the new expression.
2272 /// Subclasses may override this routine to provide different behavior.
2273 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2274 UnaryExprOrTypeTrait ExprKind,
2275 SourceRange R) {
2276 ExprResult Result
2277 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2278 if (Result.isInvalid())
2279 return ExprError();
2280
2281 return Result;
2282 }
2283
2284 /// Build a new array subscript expression.
2285 ///
2286 /// By default, performs semantic analysis to build the new expression.
2287 /// Subclasses may override this routine to provide different behavior.
2288 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2289 SourceLocation LBracketLoc,
2290 Expr *RHS,
2291 SourceLocation RBracketLoc) {
2292 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2293 LBracketLoc, RHS,
2294 RBracketLoc);
2295 }
2296
2297 /// Build a new array section expression.
2298 ///
2299 /// By default, performs semantic analysis to build the new expression.
2300 /// Subclasses may override this routine to provide different behavior.
2301 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2302 Expr *LowerBound,
2303 SourceLocation ColonLoc, Expr *Length,
2304 SourceLocation RBracketLoc) {
2305 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2306 ColonLoc, Length, RBracketLoc);
2307 }
2308
2309 /// Build a new call expression.
2310 ///
2311 /// By default, performs semantic analysis to build the new expression.
2312 /// Subclasses may override this routine to provide different behavior.
2313 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2314 MultiExprArg Args,
2315 SourceLocation RParenLoc,
2316 Expr *ExecConfig = nullptr) {
2317 return getSema().BuildCallExpr(/*Scope=*/nullptr, Callee, LParenLoc, Args,
2318 RParenLoc, ExecConfig);
2319 }
2320
2321 /// Build a new member access expression.
2322 ///
2323 /// By default, performs semantic analysis to build the new expression.
2324 /// Subclasses may override this routine to provide different behavior.
2325 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2326 bool isArrow,
2327 NestedNameSpecifierLoc QualifierLoc,
2328 SourceLocation TemplateKWLoc,
2329 const DeclarationNameInfo &MemberNameInfo,
2330 ValueDecl *Member,
2331 NamedDecl *FoundDecl,
2332 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2333 NamedDecl *FirstQualifierInScope) {
2334 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2335 isArrow);
2336 if (!Member->getDeclName()) {
2337 // We have a reference to an unnamed field. This is always the
2338 // base of an anonymous struct/union member access, i.e. the
2339 // field is always of record type.
2340 assert(Member->getType()->isRecordType() &&((Member->getType()->isRecordType() && "unnamed member not of record type?"
) ? static_cast<void> (0) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/TreeTransform.h"
, 2341, __PRETTY_FUNCTION__))
2341 "unnamed member not of record type?")((Member->getType()->isRecordType() && "unnamed member not of record type?"
) ? static_cast<void> (0) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/TreeTransform.h"
, 2341, __PRETTY_FUNCTION__))
;
2342
2343 BaseResult =
2344 getSema().PerformObjectMemberConversion(BaseResult.get(),
2345 QualifierLoc.getNestedNameSpecifier(),
2346 FoundDecl, Member);
2347 if (BaseResult.isInvalid())
2348 return ExprError();
2349 Base = BaseResult.get();
2350
2351 CXXScopeSpec EmptySS;
2352 return getSema().BuildFieldReferenceExpr(
2353 Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2354 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2355 }
2356
2357 CXXScopeSpec SS;
2358 SS.Adopt(QualifierLoc);
2359
2360 Base = BaseResult.get();
2361 QualType BaseType = Base->getType();
2362
2363 if (isArrow && !BaseType->isPointerType())
2364 return ExprError();
2365
2366 // FIXME: this involves duplicating earlier analysis in a lot of
2367 // cases; we should avoid this when possible.
2368 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2369 R.addDecl(FoundDecl);
2370 R.resolveKind();
2371
2372 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2373 SS, TemplateKWLoc,
2374 FirstQualifierInScope,
2375 R, ExplicitTemplateArgs,
2376 /*S*/nullptr);
2377 }
2378
2379 /// Build a new binary operator expression.
2380 ///
2381 /// By default, performs semantic analysis to build the new expression.
2382 /// Subclasses may override this routine to provide different behavior.
2383 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2384 BinaryOperatorKind Opc,
2385 Expr *LHS, Expr *RHS) {
2386 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2387 }
2388
2389 /// Build a new rewritten operator expression.
2390 ///
2391 /// By default, performs semantic analysis to build the new expression.
2392 /// Subclasses may override this routine to provide different behavior.
2393 ExprResult RebuildCXXRewrittenBinaryOperator(
2394 SourceLocation OpLoc, BinaryOperatorKind Opcode,
2395 const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2396 return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2397 RHS, /*RequiresADL*/false);
2398 }
2399
2400 /// Build a new conditional operator expression.
2401 ///
2402 /// By default, performs semantic analysis to build the new expression.
2403 /// Subclasses may override this routine to provide different behavior.
2404 ExprResult RebuildConditionalOperator(Expr *Cond,
2405 SourceLocation QuestionLoc,
2406 Expr *LHS,
2407 SourceLocation ColonLoc,
2408 Expr *RHS) {
2409 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2410 LHS, RHS);
2411 }
2412
2413 /// Build a new C-style cast expression.
2414 ///
2415 /// By default, performs semantic analysis to build the new expression.
2416 /// Subclasses may override this routine to provide different behavior.
2417 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2418 TypeSourceInfo *TInfo,
2419 SourceLocation RParenLoc,
2420 Expr *SubExpr) {
2421 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2422 SubExpr);
2423 }
2424
2425 /// Build a new compound literal expression.
2426 ///
2427 /// By default, performs semantic analysis to build the new expression.
2428 /// Subclasses may override this routine to provide different behavior.
2429 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2430 TypeSourceInfo *TInfo,
2431 SourceLocation RParenLoc,
2432 Expr *Init) {
2433 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2434 Init);
2435 }
2436
2437 /// Build a new extended vector element access expression.
2438 ///
2439 /// By default, performs semantic analysis to build the new expression.
2440 /// Subclasses may override this routine to provide different behavior.
2441 ExprResult RebuildExtVectorElementExpr(Expr *Base,
2442 SourceLocation OpLoc,
2443 SourceLocation AccessorLoc,
2444 IdentifierInfo &Accessor) {
2445
2446 CXXScopeSpec SS;
2447 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2448 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2449 OpLoc, /*IsArrow*/ false,
2450 SS, SourceLocation(),
2451 /*FirstQualifierInScope*/ nullptr,
2452 NameInfo,
2453 /* TemplateArgs */ nullptr,
2454 /*S*/ nullptr);
2455 }
2456
2457 /// Build a new initializer list expression.
2458 ///
2459 /// By default, performs semantic analysis to build the new expression.
2460 /// Subclasses may override this routine to provide different behavior.
2461 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2462 MultiExprArg Inits,
2463 SourceLocation RBraceLoc) {
2464 return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2465 }
2466
2467 /// Build a new designated initializer expression.
2468 ///
2469 /// By default, performs semantic analysis to build the new expression.
2470 /// Subclasses may override this routine to provide different behavior.
2471 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2472 MultiExprArg ArrayExprs,
2473 SourceLocation EqualOrColonLoc,
2474 bool GNUSyntax,
2475 Expr *Init) {
2476 ExprResult Result
2477 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2478 Init);
2479 if (Result.isInvalid())
2480 return ExprError();
2481
2482 return Result;
2483 }
2484
2485 /// Build a new value-initialized expression.
2486 ///
2487 /// By default, builds the implicit value initialization without performing
2488 /// any semantic analysis. Subclasses may override this routine to provide
2489 /// different behavior.
2490 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2491 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2492 }
2493
2494 /// Build a new \c va_arg expression.
2495 ///
2496 /// By default, performs semantic analysis to build the new expression.
2497 /// Subclasses may override this routine to provide different behavior.
2498 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2499 Expr *SubExpr, TypeSourceInfo *TInfo,
2500 SourceLocation RParenLoc) {
2501 return getSema().BuildVAArgExpr(BuiltinLoc,
2502 SubExpr, TInfo,
2503 RParenLoc);
2504 }
2505
2506 /// Build a new expression list in parentheses.
2507 ///
2508 /// By default, performs semantic analysis to build the new expression.
2509 /// Subclasses may override this routine to provide different behavior.
2510 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2511 MultiExprArg SubExprs,
2512 SourceLocation RParenLoc) {
2513 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2514 }
2515
2516 /// Build a new address-of-label expression.
2517 ///
2518 /// By default, performs semantic analysis, using the name of the label
2519 /// rather than attempting to map the label statement itself.
2520 /// Subclasses may override this routine to provide different behavior.
2521 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2522 SourceLocation LabelLoc, LabelDecl *Label) {
2523 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2524 }
2525
2526 /// Build a new GNU statement expression.
2527 ///
2528 /// By default, performs semantic analysis to build the new expression.
2529 /// Subclasses may override this routine to provide different behavior.
2530 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2531 Stmt *SubStmt,
2532 SourceLocation RParenLoc) {
2533 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2534 }
2535
2536 /// Build a new __builtin_choose_expr expression.
2537 ///
2538 /// By default, performs semantic analysis to build the new expression.
2539 /// Subclasses may override this routine to provide different behavior.
2540 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2541 Expr *Cond, Expr *LHS, Expr *RHS,
2542 SourceLocation RParenLoc) {
2543 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2544 Cond, LHS, RHS,
2545 RParenLoc);
2546 }
2547
2548 /// Build a new generic selection expression.
2549 ///
2550 /// By default, performs semantic analysis to build the new expression.
2551 /// Subclasses may override this routine to provide different behavior.
2552 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2553 SourceLocation DefaultLoc,
2554 SourceLocation RParenLoc,
2555 Expr *ControllingExpr,
2556 ArrayRef<TypeSourceInfo *> Types,
2557 ArrayRef<Expr *> Exprs) {
2558 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2559 ControllingExpr, Types, Exprs);
2560 }
2561
2562 /// Build a new overloaded operator call expression.
2563 ///
2564 /// By default, performs semantic analysis to build the new expression.
2565 /// The semantic analysis provides the behavior of template instantiation,
2566 /// copying with transformations that turn what looks like an overloaded
2567 /// operator call into a use of a builtin operator, performing
2568 /// argument-dependent lookup, etc. Subclasses may override this routine to
2569 /// provide different behavior.
2570 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2571 SourceLocation OpLoc,
2572 Expr *Callee,
2573 Expr *First,
2574 Expr *Second);
2575
2576 /// Build a new C++ "named" cast expression, such as static_cast or
2577 /// reinterpret_cast.
2578 ///
2579 /// By default, this routine dispatches to one of the more-specific routines
2580 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2581 /// Subclasses may override this routine to provide different behavior.
2582 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2583 Stmt::StmtClass Class,
2584 SourceLocation LAngleLoc,
2585 TypeSourceInfo *TInfo,
2586 SourceLocation RAngleLoc,
2587 SourceLocation LParenLoc,
2588 Expr *SubExpr,
2589 SourceLocation RParenLoc) {
2590 switch (Class) {
2591 case Stmt::CXXStaticCastExprClass:
2592 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2593 RAngleLoc, LParenLoc,
2594 SubExpr, RParenLoc);
2595
2596 case Stmt::CXXDynamicCastExprClass:
2597 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2598 RAngleLoc, LParenLoc,
2599 SubExpr, RParenLoc);
2600
2601 case Stmt::CXXReinterpretCastExprClass:
2602 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2603 RAngleLoc, LParenLoc,
2604 SubExpr,
2605 RParenLoc);
2606
2607 case Stmt::CXXConstCastExprClass:
2608 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2609 RAngleLoc, LParenLoc,
2610 SubExpr, RParenLoc);
2611
2612 default:
2613 llvm_unreachable("Invalid C++ named cast")::llvm::llvm_unreachable_internal("Invalid C++ named cast", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/TreeTransform.h"
, 2613)
;
2614 }
2615 }
2616
2617 /// Build a new C++ static_cast expression.
2618 ///
2619 /// By default, performs semantic analysis to build the new expression.
2620 /// Subclasses may override this routine to provide different behavior.
2621 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2622 SourceLocation LAngleLoc,
2623 TypeSourceInfo *TInfo,
2624 SourceLocation RAngleLoc,
2625 SourceLocation LParenLoc,
2626 Expr *SubExpr,
2627 SourceLocation RParenLoc) {
2628 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2629 TInfo, SubExpr,
2630 SourceRange(LAngleLoc, RAngleLoc),
2631 SourceRange(LParenLoc, RParenLoc));
2632 }
2633
2634 /// Build a new C++ dynamic_cast expression.
2635 ///
2636 /// By default, performs semantic analysis to build the new expression.
2637 /// Subclasses may override this routine to provide different behavior.
2638 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2639 SourceLocation LAngleLoc,
2640 TypeSourceInfo *TInfo,
2641 SourceLocation RAngleLoc,
2642 SourceLocation LParenLoc,
2643 Expr *SubExpr,
2644 SourceLocation RParenLoc) {
2645 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2646 TInfo, SubExpr,
2647 SourceRange(LAngleLoc, RAngleLoc),
2648 SourceRange(LParenLoc, RParenLoc));
2649 }
2650
2651 /// Build a new C++ reinterpret_cast expression.
2652 ///
2653 /// By default, performs semantic analysis to build the new expression.
2654 /// Subclasses may override this routine to provide different behavior.
2655 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2656 SourceLocation LAngleLoc,
2657 TypeSourceInfo *TInfo,
2658 SourceLocation RAngleLoc,
2659 SourceLocation LParenLoc,
2660 Expr *SubExpr,
2661 SourceLocation RParenLoc) {
2662 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2663 TInfo, SubExpr,
2664 SourceRange(LAngleLoc, RAngleLoc),
2665 SourceRange(LParenLoc, RParenLoc));
2666 }
2667
2668 /// Build a new C++ const_cast expression.
2669 ///
2670 /// By default, performs semantic analysis to build the new expression.
2671 /// Subclasses may override this routine to provide different behavior.
2672 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2673 SourceLocation LAngleLoc,
2674 TypeSourceInfo *TInfo,
2675 SourceLocation RAngleLoc,
2676 SourceLocation LParenLoc,
2677 Expr *SubExpr,
2678 SourceLocation RParenLoc) {
2679 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2680 TInfo, SubExpr,
2681 SourceRange(LAngleLoc, RAngleLoc),
2682 SourceRange(LParenLoc, RParenLoc));
2683 }
2684
2685 /// Build a new C++ functional-style cast expression.
2686 ///
2687 /// By default, performs semantic analysis to build the new expression.
2688 /// Subclasses may override this routine to provide different behavior.
2689 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2690 SourceLocation LParenLoc,
2691 Expr *Sub,
2692 SourceLocation RParenLoc,
2693 bool ListInitialization) {
2694 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2695 MultiExprArg(&Sub, 1), RParenLoc,
2696 ListInitialization);
2697 }
2698
2699 /// Build a new C++ __builtin_bit_cast expression.
2700 ///
2701 /// By default, performs semantic analysis to build the new expression.
2702 /// Subclasses may override this routine to provide different behavior.
2703 ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
2704 TypeSourceInfo *TSI, Expr *Sub,
2705 SourceLocation RParenLoc) {
2706 return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);