Bug Summary

File:tools/clang/lib/Sema/TreeTransform.h
Warning:line 4641, column 22
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiate.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -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~svn373517/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/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~svn373517/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

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