Bug Summary

File:tools/clang/lib/Sema/SemaTemplateInstantiate.cpp
Warning:line 2184, column 41
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~svn374877/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/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~svn374877/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp

/build/llvm-toolchain-snapshot-10~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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() &&
36
Assuming the condition is false
227 SemaRef.Diags.hasUncompilableErrorOccurred()) {
228 Invalid = true;
229 return;
230 }
231 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
37
Calling 'InstantiatingTemplate::CheckInstantiationDepth'
43
Returning from 'InstantiatingTemplate::CheckInstantiationDepth'
232 if (!Invalid
43.1
Field 'Invalid' is false
43.1
Field 'Invalid' is false
) {
44
Taking true branch
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
45
Assuming field 'second' is true
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,
35
Calling constructor for 'InstantiatingTemplate'
46
Returning from constructor for 'InstantiatingTemplate'
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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 425, __PRETTY_FUNCTION__))
38
Assuming the condition is true
39
'?' condition is true
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~svn374877/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 425, __PRETTY_FUNCTION__))
;
426 if ((SemaRef.CodeSynthesisContexts.size() -
40
Assuming the condition is true
41
Taking true branch
427 SemaRef.NonInstantiationEntries)
428 <= SemaRef.getLangOpts().InstantiationDepth)
429 return false;
42
Returning zero, which participates in a condition later
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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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());
27
Assuming the object is a 'CXXRecordDecl'
2028 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
28
Assuming the condition is false
29
Taking false branch
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
30
Assuming 'MSInfo' is null
31
Taking false branch
2045 = Instantiation->getMemberSpecializationInfo()) {
2046 MSInfo->setTemplateSpecializationKind(TSK);
2047 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2048 } else if (ClassTemplateSpecializationDecl *Spec
32.1
'Spec' is null
32.1
'Spec' is null
33
Taking false branch
2049 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
32
Assuming 'Instantiation' is not a 'ClassTemplateSpecializationDecl'
2050 Spec->setTemplateSpecializationKind(TSK); 2051 Spec->setPointOfInstantiation(PointOfInstantiation); 2052 } 2053 2054 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
34
Calling constructor for 'InstantiatingTemplate'
47
Returning from constructor for 'InstantiatingTemplate'
2055 if (Inst.isInvalid())
48
Calling 'InstantiatingTemplate::isInvalid'
50
Returning from 'InstantiatingTemplate::isInvalid'
51
Taking false branch
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~svn374877/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2057, __PRETTY_FUNCTION__))
;
52
'?' condition is true
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))
53
Taking false branch
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~svn374877/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(),
55
Loop condition is true. Entering loop body
2177 E = LateAttrs.end(); I != E; ++I) {
54
Assuming 'I' is not equal to 'E'
2178 assert(CurrentInstantiationScope == Instantiator.getStartingScope())((CurrentInstantiationScope == Instantiator.getStartingScope(
)) ? static_cast<void> (0) : __assert_fail ("CurrentInstantiationScope == Instantiator.getStartingScope()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2178, __PRETTY_FUNCTION__))
;
56
Assuming the condition is true
57
'?' condition is true
2179 CurrentInstantiationScope = I->Scope; 2180 2181 // Allow 'this' within late-parsed attributes. 2182 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
58
Assuming field 'NewDecl' is not a 'NamedDecl'
59
'ND' initialized to a null pointer value
2183 CXXRecordDecl *ThisContext = 2184 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
60
Called C++ object pointer is null
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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2612, __PRETTY_FUNCTION__))
1
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDefinition
2
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDeclaration
3
Assuming 'TSK' is equal to TSK_ImplicitInstantiation
4
'?' condition is true
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~svn374877/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~svn374877/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~svn374877/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~svn374877/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2612, __PRETTY_FUNCTION__))
; 2613 for (auto *D : Instantiation->decls()) { 2614 bool SuppressNew = false; 2615 if (auto *Function
5.1
'Function' is null
5.1
'Function' is null
= dyn_cast<FunctionDecl>(D)) {
5
Assuming 'D' is not a 'FunctionDecl'
6
Taking false branch
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~svn374877/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
7.1
'Var' is null
7.1
'Var' is null
= dyn_cast<VarDecl>(D)) {
7
Assuming 'D' is not a 'VarDecl'
8
Taking false branch
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~svn374877/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
9.1
'Record' is non-null
9.1
'Record' is non-null
= dyn_cast<CXXRecordDecl>(D)) {
9
Assuming 'D' is a 'CXXRecordDecl'
10
Taking true branch
2698 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
11
Taking false branch
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() ||
12
Assuming the condition is false
13
Taking false branch
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~svn374877/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2711, __PRETTY_FUNCTION__))
;
14
Assuming 'MSInfo' is non-null
15
'?' condition is true
2712 2713 if (MSInfo->getTemplateSpecializationKind()
16
Assuming the condition is false
17
Taking false branch
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,
18
Assuming the condition is false
19
Assuming the condition is false
20
Taking false branch
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~svn374877/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2737, __PRETTY_FUNCTION__))
;
21
Assuming 'Pattern' is non-null
22
'?' condition is true
2738 2739 if (!Record->getDefinition()) {
23
Taking true branch
2740 if (!Pattern->getDefinition()) {
24
Assuming the condition is false
25
Taking false branch
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,
26
Calling 'Sema::InstantiateClass'
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~svn374877/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~svn374877/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); 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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/tools/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/Availability.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/LocInfoType.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NSAPI.h"
29#include "clang/AST/PrettyPrinter.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/TypeOrdering.h"
33#include "clang/Basic/ExpressionTraits.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/TypoCorrection.h"
49#include "clang/Sema/Weak.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/Optional.h"
52#include "llvm/ADT/SetVector.h"
53#include "llvm/ADT/SmallBitVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <tuple>
61#include <vector>
62
63namespace llvm {
64 class APSInt;
65 template <typename ValueT> struct DenseMapInfo;
66 template <typename ValueT, typename ValueInfoT> class DenseSet;
67 class SmallBitVector;
68 struct InlineAsmIdentifierInfo;
69}
70
71namespace clang {
72 class ADLResult;
73 class ASTConsumer;
74 class ASTContext;
75 class ASTMutationListener;
76 class ASTReader;
77 class ASTWriter;
78 class ArrayType;
79 class ParsedAttr;
80 class BindingDecl;
81 class BlockDecl;
82 class CapturedDecl;
83 class CXXBasePath;
84 class CXXBasePaths;
85 class CXXBindTemporaryExpr;
86 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
87 class CXXConstructorDecl;
88 class CXXConversionDecl;
89 class CXXDeleteExpr;
90 class CXXDestructorDecl;
91 class CXXFieldCollector;
92 class CXXMemberCallExpr;
93 class CXXMethodDecl;
94 class CXXScopeSpec;
95 class CXXTemporary;
96 class CXXTryStmt;
97 class CallExpr;
98 class ClassTemplateDecl;
99 class ClassTemplatePartialSpecializationDecl;
100 class ClassTemplateSpecializationDecl;
101 class VarTemplatePartialSpecializationDecl;
102 class CodeCompleteConsumer;
103 class CodeCompletionAllocator;
104 class CodeCompletionTUInfo;
105 class CodeCompletionResult;
106 class CoroutineBodyStmt;
107 class Decl;
108 class DeclAccessPair;
109 class DeclContext;
110 class DeclRefExpr;
111 class DeclaratorDecl;
112 class DeducedTemplateArgument;
113 class DependentDiagnostic;
114 class DesignatedInitExpr;
115 class Designation;
116 class EnableIfAttr;
117 class EnumConstantDecl;
118 class Expr;
119 class ExtVectorType;
120 class FormatAttr;
121 class FriendDecl;
122 class FunctionDecl;
123 class FunctionProtoType;
124 class FunctionTemplateDecl;
125 class ImplicitConversionSequence;
126 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
127 class InitListExpr;
128 class InitializationKind;
129 class InitializationSequence;
130 class InitializedEntity;
131 class IntegerLiteral;
132 class LabelStmt;
133 class LambdaExpr;
134 class LangOptions;
135 class LocalInstantiationScope;
136 class LookupResult;
137 class MacroInfo;
138 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
139 class ModuleLoader;
140 class MultiLevelTemplateArgumentList;
141 class NamedDecl;
142 class ObjCCategoryDecl;
143 class ObjCCategoryImplDecl;
144 class ObjCCompatibleAliasDecl;
145 class ObjCContainerDecl;
146 class ObjCImplDecl;
147 class ObjCImplementationDecl;
148 class ObjCInterfaceDecl;
149 class ObjCIvarDecl;
150 template <class T> class ObjCList;
151 class ObjCMessageExpr;
152 class ObjCMethodDecl;
153 class ObjCPropertyDecl;
154 class ObjCProtocolDecl;
155 class OMPThreadPrivateDecl;
156 class OMPRequiresDecl;
157 class OMPDeclareReductionDecl;
158 class OMPDeclareSimdDecl;
159 class OMPClause;
160 struct OMPVarListLocTy;
161 struct OverloadCandidate;
162 class OverloadCandidateSet;
163 class OverloadExpr;
164 class ParenListExpr;
165 class ParmVarDecl;
166 class Preprocessor;
167 class PseudoDestructorTypeStorage;
168 class PseudoObjectExpr;
169 class QualType;
170 class StandardConversionSequence;
171 class Stmt;
172 class StringLiteral;
173 class SwitchStmt;
174 class TemplateArgument;
175 class TemplateArgumentList;
176 class TemplateArgumentLoc;
177 class TemplateDecl;
178 class TemplateInstantiationCallback;
179 class TemplateParameterList;
180 class TemplatePartialOrderingContext;
181 class TemplateTemplateParmDecl;
182 class Token;
183 class TypeAliasDecl;
184 class TypedefDecl;
185 class TypedefNameDecl;
186 class TypeLoc;
187 class TypoCorrectionConsumer;
188 class UnqualifiedId;
189 class UnresolvedLookupExpr;
190 class UnresolvedMemberExpr;
191 class UnresolvedSetImpl;
192 class UnresolvedSetIterator;
193 class UsingDecl;
194 class UsingShadowDecl;
195 class ValueDecl;
196 class VarDecl;
197 class VarTemplateSpecializationDecl;
198 class VisibilityAttr;
199 class VisibleDeclConsumer;
200 class IndirectFieldDecl;
201 struct DeductionFailureInfo;
202 class TemplateSpecCandidateSet;
203
204namespace sema {
205 class AccessedEntity;
206 class BlockScopeInfo;
207 class Capture;
208 class CapturedRegionScopeInfo;
209 class CapturingScopeInfo;
210 class CompoundScopeInfo;
211 class DelayedDiagnostic;
212 class DelayedDiagnosticPool;
213 class FunctionScopeInfo;
214 class LambdaScopeInfo;
215 class PossiblyUnreachableDiag;
216 class SemaPPCallbacks;
217 class TemplateDeductionInfo;
218}
219
220namespace threadSafety {
221 class BeforeSet;
222 void threadSafetyCleanup(BeforeSet* Cache);
223}
224
225// FIXME: No way to easily map from TemplateTypeParmTypes to
226// TemplateTypeParmDecls, so we have this horrible PointerUnion.
227typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
228 SourceLocation> UnexpandedParameterPack;
229
230/// Describes whether we've seen any nullability information for the given
231/// file.
232struct FileNullability {
233 /// The first pointer declarator (of any pointer kind) in the file that does
234 /// not have a corresponding nullability annotation.
235 SourceLocation PointerLoc;
236
237 /// The end location for the first pointer declarator in the file. Used for
238 /// placing fix-its.
239 SourceLocation PointerEndLoc;
240
241 /// Which kind of pointer declarator we saw.
242 uint8_t PointerKind;
243
244 /// Whether we saw any type nullability annotations in the given file.
245 bool SawTypeNullability = false;
246};
247
248/// A mapping from file IDs to a record of whether we've seen nullability
249/// information in that file.
250class FileNullabilityMap {
251 /// A mapping from file IDs to the nullability information for each file ID.
252 llvm::DenseMap<FileID, FileNullability> Map;
253
254 /// A single-element cache based on the file ID.
255 struct {
256 FileID File;
257 FileNullability Nullability;
258 } Cache;
259
260public:
261 FileNullability &operator[](FileID file) {
262 // Check the single-element cache.
263 if (file == Cache.File)
264 return Cache.Nullability;
265
266 // It's not in the single-element cache; flush the cache if we have one.
267 if (!Cache.File.isInvalid()) {
268 Map[Cache.File] = Cache.Nullability;
269 }
270
271 // Pull this entry into the cache.
272 Cache.File = file;
273 Cache.Nullability = Map[file];
274 return Cache.Nullability;
275 }
276};
277
278/// Keeps track of expected type during expression parsing. The type is tied to
279/// a particular token, all functions that update or consume the type take a
280/// start location of the token they are looking at as a parameter. This allows
281/// to avoid updating the type on hot paths in the parser.
282class PreferredTypeBuilder {
283public:
284 PreferredTypeBuilder() = default;
285 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
286
287 void enterCondition(Sema &S, SourceLocation Tok);
288 void enterReturn(Sema &S, SourceLocation Tok);
289 void enterVariableInit(SourceLocation Tok, Decl *D);
290 /// Computing a type for the function argument may require running
291 /// overloading, so we postpone its computation until it is actually needed.
292 ///
293 /// Clients should be very careful when using this funciton, as it stores a
294 /// function_ref, clients should make sure all calls to get() with the same
295 /// location happen while function_ref is alive.
296 void enterFunctionArgument(SourceLocation Tok,
297 llvm::function_ref<QualType()> ComputeType);
298
299 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
300 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
301 SourceLocation OpLoc);
302 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
303 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
304 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
305 /// Handles all type casts, including C-style cast, C++ casts, etc.
306 void enterTypeCast(SourceLocation Tok, QualType CastType);
307
308 QualType get(SourceLocation Tok) const {
309 if (Tok != ExpectedLoc)
310 return QualType();
311 if (!Type.isNull())
312 return Type;
313 if (ComputeType)
314 return ComputeType();
315 return QualType();
316 }
317
318private:
319 /// Start position of a token for which we store expected type.
320 SourceLocation ExpectedLoc;
321 /// Expected type for a token starting at ExpectedLoc.
322 QualType Type;
323 /// A function to compute expected type at ExpectedLoc. It is only considered
324 /// if Type is null.
325 llvm::function_ref<QualType()> ComputeType;
326};
327
328/// Sema - This implements semantic analysis and AST building for C.
329class Sema {
330 Sema(const Sema &) = delete;
331 void operator=(const Sema &) = delete;
332
333 ///Source of additional semantic information.
334 ExternalSemaSource *ExternalSource;
335
336 ///Whether Sema has generated a multiplexer and has to delete it.
337 bool isMultiplexExternalSource;
338
339 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
340
341 bool isVisibleSlow(const NamedDecl *D);
342
343 /// Determine whether two declarations should be linked together, given that
344 /// the old declaration might not be visible and the new declaration might
345 /// not have external linkage.
346 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
347 const NamedDecl *New) {
348 if (isVisible(Old))
349 return true;
350 // See comment in below overload for why it's safe to compute the linkage
351 // of the new declaration here.
352 if (New->isExternallyDeclarable()) {
353 assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 354, __PRETTY_FUNCTION__))
354 "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 354, __PRETTY_FUNCTION__))
;
355 return true;
356 }
357 return false;
358 }
359 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
360
361 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
362 QualType ResultTy,
363 ArrayRef<QualType> Args);
364
365public:
366 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
367 typedef OpaquePtr<TemplateName> TemplateTy;
368 typedef OpaquePtr<QualType> TypeTy;
369
370 OpenCLOptions OpenCLFeatures;
371 FPOptions FPFeatures;
372
373 const LangOptions &LangOpts;
374 Preprocessor &PP;
375 ASTContext &Context;
376 ASTConsumer &Consumer;
377 DiagnosticsEngine &Diags;
378 SourceManager &SourceMgr;
379
380 /// Flag indicating whether or not to collect detailed statistics.
381 bool CollectStats;
382
383 /// Code-completion consumer.
384 CodeCompleteConsumer *CodeCompleter;
385
386 /// CurContext - This is the current declaration context of parsing.
387 DeclContext *CurContext;
388
389 /// Generally null except when we temporarily switch decl contexts,
390 /// like in \see ActOnObjCTemporaryExitContainerContext.
391 DeclContext *OriginalLexicalContext;
392
393 /// VAListTagName - The declaration name corresponding to __va_list_tag.
394 /// This is used as part of a hack to omit that class from ADL results.
395 DeclarationName VAListTagName;
396
397 bool MSStructPragmaOn; // True when \#pragma ms_struct on
398
399 /// Controls member pointer representation format under the MS ABI.
400 LangOptions::PragmaMSPointersToMembersKind
401 MSPointerToMemberRepresentationMethod;
402
403 /// Stack of active SEH __finally scopes. Can be empty.
404 SmallVector<Scope*, 2> CurrentSEHFinally;
405
406 /// Source location for newly created implicit MSInheritanceAttrs
407 SourceLocation ImplicitMSInheritanceAttrLoc;
408
409 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
410 /// `TransformTypos` in order to keep track of any TypoExprs that are created
411 /// recursively during typo correction and wipe them away if the correction
412 /// fails.
413 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
414
415 /// pragma clang section kind
416 enum PragmaClangSectionKind {
417 PCSK_Invalid = 0,
418 PCSK_BSS = 1,
419 PCSK_Data = 2,
420 PCSK_Rodata = 3,
421 PCSK_Text = 4
422 };
423
424 enum PragmaClangSectionAction {
425 PCSA_Set = 0,
426 PCSA_Clear = 1
427 };
428
429 struct PragmaClangSection {
430 std::string SectionName;
431 bool Valid = false;
432 SourceLocation PragmaLocation;
433
434 void Act(SourceLocation PragmaLocation,
435 PragmaClangSectionAction Action,
436 StringLiteral* Name);
437 };
438
439 PragmaClangSection PragmaClangBSSSection;
440 PragmaClangSection PragmaClangDataSection;
441 PragmaClangSection PragmaClangRodataSection;
442 PragmaClangSection PragmaClangTextSection;
443
444 enum PragmaMsStackAction {
445 PSK_Reset = 0x0, // #pragma ()
446 PSK_Set = 0x1, // #pragma (value)
447 PSK_Push = 0x2, // #pragma (push[, id])
448 PSK_Pop = 0x4, // #pragma (pop[, id])
449 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
450 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
451 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
452 };
453
454 template<typename ValueType>
455 struct PragmaStack {
456 struct Slot {
457 llvm::StringRef StackSlotLabel;
458 ValueType Value;
459 SourceLocation PragmaLocation;
460 SourceLocation PragmaPushLocation;
461 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
462 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
463 : StackSlotLabel(StackSlotLabel), Value(Value),
464 PragmaLocation(PragmaLocation),
465 PragmaPushLocation(PragmaPushLocation) {}
466 };
467 void Act(SourceLocation PragmaLocation,
468 PragmaMsStackAction Action,
469 llvm::StringRef StackSlotLabel,
470 ValueType Value);
471
472 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
473 // method body to restore the stacks on exit, so it works like this:
474 //
475 // struct S {
476 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
477 // void Method {}
478 // #pragma <name>(pop, InternalPragmaSlot)
479 // };
480 //
481 // It works even with #pragma vtordisp, although MSVC doesn't support
482 // #pragma vtordisp(push [, id], n)
483 // syntax.
484 //
485 // Push / pop a named sentinel slot.
486 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
487 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 488, __PRETTY_FUNCTION__))
488 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 488, __PRETTY_FUNCTION__))
;
489 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
490 }
491
492 // Constructors.
493 explicit PragmaStack(const ValueType &Default)
494 : DefaultValue(Default), CurrentValue(Default) {}
495
496 bool hasValue() const { return CurrentValue != DefaultValue; }
497
498 SmallVector<Slot, 2> Stack;
499 ValueType DefaultValue; // Value used for PSK_Reset action.
500 ValueType CurrentValue;
501 SourceLocation CurrentPragmaLocation;
502 };
503 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
504 // we shouldn't do so if they're in a module).
505
506 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
507 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
508 ///
509 /// 0: Suppress all vtordisps
510 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
511 /// structors
512 /// 2: Always insert vtordisps to support RTTI on partially constructed
513 /// objects
514 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
515 // #pragma pack.
516 // Sentinel to represent when the stack is set to mac68k alignment.
517 static const unsigned kMac68kAlignmentSentinel = ~0U;
518 PragmaStack<unsigned> PackStack;
519 // The current #pragma pack values and locations at each #include.
520 struct PackIncludeState {
521 unsigned CurrentValue;
522 SourceLocation CurrentPragmaLocation;
523 bool HasNonDefaultValue, ShouldWarnOnInclude;
524 };
525 SmallVector<PackIncludeState, 8> PackIncludeStack;
526 // Segment #pragmas.
527 PragmaStack<StringLiteral *> DataSegStack;
528 PragmaStack<StringLiteral *> BSSSegStack;
529 PragmaStack<StringLiteral *> ConstSegStack;
530 PragmaStack<StringLiteral *> CodeSegStack;
531
532 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
533 // Actions should be performed only if we enter / exit a C++ method body.
534 class PragmaStackSentinelRAII {
535 public:
536 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
537 ~PragmaStackSentinelRAII();
538
539 private:
540 Sema &S;
541 StringRef SlotLabel;
542 bool ShouldAct;
543 };
544
545 /// A mapping that describes the nullability we've seen in each header file.
546 FileNullabilityMap NullabilityMap;
547
548 /// Last section used with #pragma init_seg.
549 StringLiteral *CurInitSeg;
550 SourceLocation CurInitSegLoc;
551
552 /// VisContext - Manages the stack for \#pragma GCC visibility.
553 void *VisContext; // Really a "PragmaVisStack*"
554
555 /// This an attribute introduced by \#pragma clang attribute.
556 struct PragmaAttributeEntry {
557 SourceLocation Loc;
558 ParsedAttr *Attribute;
559 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
560 bool IsUsed;
561 };
562
563 /// A push'd group of PragmaAttributeEntries.
564 struct PragmaAttributeGroup {
565 /// The location of the push attribute.
566 SourceLocation Loc;
567 /// The namespace of this push group.
568 const IdentifierInfo *Namespace;
569 SmallVector<PragmaAttributeEntry, 2> Entries;
570 };
571
572 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
573
574 /// The declaration that is currently receiving an attribute from the
575 /// #pragma attribute stack.
576 const Decl *PragmaAttributeCurrentTargetDecl;
577
578 /// This represents the last location of a "#pragma clang optimize off"
579 /// directive if such a directive has not been closed by an "on" yet. If
580 /// optimizations are currently "on", this is set to an invalid location.
581 SourceLocation OptimizeOffPragmaLocation;
582
583 /// Flag indicating if Sema is building a recovery call expression.
584 ///
585 /// This flag is used to avoid building recovery call expressions
586 /// if Sema is already doing so, which would cause infinite recursions.
587 bool IsBuildingRecoveryCallExpr;
588
589 /// Used to control the generation of ExprWithCleanups.
590 CleanupInfo Cleanup;
591
592 /// ExprCleanupObjects - This is the stack of objects requiring
593 /// cleanup that are created by the current full expression. The
594 /// element type here is ExprWithCleanups::Object.
595 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
596
597 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
598 /// to a variable (constant) that may or may not be odr-used in this Expr, and
599 /// we won't know until all lvalue-to-rvalue and discarded value conversions
600 /// have been applied to all subexpressions of the enclosing full expression.
601 /// This is cleared at the end of each full expression.
602 using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
603 MaybeODRUseExprSet MaybeODRUseExprs;
604
605 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
606
607 /// Stack containing information about each of the nested
608 /// function, block, and method scopes that are currently active.
609 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
610
611 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
612 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
613 ExtVectorDeclsType;
614
615 /// ExtVectorDecls - This is a list all the extended vector types. This allows
616 /// us to associate a raw vector type with one of the ext_vector type names.
617 /// This is only necessary for issuing pretty diagnostics.
618 ExtVectorDeclsType ExtVectorDecls;
619
620 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
621 std::unique_ptr<CXXFieldCollector> FieldCollector;
622
623 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
624
625 /// Set containing all declared private fields that are not used.
626 NamedDeclSetType UnusedPrivateFields;
627
628 /// Set containing all typedefs that are likely unused.
629 llvm::SmallSetVector<const TypedefNameDecl *, 4>
630 UnusedLocalTypedefNameCandidates;
631
632 /// Delete-expressions to be analyzed at the end of translation unit
633 ///
634 /// This list contains class members, and locations of delete-expressions
635 /// that could not be proven as to whether they mismatch with new-expression
636 /// used in initializer of the field.
637 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
638 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
639 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
640
641 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
642
643 /// PureVirtualClassDiagSet - a set of class declarations which we have
644 /// emitted a list of pure virtual functions. Used to prevent emitting the
645 /// same list more than once.
646 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
647
648 /// ParsingInitForAutoVars - a set of declarations with auto types for which
649 /// we are currently parsing the initializer.
650 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
651
652 /// Look for a locally scoped extern "C" declaration by the given name.
653 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
654
655 typedef LazyVector<VarDecl *, ExternalSemaSource,
656 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
657 TentativeDefinitionsType;
658
659 /// All the tentative definitions encountered in the TU.
660 TentativeDefinitionsType TentativeDefinitions;
661
662 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
663 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
664 UnusedFileScopedDeclsType;
665
666 /// The set of file scoped decls seen so far that have not been used
667 /// and must warn if not used. Only contains the first declaration.
668 UnusedFileScopedDeclsType UnusedFileScopedDecls;
669
670 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
671 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
672 DelegatingCtorDeclsType;
673
674 /// All the delegating constructors seen so far in the file, used for
675 /// cycle detection at the end of the TU.
676 DelegatingCtorDeclsType DelegatingCtorDecls;
677
678 /// All the overriding functions seen during a class definition
679 /// that had their exception spec checks delayed, plus the overridden
680 /// function.
681 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
682 DelayedOverridingExceptionSpecChecks;
683
684 /// All the function redeclarations seen during a class definition that had
685 /// their exception spec checks delayed, plus the prior declaration they
686 /// should be checked against. Except during error recovery, the new decl
687 /// should always be a friend declaration, as that's the only valid way to
688 /// redeclare a special member before its class is complete.
689 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
690 DelayedEquivalentExceptionSpecChecks;
691
692 typedef llvm::MapVector<const FunctionDecl *,
693 std::unique_ptr<LateParsedTemplate>>
694 LateParsedTemplateMapT;
695 LateParsedTemplateMapT LateParsedTemplateMap;
696
697 /// Callback to the parser to parse templated functions when needed.
698 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
699 typedef void LateTemplateParserCleanupCB(void *P);
700 LateTemplateParserCB *LateTemplateParser;
701 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
702 void *OpaqueParser;
703
704 void SetLateTemplateParser(LateTemplateParserCB *LTP,
705 LateTemplateParserCleanupCB *LTPCleanup,
706 void *P) {
707 LateTemplateParser = LTP;
708 LateTemplateParserCleanup = LTPCleanup;
709 OpaqueParser = P;
710 }
711
712 class DelayedDiagnostics;
713
714 class DelayedDiagnosticsState {
715 sema::DelayedDiagnosticPool *SavedPool;
716 friend class Sema::DelayedDiagnostics;
717 };
718 typedef DelayedDiagnosticsState ParsingDeclState;
719 typedef DelayedDiagnosticsState ProcessingContextState;
720
721 /// A class which encapsulates the logic for delaying diagnostics
722 /// during parsing and other processing.
723 class DelayedDiagnostics {
724 /// The current pool of diagnostics into which delayed
725 /// diagnostics should go.
726 sema::DelayedDiagnosticPool *CurPool;
727
728 public:
729 DelayedDiagnostics() : CurPool(nullptr) {}
730
731 /// Adds a delayed diagnostic.
732 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
733
734 /// Determines whether diagnostics should be delayed.
735 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
736
737 /// Returns the current delayed-diagnostics pool.
738 sema::DelayedDiagnosticPool *getCurrentPool() const {
739 return CurPool;
740 }
741
742 /// Enter a new scope. Access and deprecation diagnostics will be
743 /// collected in this pool.
744 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
745 DelayedDiagnosticsState state;
746 state.SavedPool = CurPool;
747 CurPool = &pool;
748 return state;
749 }
750
751 /// Leave a delayed-diagnostic state that was previously pushed.
752 /// Do not emit any of the diagnostics. This is performed as part
753 /// of the bookkeeping of popping a pool "properly".
754 void popWithoutEmitting(DelayedDiagnosticsState state) {
755 CurPool = state.SavedPool;
756 }
757
758 /// Enter a new scope where access and deprecation diagnostics are
759 /// not delayed.
760 DelayedDiagnosticsState pushUndelayed() {
761 DelayedDiagnosticsState state;
762 state.SavedPool = CurPool;
763 CurPool = nullptr;
764 return state;
765 }
766
767 /// Undo a previous pushUndelayed().
768 void popUndelayed(DelayedDiagnosticsState state) {
769 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 769, __PRETTY_FUNCTION__))
;
770 CurPool = state.SavedPool;
771 }
772 } DelayedDiagnostics;
773
774 /// A RAII object to temporarily push a declaration context.
775 class ContextRAII {
776 private:
777 Sema &S;
778 DeclContext *SavedContext;
779 ProcessingContextState SavedContextState;
780 QualType SavedCXXThisTypeOverride;
781
782 public:
783 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
784 : S(S), SavedContext(S.CurContext),
785 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
786 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
787 {
788 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 788, __PRETTY_FUNCTION__))
;
789 S.CurContext = ContextToPush;
790 if (NewThisContext)
791 S.CXXThisTypeOverride = QualType();
792 }
793
794 void pop() {
795 if (!SavedContext) return;
796 S.CurContext = SavedContext;
797 S.DelayedDiagnostics.popUndelayed(SavedContextState);
798 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
799 SavedContext = nullptr;
800 }
801
802 ~ContextRAII() {
803 pop();
804 }
805 };
806
807 /// Used to change context to isConstantEvaluated without pushing a heavy
808 /// ExpressionEvaluationContextRecord object.
809 bool isConstantEvaluatedOverride;
810
811 bool isConstantEvaluated() {
812 return ExprEvalContexts.back().isConstantEvaluated() ||
813 isConstantEvaluatedOverride;
814 }
815
816 /// RAII object to handle the state changes required to synthesize
817 /// a function body.
818 class SynthesizedFunctionScope {
819 Sema &S;
820 Sema::ContextRAII SavedContext;
821 bool PushedCodeSynthesisContext = false;
822
823 public:
824 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
825 : S(S), SavedContext(S, DC) {
826 S.PushFunctionScope();
827 S.PushExpressionEvaluationContext(
828 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
829 if (auto *FD = dyn_cast<FunctionDecl>(DC))
830 FD->setWillHaveBody(true);
831 else
832 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 832, __PRETTY_FUNCTION__))
;
833 }
834
835 void addContextNote(SourceLocation UseLoc) {
836 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 836, __PRETTY_FUNCTION__))
;
837
838 Sema::CodeSynthesisContext Ctx;
839 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
840 Ctx.PointOfInstantiation = UseLoc;
841 Ctx.Entity = cast<Decl>(S.CurContext);
842 S.pushCodeSynthesisContext(Ctx);
843
844 PushedCodeSynthesisContext = true;
845 }
846
847 ~SynthesizedFunctionScope() {
848 if (PushedCodeSynthesisContext)
849 S.popCodeSynthesisContext();
850 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
851 FD->setWillHaveBody(false);
852 S.PopExpressionEvaluationContext();
853 S.PopFunctionScopeInfo();
854 }
855 };
856
857 /// WeakUndeclaredIdentifiers - Identifiers contained in
858 /// \#pragma weak before declared. rare. may alias another
859 /// identifier, declared or undeclared
860 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
861
862 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
863 /// \#pragma redefine_extname before declared. Used in Solaris system headers
864 /// to define functions that occur in multiple standards to call the version
865 /// in the currently selected standard.
866 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
867
868
869 /// Load weak undeclared identifiers from the external source.
870 void LoadExternalWeakUndeclaredIdentifiers();
871
872 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
873 /// \#pragma weak during processing of other Decls.
874 /// I couldn't figure out a clean way to generate these in-line, so
875 /// we store them here and handle separately -- which is a hack.
876 /// It would be best to refactor this.
877 SmallVector<Decl*,2> WeakTopLevelDecl;
878
879 IdentifierResolver IdResolver;
880
881 /// Translation Unit Scope - useful to Objective-C actions that need
882 /// to lookup file scope declarations in the "ordinary" C decl namespace.
883 /// For example, user-defined classes, built-in "id" type, etc.
884 Scope *TUScope;
885
886 /// The C++ "std" namespace, where the standard library resides.
887 LazyDeclPtr StdNamespace;
888
889 /// The C++ "std::bad_alloc" class, which is defined by the C++
890 /// standard library.
891 LazyDeclPtr StdBadAlloc;
892
893 /// The C++ "std::align_val_t" enum class, which is defined by the C++
894 /// standard library.
895 LazyDeclPtr StdAlignValT;
896
897 /// The C++ "std::experimental" namespace, where the experimental parts
898 /// of the standard library resides.
899 NamespaceDecl *StdExperimentalNamespaceCache;
900
901 /// The C++ "std::initializer_list" template, which is defined in
902 /// \<initializer_list>.
903 ClassTemplateDecl *StdInitializerList;
904
905 /// The C++ "std::coroutine_traits" template, which is defined in
906 /// \<coroutine_traits>
907 ClassTemplateDecl *StdCoroutineTraitsCache;
908
909 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
910 RecordDecl *CXXTypeInfoDecl;
911
912 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
913 RecordDecl *MSVCGuidDecl;
914
915 /// Caches identifiers/selectors for NSFoundation APIs.
916 std::unique_ptr<NSAPI> NSAPIObj;
917
918 /// The declaration of the Objective-C NSNumber class.
919 ObjCInterfaceDecl *NSNumberDecl;
920
921 /// The declaration of the Objective-C NSValue class.
922 ObjCInterfaceDecl *NSValueDecl;
923
924 /// Pointer to NSNumber type (NSNumber *).
925 QualType NSNumberPointer;
926
927 /// Pointer to NSValue type (NSValue *).
928 QualType NSValuePointer;
929
930 /// The Objective-C NSNumber methods used to create NSNumber literals.
931 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
932
933 /// The declaration of the Objective-C NSString class.
934 ObjCInterfaceDecl *NSStringDecl;
935
936 /// Pointer to NSString type (NSString *).
937 QualType NSStringPointer;
938
939 /// The declaration of the stringWithUTF8String: method.
940 ObjCMethodDecl *StringWithUTF8StringMethod;
941
942 /// The declaration of the valueWithBytes:objCType: method.
943 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
944
945 /// The declaration of the Objective-C NSArray class.
946 ObjCInterfaceDecl *NSArrayDecl;
947
948 /// The declaration of the arrayWithObjects:count: method.
949 ObjCMethodDecl *ArrayWithObjectsMethod;
950
951 /// The declaration of the Objective-C NSDictionary class.
952 ObjCInterfaceDecl *NSDictionaryDecl;
953
954 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
955 ObjCMethodDecl *DictionaryWithObjectsMethod;
956
957 /// id<NSCopying> type.
958 QualType QIDNSCopying;
959
960 /// will hold 'respondsToSelector:'
961 Selector RespondsToSelectorSel;
962
963 /// A flag to remember whether the implicit forms of operator new and delete
964 /// have been declared.
965 bool GlobalNewDeleteDeclared;
966
967 /// A flag to indicate that we're in a context that permits abstract
968 /// references to fields. This is really a
969 bool AllowAbstractFieldReference;
970
971 /// Describes how the expressions currently being parsed are
972 /// evaluated at run-time, if at all.
973 enum class ExpressionEvaluationContext {
974 /// The current expression and its subexpressions occur within an
975 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
976 /// \c sizeof, where the type of the expression may be significant but
977 /// no code will be generated to evaluate the value of the expression at
978 /// run time.
979 Unevaluated,
980
981 /// The current expression occurs within a braced-init-list within
982 /// an unevaluated operand. This is mostly like a regular unevaluated
983 /// context, except that we still instantiate constexpr functions that are
984 /// referenced here so that we can perform narrowing checks correctly.
985 UnevaluatedList,
986
987 /// The current expression occurs within a discarded statement.
988 /// This behaves largely similarly to an unevaluated operand in preventing
989 /// definitions from being required, but not in other ways.
990 DiscardedStatement,
991
992 /// The current expression occurs within an unevaluated
993 /// operand that unconditionally permits abstract references to
994 /// fields, such as a SIZE operator in MS-style inline assembly.
995 UnevaluatedAbstract,
996
997 /// The current context is "potentially evaluated" in C++11 terms,
998 /// but the expression is evaluated at compile-time (like the values of
999 /// cases in a switch statement).
1000 ConstantEvaluated,
1001
1002 /// The current expression is potentially evaluated at run time,
1003 /// which means that code may be generated to evaluate the value of the
1004 /// expression at run time.
1005 PotentiallyEvaluated,
1006
1007 /// The current expression is potentially evaluated, but any
1008 /// declarations referenced inside that expression are only used if
1009 /// in fact the current expression is used.
1010 ///
1011 /// This value is used when parsing default function arguments, for which
1012 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1013 /// through varargs) but do not want to mark declarations as "referenced"
1014 /// until the default argument is used.
1015 PotentiallyEvaluatedIfUsed
1016 };
1017
1018 /// Data structure used to record current or nested
1019 /// expression evaluation contexts.
1020 struct ExpressionEvaluationContextRecord {
1021 /// The expression evaluation context.
1022 ExpressionEvaluationContext Context;
1023
1024 /// Whether the enclosing context needed a cleanup.
1025 CleanupInfo ParentCleanup;
1026
1027 /// Whether we are in a decltype expression.
1028 bool IsDecltype;
1029
1030 /// The number of active cleanup objects when we entered
1031 /// this expression evaluation context.
1032 unsigned NumCleanupObjects;
1033
1034 /// The number of typos encountered during this expression evaluation
1035 /// context (i.e. the number of TypoExprs created).
1036 unsigned NumTypos;
1037
1038 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1039
1040 /// The lambdas that are present within this context, if it
1041 /// is indeed an unevaluated context.
1042 SmallVector<LambdaExpr *, 2> Lambdas;
1043
1044 /// The declaration that provides context for lambda expressions
1045 /// and block literals if the normal declaration context does not
1046 /// suffice, e.g., in a default function argument.
1047 Decl *ManglingContextDecl;
1048
1049 /// If we are processing a decltype type, a set of call expressions
1050 /// for which we have deferred checking the completeness of the return type.
1051 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1052
1053 /// If we are processing a decltype type, a set of temporary binding
1054 /// expressions for which we have deferred checking the destructor.
1055 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1056
1057 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1058
1059 /// Expressions appearing as the LHS of a volatile assignment in this
1060 /// context. We produce a warning for these when popping the context if
1061 /// they are not discarded-value expressions nor unevaluated operands.
1062 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1063
1064 /// \brief Describes whether we are in an expression constext which we have
1065 /// to handle differently.
1066 enum ExpressionKind {
1067 EK_Decltype, EK_TemplateArgument, EK_Other
1068 } ExprContext;
1069
1070 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1071 unsigned NumCleanupObjects,
1072 CleanupInfo ParentCleanup,
1073 Decl *ManglingContextDecl,
1074 ExpressionKind ExprContext)
1075 : Context(Context), ParentCleanup(ParentCleanup),
1076 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1077 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1078
1079 bool isUnevaluated() const {
1080 return Context == ExpressionEvaluationContext::Unevaluated ||
1081 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1082 Context == ExpressionEvaluationContext::UnevaluatedList;
1083 }
1084 bool isConstantEvaluated() const {
1085 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1086 }
1087 };
1088
1089 /// A stack of expression evaluation contexts.
1090 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1091
1092 /// Emit a warning for all pending noderef expressions that we recorded.
1093 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1094
1095 /// Compute the mangling number context for a lambda expression or
1096 /// block literal. Also return the extra mangling decl if any.
1097 ///
1098 /// \param DC - The DeclContext containing the lambda expression or
1099 /// block literal.
1100 std::tuple<MangleNumberingContext *, Decl *>
1101 getCurrentMangleNumberContext(const DeclContext *DC);
1102
1103
1104 /// SpecialMemberOverloadResult - The overloading result for a special member
1105 /// function.
1106 ///
1107 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1108 /// integer are used to determine whether overload resolution succeeded.
1109 class SpecialMemberOverloadResult {
1110 public:
1111 enum Kind {
1112 NoMemberOrDeleted,
1113 Ambiguous,
1114 Success
1115 };
1116
1117 private:
1118 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1119
1120 public:
1121 SpecialMemberOverloadResult() : Pair() {}
1122 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1123 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1124
1125 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1126 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1127
1128 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1129 void setKind(Kind K) { Pair.setInt(K); }
1130 };
1131
1132 class SpecialMemberOverloadResultEntry
1133 : public llvm::FastFoldingSetNode,
1134 public SpecialMemberOverloadResult {
1135 public:
1136 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1137 : FastFoldingSetNode(ID)
1138 {}
1139 };
1140
1141 /// A cache of special member function overload resolution results
1142 /// for C++ records.
1143 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1144
1145 /// A cache of the flags available in enumerations with the flag_bits
1146 /// attribute.
1147 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1148
1149 /// The kind of translation unit we are processing.
1150 ///
1151 /// When we're processing a complete translation unit, Sema will perform
1152 /// end-of-translation-unit semantic tasks (such as creating
1153 /// initializers for tentative definitions in C) once parsing has
1154 /// completed. Modules and precompiled headers perform different kinds of
1155 /// checks.
1156 TranslationUnitKind TUKind;
1157
1158 llvm::BumpPtrAllocator BumpAlloc;
1159
1160 /// The number of SFINAE diagnostics that have been trapped.
1161 unsigned NumSFINAEErrors;
1162
1163 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1164 UnparsedDefaultArgInstantiationsMap;
1165
1166 /// A mapping from parameters with unparsed default arguments to the
1167 /// set of instantiations of each parameter.
1168 ///
1169 /// This mapping is a temporary data structure used when parsing
1170 /// nested class templates or nested classes of class templates,
1171 /// where we might end up instantiating an inner class before the
1172 /// default arguments of its methods have been parsed.
1173 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1174
1175 // Contains the locations of the beginning of unparsed default
1176 // argument locations.
1177 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1178
1179 /// UndefinedInternals - all the used, undefined objects which require a
1180 /// definition in this translation unit.
1181 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1182
1183 /// Determine if VD, which must be a variable or function, is an external
1184 /// symbol that nonetheless can't be referenced from outside this translation
1185 /// unit because its type has no linkage and it's not extern "C".
1186 bool isExternalWithNoLinkageType(ValueDecl *VD);
1187
1188 /// Obtain a sorted list of functions that are undefined but ODR-used.
1189 void getUndefinedButUsed(
1190 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1191
1192 /// Retrieves list of suspicious delete-expressions that will be checked at
1193 /// the end of translation unit.
1194 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1195 getMismatchingDeleteExpressions() const;
1196
1197 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1198 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1199
1200 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1201 /// We need to maintain a list, since selectors can have differing signatures
1202 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1203 /// of selectors are "overloaded").
1204 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1205 /// methods inside categories with a particular selector.
1206 GlobalMethodPool MethodPool;
1207
1208 /// Method selectors used in a \@selector expression. Used for implementation
1209 /// of -Wselector.
1210 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1211
1212 /// List of SourceLocations where 'self' is implicitly retained inside a
1213 /// block.
1214 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1215 ImplicitlyRetainedSelfLocs;
1216
1217 /// Kinds of C++ special members.
1218 enum CXXSpecialMember {
1219 CXXDefaultConstructor,
1220 CXXCopyConstructor,
1221 CXXMoveConstructor,
1222 CXXCopyAssignment,
1223 CXXMoveAssignment,
1224 CXXDestructor,
1225 CXXInvalid
1226 };
1227
1228 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1229 SpecialMemberDecl;
1230
1231 /// The C++ special members which we are currently in the process of
1232 /// declaring. If this process recursively triggers the declaration of the
1233 /// same special member, we should act as if it is not yet declared.
1234 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1235
1236 /// The function definitions which were renamed as part of typo-correction
1237 /// to match their respective declarations. We want to keep track of them
1238 /// to ensure that we don't emit a "redefinition" error if we encounter a
1239 /// correctly named definition after the renamed definition.
1240 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1241
1242 /// Stack of types that correspond to the parameter entities that are
1243 /// currently being copy-initialized. Can be empty.
1244 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1245
1246 void ReadMethodPool(Selector Sel);
1247 void updateOutOfDateSelector(Selector Sel);
1248
1249 /// Private Helper predicate to check for 'self'.
1250 bool isSelfExpr(Expr *RExpr);
1251 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1252
1253 /// Cause the active diagnostic on the DiagosticsEngine to be
1254 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1255 /// should not be used elsewhere.
1256 void EmitCurrentDiagnostic(unsigned DiagID);
1257
1258 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1259 /// statements.
1260 class FPContractStateRAII {
1261 public:
1262 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1263 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1264
1265 private:
1266 Sema& S;
1267 FPOptions OldFPFeaturesState;
1268 };
1269
1270 void addImplicitTypedef(StringRef Name, QualType T);
1271
1272 bool WarnedStackExhausted = false;
1273
1274public:
1275 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1276 TranslationUnitKind TUKind = TU_Complete,
1277 CodeCompleteConsumer *CompletionConsumer = nullptr);
1278 ~Sema();
1279
1280 /// Perform initialization that occurs after the parser has been
1281 /// initialized but before it parses anything.
1282 void Initialize();
1283
1284 const LangOptions &getLangOpts() const { return LangOpts; }
1285 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1286 FPOptions &getFPOptions() { return FPFeatures; }
1287
1288 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1289 SourceManager &getSourceManager() const { return SourceMgr; }
1290 Preprocessor &getPreprocessor() const { return PP; }
1291 ASTContext &getASTContext() const { return Context; }
1292 ASTConsumer &getASTConsumer() const { return Consumer; }
1293 ASTMutationListener *getASTMutationListener() const;
1294 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1295
1296 ///Registers an external source. If an external source already exists,
1297 /// creates a multiplex external source and appends to it.
1298 ///
1299 ///\param[in] E - A non-null external sema source.
1300 ///
1301 void addExternalSource(ExternalSemaSource *E);
1302
1303 void PrintStats() const;
1304
1305 /// Warn that the stack is nearly exhausted.
1306 void warnStackExhausted(SourceLocation Loc);
1307
1308 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1309 /// guaranteed). Produces a warning if we're low on stack space and allocates
1310 /// more in that case. Use this in code that may recurse deeply (for example,
1311 /// in template instantiation) to avoid stack overflow.
1312 void runWithSufficientStackSpace(SourceLocation Loc,
1313 llvm::function_ref<void()> Fn);
1314
1315 /// Helper class that creates diagnostics with optional
1316 /// template instantiation stacks.
1317 ///
1318 /// This class provides a wrapper around the basic DiagnosticBuilder
1319 /// class that emits diagnostics. SemaDiagnosticBuilder is
1320 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1321 /// does) and, if the diagnostic comes from inside a template
1322 /// instantiation, printing the template instantiation stack as
1323 /// well.
1324 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1325 Sema &SemaRef;
1326 unsigned DiagID;
1327
1328 public:
1329 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1330 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1331
1332 // This is a cunning lie. DiagnosticBuilder actually performs move
1333 // construction in its copy constructor (but due to varied uses, it's not
1334 // possible to conveniently express this as actual move construction). So
1335 // the default copy ctor here is fine, because the base class disables the
1336 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1337 // in that case anwyay.
1338 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1339
1340 ~SemaDiagnosticBuilder() {
1341 // If we aren't active, there is nothing to do.
1342 if (!isActive()) return;
1343
1344 // Otherwise, we need to emit the diagnostic. First flush the underlying
1345 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1346 // won't emit the diagnostic in its own destructor.
1347 //
1348 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1349 // do its own needless checks to see if the diagnostic needs to be
1350 // emitted. However, because we take care to ensure that the builder
1351 // objects never escape, a sufficiently smart compiler will be able to
1352 // eliminate that code.
1353 FlushCounts();
1354 Clear();
1355
1356 // Dispatch to Sema to emit the diagnostic.
1357 SemaRef.EmitCurrentDiagnostic(DiagID);
1358 }
1359
1360 /// Teach operator<< to produce an object of the correct type.
1361 template<typename T>
1362 friend const SemaDiagnosticBuilder &operator<<(
1363 const SemaDiagnosticBuilder &Diag, const T &Value) {
1364 const DiagnosticBuilder &BaseDiag = Diag;
1365 BaseDiag << Value;
1366 return Diag;
1367 }
1368 };
1369
1370 /// Emit a diagnostic.
1371 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1372 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1373 return SemaDiagnosticBuilder(DB, *this, DiagID);
1374 }
1375
1376 /// Emit a partial diagnostic.
1377 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1378
1379 /// Build a partial diagnostic.
1380 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1381
1382 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1383
1384 /// Get a string to suggest for zero-initialization of a type.
1385 std::string
1386 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1387 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1388
1389 /// Calls \c Lexer::getLocForEndOfToken()
1390 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1391
1392 /// Retrieve the module loader associated with the preprocessor.
1393 ModuleLoader &getModuleLoader() const;
1394
1395 void emitAndClearUnusedLocalTypedefWarnings();
1396
1397 enum TUFragmentKind {
1398 /// The global module fragment, between 'module;' and a module-declaration.
1399 Global,
1400 /// A normal translation unit fragment. For a non-module unit, this is the
1401 /// entire translation unit. Otherwise, it runs from the module-declaration
1402 /// to the private-module-fragment (if any) or the end of the TU (if not).
1403 Normal,
1404 /// The private module fragment, between 'module :private;' and the end of
1405 /// the translation unit.
1406 Private
1407 };
1408
1409 void ActOnStartOfTranslationUnit();
1410 void ActOnEndOfTranslationUnit();
1411 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1412
1413 void CheckDelegatingCtorCycles();
1414
1415 Scope *getScopeForContext(DeclContext *Ctx);
1416
1417 void PushFunctionScope();
1418 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1419 sema::LambdaScopeInfo *PushLambdaScope();
1420
1421 /// This is used to inform Sema what the current TemplateParameterDepth
1422 /// is during Parsing. Currently it is used to pass on the depth
1423 /// when parsing generic lambda 'auto' parameters.
1424 void RecordParsingTemplateParameterDepth(unsigned Depth);
1425
1426 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1427 RecordDecl *RD, CapturedRegionKind K,
1428 unsigned OpenMPCaptureLevel = 0);
1429
1430 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1431 /// time after they've been popped.
1432 class PoppedFunctionScopeDeleter {
1433 Sema *Self;
1434
1435 public:
1436 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1437 void operator()(sema::FunctionScopeInfo *Scope) const;
1438 };
1439
1440 using PoppedFunctionScopePtr =
1441 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1442
1443 PoppedFunctionScopePtr
1444 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1445 const Decl *D = nullptr,
1446 QualType BlockType = QualType());
1447
1448 sema::FunctionScopeInfo *getCurFunction() const {
1449 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1450 }
1451
1452 sema::FunctionScopeInfo *getEnclosingFunction() const;
1453
1454 void setFunctionHasBranchIntoScope();
1455 void setFunctionHasBranchProtectedScope();
1456 void setFunctionHasIndirectGoto();
1457
1458 void PushCompoundScope(bool IsStmtExpr);
1459 void PopCompoundScope();
1460
1461 sema::CompoundScopeInfo &getCurCompoundScope() const;
1462
1463 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1464
1465 /// Retrieve the current block, if any.
1466 sema::BlockScopeInfo *getCurBlock();
1467
1468 /// Get the innermost lambda enclosing the current location, if any. This
1469 /// looks through intervening non-lambda scopes such as local functions and
1470 /// blocks.
1471 sema::LambdaScopeInfo *getEnclosingLambda() const;
1472
1473 /// Retrieve the current lambda scope info, if any.
1474 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1475 /// lambda scope info ignoring all inner capturing scopes that are not
1476 /// lambda scopes.
1477 sema::LambdaScopeInfo *
1478 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1479
1480 /// Retrieve the current generic lambda info, if any.
1481 sema::LambdaScopeInfo *getCurGenericLambda();
1482
1483 /// Retrieve the current captured region, if any.
1484 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1485
1486 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1487 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1488
1489 void ActOnComment(SourceRange Comment);
1490
1491 //===--------------------------------------------------------------------===//
1492 // Type Analysis / Processing: SemaType.cpp.
1493 //
1494
1495 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1496 const DeclSpec *DS = nullptr);
1497 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1498 const DeclSpec *DS = nullptr);
1499 QualType BuildPointerType(QualType T,
1500 SourceLocation Loc, DeclarationName Entity);
1501 QualType BuildReferenceType(QualType T, bool LValueRef,
1502 SourceLocation Loc, DeclarationName Entity);
1503 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1504 Expr *ArraySize, unsigned Quals,
1505 SourceRange Brackets, DeclarationName Entity);
1506 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1507 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1508 SourceLocation AttrLoc);
1509 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1510 SourceLocation AttrLoc);
1511
1512 /// Same as above, but constructs the AddressSpace index if not provided.
1513 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1514 SourceLocation AttrLoc);
1515
1516 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1517
1518 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1519
1520 /// Build a function type.
1521 ///
1522 /// This routine checks the function type according to C++ rules and
1523 /// under the assumption that the result type and parameter types have
1524 /// just been instantiated from a template. It therefore duplicates
1525 /// some of the behavior of GetTypeForDeclarator, but in a much
1526 /// simpler form that is only suitable for this narrow use case.
1527 ///
1528 /// \param T The return type of the function.
1529 ///
1530 /// \param ParamTypes The parameter types of the function. This array
1531 /// will be modified to account for adjustments to the types of the
1532 /// function parameters.
1533 ///
1534 /// \param Loc The location of the entity whose type involves this
1535 /// function type or, if there is no such entity, the location of the
1536 /// type that will have function type.
1537 ///
1538 /// \param Entity The name of the entity that involves the function
1539 /// type, if known.
1540 ///
1541 /// \param EPI Extra information about the function type. Usually this will
1542 /// be taken from an existing function with the same prototype.
1543 ///
1544 /// \returns A suitable function type, if there are no errors. The
1545 /// unqualified type will always be a FunctionProtoType.
1546 /// Otherwise, returns a NULL type.
1547 QualType BuildFunctionType(QualType T,
1548 MutableArrayRef<QualType> ParamTypes,
1549 SourceLocation Loc, DeclarationName Entity,
1550 const FunctionProtoType::ExtProtoInfo &EPI);
1551
1552 QualType BuildMemberPointerType(QualType T, QualType Class,
1553 SourceLocation Loc,
1554 DeclarationName Entity);
1555 QualType BuildBlockPointerType(QualType T,
1556 SourceLocation Loc, DeclarationName Entity);
1557 QualType BuildParenType(QualType T);
1558 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1559 QualType BuildReadPipeType(QualType T,
1560 SourceLocation Loc);
1561 QualType BuildWritePipeType(QualType T,
1562 SourceLocation Loc);
1563
1564 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1565 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1566
1567 /// Package the given type and TSI into a ParsedType.
1568 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1569 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1570 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1571 static QualType GetTypeFromParser(ParsedType Ty,
1572 TypeSourceInfo **TInfo = nullptr);
1573 CanThrowResult canThrow(const Expr *E);
1574 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1575 const FunctionProtoType *FPT);
1576 void UpdateExceptionSpec(FunctionDecl *FD,
1577 const FunctionProtoType::ExceptionSpecInfo &ESI);
1578 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1579 bool CheckDistantExceptionSpec(QualType T);
1580 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1581 bool CheckEquivalentExceptionSpec(
1582 const FunctionProtoType *Old, SourceLocation OldLoc,
1583 const FunctionProtoType *New, SourceLocation NewLoc);
1584 bool CheckEquivalentExceptionSpec(
1585 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1586 const FunctionProtoType *Old, SourceLocation OldLoc,
1587 const FunctionProtoType *New, SourceLocation NewLoc);
1588 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1589 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1590 const PartialDiagnostic &NestedDiagID,
1591 const PartialDiagnostic &NoteID,
1592 const PartialDiagnostic &NoThrowDiagID,
1593 const FunctionProtoType *Superset,
1594 SourceLocation SuperLoc,
1595 const FunctionProtoType *Subset,
1596 SourceLocation SubLoc);
1597 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1598 const PartialDiagnostic &NoteID,
1599 const FunctionProtoType *Target,
1600 SourceLocation TargetLoc,
1601 const FunctionProtoType *Source,
1602 SourceLocation SourceLoc);
1603
1604 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1605
1606 /// The parser has parsed the context-sensitive type 'instancetype'
1607 /// in an Objective-C message declaration. Return the appropriate type.
1608 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1609
1610 /// Abstract class used to diagnose incomplete types.
1611 struct TypeDiagnoser {
1612 TypeDiagnoser() {}
1613
1614 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1615 virtual ~TypeDiagnoser() {}
1616 };
1617
1618 static int getPrintable(int I) { return I; }
1619 static unsigned getPrintable(unsigned I) { return I; }
1620 static bool getPrintable(bool B) { return B; }
1621 static const char * getPrintable(const char *S) { return S; }
1622 static StringRef getPrintable(StringRef S) { return S; }
1623 static const std::string &getPrintable(const std::string &S) { return S; }
1624 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1625 return II;
1626 }
1627 static DeclarationName getPrintable(DeclarationName N) { return N; }
1628 static QualType getPrintable(QualType T) { return T; }
1629 static SourceRange getPrintable(SourceRange R) { return R; }
1630 static SourceRange getPrintable(SourceLocation L) { return L; }
1631 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1632 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1633
1634 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1635 unsigned DiagID;
1636 std::tuple<const Ts &...> Args;
1637
1638 template <std::size_t... Is>
1639 void emit(const SemaDiagnosticBuilder &DB,
1640 std::index_sequence<Is...>) const {
1641 // Apply all tuple elements to the builder in order.
1642 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1643 (void)Dummy;
1644 }
1645
1646 public:
1647 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1648 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1649 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1649, __PRETTY_FUNCTION__))
;
1650 }
1651
1652 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1653 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1654 emit(DB, std::index_sequence_for<Ts...>());
1655 DB << T;
1656 }
1657 };
1658
1659private:
1660 /// Methods for marking which expressions involve dereferencing a pointer
1661 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1662 /// they are parsed, meaning that a noderef pointer may not be accessed. For
1663 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1664 /// `*p`, but need to check that `address of` is called on it. This requires
1665 /// keeping a container of all pending expressions and checking if the address
1666 /// of them are eventually taken.
1667 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1668 void CheckAddressOfNoDeref(const Expr *E);
1669 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1670
1671 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1672 TypeDiagnoser *Diagnoser);
1673
1674 struct ModuleScope {
1675 SourceLocation BeginLoc;
1676 clang::Module *Module = nullptr;
1677 bool ModuleInterface = false;
1678 bool ImplicitGlobalModuleFragment = false;
1679 VisibleModuleSet OuterVisibleModules;
1680 };
1681 /// The modules we're currently parsing.
1682 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1683
1684 /// Namespace definitions that we will export when they finish.
1685 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1686
1687 /// Get the module whose scope we are currently within.
1688 Module *getCurrentModule() const {
1689 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1690 }
1691
1692 VisibleModuleSet VisibleModules;
1693
1694public:
1695 /// Get the module owning an entity.
1696 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1697
1698 /// Make a merged definition of an existing hidden definition \p ND
1699 /// visible at the specified location.
1700 void makeMergedDefinitionVisible(NamedDecl *ND);
1701
1702 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1703
1704 /// Determine whether a declaration is visible to name lookup.
1705 bool isVisible(const NamedDecl *D) {
1706 return !D->isHidden() || isVisibleSlow(D);
1707 }
1708
1709 /// Determine whether any declaration of an entity is visible.
1710 bool
1711 hasVisibleDeclaration(const NamedDecl *D,
1712 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1713 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1714 }
1715 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1716 llvm::SmallVectorImpl<Module *> *Modules);
1717
1718 bool hasVisibleMergedDefinition(NamedDecl *Def);
1719 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1720
1721 /// Determine if \p D and \p Suggested have a structurally compatible
1722 /// layout as described in C11 6.2.7/1.
1723 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1724
1725 /// Determine if \p D has a visible definition. If not, suggest a declaration
1726 /// that should be made visible to expose the definition.
1727 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1728 bool OnlyNeedComplete = false);
1729 bool hasVisibleDefinition(const NamedDecl *D) {
1730 NamedDecl *Hidden;
1731 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1732 }
1733
1734 /// Determine if the template parameter \p D has a visible default argument.
1735 bool
1736 hasVisibleDefaultArgument(const NamedDecl *D,
1737 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1738
1739 /// Determine if there is a visible declaration of \p D that is an explicit
1740 /// specialization declaration for a specialization of a template. (For a
1741 /// member specialization, use hasVisibleMemberSpecialization.)
1742 bool hasVisibleExplicitSpecialization(
1743 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1744
1745 /// Determine if there is a visible declaration of \p D that is a member
1746 /// specialization declaration (as opposed to an instantiated declaration).
1747 bool hasVisibleMemberSpecialization(
1748 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1749
1750 /// Determine if \p A and \p B are equivalent internal linkage declarations
1751 /// from different modules, and thus an ambiguity error can be downgraded to
1752 /// an extension warning.
1753 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1754 const NamedDecl *B);
1755 void diagnoseEquivalentInternalLinkageDeclarations(
1756 SourceLocation Loc, const NamedDecl *D,
1757 ArrayRef<const NamedDecl *> Equiv);
1758
1759 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1760
1761 bool isCompleteType(SourceLocation Loc, QualType T) {
1762 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1763 }
1764 bool RequireCompleteType(SourceLocation Loc, QualType T,
1765 TypeDiagnoser &Diagnoser);
1766 bool RequireCompleteType(SourceLocation Loc, QualType T,
1767 unsigned DiagID);
1768
1769 template <typename... Ts>
1770 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1771 const Ts &...Args) {
1772 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1773 return RequireCompleteType(Loc, T, Diagnoser);
1774 }
1775
1776 void completeExprArrayBound(Expr *E);
1777 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1778 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1779
1780 template <typename... Ts>
1781 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1782 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1783 return RequireCompleteExprType(E, Diagnoser);
1784 }
1785
1786 bool RequireLiteralType(SourceLocation Loc, QualType T,
1787 TypeDiagnoser &Diagnoser);
1788 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1789
1790 template <typename... Ts>
1791 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1792 const Ts &...Args) {
1793 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1794 return RequireLiteralType(Loc, T, Diagnoser);
1795 }
1796
1797 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1798 const CXXScopeSpec &SS, QualType T,
1799 TagDecl *OwnedTagDecl = nullptr);
1800
1801 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1802 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1803 /// context, such as when building a type for decltype(auto).
1804 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1805 bool AsUnevaluated = true);
1806 QualType BuildUnaryTransformType(QualType BaseType,
1807 UnaryTransformType::UTTKind UKind,
1808 SourceLocation Loc);
1809
1810 //===--------------------------------------------------------------------===//
1811 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1812 //
1813
1814 struct SkipBodyInfo {
1815 SkipBodyInfo()
1816 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1817 New(nullptr) {}
1818 bool ShouldSkip;
1819 bool CheckSameAsPrevious;
1820 NamedDecl *Previous;
1821 NamedDecl *New;
1822 };
1823
1824 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1825
1826 void DiagnoseUseOfUnimplementedSelectors();
1827
1828 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1829
1830 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1831 Scope *S, CXXScopeSpec *SS = nullptr,
1832 bool isClassName = false, bool HasTrailingDot = false,
1833 ParsedType ObjectType = nullptr,
1834 bool IsCtorOrDtorName = false,
1835 bool WantNontrivialTypeSourceInfo = false,
1836 bool IsClassTemplateDeductionContext = true,
1837 IdentifierInfo **CorrectedII = nullptr);
1838 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1839 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1840 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1841 SourceLocation IILoc,
1842 Scope *S,
1843 CXXScopeSpec *SS,
1844 ParsedType &SuggestedType,
1845 bool IsTemplateName = false);
1846
1847 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1848 /// type name has failed in a dependent context. In these situations, we
1849 /// automatically form a DependentTypeName that will retry lookup in a related
1850 /// scope during instantiation.
1851 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1852 SourceLocation NameLoc,
1853 bool IsTemplateTypeArg);
1854
1855 /// Describes the result of the name lookup and resolution performed
1856 /// by \c ClassifyName().
1857 enum NameClassificationKind {
1858 /// This name is not a type or template in this context, but might be
1859 /// something else.
1860 NC_Unknown,
1861 /// Classification failed; an error has been produced.
1862 NC_Error,
1863 /// The name has been typo-corrected to a keyword.
1864 NC_Keyword,
1865 /// The name was classified as a type.
1866 NC_Type,
1867 /// The name was classified as a specific non-type, non-template
1868 /// declaration. ActOnNameClassifiedAsNonType should be called to
1869 /// convert the declaration to an expression.
1870 NC_NonType,
1871 /// The name was classified as an ADL-only function name.
1872 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1873 /// result to an expression.
1874 NC_UndeclaredNonType,
1875 /// The name denotes a member of a dependent type that could not be
1876 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1877 /// convert the result to an expression.
1878 NC_DependentNonType,
1879 /// The name was classified as a non-type, and an expression representing
1880 /// that name has been formed.
1881 NC_ContextIndependentExpr,
1882 /// The name was classified as a template whose specializations are types.
1883 NC_TypeTemplate,
1884 /// The name was classified as a variable template name.
1885 NC_VarTemplate,
1886 /// The name was classified as a function template name.
1887 NC_FunctionTemplate,
1888 /// The name was classified as an ADL-only function template name.
1889 NC_UndeclaredTemplate,
1890 };
1891
1892 class NameClassification {
1893 NameClassificationKind Kind;
1894 union {
1895 ExprResult Expr;
1896 NamedDecl *NonTypeDecl;
1897 TemplateName Template;
1898 ParsedType Type;
1899 };
1900
1901 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1902
1903 public:
1904 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1905
1906 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1907
1908 static NameClassification Error() {
1909 return NameClassification(NC_Error);
1910 }
1911
1912 static NameClassification Unknown() {
1913 return NameClassification(NC_Unknown);
1914 }
1915
1916 static NameClassification ContextIndependentExpr(ExprResult E) {
1917 NameClassification Result(NC_ContextIndependentExpr);
1918 Result.Expr = E;
1919 return Result;
1920 }
1921
1922 static NameClassification NonType(NamedDecl *D) {
1923 NameClassification Result(NC_NonType);
1924 Result.NonTypeDecl = D;
1925 return Result;
1926 }
1927
1928 static NameClassification UndeclaredNonType() {
1929 return NameClassification(NC_UndeclaredNonType);
1930 }
1931
1932 static NameClassification DependentNonType() {
1933 return NameClassification(NC_DependentNonType);
1934 }
1935
1936 static NameClassification TypeTemplate(TemplateName Name) {
1937 NameClassification Result(NC_TypeTemplate);
1938 Result.Template = Name;
1939 return Result;
1940 }
1941
1942 static NameClassification VarTemplate(TemplateName Name) {
1943 NameClassification Result(NC_VarTemplate);
1944 Result.Template = Name;
1945 return Result;
1946 }
1947
1948 static NameClassification FunctionTemplate(TemplateName Name) {
1949 NameClassification Result(NC_FunctionTemplate);
1950 Result.Template = Name;
1951 return Result;
1952 }
1953
1954 static NameClassification UndeclaredTemplate(TemplateName Name) {
1955 NameClassification Result(NC_UndeclaredTemplate);
1956 Result.Template = Name;
1957 return Result;
1958 }
1959
1960 NameClassificationKind getKind() const { return Kind; }
1961
1962 ExprResult getExpression() const {
1963 assert(Kind == NC_ContextIndependentExpr)((Kind == NC_ContextIndependentExpr) ? static_cast<void>
(0) : __assert_fail ("Kind == NC_ContextIndependentExpr", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1963, __PRETTY_FUNCTION__))
;
1964 return Expr;
1965 }
1966
1967 ParsedType getType() const {
1968 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1968, __PRETTY_FUNCTION__))
;
1969 return Type;
1970 }
1971
1972 NamedDecl *getNonTypeDecl() const {
1973 assert(Kind == NC_NonType)((Kind == NC_NonType) ? static_cast<void> (0) : __assert_fail
("Kind == NC_NonType", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1973, __PRETTY_FUNCTION__))
;
1974 return NonTypeDecl;
1975 }
1976
1977 TemplateName getTemplateName() const {
1978 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1979, __PRETTY_FUNCTION__))
1979 Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1979, __PRETTY_FUNCTION__))
;
1980 return Template;
1981 }
1982
1983 TemplateNameKind getTemplateNameKind() const {
1984 switch (Kind) {
1985 case NC_TypeTemplate:
1986 return TNK_Type_template;
1987 case NC_FunctionTemplate:
1988 return TNK_Function_template;
1989 case NC_VarTemplate:
1990 return TNK_Var_template;
1991 case NC_UndeclaredTemplate:
1992 return TNK_Undeclared_template;
1993 default:
1994 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1994)
;
1995 }
1996 }
1997 };
1998
1999 /// Perform name lookup on the given name, classifying it based on
2000 /// the results of name lookup and the following token.
2001 ///
2002 /// This routine is used by the parser to resolve identifiers and help direct
2003 /// parsing. When the identifier cannot be found, this routine will attempt
2004 /// to correct the typo and classify based on the resulting name.
2005 ///
2006 /// \param S The scope in which we're performing name lookup.
2007 ///
2008 /// \param SS The nested-name-specifier that precedes the name.
2009 ///
2010 /// \param Name The identifier. If typo correction finds an alternative name,
2011 /// this pointer parameter will be updated accordingly.
2012 ///
2013 /// \param NameLoc The location of the identifier.
2014 ///
2015 /// \param NextToken The token following the identifier. Used to help
2016 /// disambiguate the name.
2017 ///
2018 /// \param CCC The correction callback, if typo correction is desired.
2019 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2020 IdentifierInfo *&Name, SourceLocation NameLoc,
2021 const Token &NextToken,
2022 CorrectionCandidateCallback *CCC = nullptr);
2023
2024 /// Act on the result of classifying a name as an undeclared (ADL-only)
2025 /// non-type declaration.
2026 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2027 SourceLocation NameLoc);
2028 /// Act on the result of classifying a name as an undeclared member of a
2029 /// dependent base class.
2030 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2031 IdentifierInfo *Name,
2032 SourceLocation NameLoc,
2033 bool IsAddressOfOperand);
2034 /// Act on the result of classifying a name as a specific non-type
2035 /// declaration.
2036 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2037 NamedDecl *Found,
2038 SourceLocation NameLoc,
2039 const Token &NextToken);
2040
2041 /// Describes the detailed kind of a template name. Used in diagnostics.
2042 enum class TemplateNameKindForDiagnostics {
2043 ClassTemplate,
2044 FunctionTemplate,
2045 VarTemplate,
2046 AliasTemplate,
2047 TemplateTemplateParam,
2048 Concept,
2049 DependentTemplate
2050 };
2051 TemplateNameKindForDiagnostics
2052 getTemplateNameKindForDiagnostics(TemplateName Name);
2053
2054 /// Determine whether it's plausible that E was intended to be a
2055 /// template-name.
2056 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2057 if (!getLangOpts().CPlusPlus || E.isInvalid())
2058 return false;
2059 Dependent = false;
2060 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2061 return !DRE->hasExplicitTemplateArgs();
2062 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2063 return !ME->hasExplicitTemplateArgs();
2064 Dependent = true;
2065 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2066 return !DSDRE->hasExplicitTemplateArgs();
2067 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2068 return !DSME->hasExplicitTemplateArgs();
2069 // Any additional cases recognized here should also be handled by
2070 // diagnoseExprIntendedAsTemplateName.
2071 return false;
2072 }
2073 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2074 SourceLocation Less,
2075 SourceLocation Greater);
2076
2077 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2078
2079 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2080 MultiTemplateParamsArg TemplateParameterLists);
2081 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2082 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2083 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2084 DeclarationName Name, SourceLocation Loc,
2085 bool IsTemplateId);
2086 void
2087 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2088 SourceLocation FallbackLoc,
2089 SourceLocation ConstQualLoc = SourceLocation(),
2090 SourceLocation VolatileQualLoc = SourceLocation(),
2091 SourceLocation RestrictQualLoc = SourceLocation(),
2092 SourceLocation AtomicQualLoc = SourceLocation(),
2093 SourceLocation UnalignedQualLoc = SourceLocation());
2094
2095 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2096 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2097 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2098 const LookupResult &R);
2099 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2100 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2101 const LookupResult &R);
2102 void CheckShadow(Scope *S, VarDecl *D);
2103
2104 /// Warn if 'E', which is an expression that is about to be modified, refers
2105 /// to a shadowing declaration.
2106 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2107
2108 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2109
2110private:
2111 /// Map of current shadowing declarations to shadowed declarations. Warn if
2112 /// it looks like the user is trying to modify the shadowing declaration.
2113 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2114
2115public:
2116 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2117 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2118 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2119 TypedefNameDecl *NewTD);
2120 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2121 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2122 TypeSourceInfo *TInfo,
2123 LookupResult &Previous);
2124 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2125 LookupResult &Previous, bool &Redeclaration);
2126 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2127 TypeSourceInfo *TInfo,
2128 LookupResult &Previous,
2129 MultiTemplateParamsArg TemplateParamLists,
2130 bool &AddToScope,
2131 ArrayRef<BindingDecl *> Bindings = None);
2132 NamedDecl *
2133 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2134 MultiTemplateParamsArg TemplateParamLists);
2135 // Returns true if the variable declaration is a redeclaration
2136 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2137 void CheckVariableDeclarationType(VarDecl *NewVD);
2138 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2139 Expr *Init);
2140 void CheckCompleteVariableDeclaration(VarDecl *VD);
2141 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2142 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2143
2144 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2145 TypeSourceInfo *TInfo,
2146 LookupResult &Previous,
2147 MultiTemplateParamsArg TemplateParamLists,
2148 bool &AddToScope);
2149 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2150
2151 enum class CheckConstexprKind {
2152 /// Diagnose issues that are non-constant or that are extensions.
2153 Diagnose,
2154 /// Identify whether this function satisfies the formal rules for constexpr
2155 /// functions in the current lanugage mode (with no extensions).
2156 CheckValid
2157 };
2158
2159 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2160 CheckConstexprKind Kind);
2161
2162 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2163 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2164 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2165 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2166 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2167 // Returns true if the function declaration is a redeclaration
2168 bool CheckFunctionDeclaration(Scope *S,
2169 FunctionDecl *NewFD, LookupResult &Previous,
2170 bool IsMemberSpecialization);
2171 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2172 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2173 QualType NewT, QualType OldT);
2174 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2175 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2176 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2177 bool IsDefinition);
2178 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2179 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2180 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2181 SourceLocation Loc,
2182 QualType T);
2183 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2184 SourceLocation NameLoc, IdentifierInfo *Name,
2185 QualType T, TypeSourceInfo *TSInfo,
2186 StorageClass SC);
2187 void ActOnParamDefaultArgument(Decl *param,
2188 SourceLocation EqualLoc,
2189 Expr *defarg);
2190 void ActOnParamUnparsedDefaultArgument(Decl *param,
2191 SourceLocation EqualLoc,
2192 SourceLocation ArgLoc);
2193 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2194 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2195 SourceLocation EqualLoc);
2196
2197 // Contexts where using non-trivial C union types can be disallowed. This is
2198 // passed to err_non_trivial_c_union_in_invalid_context.
2199 enum NonTrivialCUnionContext {
2200 // Function parameter.
2201 NTCUC_FunctionParam,
2202 // Function return.
2203 NTCUC_FunctionReturn,
2204 // Default-initialized object.
2205 NTCUC_DefaultInitializedObject,
2206 // Variable with automatic storage duration.
2207 NTCUC_AutoVar,
2208 // Initializer expression that might copy from another object.
2209 NTCUC_CopyInit,
2210 // Assignment.
2211 NTCUC_Assignment,
2212 // Compound literal.
2213 NTCUC_CompoundLiteral,
2214 // Block capture.
2215 NTCUC_BlockCapture,
2216 // lvalue-to-rvalue conversion of volatile type.
2217 NTCUC_LValueToRValueVolatile,
2218 };
2219
2220 /// Emit diagnostics if the initializer or any of its explicit or
2221 /// implicitly-generated subexpressions require copying or
2222 /// default-initializing a type that is or contains a C union type that is
2223 /// non-trivial to copy or default-initialize.
2224 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2225
2226 // These flags are passed to checkNonTrivialCUnion.
2227 enum NonTrivialCUnionKind {
2228 NTCUK_Init = 0x1,
2229 NTCUK_Destruct = 0x2,
2230 NTCUK_Copy = 0x4,
2231 };
2232
2233 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2234 /// a non-trivial C union is used in an invalid context.
2235 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2236 NonTrivialCUnionContext UseContext,
2237 unsigned NonTrivialKind);
2238
2239 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2240 void ActOnUninitializedDecl(Decl *dcl);
2241 void ActOnInitializerError(Decl *Dcl);
2242
2243 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2244 void ActOnCXXForRangeDecl(Decl *D);
2245 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2246 IdentifierInfo *Ident,
2247 ParsedAttributes &Attrs,
2248 SourceLocation AttrEnd);
2249 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2250 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2251 void CheckStaticLocalForDllExport(VarDecl *VD);
2252 void FinalizeDeclaration(Decl *D);
2253 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2254 ArrayRef<Decl *> Group);
2255 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2256
2257 /// Should be called on all declarations that might have attached
2258 /// documentation comments.
2259 void ActOnDocumentableDecl(Decl *D);
2260 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2261
2262 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2263 SourceLocation LocAfterDecls);
2264 void CheckForFunctionRedefinition(
2265 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2266 SkipBodyInfo *SkipBody = nullptr);
2267 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2268 MultiTemplateParamsArg TemplateParamLists,
2269 SkipBodyInfo *SkipBody = nullptr);
2270 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2271 SkipBodyInfo *SkipBody = nullptr);
2272 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2273 bool isObjCMethodDecl(Decl *D) {
2274 return D && isa<ObjCMethodDecl>(D);
2275 }
2276
2277 /// Determine whether we can delay parsing the body of a function or
2278 /// function template until it is used, assuming we don't care about emitting
2279 /// code for that function.
2280 ///
2281 /// This will be \c false if we may need the body of the function in the
2282 /// middle of parsing an expression (where it's impractical to switch to
2283 /// parsing a different function), for instance, if it's constexpr in C++11
2284 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2285 bool canDelayFunctionBody(const Declarator &D);
2286
2287 /// Determine whether we can skip parsing the body of a function
2288 /// definition, assuming we don't care about analyzing its body or emitting
2289 /// code for that function.
2290 ///
2291 /// This will be \c false only if we may need the body of the function in
2292 /// order to parse the rest of the program (for instance, if it is
2293 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2294 bool canSkipFunctionBody(Decl *D);
2295
2296 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2297 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2298 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2299 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2300 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2301
2302 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2303 /// attribute for which parsing is delayed.
2304 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2305
2306 /// Diagnose any unused parameters in the given sequence of
2307 /// ParmVarDecl pointers.
2308 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2309
2310 /// Diagnose whether the size of parameters or return value of a
2311 /// function or obj-c method definition is pass-by-value and larger than a
2312 /// specified threshold.
2313 void
2314 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2315 QualType ReturnTy, NamedDecl *D);
2316
2317 void DiagnoseInvalidJumps(Stmt *Body);
2318 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2319 SourceLocation AsmLoc,
2320 SourceLocation RParenLoc);
2321
2322 /// Handle a C++11 empty-declaration and attribute-declaration.
2323 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2324 SourceLocation SemiLoc);
2325
2326 enum class ModuleDeclKind {
2327 Interface, ///< 'export module X;'
2328 Implementation, ///< 'module X;'
2329 };
2330
2331 /// The parser has processed a module-declaration that begins the definition
2332 /// of a module interface or implementation.
2333 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2334 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2335 ModuleIdPath Path, bool IsFirstDecl);
2336
2337 /// The parser has processed a global-module-fragment declaration that begins
2338 /// the definition of the global module fragment of the current module unit.
2339 /// \param ModuleLoc The location of the 'module' keyword.
2340 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2341
2342 /// The parser has processed a private-module-fragment declaration that begins
2343 /// the definition of the private module fragment of the current module unit.
2344 /// \param ModuleLoc The location of the 'module' keyword.
2345 /// \param PrivateLoc The location of the 'private' keyword.
2346 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2347 SourceLocation PrivateLoc);
2348
2349 /// The parser has processed a module import declaration.
2350 ///
2351 /// \param StartLoc The location of the first token in the declaration. This
2352 /// could be the location of an '@', 'export', or 'import'.
2353 /// \param ExportLoc The location of the 'export' keyword, if any.
2354 /// \param ImportLoc The location of the 'import' keyword.
2355 /// \param Path The module access path.
2356 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2357 SourceLocation ExportLoc,
2358 SourceLocation ImportLoc, ModuleIdPath Path);
2359 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2360 SourceLocation ExportLoc,
2361 SourceLocation ImportLoc, Module *M,
2362 ModuleIdPath Path = {});
2363
2364 /// The parser has processed a module import translated from a
2365 /// #include or similar preprocessing directive.
2366 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2367 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2368
2369 /// The parsed has entered a submodule.
2370 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2371 /// The parser has left a submodule.
2372 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2373
2374 /// Create an implicit import of the given module at the given
2375 /// source location, for error recovery, if possible.
2376 ///
2377 /// This routine is typically used when an entity found by name lookup
2378 /// is actually hidden within a module that we know about but the user
2379 /// has forgotten to import.
2380 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2381 Module *Mod);
2382
2383 /// Kinds of missing import. Note, the values of these enumerators correspond
2384 /// to %select values in diagnostics.
2385 enum class MissingImportKind {
2386 Declaration,
2387 Definition,
2388 DefaultArgument,
2389 ExplicitSpecialization,
2390 PartialSpecialization
2391 };
2392
2393 /// Diagnose that the specified declaration needs to be visible but
2394 /// isn't, and suggest a module import that would resolve the problem.
2395 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2396 MissingImportKind MIK, bool Recover = true);
2397 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2398 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2399 MissingImportKind MIK, bool Recover);
2400
2401 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2402 SourceLocation LBraceLoc);
2403 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2404 SourceLocation RBraceLoc);
2405
2406 /// We've found a use of a templated declaration that would trigger an
2407 /// implicit instantiation. Check that any relevant explicit specializations
2408 /// and partial specializations are visible, and diagnose if not.
2409 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2410
2411 /// We've found a use of a template specialization that would select a
2412 /// partial specialization. Check that the partial specialization is visible,
2413 /// and diagnose if not.
2414 void checkPartialSpecializationVisibility(SourceLocation Loc,
2415 NamedDecl *Spec);
2416
2417 /// Retrieve a suitable printing policy for diagnostics.
2418 PrintingPolicy getPrintingPolicy() const {
2419 return getPrintingPolicy(Context, PP);
2420 }
2421
2422 /// Retrieve a suitable printing policy for diagnostics.
2423 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2424 const Preprocessor &PP);
2425
2426 /// Scope actions.
2427 void ActOnPopScope(SourceLocation Loc, Scope *S);
2428 void ActOnTranslationUnitScope(Scope *S);
2429
2430 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2431 RecordDecl *&AnonRecord);
2432 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2433 MultiTemplateParamsArg TemplateParams,
2434 bool IsExplicitInstantiation,
2435 RecordDecl *&AnonRecord);
2436
2437 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2438 AccessSpecifier AS,
2439 RecordDecl *Record,
2440 const PrintingPolicy &Policy);
2441
2442 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2443 RecordDecl *Record);
2444
2445 /// Common ways to introduce type names without a tag for use in diagnostics.
2446 /// Keep in sync with err_tag_reference_non_tag.
2447 enum NonTagKind {
2448 NTK_NonStruct,
2449 NTK_NonClass,
2450 NTK_NonUnion,
2451 NTK_NonEnum,
2452 NTK_Typedef,
2453 NTK_TypeAlias,
2454 NTK_Template,
2455 NTK_TypeAliasTemplate,
2456 NTK_TemplateTemplateArgument,
2457 };
2458
2459 /// Given a non-tag type declaration, returns an enum useful for indicating
2460 /// what kind of non-tag type this is.
2461 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2462
2463 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2464 TagTypeKind NewTag, bool isDefinition,
2465 SourceLocation NewTagLoc,
2466 const IdentifierInfo *Name);
2467
2468 enum TagUseKind {
2469 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2470 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2471 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2472 TUK_Friend // Friend declaration: 'friend struct foo;'
2473 };
2474
2475 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2476 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2477 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2478 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2479 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2480 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2481 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2482 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2483 SkipBodyInfo *SkipBody = nullptr);
2484
2485 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2486 unsigned TagSpec, SourceLocation TagLoc,
2487 CXXScopeSpec &SS, IdentifierInfo *Name,
2488 SourceLocation NameLoc,
2489 const ParsedAttributesView &Attr,
2490 MultiTemplateParamsArg TempParamLists);
2491
2492 TypeResult ActOnDependentTag(Scope *S,
2493 unsigned TagSpec,
2494 TagUseKind TUK,
2495 const CXXScopeSpec &SS,
2496 IdentifierInfo *Name,
2497 SourceLocation TagLoc,
2498 SourceLocation NameLoc);
2499
2500 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2501 IdentifierInfo *ClassName,
2502 SmallVectorImpl<Decl *> &Decls);
2503 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2504 Declarator &D, Expr *BitfieldWidth);
2505
2506 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2507 Declarator &D, Expr *BitfieldWidth,
2508 InClassInitStyle InitStyle,
2509 AccessSpecifier AS);
2510 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2511 SourceLocation DeclStart, Declarator &D,
2512 Expr *BitfieldWidth,
2513 InClassInitStyle InitStyle,
2514 AccessSpecifier AS,
2515 const ParsedAttr &MSPropertyAttr);
2516
2517 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2518 TypeSourceInfo *TInfo,
2519 RecordDecl *Record, SourceLocation Loc,
2520 bool Mutable, Expr *BitfieldWidth,
2521 InClassInitStyle InitStyle,
2522 SourceLocation TSSL,
2523 AccessSpecifier AS, NamedDecl *PrevDecl,
2524 Declarator *D = nullptr);
2525
2526 bool CheckNontrivialField(FieldDecl *FD);
2527 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2528
2529 enum TrivialABIHandling {
2530 /// The triviality of a method unaffected by "trivial_abi".
2531 TAH_IgnoreTrivialABI,
2532
2533 /// The triviality of a method affected by "trivial_abi".
2534 TAH_ConsiderTrivialABI
2535 };
2536
2537 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2538 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2539 bool Diagnose = false);
2540 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2541 void ActOnLastBitfield(SourceLocation DeclStart,
2542 SmallVectorImpl<Decl *> &AllIvarDecls);
2543 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2544 Declarator &D, Expr *BitfieldWidth,
2545 tok::ObjCKeywordKind visibility);
2546
2547 // This is used for both record definitions and ObjC interface declarations.
2548 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2549 ArrayRef<Decl *> Fields, SourceLocation LBrac,
2550 SourceLocation RBrac, const ParsedAttributesView &AttrList);
2551
2552 /// ActOnTagStartDefinition - Invoked when we have entered the
2553 /// scope of a tag's definition (e.g., for an enumeration, class,
2554 /// struct, or union).
2555 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2556
2557 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2558 /// Differently from C++, actually parse the body and reject / error out
2559 /// in case of a structural mismatch.
2560 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2561 SkipBodyInfo &SkipBody);
2562
2563 typedef void *SkippedDefinitionContext;
2564
2565 /// Invoked when we enter a tag definition that we're skipping.
2566 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2567
2568 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2569
2570 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2571 /// C++ record definition's base-specifiers clause and are starting its
2572 /// member declarations.
2573 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2574 SourceLocation FinalLoc,
2575 bool IsFinalSpelledSealed,
2576 SourceLocation LBraceLoc);
2577
2578 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2579 /// the definition of a tag (enumeration, class, struct, or union).
2580 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2581 SourceRange BraceRange);
2582
2583 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2584
2585 void ActOnObjCContainerFinishDefinition();
2586
2587 /// Invoked when we must temporarily exit the objective-c container
2588 /// scope for parsing/looking-up C constructs.
2589 ///
2590 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2591 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2592 void ActOnObjCReenterContainerContext(DeclContext *DC);
2593
2594 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2595 /// error parsing the definition of a tag.
2596 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2597
2598 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2599 EnumConstantDecl *LastEnumConst,
2600 SourceLocation IdLoc,
2601 IdentifierInfo *Id,
2602 Expr *val);
2603 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2604 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2605 QualType EnumUnderlyingTy, bool IsFixed,
2606 const EnumDecl *Prev);
2607
2608 /// Determine whether the body of an anonymous enumeration should be skipped.
2609 /// \param II The name of the first enumerator.
2610 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2611 SourceLocation IILoc);
2612
2613 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2614 SourceLocation IdLoc, IdentifierInfo *Id,
2615 const ParsedAttributesView &Attrs,
2616 SourceLocation EqualLoc, Expr *Val);
2617 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2618 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2619 const ParsedAttributesView &Attr);
2620
2621 DeclContext *getContainingDC(DeclContext *DC);
2622
2623 /// Set the current declaration context until it gets popped.
2624 void PushDeclContext(Scope *S, DeclContext *DC);
2625 void PopDeclContext();
2626
2627 /// EnterDeclaratorContext - Used when we must lookup names in the context
2628 /// of a declarator's nested name specifier.
2629 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2630 void ExitDeclaratorContext(Scope *S);
2631
2632 /// Push the parameters of D, which must be a function, into scope.
2633 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2634 void ActOnExitFunctionContext();
2635
2636 DeclContext *getFunctionLevelDeclContext();
2637
2638 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2639 /// to the function decl for the function being parsed. If we're currently
2640 /// in a 'block', this returns the containing context.
2641 FunctionDecl *getCurFunctionDecl();
2642
2643 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2644 /// the method decl for the method being parsed. If we're currently
2645 /// in a 'block', this returns the containing context.
2646 ObjCMethodDecl *getCurMethodDecl();
2647
2648 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2649 /// or C function we're in, otherwise return null. If we're currently
2650 /// in a 'block', this returns the containing context.
2651 NamedDecl *getCurFunctionOrMethodDecl();
2652
2653 /// Add this decl to the scope shadowed decl chains.
2654 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2655
2656 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2657 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2658 /// true if 'D' belongs to the given declaration context.
2659 ///
2660 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2661 /// enclosing namespace set of the context, rather than contained
2662 /// directly within it.
2663 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2664 bool AllowInlineNamespace = false);
2665
2666 /// Finds the scope corresponding to the given decl context, if it
2667 /// happens to be an enclosing scope. Otherwise return NULL.
2668 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2669
2670 /// Subroutines of ActOnDeclarator().
2671 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2672 TypeSourceInfo *TInfo);
2673 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2674
2675 /// Describes the kind of merge to perform for availability
2676 /// attributes (including "deprecated", "