File: | clang/lib/Sema/SemaTemplateInstantiate.cpp |
Warning: | line 2793, column 41 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/ | ||||
2 | // | ||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||
6 | //===----------------------------------------------------------------------===/ | ||||
7 | // | ||||
8 | // This file implements C++ template instantiation. | ||||
9 | // | ||||
10 | //===----------------------------------------------------------------------===/ | ||||
11 | |||||
12 | #include "TreeTransform.h" | ||||
13 | #include "clang/AST/ASTConsumer.h" | ||||
14 | #include "clang/AST/ASTContext.h" | ||||
15 | #include "clang/AST/ASTLambda.h" | ||||
16 | #include "clang/AST/ASTMutationListener.h" | ||||
17 | #include "clang/AST/DeclTemplate.h" | ||||
18 | #include "clang/AST/Expr.h" | ||||
19 | #include "clang/AST/PrettyDeclStackTrace.h" | ||||
20 | #include "clang/AST/TypeVisitor.h" | ||||
21 | #include "clang/Basic/LangOptions.h" | ||||
22 | #include "clang/Basic/Stack.h" | ||||
23 | #include "clang/Basic/TargetInfo.h" | ||||
24 | #include "clang/Sema/DeclSpec.h" | ||||
25 | #include "clang/Sema/Initialization.h" | ||||
26 | #include "clang/Sema/Lookup.h" | ||||
27 | #include "clang/Sema/SemaConcept.h" | ||||
28 | #include "clang/Sema/SemaInternal.h" | ||||
29 | #include "clang/Sema/Template.h" | ||||
30 | #include "clang/Sema/TemplateDeduction.h" | ||||
31 | #include "clang/Sema/TemplateInstCallback.h" | ||||
32 | #include "llvm/Support/TimeProfiler.h" | ||||
33 | |||||
34 | using namespace clang; | ||||
35 | using namespace sema; | ||||
36 | |||||
37 | //===----------------------------------------------------------------------===/ | ||||
38 | // Template Instantiation Support | ||||
39 | //===----------------------------------------------------------------------===/ | ||||
40 | |||||
41 | /// Retrieve the template argument list(s) that should be used to | ||||
42 | /// instantiate the definition of the given declaration. | ||||
43 | /// | ||||
44 | /// \param D the declaration for which we are computing template instantiation | ||||
45 | /// arguments. | ||||
46 | /// | ||||
47 | /// \param Innermost if non-NULL, the innermost template argument list. | ||||
48 | /// | ||||
49 | /// \param RelativeToPrimary true if we should get the template | ||||
50 | /// arguments relative to the primary template, even when we're | ||||
51 | /// dealing with a specialization. This is only relevant for function | ||||
52 | /// template specializations. | ||||
53 | /// | ||||
54 | /// \param Pattern If non-NULL, indicates the pattern from which we will be | ||||
55 | /// instantiating the definition of the given declaration, \p D. This is | ||||
56 | /// used to determine the proper set of template instantiation arguments for | ||||
57 | /// friend function template specializations. | ||||
58 | MultiLevelTemplateArgumentList | ||||
59 | Sema::getTemplateInstantiationArgs(NamedDecl *D, | ||||
60 | const TemplateArgumentList *Innermost, | ||||
61 | bool RelativeToPrimary, | ||||
62 | const FunctionDecl *Pattern) { | ||||
63 | // Accumulate the set of template argument lists in this structure. | ||||
64 | MultiLevelTemplateArgumentList Result; | ||||
65 | |||||
66 | if (Innermost) | ||||
67 | Result.addOuterTemplateArguments(Innermost); | ||||
68 | |||||
69 | DeclContext *Ctx = dyn_cast<DeclContext>(D); | ||||
70 | if (!Ctx) { | ||||
71 | Ctx = D->getDeclContext(); | ||||
72 | |||||
73 | // Add template arguments from a variable template instantiation. For a | ||||
74 | // class-scope explicit specialization, there are no template arguments | ||||
75 | // at this level, but there may be enclosing template arguments. | ||||
76 | VarTemplateSpecializationDecl *Spec = | ||||
77 | dyn_cast<VarTemplateSpecializationDecl>(D); | ||||
78 | if (Spec && !Spec->isClassScopeExplicitSpecialization()) { | ||||
79 | // We're done when we hit an explicit specialization. | ||||
80 | if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization && | ||||
81 | !isa<VarTemplatePartialSpecializationDecl>(Spec)) | ||||
82 | return Result; | ||||
83 | |||||
84 | Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); | ||||
85 | |||||
86 | // If this variable template specialization was instantiated from a | ||||
87 | // specialized member that is a variable template, we're done. | ||||
88 | assert(Spec->getSpecializedTemplate() && "No variable template?")((Spec->getSpecializedTemplate() && "No variable template?" ) ? static_cast<void> (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No variable template?\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 88, __PRETTY_FUNCTION__)); | ||||
89 | llvm::PointerUnion<VarTemplateDecl*, | ||||
90 | VarTemplatePartialSpecializationDecl*> Specialized | ||||
91 | = Spec->getSpecializedTemplateOrPartial(); | ||||
92 | if (VarTemplatePartialSpecializationDecl *Partial = | ||||
93 | Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { | ||||
94 | if (Partial->isMemberSpecialization()) | ||||
95 | return Result; | ||||
96 | } else { | ||||
97 | VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>(); | ||||
98 | if (Tmpl->isMemberSpecialization()) | ||||
99 | return Result; | ||||
100 | } | ||||
101 | } | ||||
102 | |||||
103 | // If we have a template template parameter with translation unit context, | ||||
104 | // then we're performing substitution into a default template argument of | ||||
105 | // this template template parameter before we've constructed the template | ||||
106 | // that will own this template template parameter. In this case, we | ||||
107 | // use empty template parameter lists for all of the outer templates | ||||
108 | // to avoid performing any substitutions. | ||||
109 | if (Ctx->isTranslationUnit()) { | ||||
110 | if (TemplateTemplateParmDecl *TTP | ||||
111 | = dyn_cast<TemplateTemplateParmDecl>(D)) { | ||||
112 | for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I) | ||||
113 | Result.addOuterTemplateArguments(None); | ||||
114 | return Result; | ||||
115 | } | ||||
116 | } | ||||
117 | } | ||||
118 | |||||
119 | while (!Ctx->isFileContext()) { | ||||
120 | // Add template arguments from a class template instantiation. | ||||
121 | ClassTemplateSpecializationDecl *Spec | ||||
122 | = dyn_cast<ClassTemplateSpecializationDecl>(Ctx); | ||||
123 | if (Spec && !Spec->isClassScopeExplicitSpecialization()) { | ||||
124 | // We're done when we hit an explicit specialization. | ||||
125 | if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization && | ||||
126 | !isa<ClassTemplatePartialSpecializationDecl>(Spec)) | ||||
127 | break; | ||||
128 | |||||
129 | Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); | ||||
130 | |||||
131 | // If this class template specialization was instantiated from a | ||||
132 | // specialized member that is a class template, we're done. | ||||
133 | assert(Spec->getSpecializedTemplate() && "No class template?")((Spec->getSpecializedTemplate() && "No class template?" ) ? static_cast<void> (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No class template?\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 133, __PRETTY_FUNCTION__)); | ||||
134 | if (Spec->getSpecializedTemplate()->isMemberSpecialization()) | ||||
135 | break; | ||||
136 | } | ||||
137 | // Add template arguments from a function template specialization. | ||||
138 | else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) { | ||||
139 | if (!RelativeToPrimary && | ||||
140 | Function->getTemplateSpecializationKindForInstantiation() == | ||||
141 | TSK_ExplicitSpecialization) | ||||
142 | break; | ||||
143 | |||||
144 | if (!RelativeToPrimary && Function->getTemplateSpecializationKind() == | ||||
145 | TSK_ExplicitSpecialization) { | ||||
146 | // This is an implicit instantiation of an explicit specialization. We | ||||
147 | // don't get any template arguments from this function but might get | ||||
148 | // some from an enclosing template. | ||||
149 | } else if (const TemplateArgumentList *TemplateArgs | ||||
150 | = Function->getTemplateSpecializationArgs()) { | ||||
151 | // Add the template arguments for this specialization. | ||||
152 | Result.addOuterTemplateArguments(TemplateArgs); | ||||
153 | |||||
154 | // If this function was instantiated from a specialized member that is | ||||
155 | // a function template, we're done. | ||||
156 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 156, __PRETTY_FUNCTION__)); | ||||
157 | if (Function->getPrimaryTemplate()->isMemberSpecialization()) | ||||
158 | break; | ||||
159 | |||||
160 | // If this function is a generic lambda specialization, we are done. | ||||
161 | if (isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function)) | ||||
162 | break; | ||||
163 | |||||
164 | } else if (FunctionTemplateDecl *FunTmpl | ||||
165 | = Function->getDescribedFunctionTemplate()) { | ||||
166 | // Add the "injected" template arguments. | ||||
167 | Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs()); | ||||
168 | } | ||||
169 | |||||
170 | // If this is a friend declaration and it declares an entity at | ||||
171 | // namespace scope, take arguments from its lexical parent | ||||
172 | // instead of its semantic parent, unless of course the pattern we're | ||||
173 | // instantiating actually comes from the file's context! | ||||
174 | if (Function->getFriendObjectKind() && | ||||
175 | Function->getDeclContext()->isFileContext() && | ||||
176 | (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) { | ||||
177 | Ctx = Function->getLexicalDeclContext(); | ||||
178 | RelativeToPrimary = false; | ||||
179 | continue; | ||||
180 | } | ||||
181 | } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) { | ||||
182 | if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) { | ||||
183 | QualType T = ClassTemplate->getInjectedClassNameSpecialization(); | ||||
184 | const TemplateSpecializationType *TST = | ||||
185 | cast<TemplateSpecializationType>(Context.getCanonicalType(T)); | ||||
186 | Result.addOuterTemplateArguments( | ||||
187 | llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs())); | ||||
188 | if (ClassTemplate->isMemberSpecialization()) | ||||
189 | break; | ||||
190 | } | ||||
191 | } | ||||
192 | |||||
193 | Ctx = Ctx->getParent(); | ||||
194 | RelativeToPrimary = false; | ||||
195 | } | ||||
196 | |||||
197 | return Result; | ||||
198 | } | ||||
199 | |||||
200 | bool Sema::CodeSynthesisContext::isInstantiationRecord() const { | ||||
201 | switch (Kind) { | ||||
202 | case TemplateInstantiation: | ||||
203 | case ExceptionSpecInstantiation: | ||||
204 | case DefaultTemplateArgumentInstantiation: | ||||
205 | case DefaultFunctionArgumentInstantiation: | ||||
206 | case ExplicitTemplateArgumentSubstitution: | ||||
207 | case DeducedTemplateArgumentSubstitution: | ||||
208 | case PriorTemplateArgumentSubstitution: | ||||
209 | case ConstraintsCheck: | ||||
210 | case NestedRequirementConstraintsCheck: | ||||
211 | return true; | ||||
212 | |||||
213 | case RequirementInstantiation: | ||||
214 | case DefaultTemplateArgumentChecking: | ||||
215 | case DeclaringSpecialMember: | ||||
216 | case DeclaringImplicitEqualityComparison: | ||||
217 | case DefiningSynthesizedFunction: | ||||
218 | case ExceptionSpecEvaluation: | ||||
219 | case ConstraintSubstitution: | ||||
220 | case ParameterMappingSubstitution: | ||||
221 | case ConstraintNormalization: | ||||
222 | case RewritingOperatorAsSpaceship: | ||||
223 | case InitializingStructuredBinding: | ||||
224 | case MarkingClassDllexported: | ||||
225 | return false; | ||||
226 | |||||
227 | // This function should never be called when Kind's value is Memoization. | ||||
228 | case Memoization: | ||||
229 | break; | ||||
230 | } | ||||
231 | |||||
232 | llvm_unreachable("Invalid SynthesisKind!")::llvm::llvm_unreachable_internal("Invalid SynthesisKind!", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 232); | ||||
233 | } | ||||
234 | |||||
235 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
236 | Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, | ||||
237 | SourceLocation PointOfInstantiation, SourceRange InstantiationRange, | ||||
238 | Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, | ||||
239 | sema::TemplateDeductionInfo *DeductionInfo) | ||||
240 | : SemaRef(SemaRef) { | ||||
241 | // Don't allow further instantiation if a fatal error and an uncompilable | ||||
242 | // error have occurred. Any diagnostics we might have raised will not be | ||||
243 | // visible, and we do not need to construct a correct AST. | ||||
244 | if (SemaRef.Diags.hasFatalErrorOccurred() && | ||||
245 | SemaRef.hasUncompilableErrorOccurred()) { | ||||
246 | Invalid = true; | ||||
247 | return; | ||||
248 | } | ||||
249 | Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange); | ||||
250 | if (!Invalid
| ||||
251 | CodeSynthesisContext Inst; | ||||
252 | Inst.Kind = Kind; | ||||
253 | Inst.PointOfInstantiation = PointOfInstantiation; | ||||
254 | Inst.Entity = Entity; | ||||
255 | Inst.Template = Template; | ||||
256 | Inst.TemplateArgs = TemplateArgs.data(); | ||||
257 | Inst.NumTemplateArgs = TemplateArgs.size(); | ||||
258 | Inst.DeductionInfo = DeductionInfo; | ||||
259 | Inst.InstantiationRange = InstantiationRange; | ||||
260 | SemaRef.pushCodeSynthesisContext(Inst); | ||||
261 | |||||
262 | AlreadyInstantiating = !Inst.Entity
| ||||
263 | !SemaRef.InstantiatingSpecializations | ||||
264 | .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind}) | ||||
265 | .second; | ||||
266 | atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst); | ||||
267 | } | ||||
268 | } | ||||
269 | |||||
270 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
271 | Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, | ||||
272 | SourceRange InstantiationRange) | ||||
273 | : InstantiatingTemplate(SemaRef, | ||||
274 | CodeSynthesisContext::TemplateInstantiation, | ||||
275 | PointOfInstantiation, InstantiationRange, Entity) {} | ||||
276 | |||||
277 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
278 | Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, | ||||
279 | ExceptionSpecification, SourceRange InstantiationRange) | ||||
280 | : InstantiatingTemplate( | ||||
281 | SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation, | ||||
282 | PointOfInstantiation, InstantiationRange, Entity) {} | ||||
283 | |||||
284 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
285 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, | ||||
286 | TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, | ||||
287 | SourceRange InstantiationRange) | ||||
288 | : InstantiatingTemplate( | ||||
289 | SemaRef, | ||||
290 | CodeSynthesisContext::DefaultTemplateArgumentInstantiation, | ||||
291 | PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param), | ||||
292 | Template, TemplateArgs) {} | ||||
293 | |||||
294 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
295 | Sema &SemaRef, SourceLocation PointOfInstantiation, | ||||
296 | FunctionTemplateDecl *FunctionTemplate, | ||||
297 | ArrayRef<TemplateArgument> TemplateArgs, | ||||
298 | CodeSynthesisContext::SynthesisKind Kind, | ||||
299 | sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) | ||||
300 | : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation, | ||||
301 | InstantiationRange, FunctionTemplate, nullptr, | ||||
302 | TemplateArgs, &DeductionInfo) { | ||||
303 | assert(((Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution ) ? static_cast<void> (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 305, __PRETTY_FUNCTION__)) | ||||
304 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 305, __PRETTY_FUNCTION__)) | ||||
305 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 305, __PRETTY_FUNCTION__)); | ||||
306 | } | ||||
307 | |||||
308 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
309 | Sema &SemaRef, SourceLocation PointOfInstantiation, | ||||
310 | TemplateDecl *Template, | ||||
311 | ArrayRef<TemplateArgument> TemplateArgs, | ||||
312 | sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) | ||||
313 | : InstantiatingTemplate( | ||||
314 | SemaRef, | ||||
315 | CodeSynthesisContext::DeducedTemplateArgumentSubstitution, | ||||
316 | PointOfInstantiation, InstantiationRange, Template, nullptr, | ||||
317 | TemplateArgs, &DeductionInfo) {} | ||||
318 | |||||
319 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
320 | Sema &SemaRef, SourceLocation PointOfInstantiation, | ||||
321 | ClassTemplatePartialSpecializationDecl *PartialSpec, | ||||
322 | ArrayRef<TemplateArgument> TemplateArgs, | ||||
323 | sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) | ||||
324 | : InstantiatingTemplate( | ||||
325 | SemaRef, | ||||
326 | CodeSynthesisContext::DeducedTemplateArgumentSubstitution, | ||||
327 | PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, | ||||
328 | TemplateArgs, &DeductionInfo) {} | ||||
329 | |||||
330 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
331 | Sema &SemaRef, SourceLocation PointOfInstantiation, | ||||
332 | VarTemplatePartialSpecializationDecl *PartialSpec, | ||||
333 | ArrayRef<TemplateArgument> TemplateArgs, | ||||
334 | sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) | ||||
335 | : InstantiatingTemplate( | ||||
336 | SemaRef, | ||||
337 | CodeSynthesisContext::DeducedTemplateArgumentSubstitution, | ||||
338 | PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, | ||||
339 | TemplateArgs, &DeductionInfo) {} | ||||
340 | |||||
341 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
342 | Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, | ||||
343 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) | ||||
344 | : InstantiatingTemplate( | ||||
345 | SemaRef, | ||||
346 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation, | ||||
347 | PointOfInstantiation, InstantiationRange, Param, nullptr, | ||||
348 | TemplateArgs) {} | ||||
349 | |||||
350 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
351 | Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, | ||||
352 | NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, | ||||
353 | SourceRange InstantiationRange) | ||||
354 | : InstantiatingTemplate( | ||||
355 | SemaRef, | ||||
356 | CodeSynthesisContext::PriorTemplateArgumentSubstitution, | ||||
357 | PointOfInstantiation, InstantiationRange, Param, Template, | ||||
358 | TemplateArgs) {} | ||||
359 | |||||
360 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
361 | Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, | ||||
362 | TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, | ||||
363 | SourceRange InstantiationRange) | ||||
364 | : InstantiatingTemplate( | ||||
365 | SemaRef, | ||||
366 | CodeSynthesisContext::PriorTemplateArgumentSubstitution, | ||||
367 | PointOfInstantiation, InstantiationRange, Param, Template, | ||||
368 | TemplateArgs) {} | ||||
369 | |||||
370 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
371 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, | ||||
372 | NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, | ||||
373 | SourceRange InstantiationRange) | ||||
374 | : InstantiatingTemplate( | ||||
375 | SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking, | ||||
376 | PointOfInstantiation, InstantiationRange, Param, Template, | ||||
377 | TemplateArgs) {} | ||||
378 | |||||
379 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
380 | Sema &SemaRef, SourceLocation PointOfInstantiation, | ||||
381 | concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, | ||||
382 | SourceRange InstantiationRange) | ||||
383 | : InstantiatingTemplate( | ||||
384 | SemaRef, CodeSynthesisContext::RequirementInstantiation, | ||||
385 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, | ||||
386 | /*Template=*/nullptr, /*TemplateArgs=*/None, &DeductionInfo) {} | ||||
387 | |||||
388 | |||||
389 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
390 | Sema &SemaRef, SourceLocation PointOfInstantiation, | ||||
391 | concepts::NestedRequirement *Req, ConstraintsCheck, | ||||
392 | SourceRange InstantiationRange) | ||||
393 | : InstantiatingTemplate( | ||||
394 | SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck, | ||||
395 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, | ||||
396 | /*Template=*/nullptr, /*TemplateArgs=*/None) {} | ||||
397 | |||||
398 | |||||
399 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
400 | Sema &SemaRef, SourceLocation PointOfInstantiation, | ||||
401 | ConstraintsCheck, NamedDecl *Template, | ||||
402 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) | ||||
403 | : InstantiatingTemplate( | ||||
404 | SemaRef, CodeSynthesisContext::ConstraintsCheck, | ||||
405 | PointOfInstantiation, InstantiationRange, Template, nullptr, | ||||
406 | TemplateArgs) {} | ||||
407 | |||||
408 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
409 | Sema &SemaRef, SourceLocation PointOfInstantiation, | ||||
410 | ConstraintSubstitution, NamedDecl *Template, | ||||
411 | sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) | ||||
412 | : InstantiatingTemplate( | ||||
413 | SemaRef, CodeSynthesisContext::ConstraintSubstitution, | ||||
414 | PointOfInstantiation, InstantiationRange, Template, nullptr, | ||||
415 | {}, &DeductionInfo) {} | ||||
416 | |||||
417 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
418 | Sema &SemaRef, SourceLocation PointOfInstantiation, | ||||
419 | ConstraintNormalization, NamedDecl *Template, | ||||
420 | SourceRange InstantiationRange) | ||||
421 | : InstantiatingTemplate( | ||||
422 | SemaRef, CodeSynthesisContext::ConstraintNormalization, | ||||
423 | PointOfInstantiation, InstantiationRange, Template) {} | ||||
424 | |||||
425 | Sema::InstantiatingTemplate::InstantiatingTemplate( | ||||
426 | Sema &SemaRef, SourceLocation PointOfInstantiation, | ||||
427 | ParameterMappingSubstitution, NamedDecl *Template, | ||||
428 | SourceRange InstantiationRange) | ||||
429 | : InstantiatingTemplate( | ||||
430 | SemaRef, CodeSynthesisContext::ParameterMappingSubstitution, | ||||
431 | PointOfInstantiation, InstantiationRange, Template) {} | ||||
432 | |||||
433 | void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) { | ||||
434 | Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext; | ||||
435 | InNonInstantiationSFINAEContext = false; | ||||
436 | |||||
437 | CodeSynthesisContexts.push_back(Ctx); | ||||
438 | |||||
439 | if (!Ctx.isInstantiationRecord()) | ||||
440 | ++NonInstantiationEntries; | ||||
441 | |||||
442 | // Check to see if we're low on stack space. We can't do anything about this | ||||
443 | // from here, but we can at least warn the user. | ||||
444 | if (isStackNearlyExhausted()) | ||||
445 | warnStackExhausted(Ctx.PointOfInstantiation); | ||||
446 | } | ||||
447 | |||||
448 | void Sema::popCodeSynthesisContext() { | ||||
449 | auto &Active = CodeSynthesisContexts.back(); | ||||
450 | if (!Active.isInstantiationRecord()) { | ||||
451 | assert(NonInstantiationEntries > 0)((NonInstantiationEntries > 0) ? static_cast<void> ( 0) : __assert_fail ("NonInstantiationEntries > 0", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 451, __PRETTY_FUNCTION__)); | ||||
452 | --NonInstantiationEntries; | ||||
453 | } | ||||
454 | |||||
455 | InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext; | ||||
456 | |||||
457 | // Name lookup no longer looks in this template's defining module. | ||||
458 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 460, __PRETTY_FUNCTION__)) | ||||
459 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 460, __PRETTY_FUNCTION__)) | ||||
460 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 460, __PRETTY_FUNCTION__)); | ||||
461 | if (CodeSynthesisContexts.size() == | ||||
462 | CodeSynthesisContextLookupModules.size()) { | ||||
463 | if (Module *M = CodeSynthesisContextLookupModules.back()) | ||||
464 | LookupModulesCache.erase(M); | ||||
465 | CodeSynthesisContextLookupModules.pop_back(); | ||||
466 | } | ||||
467 | |||||
468 | // If we've left the code synthesis context for the current context stack, | ||||
469 | // stop remembering that we've emitted that stack. | ||||
470 | if (CodeSynthesisContexts.size() == | ||||
471 | LastEmittedCodeSynthesisContextDepth) | ||||
472 | LastEmittedCodeSynthesisContextDepth = 0; | ||||
473 | |||||
474 | CodeSynthesisContexts.pop_back(); | ||||
475 | } | ||||
476 | |||||
477 | void Sema::InstantiatingTemplate::Clear() { | ||||
478 | if (!Invalid) { | ||||
479 | if (!AlreadyInstantiating) { | ||||
480 | auto &Active = SemaRef.CodeSynthesisContexts.back(); | ||||
481 | if (Active.Entity) | ||||
482 | SemaRef.InstantiatingSpecializations.erase( | ||||
483 | {Active.Entity->getCanonicalDecl(), Active.Kind}); | ||||
484 | } | ||||
485 | |||||
486 | atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, | ||||
487 | SemaRef.CodeSynthesisContexts.back()); | ||||
488 | |||||
489 | SemaRef.popCodeSynthesisContext(); | ||||
490 | Invalid = true; | ||||
491 | } | ||||
492 | } | ||||
493 | |||||
494 | bool Sema::InstantiatingTemplate::CheckInstantiationDepth( | ||||
495 | SourceLocation PointOfInstantiation, | ||||
496 | SourceRange InstantiationRange) { | ||||
497 | assert(SemaRef.NonInstantiationEntries <=((SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts .size()) ? static_cast<void> (0) : __assert_fail ("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 498, __PRETTY_FUNCTION__)) | ||||
498 | SemaRef.CodeSynthesisContexts.size())((SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts .size()) ? static_cast<void> (0) : __assert_fail ("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 498, __PRETTY_FUNCTION__)); | ||||
499 | if ((SemaRef.CodeSynthesisContexts.size() - | ||||
500 | SemaRef.NonInstantiationEntries) | ||||
501 | <= SemaRef.getLangOpts().InstantiationDepth) | ||||
502 | return false; | ||||
503 | |||||
504 | SemaRef.Diag(PointOfInstantiation, | ||||
505 | diag::err_template_recursion_depth_exceeded) | ||||
506 | << SemaRef.getLangOpts().InstantiationDepth | ||||
507 | << InstantiationRange; | ||||
508 | SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth) | ||||
509 | << SemaRef.getLangOpts().InstantiationDepth; | ||||
510 | return true; | ||||
511 | } | ||||
512 | |||||
513 | /// Prints the current instantiation stack through a series of | ||||
514 | /// notes. | ||||
515 | void Sema::PrintInstantiationStack() { | ||||
516 | // Determine which template instantiations to skip, if any. | ||||
517 | unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart; | ||||
518 | unsigned Limit = Diags.getTemplateBacktraceLimit(); | ||||
519 | if (Limit && Limit < CodeSynthesisContexts.size()) { | ||||
520 | SkipStart = Limit / 2 + Limit % 2; | ||||
521 | SkipEnd = CodeSynthesisContexts.size() - Limit / 2; | ||||
522 | } | ||||
523 | |||||
524 | // FIXME: In all of these cases, we need to show the template arguments | ||||
525 | unsigned InstantiationIdx = 0; | ||||
526 | for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator | ||||
527 | Active = CodeSynthesisContexts.rbegin(), | ||||
528 | ActiveEnd = CodeSynthesisContexts.rend(); | ||||
529 | Active != ActiveEnd; | ||||
530 | ++Active, ++InstantiationIdx) { | ||||
531 | // Skip this instantiation? | ||||
532 | if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) { | ||||
533 | if (InstantiationIdx == SkipStart) { | ||||
534 | // Note that we're skipping instantiations. | ||||
535 | Diags.Report(Active->PointOfInstantiation, | ||||
536 | diag::note_instantiation_contexts_suppressed) | ||||
537 | << unsigned(CodeSynthesisContexts.size() - Limit); | ||||
538 | } | ||||
539 | continue; | ||||
540 | } | ||||
541 | |||||
542 | switch (Active->Kind) { | ||||
543 | case CodeSynthesisContext::TemplateInstantiation: { | ||||
544 | Decl *D = Active->Entity; | ||||
545 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { | ||||
546 | unsigned DiagID = diag::note_template_member_class_here; | ||||
547 | if (isa<ClassTemplateSpecializationDecl>(Record)) | ||||
548 | DiagID = diag::note_template_class_instantiation_here; | ||||
549 | Diags.Report(Active->PointOfInstantiation, DiagID) | ||||
550 | << Record << Active->InstantiationRange; | ||||
551 | } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { | ||||
552 | unsigned DiagID; | ||||
553 | if (Function->getPrimaryTemplate()) | ||||
554 | DiagID = diag::note_function_template_spec_here; | ||||
555 | else | ||||
556 | DiagID = diag::note_template_member_function_here; | ||||
557 | Diags.Report(Active->PointOfInstantiation, DiagID) | ||||
558 | << Function | ||||
559 | << Active->InstantiationRange; | ||||
560 | } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
561 | Diags.Report(Active->PointOfInstantiation, | ||||
562 | VD->isStaticDataMember()? | ||||
563 | diag::note_template_static_data_member_def_here | ||||
564 | : diag::note_template_variable_def_here) | ||||
565 | << VD | ||||
566 | << Active->InstantiationRange; | ||||
567 | } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { | ||||
568 | Diags.Report(Active->PointOfInstantiation, | ||||
569 | diag::note_template_enum_def_here) | ||||
570 | << ED | ||||
571 | << Active->InstantiationRange; | ||||
572 | } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { | ||||
573 | Diags.Report(Active->PointOfInstantiation, | ||||
574 | diag::note_template_nsdmi_here) | ||||
575 | << FD << Active->InstantiationRange; | ||||
576 | } else { | ||||
577 | Diags.Report(Active->PointOfInstantiation, | ||||
578 | diag::note_template_type_alias_instantiation_here) | ||||
579 | << cast<TypeAliasTemplateDecl>(D) | ||||
580 | << Active->InstantiationRange; | ||||
581 | } | ||||
582 | break; | ||||
583 | } | ||||
584 | |||||
585 | case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: { | ||||
586 | TemplateDecl *Template = cast<TemplateDecl>(Active->Template); | ||||
587 | SmallString<128> TemplateArgsStr; | ||||
588 | llvm::raw_svector_ostream OS(TemplateArgsStr); | ||||
589 | Template->printName(OS); | ||||
590 | printTemplateArgumentList(OS, Active->template_arguments(), | ||||
591 | getPrintingPolicy()); | ||||
592 | Diags.Report(Active->PointOfInstantiation, | ||||
593 | diag::note_default_arg_instantiation_here) | ||||
594 | << OS.str() | ||||
595 | << Active->InstantiationRange; | ||||
596 | break; | ||||
597 | } | ||||
598 | |||||
599 | case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: { | ||||
600 | FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity); | ||||
601 | Diags.Report(Active->PointOfInstantiation, | ||||
602 | diag::note_explicit_template_arg_substitution_here) | ||||
603 | << FnTmpl | ||||
604 | << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), | ||||
605 | Active->TemplateArgs, | ||||
606 | Active->NumTemplateArgs) | ||||
607 | << Active->InstantiationRange; | ||||
608 | break; | ||||
609 | } | ||||
610 | |||||
611 | case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: { | ||||
612 | if (FunctionTemplateDecl *FnTmpl = | ||||
613 | dyn_cast<FunctionTemplateDecl>(Active->Entity)) { | ||||
614 | Diags.Report(Active->PointOfInstantiation, | ||||
615 | diag::note_function_template_deduction_instantiation_here) | ||||
616 | << FnTmpl | ||||
617 | << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), | ||||
618 | Active->TemplateArgs, | ||||
619 | Active->NumTemplateArgs) | ||||
620 | << Active->InstantiationRange; | ||||
621 | } else { | ||||
622 | bool IsVar = isa<VarTemplateDecl>(Active->Entity) || | ||||
623 | isa<VarTemplateSpecializationDecl>(Active->Entity); | ||||
624 | bool IsTemplate = false; | ||||
625 | TemplateParameterList *Params; | ||||
626 | if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) { | ||||
627 | IsTemplate = true; | ||||
628 | Params = D->getTemplateParameters(); | ||||
629 | } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>( | ||||
630 | Active->Entity)) { | ||||
631 | Params = D->getTemplateParameters(); | ||||
632 | } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>( | ||||
633 | Active->Entity)) { | ||||
634 | Params = D->getTemplateParameters(); | ||||
635 | } else { | ||||
636 | llvm_unreachable("unexpected template kind")::llvm::llvm_unreachable_internal("unexpected template kind", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 636); | ||||
637 | } | ||||
638 | |||||
639 | Diags.Report(Active->PointOfInstantiation, | ||||
640 | diag::note_deduced_template_arg_substitution_here) | ||||
641 | << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity) | ||||
642 | << getTemplateArgumentBindingsText(Params, Active->TemplateArgs, | ||||
643 | Active->NumTemplateArgs) | ||||
644 | << Active->InstantiationRange; | ||||
645 | } | ||||
646 | break; | ||||
647 | } | ||||
648 | |||||
649 | case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: { | ||||
650 | ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity); | ||||
651 | FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext()); | ||||
652 | |||||
653 | SmallString<128> TemplateArgsStr; | ||||
654 | llvm::raw_svector_ostream OS(TemplateArgsStr); | ||||
655 | FD->printName(OS); | ||||
656 | printTemplateArgumentList(OS, Active->template_arguments(), | ||||
657 | getPrintingPolicy()); | ||||
658 | Diags.Report(Active->PointOfInstantiation, | ||||
659 | diag::note_default_function_arg_instantiation_here) | ||||
660 | << OS.str() | ||||
661 | << Active->InstantiationRange; | ||||
662 | break; | ||||
663 | } | ||||
664 | |||||
665 | case CodeSynthesisContext::PriorTemplateArgumentSubstitution: { | ||||
666 | NamedDecl *Parm = cast<NamedDecl>(Active->Entity); | ||||
667 | std::string Name; | ||||
668 | if (!Parm->getName().empty()) | ||||
669 | Name = std::string(" '") + Parm->getName().str() + "'"; | ||||
670 | |||||
671 | TemplateParameterList *TemplateParams = nullptr; | ||||
672 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template)) | ||||
673 | TemplateParams = Template->getTemplateParameters(); | ||||
674 | else | ||||
675 | TemplateParams = | ||||
676 | cast<ClassTemplatePartialSpecializationDecl>(Active->Template) | ||||
677 | ->getTemplateParameters(); | ||||
678 | Diags.Report(Active->PointOfInstantiation, | ||||
679 | diag::note_prior_template_arg_substitution) | ||||
680 | << isa<TemplateTemplateParmDecl>(Parm) | ||||
681 | << Name | ||||
682 | << getTemplateArgumentBindingsText(TemplateParams, | ||||
683 | Active->TemplateArgs, | ||||
684 | Active->NumTemplateArgs) | ||||
685 | << Active->InstantiationRange; | ||||
686 | break; | ||||
687 | } | ||||
688 | |||||
689 | case CodeSynthesisContext::DefaultTemplateArgumentChecking: { | ||||
690 | TemplateParameterList *TemplateParams = nullptr; | ||||
691 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template)) | ||||
692 | TemplateParams = Template->getTemplateParameters(); | ||||
693 | else | ||||
694 | TemplateParams = | ||||
695 | cast<ClassTemplatePartialSpecializationDecl>(Active->Template) | ||||
696 | ->getTemplateParameters(); | ||||
697 | |||||
698 | Diags.Report(Active->PointOfInstantiation, | ||||
699 | diag::note_template_default_arg_checking) | ||||
700 | << getTemplateArgumentBindingsText(TemplateParams, | ||||
701 | Active->TemplateArgs, | ||||
702 | Active->NumTemplateArgs) | ||||
703 | << Active->InstantiationRange; | ||||
704 | break; | ||||
705 | } | ||||
706 | |||||
707 | case CodeSynthesisContext::ExceptionSpecEvaluation: | ||||
708 | Diags.Report(Active->PointOfInstantiation, | ||||
709 | diag::note_evaluating_exception_spec_here) | ||||
710 | << cast<FunctionDecl>(Active->Entity); | ||||
711 | break; | ||||
712 | |||||
713 | case CodeSynthesisContext::ExceptionSpecInstantiation: | ||||
714 | Diags.Report(Active->PointOfInstantiation, | ||||
715 | diag::note_template_exception_spec_instantiation_here) | ||||
716 | << cast<FunctionDecl>(Active->Entity) | ||||
717 | << Active->InstantiationRange; | ||||
718 | break; | ||||
719 | |||||
720 | case CodeSynthesisContext::RequirementInstantiation: | ||||
721 | Diags.Report(Active->PointOfInstantiation, | ||||
722 | diag::note_template_requirement_instantiation_here) | ||||
723 | << Active->InstantiationRange; | ||||
724 | break; | ||||
725 | |||||
726 | case CodeSynthesisContext::NestedRequirementConstraintsCheck: | ||||
727 | Diags.Report(Active->PointOfInstantiation, | ||||
728 | diag::note_nested_requirement_here) | ||||
729 | << Active->InstantiationRange; | ||||
730 | break; | ||||
731 | |||||
732 | case CodeSynthesisContext::DeclaringSpecialMember: | ||||
733 | Diags.Report(Active->PointOfInstantiation, | ||||
734 | diag::note_in_declaration_of_implicit_special_member) | ||||
735 | << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember; | ||||
736 | break; | ||||
737 | |||||
738 | case CodeSynthesisContext::DeclaringImplicitEqualityComparison: | ||||
739 | Diags.Report(Active->Entity->getLocation(), | ||||
740 | diag::note_in_declaration_of_implicit_equality_comparison); | ||||
741 | break; | ||||
742 | |||||
743 | case CodeSynthesisContext::DefiningSynthesizedFunction: { | ||||
744 | // FIXME: For synthesized functions that are not defaulted, | ||||
745 | // produce a note. | ||||
746 | auto *FD = dyn_cast<FunctionDecl>(Active->Entity); | ||||
747 | DefaultedFunctionKind DFK = | ||||
748 | FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind(); | ||||
749 | if (DFK.isSpecialMember()) { | ||||
750 | auto *MD = cast<CXXMethodDecl>(FD); | ||||
751 | Diags.Report(Active->PointOfInstantiation, | ||||
752 | diag::note_member_synthesized_at) | ||||
753 | << MD->isExplicitlyDefaulted() << DFK.asSpecialMember() | ||||
754 | << Context.getTagDeclType(MD->getParent()); | ||||
755 | } else if (DFK.isComparison()) { | ||||
756 | Diags.Report(Active->PointOfInstantiation, | ||||
757 | diag::note_comparison_synthesized_at) | ||||
758 | << (int)DFK.asComparison() | ||||
759 | << Context.getTagDeclType( | ||||
760 | cast<CXXRecordDecl>(FD->getLexicalDeclContext())); | ||||
761 | } | ||||
762 | break; | ||||
763 | } | ||||
764 | |||||
765 | case CodeSynthesisContext::RewritingOperatorAsSpaceship: | ||||
766 | Diags.Report(Active->Entity->getLocation(), | ||||
767 | diag::note_rewriting_operator_as_spaceship); | ||||
768 | break; | ||||
769 | |||||
770 | case CodeSynthesisContext::InitializingStructuredBinding: | ||||
771 | Diags.Report(Active->PointOfInstantiation, | ||||
772 | diag::note_in_binding_decl_init) | ||||
773 | << cast<BindingDecl>(Active->Entity); | ||||
774 | break; | ||||
775 | |||||
776 | case CodeSynthesisContext::MarkingClassDllexported: | ||||
777 | Diags.Report(Active->PointOfInstantiation, | ||||
778 | diag::note_due_to_dllexported_class) | ||||
779 | << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11; | ||||
780 | break; | ||||
781 | |||||
782 | case CodeSynthesisContext::Memoization: | ||||
783 | break; | ||||
784 | |||||
785 | case CodeSynthesisContext::ConstraintsCheck: { | ||||
786 | unsigned DiagID = 0; | ||||
787 | if (!Active->Entity) { | ||||
788 | Diags.Report(Active->PointOfInstantiation, | ||||
789 | diag::note_nested_requirement_here) | ||||
790 | << Active->InstantiationRange; | ||||
791 | break; | ||||
792 | } | ||||
793 | if (isa<ConceptDecl>(Active->Entity)) | ||||
794 | DiagID = diag::note_concept_specialization_here; | ||||
795 | else if (isa<TemplateDecl>(Active->Entity)) | ||||
796 | DiagID = diag::note_checking_constraints_for_template_id_here; | ||||
797 | else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity)) | ||||
798 | DiagID = diag::note_checking_constraints_for_var_spec_id_here; | ||||
799 | else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity)) | ||||
800 | DiagID = diag::note_checking_constraints_for_class_spec_id_here; | ||||
801 | else { | ||||
802 | assert(isa<FunctionDecl>(Active->Entity))((isa<FunctionDecl>(Active->Entity)) ? static_cast< void> (0) : __assert_fail ("isa<FunctionDecl>(Active->Entity)" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 802, __PRETTY_FUNCTION__)); | ||||
803 | DiagID = diag::note_checking_constraints_for_function_here; | ||||
804 | } | ||||
805 | SmallString<128> TemplateArgsStr; | ||||
806 | llvm::raw_svector_ostream OS(TemplateArgsStr); | ||||
807 | cast<NamedDecl>(Active->Entity)->printName(OS); | ||||
808 | if (!isa<FunctionDecl>(Active->Entity)) | ||||
809 | printTemplateArgumentList(OS, Active->template_arguments(), | ||||
810 | getPrintingPolicy()); | ||||
811 | Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str() | ||||
812 | << Active->InstantiationRange; | ||||
813 | break; | ||||
814 | } | ||||
815 | case CodeSynthesisContext::ConstraintSubstitution: | ||||
816 | Diags.Report(Active->PointOfInstantiation, | ||||
817 | diag::note_constraint_substitution_here) | ||||
818 | << Active->InstantiationRange; | ||||
819 | break; | ||||
820 | case CodeSynthesisContext::ConstraintNormalization: | ||||
821 | Diags.Report(Active->PointOfInstantiation, | ||||
822 | diag::note_constraint_normalization_here) | ||||
823 | << cast<NamedDecl>(Active->Entity)->getName() | ||||
824 | << Active->InstantiationRange; | ||||
825 | break; | ||||
826 | case CodeSynthesisContext::ParameterMappingSubstitution: | ||||
827 | Diags.Report(Active->PointOfInstantiation, | ||||
828 | diag::note_parameter_mapping_substitution_here) | ||||
829 | << Active->InstantiationRange; | ||||
830 | break; | ||||
831 | } | ||||
832 | } | ||||
833 | } | ||||
834 | |||||
835 | Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { | ||||
836 | if (InNonInstantiationSFINAEContext) | ||||
837 | return Optional<TemplateDeductionInfo *>(nullptr); | ||||
838 | |||||
839 | for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator | ||||
840 | Active = CodeSynthesisContexts.rbegin(), | ||||
841 | ActiveEnd = CodeSynthesisContexts.rend(); | ||||
842 | Active != ActiveEnd; | ||||
843 | ++Active) | ||||
844 | { | ||||
845 | switch (Active->Kind) { | ||||
846 | case CodeSynthesisContext::TemplateInstantiation: | ||||
847 | // An instantiation of an alias template may or may not be a SFINAE | ||||
848 | // context, depending on what else is on the stack. | ||||
849 | if (isa<TypeAliasTemplateDecl>(Active->Entity)) | ||||
850 | break; | ||||
851 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
852 | case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: | ||||
853 | case CodeSynthesisContext::ExceptionSpecInstantiation: | ||||
854 | case CodeSynthesisContext::ConstraintsCheck: | ||||
855 | case CodeSynthesisContext::ParameterMappingSubstitution: | ||||
856 | case CodeSynthesisContext::ConstraintNormalization: | ||||
857 | case CodeSynthesisContext::NestedRequirementConstraintsCheck: | ||||
858 | // This is a template instantiation, so there is no SFINAE. | ||||
859 | return None; | ||||
860 | |||||
861 | case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: | ||||
862 | case CodeSynthesisContext::PriorTemplateArgumentSubstitution: | ||||
863 | case CodeSynthesisContext::DefaultTemplateArgumentChecking: | ||||
864 | case CodeSynthesisContext::RewritingOperatorAsSpaceship: | ||||
865 | // A default template argument instantiation and substitution into | ||||
866 | // template parameters with arguments for prior parameters may or may | ||||
867 | // not be a SFINAE context; look further up the stack. | ||||
868 | break; | ||||
869 | |||||
870 | case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: | ||||
871 | case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: | ||||
872 | case CodeSynthesisContext::ConstraintSubstitution: | ||||
873 | case CodeSynthesisContext::RequirementInstantiation: | ||||
874 | // We're either substituting explicitly-specified template arguments, | ||||
875 | // deduced template arguments, a constraint expression or a requirement | ||||
876 | // in a requires expression, so SFINAE applies. | ||||
877 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 877, __PRETTY_FUNCTION__)); | ||||
878 | return Active->DeductionInfo; | ||||
879 | |||||
880 | case CodeSynthesisContext::DeclaringSpecialMember: | ||||
881 | case CodeSynthesisContext::DeclaringImplicitEqualityComparison: | ||||
882 | case CodeSynthesisContext::DefiningSynthesizedFunction: | ||||
883 | case CodeSynthesisContext::InitializingStructuredBinding: | ||||
884 | case CodeSynthesisContext::MarkingClassDllexported: | ||||
885 | // This happens in a context unrelated to template instantiation, so | ||||
886 | // there is no SFINAE. | ||||
887 | return None; | ||||
888 | |||||
889 | case CodeSynthesisContext::ExceptionSpecEvaluation: | ||||
890 | // FIXME: This should not be treated as a SFINAE context, because | ||||
891 | // we will cache an incorrect exception specification. However, clang | ||||
892 | // bootstrap relies this! See PR31692. | ||||
893 | break; | ||||
894 | |||||
895 | case CodeSynthesisContext::Memoization: | ||||
896 | break; | ||||
897 | } | ||||
898 | |||||
899 | // The inner context was transparent for SFINAE. If it occurred within a | ||||
900 | // non-instantiation SFINAE context, then SFINAE applies. | ||||
901 | if (Active->SavedInNonInstantiationSFINAEContext) | ||||
902 | return Optional<TemplateDeductionInfo *>(nullptr); | ||||
903 | } | ||||
904 | |||||
905 | return None; | ||||
906 | } | ||||
907 | |||||
908 | //===----------------------------------------------------------------------===/ | ||||
909 | // Template Instantiation for Types | ||||
910 | //===----------------------------------------------------------------------===/ | ||||
911 | namespace { | ||||
912 | class TemplateInstantiator : public TreeTransform<TemplateInstantiator> { | ||||
913 | const MultiLevelTemplateArgumentList &TemplateArgs; | ||||
914 | SourceLocation Loc; | ||||
915 | DeclarationName Entity; | ||||
916 | |||||
917 | public: | ||||
918 | typedef TreeTransform<TemplateInstantiator> inherited; | ||||
919 | |||||
920 | TemplateInstantiator(Sema &SemaRef, | ||||
921 | const MultiLevelTemplateArgumentList &TemplateArgs, | ||||
922 | SourceLocation Loc, | ||||
923 | DeclarationName Entity) | ||||
924 | : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), | ||||
925 | Entity(Entity) { } | ||||
926 | |||||
927 | /// Determine whether the given type \p T has already been | ||||
928 | /// transformed. | ||||
929 | /// | ||||
930 | /// For the purposes of template instantiation, a type has already been | ||||
931 | /// transformed if it is NULL or if it is not dependent. | ||||
932 | bool AlreadyTransformed(QualType T); | ||||
933 | |||||
934 | /// Returns the location of the entity being instantiated, if known. | ||||
935 | SourceLocation getBaseLocation() { return Loc; } | ||||
936 | |||||
937 | /// Returns the name of the entity being instantiated, if any. | ||||
938 | DeclarationName getBaseEntity() { return Entity; } | ||||
939 | |||||
940 | /// Sets the "base" location and entity when that | ||||
941 | /// information is known based on another transformation. | ||||
942 | void setBase(SourceLocation Loc, DeclarationName Entity) { | ||||
943 | this->Loc = Loc; | ||||
944 | this->Entity = Entity; | ||||
945 | } | ||||
946 | |||||
947 | unsigned TransformTemplateDepth(unsigned Depth) { | ||||
948 | return TemplateArgs.getNewDepth(Depth); | ||||
949 | } | ||||
950 | |||||
951 | bool TryExpandParameterPacks(SourceLocation EllipsisLoc, | ||||
952 | SourceRange PatternRange, | ||||
953 | ArrayRef<UnexpandedParameterPack> Unexpanded, | ||||
954 | bool &ShouldExpand, bool &RetainExpansion, | ||||
955 | Optional<unsigned> &NumExpansions) { | ||||
956 | return getSema().CheckParameterPacksForExpansion(EllipsisLoc, | ||||
957 | PatternRange, Unexpanded, | ||||
958 | TemplateArgs, | ||||
959 | ShouldExpand, | ||||
960 | RetainExpansion, | ||||
961 | NumExpansions); | ||||
962 | } | ||||
963 | |||||
964 | void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { | ||||
965 | SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack); | ||||
966 | } | ||||
967 | |||||
968 | TemplateArgument ForgetPartiallySubstitutedPack() { | ||||
969 | TemplateArgument Result; | ||||
970 | if (NamedDecl *PartialPack | ||||
971 | = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ | ||||
972 | MultiLevelTemplateArgumentList &TemplateArgs | ||||
973 | = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); | ||||
974 | unsigned Depth, Index; | ||||
975 | std::tie(Depth, Index) = getDepthAndIndex(PartialPack); | ||||
976 | if (TemplateArgs.hasTemplateArgument(Depth, Index)) { | ||||
977 | Result = TemplateArgs(Depth, Index); | ||||
978 | TemplateArgs.setArgument(Depth, Index, TemplateArgument()); | ||||
979 | } | ||||
980 | } | ||||
981 | |||||
982 | return Result; | ||||
983 | } | ||||
984 | |||||
985 | void RememberPartiallySubstitutedPack(TemplateArgument Arg) { | ||||
986 | if (Arg.isNull()) | ||||
987 | return; | ||||
988 | |||||
989 | if (NamedDecl *PartialPack | ||||
990 | = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ | ||||
991 | MultiLevelTemplateArgumentList &TemplateArgs | ||||
992 | = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); | ||||
993 | unsigned Depth, Index; | ||||
994 | std::tie(Depth, Index) = getDepthAndIndex(PartialPack); | ||||
995 | TemplateArgs.setArgument(Depth, Index, Arg); | ||||
996 | } | ||||
997 | } | ||||
998 | |||||
999 | /// Transform the given declaration by instantiating a reference to | ||||
1000 | /// this declaration. | ||||
1001 | Decl *TransformDecl(SourceLocation Loc, Decl *D); | ||||
1002 | |||||
1003 | void transformAttrs(Decl *Old, Decl *New) { | ||||
1004 | SemaRef.InstantiateAttrs(TemplateArgs, Old, New); | ||||
1005 | } | ||||
1006 | |||||
1007 | void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) { | ||||
1008 | if (Old->isParameterPack()) { | ||||
1009 | SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old); | ||||
1010 | for (auto *New : NewDecls) | ||||
1011 | SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg( | ||||
1012 | Old, cast<VarDecl>(New)); | ||||
1013 | return; | ||||
1014 | } | ||||
1015 | |||||
1016 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1017, __PRETTY_FUNCTION__)) | ||||
1017 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1017, __PRETTY_FUNCTION__)); | ||||
1018 | Decl *New = NewDecls.front(); | ||||
1019 | |||||
1020 | // If we've instantiated the call operator of a lambda or the call | ||||
1021 | // operator template of a generic lambda, update the "instantiation of" | ||||
1022 | // information. | ||||
1023 | auto *NewMD = dyn_cast<CXXMethodDecl>(New); | ||||
1024 | if (NewMD && isLambdaCallOperator(NewMD)) { | ||||
1025 | auto *OldMD = dyn_cast<CXXMethodDecl>(Old); | ||||
1026 | if (auto *NewTD = NewMD->getDescribedFunctionTemplate()) | ||||
1027 | NewTD->setInstantiatedFromMemberTemplate( | ||||
1028 | OldMD->getDescribedFunctionTemplate()); | ||||
1029 | else | ||||
1030 | NewMD->setInstantiationOfMemberFunction(OldMD, | ||||
1031 | TSK_ImplicitInstantiation); | ||||
1032 | } | ||||
1033 | |||||
1034 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New); | ||||
1035 | |||||
1036 | // We recreated a local declaration, but not by instantiating it. There | ||||
1037 | // may be pending dependent diagnostics to produce. | ||||
1038 | if (auto *DC = dyn_cast<DeclContext>(Old)) | ||||
1039 | SemaRef.PerformDependentDiagnostics(DC, TemplateArgs); | ||||
1040 | } | ||||
1041 | |||||
1042 | /// Transform the definition of the given declaration by | ||||
1043 | /// instantiating it. | ||||
1044 | Decl *TransformDefinition(SourceLocation Loc, Decl *D); | ||||
1045 | |||||
1046 | /// Transform the first qualifier within a scope by instantiating the | ||||
1047 | /// declaration. | ||||
1048 | NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc); | ||||
1049 | |||||
1050 | /// Rebuild the exception declaration and register the declaration | ||||
1051 | /// as an instantiated local. | ||||
1052 | VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, | ||||
1053 | TypeSourceInfo *Declarator, | ||||
1054 | SourceLocation StartLoc, | ||||
1055 | SourceLocation NameLoc, | ||||
1056 | IdentifierInfo *Name); | ||||
1057 | |||||
1058 | /// Rebuild the Objective-C exception declaration and register the | ||||
1059 | /// declaration as an instantiated local. | ||||
1060 | VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, | ||||
1061 | TypeSourceInfo *TSInfo, QualType T); | ||||
1062 | |||||
1063 | /// Check for tag mismatches when instantiating an | ||||
1064 | /// elaborated type. | ||||
1065 | QualType RebuildElaboratedType(SourceLocation KeywordLoc, | ||||
1066 | ElaboratedTypeKeyword Keyword, | ||||
1067 | NestedNameSpecifierLoc QualifierLoc, | ||||
1068 | QualType T); | ||||
1069 | |||||
1070 | TemplateName | ||||
1071 | TransformTemplateName(CXXScopeSpec &SS, TemplateName Name, | ||||
1072 | SourceLocation NameLoc, | ||||
1073 | QualType ObjectType = QualType(), | ||||
1074 | NamedDecl *FirstQualifierInScope = nullptr, | ||||
1075 | bool AllowInjectedClassName = false); | ||||
1076 | |||||
1077 | const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH); | ||||
1078 | |||||
1079 | ExprResult TransformPredefinedExpr(PredefinedExpr *E); | ||||
1080 | ExprResult TransformDeclRefExpr(DeclRefExpr *E); | ||||
1081 | ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E); | ||||
1082 | |||||
1083 | ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E, | ||||
1084 | NonTypeTemplateParmDecl *D); | ||||
1085 | ExprResult TransformSubstNonTypeTemplateParmPackExpr( | ||||
1086 | SubstNonTypeTemplateParmPackExpr *E); | ||||
1087 | ExprResult TransformSubstNonTypeTemplateParmExpr( | ||||
1088 | SubstNonTypeTemplateParmExpr *E); | ||||
1089 | |||||
1090 | /// Rebuild a DeclRefExpr for a VarDecl reference. | ||||
1091 | ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc); | ||||
1092 | |||||
1093 | /// Transform a reference to a function or init-capture parameter pack. | ||||
1094 | ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD); | ||||
1095 | |||||
1096 | /// Transform a FunctionParmPackExpr which was built when we couldn't | ||||
1097 | /// expand a function parameter pack reference which refers to an expanded | ||||
1098 | /// pack. | ||||
1099 | ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E); | ||||
1100 | |||||
1101 | QualType TransformFunctionProtoType(TypeLocBuilder &TLB, | ||||
1102 | FunctionProtoTypeLoc TL) { | ||||
1103 | // Call the base version; it will forward to our overridden version below. | ||||
1104 | return inherited::TransformFunctionProtoType(TLB, TL); | ||||
1105 | } | ||||
1106 | |||||
1107 | template<typename Fn> | ||||
1108 | QualType TransformFunctionProtoType(TypeLocBuilder &TLB, | ||||
1109 | FunctionProtoTypeLoc TL, | ||||
1110 | CXXRecordDecl *ThisContext, | ||||
1111 | Qualifiers ThisTypeQuals, | ||||
1112 | Fn TransformExceptionSpec); | ||||
1113 | |||||
1114 | ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm, | ||||
1115 | int indexAdjustment, | ||||
1116 | Optional<unsigned> NumExpansions, | ||||
1117 | bool ExpectParameterPack); | ||||
1118 | |||||
1119 | /// Transforms a template type parameter type by performing | ||||
1120 | /// substitution of the corresponding template type argument. | ||||
1121 | QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, | ||||
1122 | TemplateTypeParmTypeLoc TL); | ||||
1123 | |||||
1124 | /// Transforms an already-substituted template type parameter pack | ||||
1125 | /// into either itself (if we aren't substituting into its pack expansion) | ||||
1126 | /// or the appropriate substituted argument. | ||||
1127 | QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB, | ||||
1128 | SubstTemplateTypeParmPackTypeLoc TL); | ||||
1129 | |||||
1130 | ExprResult TransformLambdaExpr(LambdaExpr *E) { | ||||
1131 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); | ||||
1132 | return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E); | ||||
1133 | } | ||||
1134 | |||||
1135 | ExprResult TransformRequiresExpr(RequiresExpr *E) { | ||||
1136 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); | ||||
1137 | return TreeTransform<TemplateInstantiator>::TransformRequiresExpr(E); | ||||
1138 | } | ||||
1139 | |||||
1140 | bool TransformRequiresExprRequirements( | ||||
1141 | ArrayRef<concepts::Requirement *> Reqs, | ||||
1142 | SmallVectorImpl<concepts::Requirement *> &Transformed) { | ||||
1143 | bool SatisfactionDetermined = false; | ||||
1144 | for (concepts::Requirement *Req : Reqs) { | ||||
1145 | concepts::Requirement *TransReq = nullptr; | ||||
1146 | if (!SatisfactionDetermined) { | ||||
1147 | if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req)) | ||||
1148 | TransReq = TransformTypeRequirement(TypeReq); | ||||
1149 | else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req)) | ||||
1150 | TransReq = TransformExprRequirement(ExprReq); | ||||
1151 | else | ||||
1152 | TransReq = TransformNestedRequirement( | ||||
1153 | cast<concepts::NestedRequirement>(Req)); | ||||
1154 | if (!TransReq) | ||||
1155 | return true; | ||||
1156 | if (!TransReq->isDependent() && !TransReq->isSatisfied()) | ||||
1157 | // [expr.prim.req]p6 | ||||
1158 | // [...] The substitution and semantic constraint checking | ||||
1159 | // proceeds in lexical order and stops when a condition that | ||||
1160 | // determines the result of the requires-expression is | ||||
1161 | // encountered. [..] | ||||
1162 | SatisfactionDetermined = true; | ||||
1163 | } else | ||||
1164 | TransReq = Req; | ||||
1165 | Transformed.push_back(TransReq); | ||||
1166 | } | ||||
1167 | return false; | ||||
1168 | } | ||||
1169 | |||||
1170 | TemplateParameterList *TransformTemplateParameterList( | ||||
1171 | TemplateParameterList *OrigTPL) { | ||||
1172 | if (!OrigTPL || !OrigTPL->size()) return OrigTPL; | ||||
1173 | |||||
1174 | DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext(); | ||||
1175 | TemplateDeclInstantiator DeclInstantiator(getSema(), | ||||
1176 | /* DeclContext *Owner */ Owner, TemplateArgs); | ||||
1177 | return DeclInstantiator.SubstTemplateParams(OrigTPL); | ||||
1178 | } | ||||
1179 | |||||
1180 | concepts::TypeRequirement * | ||||
1181 | TransformTypeRequirement(concepts::TypeRequirement *Req); | ||||
1182 | concepts::ExprRequirement * | ||||
1183 | TransformExprRequirement(concepts::ExprRequirement *Req); | ||||
1184 | concepts::NestedRequirement * | ||||
1185 | TransformNestedRequirement(concepts::NestedRequirement *Req); | ||||
1186 | |||||
1187 | private: | ||||
1188 | ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm, | ||||
1189 | SourceLocation loc, | ||||
1190 | TemplateArgument arg); | ||||
1191 | }; | ||||
1192 | } | ||||
1193 | |||||
1194 | bool TemplateInstantiator::AlreadyTransformed(QualType T) { | ||||
1195 | if (T.isNull()) | ||||
1196 | return true; | ||||
1197 | |||||
1198 | if (T->isInstantiationDependentType() || T->isVariablyModifiedType()) | ||||
1199 | return false; | ||||
1200 | |||||
1201 | getSema().MarkDeclarationsReferencedInType(Loc, T); | ||||
1202 | return true; | ||||
1203 | } | ||||
1204 | |||||
1205 | static TemplateArgument | ||||
1206 | getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) { | ||||
1207 | assert(S.ArgumentPackSubstitutionIndex >= 0)((S.ArgumentPackSubstitutionIndex >= 0) ? static_cast<void > (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex >= 0" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1207, __PRETTY_FUNCTION__)); | ||||
1208 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1208, __PRETTY_FUNCTION__)); | ||||
1209 | Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex]; | ||||
1210 | if (Arg.isPackExpansion()) | ||||
1211 | Arg = Arg.getPackExpansionPattern(); | ||||
1212 | return Arg; | ||||
1213 | } | ||||
1214 | |||||
1215 | Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) { | ||||
1216 | if (!D) | ||||
1217 | return nullptr; | ||||
1218 | |||||
1219 | if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) { | ||||
1220 | if (TTP->getDepth() < TemplateArgs.getNumLevels()) { | ||||
1221 | // If the corresponding template argument is NULL or non-existent, it's | ||||
1222 | // because we are performing instantiation from explicitly-specified | ||||
1223 | // template arguments in a function template, but there were some | ||||
1224 | // arguments left unspecified. | ||||
1225 | if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), | ||||
1226 | TTP->getPosition())) | ||||
1227 | return D; | ||||
1228 | |||||
1229 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); | ||||
1230 | |||||
1231 | if (TTP->isParameterPack()) { | ||||
1232 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1233, __PRETTY_FUNCTION__)) | ||||
1233 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1233, __PRETTY_FUNCTION__)); | ||||
1234 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); | ||||
1235 | } | ||||
1236 | |||||
1237 | TemplateName Template = Arg.getAsTemplate().getNameToSubstitute(); | ||||
1238 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1239, __PRETTY_FUNCTION__)) | ||||
1239 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1239, __PRETTY_FUNCTION__)); | ||||
1240 | return Template.getAsTemplateDecl(); | ||||
1241 | } | ||||
1242 | |||||
1243 | // Fall through to find the instantiated declaration for this template | ||||
1244 | // template parameter. | ||||
1245 | } | ||||
1246 | |||||
1247 | return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs); | ||||
1248 | } | ||||
1249 | |||||
1250 | Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) { | ||||
1251 | Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs); | ||||
1252 | if (!Inst) | ||||
1253 | return nullptr; | ||||
1254 | |||||
1255 | getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst); | ||||
1256 | return Inst; | ||||
1257 | } | ||||
1258 | |||||
1259 | NamedDecl * | ||||
1260 | TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, | ||||
1261 | SourceLocation Loc) { | ||||
1262 | // If the first part of the nested-name-specifier was a template type | ||||
1263 | // parameter, instantiate that type parameter down to a tag type. | ||||
1264 | if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) { | ||||
1265 | const TemplateTypeParmType *TTP | ||||
1266 | = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD)); | ||||
1267 | |||||
1268 | if (TTP->getDepth() < TemplateArgs.getNumLevels()) { | ||||
1269 | // FIXME: This needs testing w/ member access expressions. | ||||
1270 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex()); | ||||
1271 | |||||
1272 | if (TTP->isParameterPack()) { | ||||
1273 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1274, __PRETTY_FUNCTION__)) | ||||
1274 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1274, __PRETTY_FUNCTION__)); | ||||
1275 | |||||
1276 | if (getSema().ArgumentPackSubstitutionIndex == -1) | ||||
1277 | return nullptr; | ||||
1278 | |||||
1279 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); | ||||
1280 | } | ||||
1281 | |||||
1282 | QualType T = Arg.getAsType(); | ||||
1283 | if (T.isNull()) | ||||
1284 | return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); | ||||
1285 | |||||
1286 | if (const TagType *Tag = T->getAs<TagType>()) | ||||
1287 | return Tag->getDecl(); | ||||
1288 | |||||
1289 | // The resulting type is not a tag; complain. | ||||
1290 | getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T; | ||||
1291 | return nullptr; | ||||
1292 | } | ||||
1293 | } | ||||
1294 | |||||
1295 | return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); | ||||
1296 | } | ||||
1297 | |||||
1298 | VarDecl * | ||||
1299 | TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, | ||||
1300 | TypeSourceInfo *Declarator, | ||||
1301 | SourceLocation StartLoc, | ||||
1302 | SourceLocation NameLoc, | ||||
1303 | IdentifierInfo *Name) { | ||||
1304 | VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator, | ||||
1305 | StartLoc, NameLoc, Name); | ||||
1306 | if (Var) | ||||
1307 | getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); | ||||
1308 | return Var; | ||||
1309 | } | ||||
1310 | |||||
1311 | VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, | ||||
1312 | TypeSourceInfo *TSInfo, | ||||
1313 | QualType T) { | ||||
1314 | VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T); | ||||
1315 | if (Var) | ||||
1316 | getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); | ||||
1317 | return Var; | ||||
1318 | } | ||||
1319 | |||||
1320 | QualType | ||||
1321 | TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc, | ||||
1322 | ElaboratedTypeKeyword Keyword, | ||||
1323 | NestedNameSpecifierLoc QualifierLoc, | ||||
1324 | QualType T) { | ||||
1325 | if (const TagType *TT = T->getAs<TagType>()) { | ||||
1326 | TagDecl* TD = TT->getDecl(); | ||||
1327 | |||||
1328 | SourceLocation TagLocation = KeywordLoc; | ||||
1329 | |||||
1330 | IdentifierInfo *Id = TD->getIdentifier(); | ||||
1331 | |||||
1332 | // TODO: should we even warn on struct/class mismatches for this? Seems | ||||
1333 | // like it's likely to produce a lot of spurious errors. | ||||
1334 | if (Id && Keyword != ETK_None && Keyword != ETK_Typename) { | ||||
1335 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword); | ||||
1336 | if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false, | ||||
1337 | TagLocation, Id)) { | ||||
1338 | SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag) | ||||
1339 | << Id | ||||
1340 | << FixItHint::CreateReplacement(SourceRange(TagLocation), | ||||
1341 | TD->getKindName()); | ||||
1342 | SemaRef.Diag(TD->getLocation(), diag::note_previous_use); | ||||
1343 | } | ||||
1344 | } | ||||
1345 | } | ||||
1346 | |||||
1347 | return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc, | ||||
1348 | Keyword, | ||||
1349 | QualifierLoc, | ||||
1350 | T); | ||||
1351 | } | ||||
1352 | |||||
1353 | TemplateName TemplateInstantiator::TransformTemplateName( | ||||
1354 | CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc, | ||||
1355 | QualType ObjectType, NamedDecl *FirstQualifierInScope, | ||||
1356 | bool AllowInjectedClassName) { | ||||
1357 | if (TemplateTemplateParmDecl *TTP | ||||
1358 | = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) { | ||||
1359 | if (TTP->getDepth() < TemplateArgs.getNumLevels()) { | ||||
1360 | // If the corresponding template argument is NULL or non-existent, it's | ||||
1361 | // because we are performing instantiation from explicitly-specified | ||||
1362 | // template arguments in a function template, but there were some | ||||
1363 | // arguments left unspecified. | ||||
1364 | if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), | ||||
1365 | TTP->getPosition())) | ||||
1366 | return Name; | ||||
1367 | |||||
1368 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); | ||||
1369 | |||||
1370 | if (TemplateArgs.isRewrite()) { | ||||
1371 | // We're rewriting the template parameter as a reference to another | ||||
1372 | // template parameter. | ||||
1373 | if (Arg.getKind() == TemplateArgument::Pack) { | ||||
1374 | assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion () && "unexpected pack arguments in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1375, __PRETTY_FUNCTION__)) | ||||
1375 | "unexpected pack arguments in template rewrite")((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion () && "unexpected pack arguments in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1375, __PRETTY_FUNCTION__)); | ||||
1376 | Arg = Arg.pack_begin()->getPackExpansionPattern(); | ||||
1377 | } | ||||
1378 | assert(Arg.getKind() == TemplateArgument::Template &&((Arg.getKind() == TemplateArgument::Template && "unexpected nontype template argument kind in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Template && \"unexpected nontype template argument kind in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1379, __PRETTY_FUNCTION__)) | ||||
1379 | "unexpected nontype template argument kind in template rewrite")((Arg.getKind() == TemplateArgument::Template && "unexpected nontype template argument kind in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Template && \"unexpected nontype template argument kind in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1379, __PRETTY_FUNCTION__)); | ||||
1380 | return Arg.getAsTemplate(); | ||||
1381 | } | ||||
1382 | |||||
1383 | if (TTP->isParameterPack()) { | ||||
1384 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1385, __PRETTY_FUNCTION__)) | ||||
1385 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1385, __PRETTY_FUNCTION__)); | ||||
1386 | |||||
1387 | if (getSema().ArgumentPackSubstitutionIndex == -1) { | ||||
1388 | // We have the template argument pack to substitute, but we're not | ||||
1389 | // actually expanding the enclosing pack expansion yet. So, just | ||||
1390 | // keep the entire argument pack. | ||||
1391 | return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg); | ||||
1392 | } | ||||
1393 | |||||
1394 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); | ||||
1395 | } | ||||
1396 | |||||
1397 | TemplateName Template = Arg.getAsTemplate().getNameToSubstitute(); | ||||
1398 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1398, __PRETTY_FUNCTION__)); | ||||
1399 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1400, __PRETTY_FUNCTION__)) | ||||
1400 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1400, __PRETTY_FUNCTION__)); | ||||
1401 | |||||
1402 | Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template); | ||||
1403 | return Template; | ||||
1404 | } | ||||
1405 | } | ||||
1406 | |||||
1407 | if (SubstTemplateTemplateParmPackStorage *SubstPack | ||||
1408 | = Name.getAsSubstTemplateTemplateParmPack()) { | ||||
1409 | if (getSema().ArgumentPackSubstitutionIndex == -1) | ||||
1410 | return Name; | ||||
1411 | |||||
1412 | TemplateArgument Arg = SubstPack->getArgumentPack(); | ||||
1413 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); | ||||
1414 | return Arg.getAsTemplate().getNameToSubstitute(); | ||||
1415 | } | ||||
1416 | |||||
1417 | return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType, | ||||
1418 | FirstQualifierInScope, | ||||
1419 | AllowInjectedClassName); | ||||
1420 | } | ||||
1421 | |||||
1422 | ExprResult | ||||
1423 | TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) { | ||||
1424 | if (!E->isTypeDependent()) | ||||
1425 | return E; | ||||
1426 | |||||
1427 | return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind()); | ||||
1428 | } | ||||
1429 | |||||
1430 | ExprResult | ||||
1431 | TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, | ||||
1432 | NonTypeTemplateParmDecl *NTTP) { | ||||
1433 | // If the corresponding template argument is NULL or non-existent, it's | ||||
1434 | // because we are performing instantiation from explicitly-specified | ||||
1435 | // template arguments in a function template, but there were some | ||||
1436 | // arguments left unspecified. | ||||
1437 | if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(), | ||||
1438 | NTTP->getPosition())) | ||||
1439 | return E; | ||||
1440 | |||||
1441 | TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition()); | ||||
1442 | |||||
1443 | if (TemplateArgs.isRewrite()) { | ||||
1444 | // We're rewriting the template parameter as a reference to another | ||||
1445 | // template parameter. | ||||
1446 | if (Arg.getKind() == TemplateArgument::Pack) { | ||||
1447 | assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion () && "unexpected pack arguments in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1448, __PRETTY_FUNCTION__)) | ||||
1448 | "unexpected pack arguments in template rewrite")((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion () && "unexpected pack arguments in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1448, __PRETTY_FUNCTION__)); | ||||
1449 | Arg = Arg.pack_begin()->getPackExpansionPattern(); | ||||
1450 | } | ||||
1451 | assert(Arg.getKind() == TemplateArgument::Expression &&((Arg.getKind() == TemplateArgument::Expression && "unexpected nontype template argument kind in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1452, __PRETTY_FUNCTION__)) | ||||
1452 | "unexpected nontype template argument kind in template rewrite")((Arg.getKind() == TemplateArgument::Expression && "unexpected nontype template argument kind in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1452, __PRETTY_FUNCTION__)); | ||||
1453 | // FIXME: This can lead to the same subexpression appearing multiple times | ||||
1454 | // in a complete expression. | ||||
1455 | return Arg.getAsExpr(); | ||||
1456 | } | ||||
1457 | |||||
1458 | if (NTTP->isParameterPack()) { | ||||
1459 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1460, __PRETTY_FUNCTION__)) | ||||
1460 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1460, __PRETTY_FUNCTION__)); | ||||
1461 | |||||
1462 | if (getSema().ArgumentPackSubstitutionIndex == -1) { | ||||
1463 | // We have an argument pack, but we can't select a particular argument | ||||
1464 | // out of it yet. Therefore, we'll build an expression to hold on to that | ||||
1465 | // argument pack. | ||||
1466 | QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs, | ||||
1467 | E->getLocation(), | ||||
1468 | NTTP->getDeclName()); | ||||
1469 | if (TargetType.isNull()) | ||||
1470 | return ExprError(); | ||||
1471 | |||||
1472 | QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context); | ||||
1473 | if (TargetType->isRecordType()) | ||||
1474 | ExprType.addConst(); | ||||
1475 | |||||
1476 | return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr( | ||||
1477 | ExprType, TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP, | ||||
1478 | E->getLocation(), Arg); | ||||
1479 | } | ||||
1480 | |||||
1481 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); | ||||
1482 | } | ||||
1483 | |||||
1484 | return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg); | ||||
1485 | } | ||||
1486 | |||||
1487 | const LoopHintAttr * | ||||
1488 | TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) { | ||||
1489 | Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get(); | ||||
1490 | |||||
1491 | if (TransformedExpr == LH->getValue()) | ||||
1492 | return LH; | ||||
1493 | |||||
1494 | // Generate error if there is a problem with the value. | ||||
1495 | if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation())) | ||||
1496 | return LH; | ||||
1497 | |||||
1498 | // Create new LoopHintValueAttr with integral expression in place of the | ||||
1499 | // non-type template parameter. | ||||
1500 | return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(), | ||||
1501 | LH->getState(), TransformedExpr, *LH); | ||||
1502 | } | ||||
1503 | |||||
1504 | ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef( | ||||
1505 | NonTypeTemplateParmDecl *parm, | ||||
1506 | SourceLocation loc, | ||||
1507 | TemplateArgument arg) { | ||||
1508 | ExprResult result; | ||||
1509 | |||||
1510 | // Determine the substituted parameter type. We can usually infer this from | ||||
1511 | // the template argument, but not always. | ||||
1512 | auto SubstParamType = [&] { | ||||
1513 | QualType T; | ||||
1514 | if (parm->isExpandedParameterPack()) | ||||
1515 | T = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex); | ||||
1516 | else | ||||
1517 | T = parm->getType(); | ||||
1518 | if (parm->isParameterPack() && isa<PackExpansionType>(T)) | ||||
1519 | T = cast<PackExpansionType>(T)->getPattern(); | ||||
1520 | return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName()); | ||||
1521 | }; | ||||
1522 | |||||
1523 | bool refParam = false; | ||||
1524 | |||||
1525 | // The template argument itself might be an expression, in which case we just | ||||
1526 | // return that expression. This happens when substituting into an alias | ||||
1527 | // template. | ||||
1528 | if (arg.getKind() == TemplateArgument::Expression) { | ||||
1529 | Expr *argExpr = arg.getAsExpr(); | ||||
1530 | result = argExpr; | ||||
1531 | if (argExpr->isLValue()) { | ||||
1532 | if (argExpr->getType()->isRecordType()) { | ||||
1533 | // Check whether the parameter was actually a reference. | ||||
1534 | QualType paramType = SubstParamType(); | ||||
1535 | if (paramType.isNull()) | ||||
1536 | return ExprError(); | ||||
1537 | refParam = paramType->isReferenceType(); | ||||
1538 | } else { | ||||
1539 | refParam = true; | ||||
1540 | } | ||||
1541 | } | ||||
1542 | } else if (arg.getKind() == TemplateArgument::Declaration || | ||||
1543 | arg.getKind() == TemplateArgument::NullPtr) { | ||||
1544 | ValueDecl *VD; | ||||
1545 | if (arg.getKind() == TemplateArgument::Declaration) { | ||||
1546 | VD = arg.getAsDecl(); | ||||
1547 | |||||
1548 | // Find the instantiation of the template argument. This is | ||||
1549 | // required for nested templates. | ||||
1550 | VD = cast_or_null<ValueDecl>( | ||||
1551 | getSema().FindInstantiatedDecl(loc, VD, TemplateArgs)); | ||||
1552 | if (!VD) | ||||
1553 | return ExprError(); | ||||
1554 | } else { | ||||
1555 | // Propagate NULL template argument. | ||||
1556 | VD = nullptr; | ||||
1557 | } | ||||
1558 | |||||
1559 | QualType paramType = VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(); | ||||
1560 | assert(!paramType.isNull() && "type substitution failed for param type")((!paramType.isNull() && "type substitution failed for param type" ) ? static_cast<void> (0) : __assert_fail ("!paramType.isNull() && \"type substitution failed for param type\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1560, __PRETTY_FUNCTION__)); | ||||
1561 | assert(!paramType->isDependentType() && "param type still dependent")((!paramType->isDependentType() && "param type still dependent" ) ? static_cast<void> (0) : __assert_fail ("!paramType->isDependentType() && \"param type still dependent\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1561, __PRETTY_FUNCTION__)); | ||||
1562 | result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc); | ||||
1563 | refParam = paramType->isReferenceType(); | ||||
1564 | } else { | ||||
1565 | result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc); | ||||
1566 | assert(result.isInvalid() ||((result.isInvalid() || SemaRef.Context.hasSameType(result.get ()->getType(), arg.getIntegralType())) ? static_cast<void > (0) : __assert_fail ("result.isInvalid() || SemaRef.Context.hasSameType(result.get()->getType(), arg.getIntegralType())" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1568, __PRETTY_FUNCTION__)) | ||||
1567 | SemaRef.Context.hasSameType(result.get()->getType(),((result.isInvalid() || SemaRef.Context.hasSameType(result.get ()->getType(), arg.getIntegralType())) ? static_cast<void > (0) : __assert_fail ("result.isInvalid() || SemaRef.Context.hasSameType(result.get()->getType(), arg.getIntegralType())" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1568, __PRETTY_FUNCTION__)) | ||||
1568 | arg.getIntegralType()))((result.isInvalid() || SemaRef.Context.hasSameType(result.get ()->getType(), arg.getIntegralType())) ? static_cast<void > (0) : __assert_fail ("result.isInvalid() || SemaRef.Context.hasSameType(result.get()->getType(), arg.getIntegralType())" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1568, __PRETTY_FUNCTION__)); | ||||
1569 | } | ||||
1570 | |||||
1571 | if (result.isInvalid()) | ||||
1572 | return ExprError(); | ||||
1573 | |||||
1574 | Expr *resultExpr = result.get(); | ||||
1575 | return new (SemaRef.Context) SubstNonTypeTemplateParmExpr( | ||||
1576 | resultExpr->getType(), resultExpr->getValueKind(), loc, parm, refParam, | ||||
1577 | resultExpr); | ||||
1578 | } | ||||
1579 | |||||
1580 | ExprResult | ||||
1581 | TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr( | ||||
1582 | SubstNonTypeTemplateParmPackExpr *E) { | ||||
1583 | if (getSema().ArgumentPackSubstitutionIndex == -1) { | ||||
1584 | // We aren't expanding the parameter pack, so just return ourselves. | ||||
1585 | return E; | ||||
1586 | } | ||||
1587 | |||||
1588 | TemplateArgument Arg = E->getArgumentPack(); | ||||
1589 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); | ||||
1590 | return transformNonTypeTemplateParmRef(E->getParameterPack(), | ||||
1591 | E->getParameterPackLocation(), | ||||
1592 | Arg); | ||||
1593 | } | ||||
1594 | |||||
1595 | ExprResult | ||||
1596 | TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr( | ||||
1597 | SubstNonTypeTemplateParmExpr *E) { | ||||
1598 | ExprResult SubstReplacement = E->getReplacement(); | ||||
1599 | if (!isa<ConstantExpr>(SubstReplacement.get())) | ||||
1600 | SubstReplacement = TransformExpr(E->getReplacement()); | ||||
1601 | if (SubstReplacement.isInvalid()) | ||||
1602 | return true; | ||||
1603 | QualType SubstType = TransformType(E->getParameterType(getSema().Context)); | ||||
1604 | if (SubstType.isNull()) | ||||
1605 | return true; | ||||
1606 | // The type may have been previously dependent and not now, which means we | ||||
1607 | // might have to implicit cast the argument to the new type, for example: | ||||
1608 | // template<auto T, decltype(T) U> | ||||
1609 | // concept C = sizeof(U) == 4; | ||||
1610 | // void foo() requires C<2, 'a'> { } | ||||
1611 | // When normalizing foo(), we first form the normalized constraints of C: | ||||
1612 | // AtomicExpr(sizeof(U) == 4, | ||||
1613 | // U=SubstNonTypeTemplateParmExpr(Param=U, | ||||
1614 | // Expr=DeclRef(U), | ||||
1615 | // Type=decltype(T))) | ||||
1616 | // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to | ||||
1617 | // produce: | ||||
1618 | // AtomicExpr(sizeof(U) == 4, | ||||
1619 | // U=SubstNonTypeTemplateParmExpr(Param=U, | ||||
1620 | // Expr=ImpCast( | ||||
1621 | // decltype(2), | ||||
1622 | // SubstNTTPE(Param=U, Expr='a', | ||||
1623 | // Type=char)), | ||||
1624 | // Type=decltype(2))) | ||||
1625 | // The call to CheckTemplateArgument here produces the ImpCast. | ||||
1626 | TemplateArgument Converted; | ||||
1627 | if (SemaRef.CheckTemplateArgument(E->getParameter(), SubstType, | ||||
1628 | SubstReplacement.get(), | ||||
1629 | Converted).isInvalid()) | ||||
1630 | return true; | ||||
1631 | return transformNonTypeTemplateParmRef(E->getParameter(), | ||||
1632 | E->getExprLoc(), Converted); | ||||
1633 | } | ||||
1634 | |||||
1635 | ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD, | ||||
1636 | SourceLocation Loc) { | ||||
1637 | DeclarationNameInfo NameInfo(PD->getDeclName(), Loc); | ||||
1638 | return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD); | ||||
1639 | } | ||||
1640 | |||||
1641 | ExprResult | ||||
1642 | TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) { | ||||
1643 | if (getSema().ArgumentPackSubstitutionIndex != -1) { | ||||
1644 | // We can expand this parameter pack now. | ||||
1645 | VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex); | ||||
1646 | VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D)); | ||||
1647 | if (!VD) | ||||
1648 | return ExprError(); | ||||
1649 | return RebuildVarDeclRefExpr(VD, E->getExprLoc()); | ||||
1650 | } | ||||
1651 | |||||
1652 | QualType T = TransformType(E->getType()); | ||||
1653 | if (T.isNull()) | ||||
1654 | return ExprError(); | ||||
1655 | |||||
1656 | // Transform each of the parameter expansions into the corresponding | ||||
1657 | // parameters in the instantiation of the function decl. | ||||
1658 | SmallVector<VarDecl *, 8> Vars; | ||||
1659 | Vars.reserve(E->getNumExpansions()); | ||||
1660 | for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end(); | ||||
1661 | I != End; ++I) { | ||||
1662 | VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I)); | ||||
1663 | if (!D) | ||||
1664 | return ExprError(); | ||||
1665 | Vars.push_back(D); | ||||
1666 | } | ||||
1667 | |||||
1668 | auto *PackExpr = | ||||
1669 | FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(), | ||||
1670 | E->getParameterPackLocation(), Vars); | ||||
1671 | getSema().MarkFunctionParmPackReferenced(PackExpr); | ||||
1672 | return PackExpr; | ||||
1673 | } | ||||
1674 | |||||
1675 | ExprResult | ||||
1676 | TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E, | ||||
1677 | VarDecl *PD) { | ||||
1678 | typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; | ||||
1679 | llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found | ||||
1680 | = getSema().CurrentInstantiationScope->findInstantiationOf(PD); | ||||
1681 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1681, __PRETTY_FUNCTION__)); | ||||
1682 | |||||
1683 | Decl *TransformedDecl; | ||||
1684 | if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) { | ||||
1685 | // If this is a reference to a function parameter pack which we can | ||||
1686 | // substitute but can't yet expand, build a FunctionParmPackExpr for it. | ||||
1687 | if (getSema().ArgumentPackSubstitutionIndex == -1) { | ||||
1688 | QualType T = TransformType(E->getType()); | ||||
1689 | if (T.isNull()) | ||||
1690 | return ExprError(); | ||||
1691 | auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD, | ||||
1692 | E->getExprLoc(), *Pack); | ||||
1693 | getSema().MarkFunctionParmPackReferenced(PackExpr); | ||||
1694 | return PackExpr; | ||||
1695 | } | ||||
1696 | |||||
1697 | TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex]; | ||||
1698 | } else { | ||||
1699 | TransformedDecl = Found->get<Decl*>(); | ||||
1700 | } | ||||
1701 | |||||
1702 | // We have either an unexpanded pack or a specific expansion. | ||||
1703 | return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc()); | ||||
1704 | } | ||||
1705 | |||||
1706 | ExprResult | ||||
1707 | TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { | ||||
1708 | NamedDecl *D = E->getDecl(); | ||||
1709 | |||||
1710 | // Handle references to non-type template parameters and non-type template | ||||
1711 | // parameter packs. | ||||
1712 | if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) { | ||||
1713 | if (NTTP->getDepth() < TemplateArgs.getNumLevels()) | ||||
1714 | return TransformTemplateParmRefExpr(E, NTTP); | ||||
1715 | |||||
1716 | // We have a non-type template parameter that isn't fully substituted; | ||||
1717 | // FindInstantiatedDecl will find it in the local instantiation scope. | ||||
1718 | } | ||||
1719 | |||||
1720 | // Handle references to function parameter packs. | ||||
1721 | if (VarDecl *PD = dyn_cast<VarDecl>(D)) | ||||
1722 | if (PD->isParameterPack()) | ||||
1723 | return TransformFunctionParmPackRefExpr(E, PD); | ||||
1724 | |||||
1725 | return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E); | ||||
1726 | } | ||||
1727 | |||||
1728 | ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr( | ||||
1729 | CXXDefaultArgExpr *E) { | ||||
1730 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1732, __PRETTY_FUNCTION__)) | ||||
1731 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1732, __PRETTY_FUNCTION__)) | ||||
1732 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1732, __PRETTY_FUNCTION__)); | ||||
1733 | return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(), | ||||
1734 | cast<FunctionDecl>(E->getParam()->getDeclContext()), | ||||
1735 | E->getParam()); | ||||
1736 | } | ||||
1737 | |||||
1738 | template<typename Fn> | ||||
1739 | QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB, | ||||
1740 | FunctionProtoTypeLoc TL, | ||||
1741 | CXXRecordDecl *ThisContext, | ||||
1742 | Qualifiers ThisTypeQuals, | ||||
1743 | Fn TransformExceptionSpec) { | ||||
1744 | // We need a local instantiation scope for this function prototype. | ||||
1745 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); | ||||
1746 | return inherited::TransformFunctionProtoType( | ||||
1747 | TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec); | ||||
1748 | } | ||||
1749 | |||||
1750 | ParmVarDecl * | ||||
1751 | TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm, | ||||
1752 | int indexAdjustment, | ||||
1753 | Optional<unsigned> NumExpansions, | ||||
1754 | bool ExpectParameterPack) { | ||||
1755 | auto NewParm = | ||||
1756 | SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment, | ||||
1757 | NumExpansions, ExpectParameterPack); | ||||
1758 | if (NewParm && SemaRef.getLangOpts().OpenCL) | ||||
1759 | SemaRef.deduceOpenCLAddressSpace(NewParm); | ||||
1760 | return NewParm; | ||||
1761 | } | ||||
1762 | |||||
1763 | QualType | ||||
1764 | TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, | ||||
1765 | TemplateTypeParmTypeLoc TL) { | ||||
1766 | const TemplateTypeParmType *T = TL.getTypePtr(); | ||||
1767 | if (T->getDepth() < TemplateArgs.getNumLevels()) { | ||||
1768 | // Replace the template type parameter with its corresponding | ||||
1769 | // template argument. | ||||
1770 | |||||
1771 | // If the corresponding template argument is NULL or doesn't exist, it's | ||||
1772 | // because we are performing instantiation from explicitly-specified | ||||
1773 | // template arguments in a function template class, but there were some | ||||
1774 | // arguments left unspecified. | ||||
1775 | if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) { | ||||
1776 | TemplateTypeParmTypeLoc NewTL | ||||
1777 | = TLB.push<TemplateTypeParmTypeLoc>(TL.getType()); | ||||
1778 | NewTL.setNameLoc(TL.getNameLoc()); | ||||
1779 | return TL.getType(); | ||||
1780 | } | ||||
1781 | |||||
1782 | TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex()); | ||||
1783 | |||||
1784 | if (TemplateArgs.isRewrite()) { | ||||
1785 | // We're rewriting the template parameter as a reference to another | ||||
1786 | // template parameter. | ||||
1787 | if (Arg.getKind() == TemplateArgument::Pack) { | ||||
1788 | assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion () && "unexpected pack arguments in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1789, __PRETTY_FUNCTION__)) | ||||
1789 | "unexpected pack arguments in template rewrite")((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion () && "unexpected pack arguments in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1789, __PRETTY_FUNCTION__)); | ||||
1790 | Arg = Arg.pack_begin()->getPackExpansionPattern(); | ||||
1791 | } | ||||
1792 | assert(Arg.getKind() == TemplateArgument::Type &&((Arg.getKind() == TemplateArgument::Type && "unexpected nontype template argument kind in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"unexpected nontype template argument kind in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1793, __PRETTY_FUNCTION__)) | ||||
1793 | "unexpected nontype template argument kind in template rewrite")((Arg.getKind() == TemplateArgument::Type && "unexpected nontype template argument kind in template rewrite" ) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"unexpected nontype template argument kind in template rewrite\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1793, __PRETTY_FUNCTION__)); | ||||
1794 | QualType NewT = Arg.getAsType(); | ||||
1795 | assert(isa<TemplateTypeParmType>(NewT) &&((isa<TemplateTypeParmType>(NewT) && "type parm not rewritten to type parm" ) ? static_cast<void> (0) : __assert_fail ("isa<TemplateTypeParmType>(NewT) && \"type parm not rewritten to type parm\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1796, __PRETTY_FUNCTION__)) | ||||
1796 | "type parm not rewritten to type parm")((isa<TemplateTypeParmType>(NewT) && "type parm not rewritten to type parm" ) ? static_cast<void> (0) : __assert_fail ("isa<TemplateTypeParmType>(NewT) && \"type parm not rewritten to type parm\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1796, __PRETTY_FUNCTION__)); | ||||
1797 | auto NewTL = TLB.push<TemplateTypeParmTypeLoc>(NewT); | ||||
1798 | NewTL.setNameLoc(TL.getNameLoc()); | ||||
1799 | return NewT; | ||||
1800 | } | ||||
1801 | |||||
1802 | if (T->isParameterPack()) { | ||||
1803 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1804, __PRETTY_FUNCTION__)) | ||||
1804 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1804, __PRETTY_FUNCTION__)); | ||||
1805 | |||||
1806 | if (getSema().ArgumentPackSubstitutionIndex == -1) { | ||||
1807 | // We have the template argument pack, but we're not expanding the | ||||
1808 | // enclosing pack expansion yet. Just save the template argument | ||||
1809 | // pack for later substitution. | ||||
1810 | QualType Result | ||||
1811 | = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg); | ||||
1812 | SubstTemplateTypeParmPackTypeLoc NewTL | ||||
1813 | = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result); | ||||
1814 | NewTL.setNameLoc(TL.getNameLoc()); | ||||
1815 | return Result; | ||||
1816 | } | ||||
1817 | |||||
1818 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); | ||||
1819 | } | ||||
1820 | |||||
1821 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1822, __PRETTY_FUNCTION__)) | ||||
1822 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1822, __PRETTY_FUNCTION__)); | ||||
1823 | |||||
1824 | QualType Replacement = Arg.getAsType(); | ||||
1825 | |||||
1826 | // TODO: only do this uniquing once, at the start of instantiation. | ||||
1827 | QualType Result | ||||
1828 | = getSema().Context.getSubstTemplateTypeParmType(T, Replacement); | ||||
1829 | SubstTemplateTypeParmTypeLoc NewTL | ||||
1830 | = TLB.push<SubstTemplateTypeParmTypeLoc>(Result); | ||||
1831 | NewTL.setNameLoc(TL.getNameLoc()); | ||||
1832 | return Result; | ||||
1833 | } | ||||
1834 | |||||
1835 | // The template type parameter comes from an inner template (e.g., | ||||
1836 | // the template parameter list of a member template inside the | ||||
1837 | // template we are instantiating). Create a new template type | ||||
1838 | // parameter with the template "level" reduced by one. | ||||
1839 | TemplateTypeParmDecl *NewTTPDecl = nullptr; | ||||
1840 | if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl()) | ||||
1841 | NewTTPDecl = cast_or_null<TemplateTypeParmDecl>( | ||||
1842 | TransformDecl(TL.getNameLoc(), OldTTPDecl)); | ||||
1843 | |||||
1844 | QualType Result = getSema().Context.getTemplateTypeParmType( | ||||
1845 | T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(), | ||||
1846 | T->isParameterPack(), NewTTPDecl); | ||||
1847 | TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result); | ||||
1848 | NewTL.setNameLoc(TL.getNameLoc()); | ||||
1849 | return Result; | ||||
1850 | } | ||||
1851 | |||||
1852 | QualType | ||||
1853 | TemplateInstantiator::TransformSubstTemplateTypeParmPackType( | ||||
1854 | TypeLocBuilder &TLB, | ||||
1855 | SubstTemplateTypeParmPackTypeLoc TL) { | ||||
1856 | if (getSema().ArgumentPackSubstitutionIndex == -1) { | ||||
1857 | // We aren't expanding the parameter pack, so just return ourselves. | ||||
1858 | SubstTemplateTypeParmPackTypeLoc NewTL | ||||
1859 | = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType()); | ||||
1860 | NewTL.setNameLoc(TL.getNameLoc()); | ||||
1861 | return TL.getType(); | ||||
1862 | } | ||||
1863 | |||||
1864 | TemplateArgument Arg = TL.getTypePtr()->getArgumentPack(); | ||||
1865 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); | ||||
1866 | QualType Result = Arg.getAsType(); | ||||
1867 | |||||
1868 | Result = getSema().Context.getSubstTemplateTypeParmType( | ||||
1869 | TL.getTypePtr()->getReplacedParameter(), | ||||
1870 | Result); | ||||
1871 | SubstTemplateTypeParmTypeLoc NewTL | ||||
1872 | = TLB.push<SubstTemplateTypeParmTypeLoc>(Result); | ||||
1873 | NewTL.setNameLoc(TL.getNameLoc()); | ||||
1874 | return Result; | ||||
1875 | } | ||||
1876 | |||||
1877 | template<typename EntityPrinter> | ||||
1878 | static concepts::Requirement::SubstitutionDiagnostic * | ||||
1879 | createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) { | ||||
1880 | SmallString<128> Message; | ||||
1881 | SourceLocation ErrorLoc; | ||||
1882 | if (Info.hasSFINAEDiagnostic()) { | ||||
1883 | PartialDiagnosticAt PDA(SourceLocation(), | ||||
1884 | PartialDiagnostic::NullDiagnostic{}); | ||||
1885 | Info.takeSFINAEDiagnostic(PDA); | ||||
1886 | PDA.second.EmitToString(S.getDiagnostics(), Message); | ||||
1887 | ErrorLoc = PDA.first; | ||||
1888 | } else { | ||||
1889 | ErrorLoc = Info.getLocation(); | ||||
1890 | } | ||||
1891 | char *MessageBuf = new (S.Context) char[Message.size()]; | ||||
1892 | std::copy(Message.begin(), Message.end(), MessageBuf); | ||||
1893 | SmallString<128> Entity; | ||||
1894 | llvm::raw_svector_ostream OS(Entity); | ||||
1895 | Printer(OS); | ||||
1896 | char *EntityBuf = new (S.Context) char[Entity.size()]; | ||||
1897 | std::copy(Entity.begin(), Entity.end(), EntityBuf); | ||||
1898 | return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{ | ||||
1899 | StringRef(EntityBuf, Entity.size()), ErrorLoc, | ||||
1900 | StringRef(MessageBuf, Message.size())}; | ||||
1901 | } | ||||
1902 | |||||
1903 | concepts::TypeRequirement * | ||||
1904 | TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) { | ||||
1905 | if (!Req->isDependent() && !AlwaysRebuild()) | ||||
1906 | return Req; | ||||
1907 | if (Req->isSubstitutionFailure()) { | ||||
1908 | if (AlwaysRebuild()) | ||||
1909 | return RebuildTypeRequirement( | ||||
1910 | Req->getSubstitutionDiagnostic()); | ||||
1911 | return Req; | ||||
1912 | } | ||||
1913 | |||||
1914 | Sema::SFINAETrap Trap(SemaRef); | ||||
1915 | TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc()); | ||||
1916 | Sema::InstantiatingTemplate TypeInst(SemaRef, | ||||
1917 | Req->getType()->getTypeLoc().getBeginLoc(), Req, Info, | ||||
1918 | Req->getType()->getTypeLoc().getSourceRange()); | ||||
1919 | if (TypeInst.isInvalid()) | ||||
1920 | return nullptr; | ||||
1921 | TypeSourceInfo *TransType = TransformType(Req->getType()); | ||||
1922 | if (!TransType || Trap.hasErrorOccurred()) | ||||
1923 | return RebuildTypeRequirement(createSubstDiag(SemaRef, Info, | ||||
1924 | [&] (llvm::raw_ostream& OS) { | ||||
1925 | Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy()); | ||||
1926 | })); | ||||
1927 | return RebuildTypeRequirement(TransType); | ||||
1928 | } | ||||
1929 | |||||
1930 | concepts::ExprRequirement * | ||||
1931 | TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) { | ||||
1932 | if (!Req->isDependent() && !AlwaysRebuild()) | ||||
1933 | return Req; | ||||
1934 | |||||
1935 | Sema::SFINAETrap Trap(SemaRef); | ||||
1936 | TemplateDeductionInfo Info(Req->getExpr()->getBeginLoc()); | ||||
1937 | |||||
1938 | llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> | ||||
1939 | TransExpr; | ||||
1940 | if (Req->isExprSubstitutionFailure()) | ||||
1941 | TransExpr = Req->getExprSubstitutionDiagnostic(); | ||||
1942 | else { | ||||
1943 | Sema::InstantiatingTemplate ExprInst(SemaRef, Req->getExpr()->getBeginLoc(), | ||||
1944 | Req, Info, | ||||
1945 | Req->getExpr()->getSourceRange()); | ||||
1946 | if (ExprInst.isInvalid()) | ||||
1947 | return nullptr; | ||||
1948 | ExprResult TransExprRes = TransformExpr(Req->getExpr()); | ||||
1949 | if (TransExprRes.isInvalid() || Trap.hasErrorOccurred()) | ||||
1950 | TransExpr = createSubstDiag(SemaRef, Info, | ||||
1951 | [&] (llvm::raw_ostream& OS) { | ||||
1952 | Req->getExpr()->printPretty(OS, nullptr, | ||||
1953 | SemaRef.getPrintingPolicy()); | ||||
1954 | }); | ||||
1955 | else | ||||
1956 | TransExpr = TransExprRes.get(); | ||||
1957 | } | ||||
1958 | |||||
1959 | llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq; | ||||
1960 | const auto &RetReq = Req->getReturnTypeRequirement(); | ||||
1961 | if (RetReq.isEmpty()) | ||||
1962 | TransRetReq.emplace(); | ||||
1963 | else if (RetReq.isSubstitutionFailure()) | ||||
1964 | TransRetReq.emplace(RetReq.getSubstitutionDiagnostic()); | ||||
1965 | else if (RetReq.isTypeConstraint()) { | ||||
1966 | TemplateParameterList *OrigTPL = | ||||
1967 | RetReq.getTypeConstraintTemplateParameterList(); | ||||
1968 | Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), | ||||
1969 | Req, Info, OrigTPL->getSourceRange()); | ||||
1970 | if (TPLInst.isInvalid()) | ||||
1971 | return nullptr; | ||||
1972 | TemplateParameterList *TPL = | ||||
1973 | TransformTemplateParameterList(OrigTPL); | ||||
1974 | if (!TPL) | ||||
1975 | TransRetReq.emplace(createSubstDiag(SemaRef, Info, | ||||
1976 | [&] (llvm::raw_ostream& OS) { | ||||
1977 | RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint() | ||||
1978 | ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy()); | ||||
1979 | })); | ||||
1980 | else { | ||||
1981 | TPLInst.Clear(); | ||||
1982 | TransRetReq.emplace(TPL); | ||||
1983 | } | ||||
1984 | } | ||||
1985 | assert(TransRetReq.hasValue() &&((TransRetReq.hasValue() && "All code paths leading here must set TransRetReq" ) ? static_cast<void> (0) : __assert_fail ("TransRetReq.hasValue() && \"All code paths leading here must set TransRetReq\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1986, __PRETTY_FUNCTION__)) | ||||
1986 | "All code paths leading here must set TransRetReq")((TransRetReq.hasValue() && "All code paths leading here must set TransRetReq" ) ? static_cast<void> (0) : __assert_fail ("TransRetReq.hasValue() && \"All code paths leading here must set TransRetReq\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 1986, __PRETTY_FUNCTION__)); | ||||
1987 | if (Expr *E = TransExpr.dyn_cast<Expr *>()) | ||||
1988 | return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(), | ||||
1989 | std::move(*TransRetReq)); | ||||
1990 | return RebuildExprRequirement( | ||||
1991 | TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(), | ||||
1992 | Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq)); | ||||
1993 | } | ||||
1994 | |||||
1995 | concepts::NestedRequirement * | ||||
1996 | TemplateInstantiator::TransformNestedRequirement( | ||||
1997 | concepts::NestedRequirement *Req) { | ||||
1998 | if (!Req->isDependent() && !AlwaysRebuild()) | ||||
1999 | return Req; | ||||
2000 | if (Req->isSubstitutionFailure()) { | ||||
2001 | if (AlwaysRebuild()) | ||||
2002 | return RebuildNestedRequirement( | ||||
2003 | Req->getSubstitutionDiagnostic()); | ||||
2004 | return Req; | ||||
2005 | } | ||||
2006 | Sema::InstantiatingTemplate ReqInst(SemaRef, | ||||
2007 | Req->getConstraintExpr()->getBeginLoc(), Req, | ||||
2008 | Sema::InstantiatingTemplate::ConstraintsCheck{}, | ||||
2009 | Req->getConstraintExpr()->getSourceRange()); | ||||
2010 | |||||
2011 | ExprResult TransConstraint; | ||||
2012 | TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc()); | ||||
2013 | { | ||||
2014 | EnterExpressionEvaluationContext ContextRAII( | ||||
2015 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); | ||||
2016 | Sema::SFINAETrap Trap(SemaRef); | ||||
2017 | Sema::InstantiatingTemplate ConstrInst(SemaRef, | ||||
2018 | Req->getConstraintExpr()->getBeginLoc(), Req, Info, | ||||
2019 | Req->getConstraintExpr()->getSourceRange()); | ||||
2020 | if (ConstrInst.isInvalid()) | ||||
2021 | return nullptr; | ||||
2022 | TransConstraint = TransformExpr(Req->getConstraintExpr()); | ||||
2023 | if (TransConstraint.isInvalid() || Trap.hasErrorOccurred()) | ||||
2024 | return RebuildNestedRequirement(createSubstDiag(SemaRef, Info, | ||||
2025 | [&] (llvm::raw_ostream& OS) { | ||||
2026 | Req->getConstraintExpr()->printPretty(OS, nullptr, | ||||
2027 | SemaRef.getPrintingPolicy()); | ||||
2028 | })); | ||||
2029 | } | ||||
2030 | return RebuildNestedRequirement(TransConstraint.get()); | ||||
2031 | } | ||||
2032 | |||||
2033 | |||||
2034 | /// Perform substitution on the type T with a given set of template | ||||
2035 | /// arguments. | ||||
2036 | /// | ||||
2037 | /// This routine substitutes the given template arguments into the | ||||
2038 | /// type T and produces the instantiated type. | ||||
2039 | /// | ||||
2040 | /// \param T the type into which the template arguments will be | ||||
2041 | /// substituted. If this type is not dependent, it will be returned | ||||
2042 | /// immediately. | ||||
2043 | /// | ||||
2044 | /// \param Args the template arguments that will be | ||||
2045 | /// substituted for the top-level template parameters within T. | ||||
2046 | /// | ||||
2047 | /// \param Loc the location in the source code where this substitution | ||||
2048 | /// is being performed. It will typically be the location of the | ||||
2049 | /// declarator (if we're instantiating the type of some declaration) | ||||
2050 | /// or the location of the type in the source code (if, e.g., we're | ||||
2051 | /// instantiating the type of a cast expression). | ||||
2052 | /// | ||||
2053 | /// \param Entity the name of the entity associated with a declaration | ||||
2054 | /// being instantiated (if any). May be empty to indicate that there | ||||
2055 | /// is no such entity (if, e.g., this is a type that occurs as part of | ||||
2056 | /// a cast expression) or that the entity has no name (e.g., an | ||||
2057 | /// unnamed function parameter). | ||||
2058 | /// | ||||
2059 | /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is | ||||
2060 | /// acceptable as the top level type of the result. | ||||
2061 | /// | ||||
2062 | /// \returns If the instantiation succeeds, the instantiated | ||||
2063 | /// type. Otherwise, produces diagnostics and returns a NULL type. | ||||
2064 | TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T, | ||||
2065 | const MultiLevelTemplateArgumentList &Args, | ||||
2066 | SourceLocation Loc, | ||||
2067 | DeclarationName Entity, | ||||
2068 | bool AllowDeducedTST) { | ||||
2069 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2071, __PRETTY_FUNCTION__)) | ||||
2070 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2071, __PRETTY_FUNCTION__)) | ||||
2071 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2071, __PRETTY_FUNCTION__)); | ||||
2072 | |||||
2073 | if (!T->getType()->isInstantiationDependentType() && | ||||
2074 | !T->getType()->isVariablyModifiedType()) | ||||
2075 | return T; | ||||
2076 | |||||
2077 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); | ||||
2078 | return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T) | ||||
2079 | : Instantiator.TransformType(T); | ||||
2080 | } | ||||
2081 | |||||
2082 | TypeSourceInfo *Sema::SubstType(TypeLoc TL, | ||||
2083 | const MultiLevelTemplateArgumentList &Args, | ||||
2084 | SourceLocation Loc, | ||||
2085 | DeclarationName Entity) { | ||||
2086 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2088, __PRETTY_FUNCTION__)) | ||||
2087 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2088, __PRETTY_FUNCTION__)) | ||||
2088 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2088, __PRETTY_FUNCTION__)); | ||||
2089 | |||||
2090 | if (TL.getType().isNull()) | ||||
2091 | return nullptr; | ||||
2092 | |||||
2093 | if (!TL.getType()->isInstantiationDependentType() && | ||||
2094 | !TL.getType()->isVariablyModifiedType()) { | ||||
2095 | // FIXME: Make a copy of the TypeLoc data here, so that we can | ||||
2096 | // return a new TypeSourceInfo. Inefficient! | ||||
2097 | TypeLocBuilder TLB; | ||||
2098 | TLB.pushFullCopy(TL); | ||||
2099 | return TLB.getTypeSourceInfo(Context, TL.getType()); | ||||
2100 | } | ||||
2101 | |||||
2102 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); | ||||
2103 | TypeLocBuilder TLB; | ||||
2104 | TLB.reserve(TL.getFullDataSize()); | ||||
2105 | QualType Result = Instantiator.TransformType(TLB, TL); | ||||
2106 | if (Result.isNull()) | ||||
2107 | return nullptr; | ||||
2108 | |||||
2109 | return TLB.getTypeSourceInfo(Context, Result); | ||||
2110 | } | ||||
2111 | |||||
2112 | /// Deprecated form of the above. | ||||
2113 | QualType Sema::SubstType(QualType T, | ||||
2114 | const MultiLevelTemplateArgumentList &TemplateArgs, | ||||
2115 | SourceLocation Loc, DeclarationName Entity) { | ||||
2116 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2118, __PRETTY_FUNCTION__)) | ||||
2117 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2118, __PRETTY_FUNCTION__)) | ||||
2118 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2118, __PRETTY_FUNCTION__)); | ||||
2119 | |||||
2120 | // If T is not a dependent type or a variably-modified type, there | ||||
2121 | // is nothing to do. | ||||
2122 | if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType()) | ||||
2123 | return T; | ||||
2124 | |||||
2125 | TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity); | ||||
2126 | return Instantiator.TransformType(T); | ||||
2127 | } | ||||
2128 | |||||
2129 | static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) { | ||||
2130 | if (T->getType()->isInstantiationDependentType() || | ||||
2131 | T->getType()->isVariablyModifiedType()) | ||||
2132 | return true; | ||||
2133 | |||||
2134 | TypeLoc TL = T->getTypeLoc().IgnoreParens(); | ||||
2135 | if (!TL.getAs<FunctionProtoTypeLoc>()) | ||||
2136 | return false; | ||||
2137 | |||||
2138 | FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>(); | ||||
2139 | for (ParmVarDecl *P : FP.getParams()) { | ||||
2140 | // This must be synthesized from a typedef. | ||||
2141 | if (!P) continue; | ||||
2142 | |||||
2143 | // If there are any parameters, a new TypeSourceInfo that refers to the | ||||
2144 | // instantiated parameters must be built. | ||||
2145 | return true; | ||||
2146 | } | ||||
2147 | |||||
2148 | return false; | ||||
2149 | } | ||||
2150 | |||||
2151 | /// A form of SubstType intended specifically for instantiating the | ||||
2152 | /// type of a FunctionDecl. Its purpose is solely to force the | ||||
2153 | /// instantiation of default-argument expressions and to avoid | ||||
2154 | /// instantiating an exception-specification. | ||||
2155 | TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T, | ||||
2156 | const MultiLevelTemplateArgumentList &Args, | ||||
2157 | SourceLocation Loc, | ||||
2158 | DeclarationName Entity, | ||||
2159 | CXXRecordDecl *ThisContext, | ||||
2160 | Qualifiers ThisTypeQuals) { | ||||
2161 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2163, __PRETTY_FUNCTION__)) | ||||
2162 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2163, __PRETTY_FUNCTION__)) | ||||
2163 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2163, __PRETTY_FUNCTION__)); | ||||
2164 | |||||
2165 | if (!NeedsInstantiationAsFunctionType(T)) | ||||
2166 | return T; | ||||
2167 | |||||
2168 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); | ||||
2169 | |||||
2170 | TypeLocBuilder TLB; | ||||
2171 | |||||
2172 | TypeLoc TL = T->getTypeLoc(); | ||||
2173 | TLB.reserve(TL.getFullDataSize()); | ||||
2174 | |||||
2175 | QualType Result; | ||||
2176 | |||||
2177 | if (FunctionProtoTypeLoc Proto = | ||||
2178 | TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) { | ||||
2179 | // Instantiate the type, other than its exception specification. The | ||||
2180 | // exception specification is instantiated in InitFunctionInstantiation | ||||
2181 | // once we've built the FunctionDecl. | ||||
2182 | // FIXME: Set the exception specification to EST_Uninstantiated here, | ||||
2183 | // instead of rebuilding the function type again later. | ||||
2184 | Result = Instantiator.TransformFunctionProtoType( | ||||
2185 | TLB, Proto, ThisContext, ThisTypeQuals, | ||||
2186 | [](FunctionProtoType::ExceptionSpecInfo &ESI, | ||||
2187 | bool &Changed) { return false; }); | ||||
2188 | } else { | ||||
2189 | Result = Instantiator.TransformType(TLB, TL); | ||||
2190 | } | ||||
2191 | if (Result.isNull()) | ||||
2192 | return nullptr; | ||||
2193 | |||||
2194 | return TLB.getTypeSourceInfo(Context, Result); | ||||
2195 | } | ||||
2196 | |||||
2197 | bool Sema::SubstExceptionSpec(SourceLocation Loc, | ||||
2198 | FunctionProtoType::ExceptionSpecInfo &ESI, | ||||
2199 | SmallVectorImpl<QualType> &ExceptionStorage, | ||||
2200 | const MultiLevelTemplateArgumentList &Args) { | ||||
2201 | assert(ESI.Type != EST_Uninstantiated)((ESI.Type != EST_Uninstantiated) ? static_cast<void> ( 0) : __assert_fail ("ESI.Type != EST_Uninstantiated", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2201, __PRETTY_FUNCTION__)); | ||||
2202 | |||||
2203 | bool Changed = false; | ||||
2204 | TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName()); | ||||
2205 | return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage, | ||||
2206 | Changed); | ||||
2207 | } | ||||
2208 | |||||
2209 | void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, | ||||
2210 | const MultiLevelTemplateArgumentList &Args) { | ||||
2211 | FunctionProtoType::ExceptionSpecInfo ESI = | ||||
2212 | Proto->getExtProtoInfo().ExceptionSpec; | ||||
2213 | |||||
2214 | SmallVector<QualType, 4> ExceptionStorage; | ||||
2215 | if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(), | ||||
2216 | ESI, ExceptionStorage, Args)) | ||||
2217 | // On error, recover by dropping the exception specification. | ||||
2218 | ESI.Type = EST_None; | ||||
2219 | |||||
2220 | UpdateExceptionSpec(New, ESI); | ||||
2221 | } | ||||
2222 | |||||
2223 | namespace { | ||||
2224 | |||||
2225 | struct GetContainedInventedTypeParmVisitor : | ||||
2226 | public TypeVisitor<GetContainedInventedTypeParmVisitor, | ||||
2227 | TemplateTypeParmDecl *> { | ||||
2228 | using TypeVisitor<GetContainedInventedTypeParmVisitor, | ||||
2229 | TemplateTypeParmDecl *>::Visit; | ||||
2230 | |||||
2231 | TemplateTypeParmDecl *Visit(QualType T) { | ||||
2232 | if (T.isNull()) | ||||
2233 | return nullptr; | ||||
2234 | return Visit(T.getTypePtr()); | ||||
2235 | } | ||||
2236 | // The deduced type itself. | ||||
2237 | TemplateTypeParmDecl *VisitTemplateTypeParmType( | ||||
2238 | const TemplateTypeParmType *T) { | ||||
2239 | if (!T->getDecl() || !T->getDecl()->isImplicit()) | ||||
2240 | return nullptr; | ||||
2241 | return T->getDecl(); | ||||
2242 | } | ||||
2243 | |||||
2244 | // Only these types can contain 'auto' types, and subsequently be replaced | ||||
2245 | // by references to invented parameters. | ||||
2246 | |||||
2247 | TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) { | ||||
2248 | return Visit(T->getNamedType()); | ||||
2249 | } | ||||
2250 | |||||
2251 | TemplateTypeParmDecl *VisitPointerType(const PointerType *T) { | ||||
2252 | return Visit(T->getPointeeType()); | ||||
2253 | } | ||||
2254 | |||||
2255 | TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) { | ||||
2256 | return Visit(T->getPointeeType()); | ||||
2257 | } | ||||
2258 | |||||
2259 | TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) { | ||||
2260 | return Visit(T->getPointeeTypeAsWritten()); | ||||
2261 | } | ||||
2262 | |||||
2263 | TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) { | ||||
2264 | return Visit(T->getPointeeType()); | ||||
2265 | } | ||||
2266 | |||||
2267 | TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) { | ||||
2268 | return Visit(T->getElementType()); | ||||
2269 | } | ||||
2270 | |||||
2271 | TemplateTypeParmDecl *VisitDependentSizedExtVectorType( | ||||
2272 | const DependentSizedExtVectorType *T) { | ||||
2273 | return Visit(T->getElementType()); | ||||
2274 | } | ||||
2275 | |||||
2276 | TemplateTypeParmDecl *VisitVectorType(const VectorType *T) { | ||||
2277 | return Visit(T->getElementType()); | ||||
2278 | } | ||||
2279 | |||||
2280 | TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) { | ||||
2281 | return VisitFunctionType(T); | ||||
2282 | } | ||||
2283 | |||||
2284 | TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) { | ||||
2285 | return Visit(T->getReturnType()); | ||||
2286 | } | ||||
2287 | |||||
2288 | TemplateTypeParmDecl *VisitParenType(const ParenType *T) { | ||||
2289 | return Visit(T->getInnerType()); | ||||
2290 | } | ||||
2291 | |||||
2292 | TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) { | ||||
2293 | return Visit(T->getModifiedType()); | ||||
2294 | } | ||||
2295 | |||||
2296 | TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) { | ||||
2297 | return Visit(T->getUnderlyingType()); | ||||
2298 | } | ||||
2299 | |||||
2300 | TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) { | ||||
2301 | return Visit(T->getOriginalType()); | ||||
2302 | } | ||||
2303 | |||||
2304 | TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) { | ||||
2305 | return Visit(T->getPattern()); | ||||
2306 | } | ||||
2307 | }; | ||||
2308 | |||||
2309 | } // namespace | ||||
2310 | |||||
2311 | ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, | ||||
2312 | const MultiLevelTemplateArgumentList &TemplateArgs, | ||||
2313 | int indexAdjustment, | ||||
2314 | Optional<unsigned> NumExpansions, | ||||
2315 | bool ExpectParameterPack) { | ||||
2316 | TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo(); | ||||
2317 | TypeSourceInfo *NewDI = nullptr; | ||||
2318 | |||||
2319 | TypeLoc OldTL = OldDI->getTypeLoc(); | ||||
2320 | if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) { | ||||
2321 | |||||
2322 | // We have a function parameter pack. Substitute into the pattern of the | ||||
2323 | // expansion. | ||||
2324 | NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs, | ||||
2325 | OldParm->getLocation(), OldParm->getDeclName()); | ||||
2326 | if (!NewDI) | ||||
2327 | return nullptr; | ||||
2328 | |||||
2329 | if (NewDI->getType()->containsUnexpandedParameterPack()) { | ||||
2330 | // We still have unexpanded parameter packs, which means that | ||||
2331 | // our function parameter is still a function parameter pack. | ||||
2332 | // Therefore, make its type a pack expansion type. | ||||
2333 | NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(), | ||||
2334 | NumExpansions); | ||||
2335 | } else if (ExpectParameterPack) { | ||||
2336 | // We expected to get a parameter pack but didn't (because the type | ||||
2337 | // itself is not a pack expansion type), so complain. This can occur when | ||||
2338 | // the substitution goes through an alias template that "loses" the | ||||
2339 | // pack expansion. | ||||
2340 | Diag(OldParm->getLocation(), | ||||
2341 | diag::err_function_parameter_pack_without_parameter_packs) | ||||
2342 | << NewDI->getType(); | ||||
2343 | return nullptr; | ||||
2344 | } | ||||
2345 | } else { | ||||
2346 | NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(), | ||||
2347 | OldParm->getDeclName()); | ||||
2348 | } | ||||
2349 | |||||
2350 | if (!NewDI) | ||||
2351 | return nullptr; | ||||
2352 | |||||
2353 | if (NewDI->getType()->isVoidType()) { | ||||
2354 | Diag(OldParm->getLocation(), diag::err_param_with_void_type); | ||||
2355 | return nullptr; | ||||
2356 | } | ||||
2357 | |||||
2358 | // In abbreviated templates, TemplateTypeParmDecls with possible | ||||
2359 | // TypeConstraints are created when the parameter list is originally parsed. | ||||
2360 | // The TypeConstraints can therefore reference other functions parameters in | ||||
2361 | // the abbreviated function template, which is why we must instantiate them | ||||
2362 | // here, when the instantiated versions of those referenced parameters are in | ||||
2363 | // scope. | ||||
2364 | if (TemplateTypeParmDecl *TTP = | ||||
2365 | GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) { | ||||
2366 | if (const TypeConstraint *TC = TTP->getTypeConstraint()) { | ||||
2367 | auto *Inst = cast_or_null<TemplateTypeParmDecl>( | ||||
2368 | FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs)); | ||||
2369 | // We will first get here when instantiating the abbreviated function | ||||
2370 | // template's described function, but we might also get here later. | ||||
2371 | // Make sure we do not instantiate the TypeConstraint more than once. | ||||
2372 | if (Inst && !Inst->getTypeConstraint()) { | ||||
2373 | // TODO: Concepts: do not instantiate the constraint (delayed constraint | ||||
2374 | // substitution) | ||||
2375 | const ASTTemplateArgumentListInfo *TemplArgInfo | ||||
2376 | = TC->getTemplateArgsAsWritten(); | ||||
2377 | TemplateArgumentListInfo InstArgs; | ||||
2378 | |||||
2379 | if (TemplArgInfo) { | ||||
2380 | InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc); | ||||
2381 | InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc); | ||||
2382 | if (Subst(TemplArgInfo->getTemplateArgs(), | ||||
2383 | TemplArgInfo->NumTemplateArgs, InstArgs, TemplateArgs)) | ||||
2384 | return nullptr; | ||||
2385 | } | ||||
2386 | if (AttachTypeConstraint( | ||||
2387 | TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(), | ||||
2388 | TC->getNamedConcept(), &InstArgs, Inst, | ||||
2389 | TTP->isParameterPack() | ||||
2390 | ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint()) | ||||
2391 | ->getEllipsisLoc() | ||||
2392 | : SourceLocation())) | ||||
2393 | return nullptr; | ||||
2394 | } | ||||
2395 | } | ||||
2396 | } | ||||
2397 | |||||
2398 | ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(), | ||||
2399 | OldParm->getInnerLocStart(), | ||||
2400 | OldParm->getLocation(), | ||||
2401 | OldParm->getIdentifier(), | ||||
2402 | NewDI->getType(), NewDI, | ||||
2403 | OldParm->getStorageClass()); | ||||
2404 | if (!NewParm) | ||||
2405 | return nullptr; | ||||
2406 | |||||
2407 | // Mark the (new) default argument as uninstantiated (if any). | ||||
2408 | if (OldParm->hasUninstantiatedDefaultArg()) { | ||||
2409 | Expr *Arg = OldParm->getUninstantiatedDefaultArg(); | ||||
2410 | NewParm->setUninstantiatedDefaultArg(Arg); | ||||
2411 | } else if (OldParm->hasUnparsedDefaultArg()) { | ||||
2412 | NewParm->setUnparsedDefaultArg(); | ||||
2413 | UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm); | ||||
2414 | } else if (Expr *Arg = OldParm->getDefaultArg()) { | ||||
2415 | FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext()); | ||||
2416 | if (OwningFunc->isInLocalScopeForInstantiation()) { | ||||
2417 | // Instantiate default arguments for methods of local classes (DR1484) | ||||
2418 | // and non-defining declarations. | ||||
2419 | Sema::ContextRAII SavedContext(*this, OwningFunc); | ||||
2420 | LocalInstantiationScope Local(*this, true); | ||||
2421 | ExprResult NewArg = SubstExpr(Arg, TemplateArgs); | ||||
2422 | if (NewArg.isUsable()) { | ||||
2423 | // It would be nice if we still had this. | ||||
2424 | SourceLocation EqualLoc = NewArg.get()->getBeginLoc(); | ||||
2425 | ExprResult Result = | ||||
2426 | ConvertParamDefaultArgument(NewParm, NewArg.get(), EqualLoc); | ||||
2427 | if (Result.isInvalid()) | ||||
2428 | return nullptr; | ||||
2429 | |||||
2430 | SetParamDefaultArgument(NewParm, Result.getAs<Expr>(), EqualLoc); | ||||
2431 | } | ||||
2432 | } else { | ||||
2433 | // FIXME: if we non-lazily instantiated non-dependent default args for | ||||
2434 | // non-dependent parameter types we could remove a bunch of duplicate | ||||
2435 | // conversion warnings for such arguments. | ||||
2436 | NewParm->setUninstantiatedDefaultArg(Arg); | ||||
2437 | } | ||||
2438 | } | ||||
2439 | |||||
2440 | NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg()); | ||||
2441 | |||||
2442 | if (OldParm->isParameterPack() && !NewParm->isParameterPack()) { | ||||
2443 | // Add the new parameter to the instantiated parameter pack. | ||||
2444 | CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm); | ||||
2445 | } else { | ||||
2446 | // Introduce an Old -> New mapping | ||||
2447 | CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm); | ||||
2448 | } | ||||
2449 | |||||
2450 | // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext | ||||
2451 | // can be anything, is this right ? | ||||
2452 | NewParm->setDeclContext(CurContext); | ||||
2453 | |||||
2454 | NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(), | ||||
2455 | OldParm->getFunctionScopeIndex() + indexAdjustment); | ||||
2456 | |||||
2457 | InstantiateAttrs(TemplateArgs, OldParm, NewParm); | ||||
2458 | |||||
2459 | return NewParm; | ||||
2460 | } | ||||
2461 | |||||
2462 | /// Substitute the given template arguments into the given set of | ||||
2463 | /// parameters, producing the set of parameter types that would be generated | ||||
2464 | /// from such a substitution. | ||||
2465 | bool Sema::SubstParmTypes( | ||||
2466 | SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, | ||||
2467 | const FunctionProtoType::ExtParameterInfo *ExtParamInfos, | ||||
2468 | const MultiLevelTemplateArgumentList &TemplateArgs, | ||||
2469 | SmallVectorImpl<QualType> &ParamTypes, | ||||
2470 | SmallVectorImpl<ParmVarDecl *> *OutParams, | ||||
2471 | ExtParameterInfoBuilder &ParamInfos) { | ||||
2472 | 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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2474, __PRETTY_FUNCTION__)) | ||||
2473 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2474, __PRETTY_FUNCTION__)) | ||||
2474 | "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-13~++20210223111116+16ede0956cb1/clang/lib/Sema/SemaTemplateInstantiate.cpp" , 2474, __PRETTY_FUNCTION__)); | ||||
2475 | |||||
2476 | TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, | ||||
2477 | DeclarationName()); | ||||
2478 | return Instantiator.TransformFunctionTypeParams( | ||||
2479 | Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos); | ||||
2480 | } | ||||
2481 | |||||
2482 | /// Perform substitution on the base class specifiers of the | ||||
2483 | /// given class template specialization. | ||||
2484 | /// | ||||
2485 | /// Produces a diagnostic and returns true on error, returns false and | ||||
2486 | /// attaches the instantiated base classes to the class template | ||||
2487 | /// specialization if successful. | ||||
2488 | bool | ||||
2489 | Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, | ||||
2490 | CXXRecordDecl *Pattern, | ||||
2491 | const MultiLevelTemplateArgumentList &TemplateArgs) { | ||||
2492 | bool Invalid = false; | ||||
2493 | SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; | ||||
2494 | for (const auto &Base : Pattern->bases()) { | ||||
2495 | if (!Base.getType()->isDependentType()) { | ||||
2496 | if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) { | ||||
2497 | if (RD->isInvalidDecl()) | ||||
2498 | Instantiation->setInvalidDecl(); | ||||
2499 | } | ||||
2500 | InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base)); | ||||
2501 | continue; | ||||
2502 | } | ||||
2503 | |||||
2504 | SourceLocation EllipsisLoc; | ||||
2505 | TypeSourceInfo *BaseTypeLoc; | ||||
2506 | if (Base.isPackExpansion()) { | ||||
2507 | // This is a pack expansion. See whether we should expand it now, or | ||||
2508 | // wait until later. | ||||
2509 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; | ||||
2510 | collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(), | ||||
2511 | Unexpanded); | ||||
2512 | bool ShouldExpand = false; | ||||
2513 | bool RetainExpansion = false; | ||||
2514 | Optional<unsigned> NumExpansions; | ||||
2515 | if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(), | ||||
2516 | Base.getSourceRange(), | ||||
2517 | Unexpanded, | ||||
2518 | TemplateArgs, ShouldExpand, | ||||
2519 | RetainExpansion, | ||||
2520 | NumExpansions)) { | ||||
2521 | Invalid = true; | ||||
2522 | continue; | ||||
2523 | } | ||||
2524 | |||||
2525 | // If we should expand this pack expansion now, do so. | ||||
2526 | if (ShouldExpand) { | ||||
2527 | for (unsigned I = 0; I != *NumExpansions; ++I) { | ||||
2528 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); | ||||
2529 | |||||
2530 | TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(), | ||||
2531 | TemplateArgs, | ||||
2532 | Base.getSourceRange().getBegin(), | ||||
2533 | DeclarationName()); | ||||
2534 | if (!BaseTypeLoc) { | ||||
2535 | Invalid = true; | ||||
2536 | continue; | ||||
2537 | } | ||||
2538 | |||||
2539 | if (CXXBaseSpecifier *InstantiatedBase | ||||
2540 | = CheckBaseSpecifier(Instantiation, | ||||
2541 | Base.getSourceRange(), | ||||
2542 | Base.isVirtual(), | ||||
2543 | Base.getAccessSpecifierAsWritten(), | ||||
2544 | BaseTypeLoc, | ||||
2545 | SourceLocation())) | ||||
2546 | InstantiatedBases.push_back(InstantiatedBase); | ||||
2547 | else | ||||
2548 | Invalid = true; | ||||
2549 | } | ||||
2550 | |||||
2551 | continue; | ||||
2552 | } | ||||
2553 | |||||
2554 | // The resulting base specifier will (still) be a pack expansion. | ||||
2555 | EllipsisLoc = Base.getEllipsisLoc(); | ||||
2556 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); | ||||
2557 | BaseTypeLoc = SubstType(Base.getTypeSourceInfo(), | ||||
2558 | TemplateArgs, | ||||
2559 | Base.getSourceRange().getBegin(), | ||||
2560 | DeclarationName()); | ||||
2561 | } else { | ||||
2562 | BaseTypeLoc = SubstType(Base.getTypeSourceInfo(), | ||||
2563 | TemplateArgs, | ||||
2564 | Base.getSourceRange().getBegin(), | ||||
2565 | DeclarationName()); | ||||
2566 | } | ||||
2567 | |||||
2568 | if (!BaseTypeLoc) { | ||||
2569 | Invalid = true; | ||||
2570 | continue; | ||||
2571 | } | ||||
2572 | |||||
2573 | if (CXXBaseSpecifier *InstantiatedBase | ||||
2574 | = CheckBaseSpecifier(Instantiation, | ||||
2575 | Base.getSourceRange(), | ||||
2576 | Base.isVirtual(), | ||||
2577 | Base.getAccessSpecifierAsWritten(), | ||||
2578 | BaseTypeLoc, | ||||
2579 | EllipsisLoc)) | ||||
2580 | InstantiatedBases.push_back(InstantiatedBase); | ||||
2581 | else | ||||
2582 | Invalid = true; | ||||
2583 | } | ||||
2584 | |||||
2585 | if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases)) | ||||
2586 | Invalid = true; | ||||
2587 | |||||
2588 | return Invalid; | ||||
2589 | } | ||||
2590 | |||||
2591 | // Defined via #include from SemaTemplateInstantiateDecl.cpp | ||||
2592 | namespace clang { | ||||
2593 | namespace sema { | ||||
2594 | Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, | ||||
2595 | const MultiLevelTemplateArgumentList &TemplateArgs); | ||||
2596 | Attr *instantiateTemplateAttributeForDecl( | ||||
2597 | const Attr *At, ASTContext &C, Sema &S, | ||||
2598 | const MultiLevelTemplateArgumentList &TemplateArgs); | ||||
2599 | } | ||||
2600 | } | ||||
2601 | |||||
2602 | /// Instantiate the definition of a class from a given pattern. | ||||
2603 | /// | ||||
2604 | /// \param PointOfInstantiation The point of instantiation within the | ||||
2605 | /// source code. | ||||
2606 | /// | ||||
2607 | /// \param Instantiation is the declaration whose definition is being | ||||
2608 | /// instantiated. This will be either a class template specialization | ||||
2609 | /// or a member class of a class template specialization. | ||||
2610 | /// | ||||
2611 | /// \param Pattern is the pattern from which the instantiation | ||||
2612 | /// occurs. This will be either the declaration of a class template or | ||||
2613 | /// the declaration of a member class of a class template. | ||||
2614 | /// | ||||
2615 | /// \param TemplateArgs The template arguments to be substituted into | ||||
2616 | /// the pattern. | ||||
2617 | /// | ||||
2618 | /// \param TSK the kind of implicit or explicit instantiation to perform. | ||||
2619 | /// | ||||
2620 | /// \param Complain whether to complain if the class cannot be instantiated due | ||||
2621 | /// to the lack of a definition. | ||||
2622 | /// | ||||
2623 | /// \returns true if an error occurred, false otherwise. | ||||
2624 | bool | ||||
2625 | Sema::InstantiateClass(SourceLocation PointOfInstantiation, | ||||
2626 | CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, | ||||
2627 | const MultiLevelTemplateArgumentList &TemplateArgs, | ||||
2628 | TemplateSpecializationKind TSK, | ||||
2629 | bool Complain) { | ||||
2630 | CXXRecordDecl *PatternDef | ||||
2631 | = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); | ||||
2632 | if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation, | ||||
2633 | Instantiation->getInstantiatedFromMemberClass(), | ||||
2634 | Pattern, PatternDef, TSK, Complain)) | ||||
2635 | return true; | ||||
2636 | |||||
2637 | llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() { | ||||
2638 | std::string Name; | ||||
2639 | llvm::raw_string_ostream OS(Name); | ||||
2640 | Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(), | ||||
2641 | /*Qualified=*/true); | ||||
2642 | return Name; | ||||
2643 | }); | ||||
2644 | |||||
2645 | Pattern = PatternDef; | ||||
2646 | |||||
2647 | // Record the point of instantiation. | ||||
2648 | if (MemberSpecializationInfo *MSInfo | ||||
2649 | = Instantiation->getMemberSpecializationInfo()) { | ||||
2650 | MSInfo->setTemplateSpecializationKind(TSK); | ||||
2651 | MSInfo->setPointOfInstantiation(PointOfInstantiation); | ||||
2652 | } else if (ClassTemplateSpecializationDecl *Spec
|
32.1 | 'Spec' is null |
63 | Called C++ object pointer is null |
1 | Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDefinition |
5.1 | 'Function' is null |
5.1 | 'Function' is null |
7.1 | 'Var' is null |
7.1 | 'Var' is null |
9.1 | 'Record' is non-null |
9.1 | 'Record' is non-null |
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/ASTConcept.h" |
18 | #include "clang/AST/ASTFwd.h" |
19 | #include "clang/AST/Attr.h" |
20 | #include "clang/AST/Availability.h" |
21 | #include "clang/AST/ComparisonCategories.h" |
22 | #include "clang/AST/DeclTemplate.h" |
23 | #include "clang/AST/DeclarationName.h" |
24 | #include "clang/AST/Expr.h" |
25 | #include "clang/AST/ExprCXX.h" |
26 | #include "clang/AST/ExprConcepts.h" |
27 | #include "clang/AST/ExprObjC.h" |
28 | #include "clang/AST/ExprOpenMP.h" |
29 | #include "clang/AST/ExternalASTSource.h" |
30 | #include "clang/AST/LocInfoType.h" |
31 | #include "clang/AST/MangleNumberingContext.h" |
32 | #include "clang/AST/NSAPI.h" |
33 | #include "clang/AST/PrettyPrinter.h" |
34 | #include "clang/AST/StmtCXX.h" |
35 | #include "clang/AST/TypeLoc.h" |
36 | #include "clang/AST/TypeOrdering.h" |
37 | #include "clang/Basic/BitmaskEnum.h" |
38 | #include "clang/Basic/ExpressionTraits.h" |
39 | #include "clang/Basic/Module.h" |
40 | #include "clang/Basic/OpenCLOptions.h" |
41 | #include "clang/Basic/OpenMPKinds.h" |
42 | #include "clang/Basic/PragmaKinds.h" |
43 | #include "clang/Basic/Specifiers.h" |
44 | #include "clang/Basic/TemplateKinds.h" |
45 | #include "clang/Basic/TypeTraits.h" |
46 | #include "clang/Sema/AnalysisBasedWarnings.h" |
47 | #include "clang/Sema/CleanupInfo.h" |
48 | #include "clang/Sema/DeclSpec.h" |
49 | #include "clang/Sema/ExternalSemaSource.h" |
50 | #include "clang/Sema/IdentifierResolver.h" |
51 | #include "clang/Sema/ObjCMethodList.h" |
52 | #include "clang/Sema/Ownership.h" |
53 | #include "clang/Sema/Scope.h" |
54 | #include "clang/Sema/SemaConcept.h" |
55 | #include "clang/Sema/TypoCorrection.h" |
56 | #include "clang/Sema/Weak.h" |
57 | #include "llvm/ADT/ArrayRef.h" |
58 | #include "llvm/ADT/Optional.h" |
59 | #include "llvm/ADT/SetVector.h" |
60 | #include "llvm/ADT/SmallBitVector.h" |
61 | #include "llvm/ADT/SmallPtrSet.h" |
62 | #include "llvm/ADT/SmallSet.h" |
63 | #include "llvm/ADT/SmallVector.h" |
64 | #include "llvm/ADT/TinyPtrVector.h" |
65 | #include "llvm/Frontend/OpenMP/OMPConstants.h" |
66 | #include <deque> |
67 | #include <memory> |
68 | #include <string> |
69 | #include <tuple> |
70 | #include <vector> |
71 | |
72 | namespace llvm { |
73 | class APSInt; |
74 | template <typename ValueT> struct DenseMapInfo; |
75 | template <typename ValueT, typename ValueInfoT> class DenseSet; |
76 | class SmallBitVector; |
77 | struct InlineAsmIdentifierInfo; |
78 | } |
79 | |
80 | namespace clang { |
81 | class ADLResult; |
82 | class ASTConsumer; |
83 | class ASTContext; |
84 | class ASTMutationListener; |
85 | class ASTReader; |
86 | class ASTWriter; |
87 | class ArrayType; |
88 | class ParsedAttr; |
89 | class BindingDecl; |
90 | class BlockDecl; |
91 | class CapturedDecl; |
92 | class CXXBasePath; |
93 | class CXXBasePaths; |
94 | class CXXBindTemporaryExpr; |
95 | typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; |
96 | class CXXConstructorDecl; |
97 | class CXXConversionDecl; |
98 | class CXXDeleteExpr; |
99 | class CXXDestructorDecl; |
100 | class CXXFieldCollector; |
101 | class CXXMemberCallExpr; |
102 | class CXXMethodDecl; |
103 | class CXXScopeSpec; |
104 | class CXXTemporary; |
105 | class CXXTryStmt; |
106 | class CallExpr; |
107 | class ClassTemplateDecl; |
108 | class ClassTemplatePartialSpecializationDecl; |
109 | class ClassTemplateSpecializationDecl; |
110 | class VarTemplatePartialSpecializationDecl; |
111 | class CodeCompleteConsumer; |
112 | class CodeCompletionAllocator; |
113 | class CodeCompletionTUInfo; |
114 | class CodeCompletionResult; |
115 | class CoroutineBodyStmt; |
116 | class Decl; |
117 | class DeclAccessPair; |
118 | class DeclContext; |
119 | class DeclRefExpr; |
120 | class DeclaratorDecl; |
121 | class DeducedTemplateArgument; |
122 | class DependentDiagnostic; |
123 | class DesignatedInitExpr; |
124 | class Designation; |
125 | class EnableIfAttr; |
126 | class EnumConstantDecl; |
127 | class Expr; |
128 | class ExtVectorType; |
129 | class FormatAttr; |
130 | class FriendDecl; |
131 | class FunctionDecl; |
132 | class FunctionProtoType; |
133 | class FunctionTemplateDecl; |
134 | class ImplicitConversionSequence; |
135 | typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; |
136 | class InitListExpr; |
137 | class InitializationKind; |
138 | class InitializationSequence; |
139 | class InitializedEntity; |
140 | class IntegerLiteral; |
141 | class LabelStmt; |
142 | class LambdaExpr; |
143 | class LangOptions; |
144 | class LocalInstantiationScope; |
145 | class LookupResult; |
146 | class MacroInfo; |
147 | typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; |
148 | class ModuleLoader; |
149 | class MultiLevelTemplateArgumentList; |
150 | class NamedDecl; |
151 | class ObjCCategoryDecl; |
152 | class ObjCCategoryImplDecl; |
153 | class ObjCCompatibleAliasDecl; |
154 | class ObjCContainerDecl; |
155 | class ObjCImplDecl; |
156 | class ObjCImplementationDecl; |
157 | class ObjCInterfaceDecl; |
158 | class ObjCIvarDecl; |
159 | template <class T> class ObjCList; |
160 | class ObjCMessageExpr; |
161 | class ObjCMethodDecl; |
162 | class ObjCPropertyDecl; |
163 | class ObjCProtocolDecl; |
164 | class OMPThreadPrivateDecl; |
165 | class OMPRequiresDecl; |
166 | class OMPDeclareReductionDecl; |
167 | class OMPDeclareSimdDecl; |
168 | class OMPClause; |
169 | struct OMPVarListLocTy; |
170 | struct OverloadCandidate; |
171 | enum class OverloadCandidateParamOrder : char; |
172 | enum OverloadCandidateRewriteKind : unsigned; |
173 | class OverloadCandidateSet; |
174 | class OverloadExpr; |
175 | class ParenListExpr; |
176 | class ParmVarDecl; |
177 | class Preprocessor; |
178 | class PseudoDestructorTypeStorage; |
179 | class PseudoObjectExpr; |
180 | class QualType; |
181 | class StandardConversionSequence; |
182 | class Stmt; |
183 | class StringLiteral; |
184 | class SwitchStmt; |
185 | class TemplateArgument; |
186 | class TemplateArgumentList; |
187 | class TemplateArgumentLoc; |
188 | class TemplateDecl; |
189 | class TemplateInstantiationCallback; |
190 | class TemplateParameterList; |
191 | class TemplatePartialOrderingContext; |
192 | class TemplateTemplateParmDecl; |
193 | class Token; |
194 | class TypeAliasDecl; |
195 | class TypedefDecl; |
196 | class TypedefNameDecl; |
197 | class TypeLoc; |
198 | class TypoCorrectionConsumer; |
199 | class UnqualifiedId; |
200 | class UnresolvedLookupExpr; |
201 | class UnresolvedMemberExpr; |
202 | class UnresolvedSetImpl; |
203 | class UnresolvedSetIterator; |
204 | class UsingDecl; |
205 | class UsingShadowDecl; |
206 | class ValueDecl; |
207 | class VarDecl; |
208 | class VarTemplateSpecializationDecl; |
209 | class VisibilityAttr; |
210 | class VisibleDeclConsumer; |
211 | class IndirectFieldDecl; |
212 | struct DeductionFailureInfo; |
213 | class TemplateSpecCandidateSet; |
214 | |
215 | namespace sema { |
216 | class AccessedEntity; |
217 | class BlockScopeInfo; |
218 | class Capture; |
219 | class CapturedRegionScopeInfo; |
220 | class CapturingScopeInfo; |
221 | class CompoundScopeInfo; |
222 | class DelayedDiagnostic; |
223 | class DelayedDiagnosticPool; |
224 | class FunctionScopeInfo; |
225 | class LambdaScopeInfo; |
226 | class PossiblyUnreachableDiag; |
227 | class SemaPPCallbacks; |
228 | class TemplateDeductionInfo; |
229 | } |
230 | |
231 | namespace threadSafety { |
232 | class BeforeSet; |
233 | void threadSafetyCleanup(BeforeSet* Cache); |
234 | } |
235 | |
236 | // FIXME: No way to easily map from TemplateTypeParmTypes to |
237 | // TemplateTypeParmDecls, so we have this horrible PointerUnion. |
238 | typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, |
239 | SourceLocation> UnexpandedParameterPack; |
240 | |
241 | /// Describes whether we've seen any nullability information for the given |
242 | /// file. |
243 | struct FileNullability { |
244 | /// The first pointer declarator (of any pointer kind) in the file that does |
245 | /// not have a corresponding nullability annotation. |
246 | SourceLocation PointerLoc; |
247 | |
248 | /// The end location for the first pointer declarator in the file. Used for |
249 | /// placing fix-its. |
250 | SourceLocation PointerEndLoc; |
251 | |
252 | /// Which kind of pointer declarator we saw. |
253 | uint8_t PointerKind; |
254 | |
255 | /// Whether we saw any type nullability annotations in the given file. |
256 | bool SawTypeNullability = false; |
257 | }; |
258 | |
259 | /// A mapping from file IDs to a record of whether we've seen nullability |
260 | /// information in that file. |
261 | class FileNullabilityMap { |
262 | /// A mapping from file IDs to the nullability information for each file ID. |
263 | llvm::DenseMap<FileID, FileNullability> Map; |
264 | |
265 | /// A single-element cache based on the file ID. |
266 | struct { |
267 | FileID File; |
268 | FileNullability Nullability; |
269 | } Cache; |
270 | |
271 | public: |
272 | FileNullability &operator[](FileID file) { |
273 | // Check the single-element cache. |
274 | if (file == Cache.File) |
275 | return Cache.Nullability; |
276 | |
277 | // It's not in the single-element cache; flush the cache if we have one. |
278 | if (!Cache.File.isInvalid()) { |
279 | Map[Cache.File] = Cache.Nullability; |
280 | } |
281 | |
282 | // Pull this entry into the cache. |
283 | Cache.File = file; |
284 | Cache.Nullability = Map[file]; |
285 | return Cache.Nullability; |
286 | } |
287 | }; |
288 | |
289 | /// Keeps track of expected type during expression parsing. The type is tied to |
290 | /// a particular token, all functions that update or consume the type take a |
291 | /// start location of the token they are looking at as a parameter. This allows |
292 | /// to avoid updating the type on hot paths in the parser. |
293 | class PreferredTypeBuilder { |
294 | public: |
295 | PreferredTypeBuilder() = default; |
296 | explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} |
297 | |
298 | void enterCondition(Sema &S, SourceLocation Tok); |
299 | void enterReturn(Sema &S, SourceLocation Tok); |
300 | void enterVariableInit(SourceLocation Tok, Decl *D); |
301 | /// Handles e.g. BaseType{ .D = Tok... |
302 | void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, |
303 | const Designation &D); |
304 | /// Computing a type for the function argument may require running |
305 | /// overloading, so we postpone its computation until it is actually needed. |
306 | /// |
307 | /// Clients should be very careful when using this funciton, as it stores a |
308 | /// function_ref, clients should make sure all calls to get() with the same |
309 | /// location happen while function_ref is alive. |
310 | void enterFunctionArgument(SourceLocation Tok, |
311 | llvm::function_ref<QualType()> ComputeType); |
312 | |
313 | void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); |
314 | void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, |
315 | SourceLocation OpLoc); |
316 | void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); |
317 | void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); |
318 | void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); |
319 | /// Handles all type casts, including C-style cast, C++ casts, etc. |
320 | void enterTypeCast(SourceLocation Tok, QualType CastType); |
321 | |
322 | QualType get(SourceLocation Tok) const { |
323 | if (Tok != ExpectedLoc) |
324 | return QualType(); |
325 | if (!Type.isNull()) |
326 | return Type; |
327 | if (ComputeType) |
328 | return ComputeType(); |
329 | return QualType(); |
330 | } |
331 | |
332 | private: |
333 | /// Start position of a token for which we store expected type. |
334 | SourceLocation ExpectedLoc; |
335 | /// Expected type for a token starting at ExpectedLoc. |
336 | QualType Type; |
337 | /// A function to compute expected type at ExpectedLoc. It is only considered |
338 | /// if Type is null. |
339 | llvm::function_ref<QualType()> ComputeType; |
340 | }; |
341 | |
342 | /// Sema - This implements semantic analysis and AST building for C. |
343 | class Sema final { |
344 | Sema(const Sema &) = delete; |
345 | void operator=(const Sema &) = delete; |
346 | |
347 | /// A key method to reduce duplicate debug info from Sema. |
348 | virtual void anchor(); |
349 | |
350 | ///Source of additional semantic information. |
351 | ExternalSemaSource *ExternalSource; |
352 | |
353 | ///Whether Sema has generated a multiplexer and has to delete it. |
354 | bool isMultiplexExternalSource; |
355 | |
356 | static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); |
357 | |
358 | bool isVisibleSlow(const NamedDecl *D); |
359 | |
360 | /// Determine whether two declarations should be linked together, given that |
361 | /// the old declaration might not be visible and the new declaration might |
362 | /// not have external linkage. |
363 | bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, |
364 | const NamedDecl *New) { |
365 | if (isVisible(Old)) |
366 | return true; |
367 | // See comment in below overload for why it's safe to compute the linkage |
368 | // of the new declaration here. |
369 | if (New->isExternallyDeclarable()) { |
370 | 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-13~++20210223111116+16ede0956cb1/clang/include/clang/Sema/Sema.h" , 371, __PRETTY_FUNCTION__)) |
371 | "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-13~++20210223111116+16ede0956cb1/clang/include/clang/Sema/Sema.h" , 371, __PRETTY_FUNCTION__)); |
372 | return true; |
373 | } |
374 | return false; |
375 | } |
376 | bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); |
377 | |
378 | void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, |
379 | QualType ResultTy, |
380 | ArrayRef<QualType> Args); |
381 | |
382 | public: |
383 | /// The maximum alignment, same as in llvm::Value. We duplicate them here |
384 | /// because that allows us not to duplicate the constants in clang code, |
385 | /// which we must to since we can't directly use the llvm constants. |
386 | /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp |
387 | /// |
388 | /// This is the greatest alignment value supported by load, store, and alloca |
389 | /// instructions, and global values. |
390 | static const unsigned MaxAlignmentExponent = 29; |
391 | static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent; |
392 | |
393 | typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; |
394 | typedef OpaquePtr<TemplateName> TemplateTy; |
395 | typedef OpaquePtr<QualType> TypeTy; |
396 | |
397 | OpenCLOptions OpenCLFeatures; |
398 | FPOptions CurFPFeatures; |
399 | |
400 | const LangOptions &LangOpts; |
401 | Preprocessor &PP; |
402 | ASTContext &Context; |
403 | ASTConsumer &Consumer; |
404 | DiagnosticsEngine &Diags; |
405 | SourceManager &SourceMgr; |
406 | |
407 | /// Flag indicating whether or not to collect detailed statistics. |
408 | bool CollectStats; |
409 | |
410 | /// Code-completion consumer. |
411 | CodeCompleteConsumer *CodeCompleter; |
412 | |
413 | /// CurContext - This is the current declaration context of parsing. |
414 | DeclContext *CurContext; |
415 | |
416 | /// Generally null except when we temporarily switch decl contexts, |
417 | /// like in \see ActOnObjCTemporaryExitContainerContext. |
418 | DeclContext *OriginalLexicalContext; |
419 | |
420 | /// VAListTagName - The declaration name corresponding to __va_list_tag. |
421 | /// This is used as part of a hack to omit that class from ADL results. |
422 | DeclarationName VAListTagName; |
423 | |
424 | bool MSStructPragmaOn; // True when \#pragma ms_struct on |
425 | |
426 | /// Controls member pointer representation format under the MS ABI. |
427 | LangOptions::PragmaMSPointersToMembersKind |
428 | MSPointerToMemberRepresentationMethod; |
429 | |
430 | /// Stack of active SEH __finally scopes. Can be empty. |
431 | SmallVector<Scope*, 2> CurrentSEHFinally; |
432 | |
433 | /// Source location for newly created implicit MSInheritanceAttrs |
434 | SourceLocation ImplicitMSInheritanceAttrLoc; |
435 | |
436 | /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by |
437 | /// `TransformTypos` in order to keep track of any TypoExprs that are created |
438 | /// recursively during typo correction and wipe them away if the correction |
439 | /// fails. |
440 | llvm::SmallVector<TypoExpr *, 2> TypoExprs; |
441 | |
442 | /// pragma clang section kind |
443 | enum PragmaClangSectionKind { |
444 | PCSK_Invalid = 0, |
445 | PCSK_BSS = 1, |
446 | PCSK_Data = 2, |
447 | PCSK_Rodata = 3, |
448 | PCSK_Text = 4, |
449 | PCSK_Relro = 5 |
450 | }; |
451 | |
452 | enum PragmaClangSectionAction { |
453 | PCSA_Set = 0, |
454 | PCSA_Clear = 1 |
455 | }; |
456 | |
457 | struct PragmaClangSection { |
458 | std::string SectionName; |
459 | bool Valid = false; |
460 | SourceLocation PragmaLocation; |
461 | }; |
462 | |
463 | PragmaClangSection PragmaClangBSSSection; |
464 | PragmaClangSection PragmaClangDataSection; |
465 | PragmaClangSection PragmaClangRodataSection; |
466 | PragmaClangSection PragmaClangRelroSection; |
467 | PragmaClangSection PragmaClangTextSection; |
468 | |
469 | enum PragmaMsStackAction { |
470 | PSK_Reset = 0x0, // #pragma () |
471 | PSK_Set = 0x1, // #pragma (value) |
472 | PSK_Push = 0x2, // #pragma (push[, id]) |
473 | PSK_Pop = 0x4, // #pragma (pop[, id]) |
474 | PSK_Show = 0x8, // #pragma (show) -- only for "pack"! |
475 | PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) |
476 | PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) |
477 | }; |
478 | |
479 | // #pragma pack and align. |
480 | class AlignPackInfo { |
481 | public: |
482 | // `Native` represents default align mode, which may vary based on the |
483 | // platform. |
484 | enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; |
485 | |
486 | // #pragma pack info constructor |
487 | AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) |
488 | : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { |
489 | assert(Num == PackNumber && "The pack number has been truncated.")((Num == PackNumber && "The pack number has been truncated." ) ? static_cast<void> (0) : __assert_fail ("Num == PackNumber && \"The pack number has been truncated.\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/Sema/Sema.h" , 489, __PRETTY_FUNCTION__)); |
490 | } |
491 | |
492 | // #pragma align info constructor |
493 | AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) |
494 | : PackAttr(false), AlignMode(M), |
495 | PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} |
496 | |
497 | explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} |
498 | |
499 | AlignPackInfo() : AlignPackInfo(Native, false) {} |
500 | |
501 | // When a AlignPackInfo itself cannot be used, this returns an 32-bit |
502 | // integer encoding for it. This should only be passed to |
503 | // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. |
504 | static uint32_t getRawEncoding(const AlignPackInfo &Info) { |
505 | std::uint32_t Encoding{}; |
506 | if (Info.IsXLStack()) |
507 | Encoding |= IsXLMask; |
508 | |
509 | Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; |
510 | |
511 | if (Info.IsPackAttr()) |
512 | Encoding |= PackAttrMask; |
513 | |
514 | Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; |
515 | |
516 | return Encoding; |
517 | } |
518 | |
519 | static AlignPackInfo getFromRawEncoding(unsigned Encoding) { |
520 | bool IsXL = static_cast<bool>(Encoding & IsXLMask); |
521 | AlignPackInfo::Mode M = |
522 | static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); |
523 | int PackNumber = (Encoding & PackNumMask) >> 4; |
524 | |
525 | if (Encoding & PackAttrMask) |
526 | return AlignPackInfo(M, PackNumber, IsXL); |
527 | |
528 | return AlignPackInfo(M, IsXL); |
529 | } |
530 | |
531 | bool IsPackAttr() const { return PackAttr; } |
532 | |
533 | bool IsAlignAttr() const { return !PackAttr; } |
534 | |
535 | Mode getAlignMode() const { return AlignMode; } |
536 | |
537 | unsigned getPackNumber() const { return PackNumber; } |
538 | |
539 | bool IsPackSet() const { |
540 | // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack |
541 | // attriute on a decl. |
542 | return PackNumber != UninitPackVal && PackNumber != 0; |
543 | } |
544 | |
545 | bool IsXLStack() const { return XLStack; } |
546 | |
547 | bool operator==(const AlignPackInfo &Info) const { |
548 | return std::tie(AlignMode, PackNumber, PackAttr, XLStack) == |
549 | std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr, |
550 | Info.XLStack); |
551 | } |
552 | |
553 | bool operator!=(const AlignPackInfo &Info) const { |
554 | return !(*this == Info); |
555 | } |
556 | |
557 | private: |
558 | /// \brief True if this is a pragma pack attribute, |
559 | /// not a pragma align attribute. |
560 | bool PackAttr; |
561 | |
562 | /// \brief The alignment mode that is in effect. |
563 | Mode AlignMode; |
564 | |
565 | /// \brief The pack number of the stack. |
566 | unsigned char PackNumber; |
567 | |
568 | /// \brief True if it is a XL #pragma align/pack stack. |
569 | bool XLStack; |
570 | |
571 | /// \brief Uninitialized pack value. |
572 | static constexpr unsigned char UninitPackVal = -1; |
573 | |
574 | // Masks to encode and decode an AlignPackInfo. |
575 | static constexpr uint32_t IsXLMask{0x0000'0001}; |
576 | static constexpr uint32_t AlignModeMask{0x0000'0006}; |
577 | static constexpr uint32_t PackAttrMask{0x00000'0008}; |
578 | static constexpr uint32_t PackNumMask{0x0000'01F0}; |
579 | }; |
580 | |
581 | template<typename ValueType> |
582 | struct PragmaStack { |
583 | struct Slot { |
584 | llvm::StringRef StackSlotLabel; |
585 | ValueType Value; |
586 | SourceLocation PragmaLocation; |
587 | SourceLocation PragmaPushLocation; |
588 | Slot(llvm::StringRef StackSlotLabel, ValueType Value, |
589 | SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) |
590 | : StackSlotLabel(StackSlotLabel), Value(Value), |
591 | PragmaLocation(PragmaLocation), |
592 | PragmaPushLocation(PragmaPushLocation) {} |
593 | }; |
594 | |
595 | void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, |
596 | llvm::StringRef StackSlotLabel, ValueType Value) { |
597 | if (Action == PSK_Reset) { |
598 | CurrentValue = DefaultValue; |
599 | CurrentPragmaLocation = PragmaLocation; |
600 | return; |
601 | } |
602 | if (Action & PSK_Push) |
603 | Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, |
604 | PragmaLocation); |
605 | else if (Action & PSK_Pop) { |
606 | if (!StackSlotLabel.empty()) { |
607 | // If we've got a label, try to find it and jump there. |
608 | auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { |
609 | return x.StackSlotLabel == StackSlotLabel; |
610 | }); |
611 | // If we found the label so pop from there. |
612 | if (I != Stack.rend()) { |
613 | CurrentValue = I->Value; |
614 | CurrentPragmaLocation = I->PragmaLocation; |
615 | Stack.erase(std::prev(I.base()), Stack.end()); |
616 | } |
617 | } else if (!Stack.empty()) { |
618 | // We do not have a label, just pop the last entry. |
619 | CurrentValue = Stack.back().Value; |
620 | CurrentPragmaLocation = Stack.back().PragmaLocation; |
621 | Stack.pop_back(); |
622 | } |
623 | } |
624 | if (Action & PSK_Set) { |
625 | CurrentValue = Value; |
626 | CurrentPragmaLocation = PragmaLocation; |
627 | } |
628 | } |
629 | |
630 | // MSVC seems to add artificial slots to #pragma stacks on entering a C++ |
631 | // method body to restore the stacks on exit, so it works like this: |
632 | // |
633 | // struct S { |
634 | // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) |
635 | // void Method {} |
636 | // #pragma <name>(pop, InternalPragmaSlot) |
637 | // }; |
638 | // |
639 | // It works even with #pragma vtordisp, although MSVC doesn't support |
640 | // #pragma vtordisp(push [, id], n) |
641 | // syntax. |
642 | // |
643 | // Push / pop a named sentinel slot. |
644 | void SentinelAction(PragmaMsStackAction Action, StringRef Label) { |
645 | 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-13~++20210223111116+16ede0956cb1/clang/include/clang/Sema/Sema.h" , 646, __PRETTY_FUNCTION__)) |
646 | "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-13~++20210223111116+16ede0956cb1/clang/include/clang/Sema/Sema.h" , 646, __PRETTY_FUNCTION__)); |
647 | Act(CurrentPragmaLocation, Action, Label, CurrentValue); |
648 | } |
649 | |
650 | // Constructors. |
651 | explicit PragmaStack(const ValueType &Default) |
652 | : DefaultValue(Default), CurrentValue(Default) {} |
653 | |
654 | bool hasValue() const { return CurrentValue != DefaultValue; } |
655 | |
656 | SmallVector<Slot, 2> Stack; |
657 | ValueType DefaultValue; // Value used for PSK_Reset action. |
658 | ValueType CurrentValue; |
659 | SourceLocation CurrentPragmaLocation; |
660 | }; |
661 | // FIXME: We should serialize / deserialize these if they occur in a PCH (but |
662 | // we shouldn't do so if they're in a module). |
663 | |
664 | /// Whether to insert vtordisps prior to virtual bases in the Microsoft |
665 | /// C++ ABI. Possible values are 0, 1, and 2, which mean: |
666 | /// |
667 | /// 0: Suppress all vtordisps |
668 | /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial |
669 | /// structors |
670 | /// 2: Always insert vtordisps to support RTTI on partially constructed |
671 | /// objects |
672 | PragmaStack<MSVtorDispMode> VtorDispStack; |
673 | PragmaStack<AlignPackInfo> AlignPackStack; |
674 | // The current #pragma align/pack values and locations at each #include. |
675 | struct AlignPackIncludeState { |
676 | AlignPackInfo CurrentValue; |
677 | SourceLocation CurrentPragmaLocation; |
678 | bool HasNonDefaultValue, ShouldWarnOnInclude; |
679 | }; |
680 | SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; |
681 | // Segment #pragmas. |
682 | PragmaStack<StringLiteral *> DataSegStack; |
683 | PragmaStack<StringLiteral *> BSSSegStack; |
684 | PragmaStack<StringLiteral *> ConstSegStack; |
685 | PragmaStack<StringLiteral *> CodeSegStack; |
686 | |
687 | // This stack tracks the current state of Sema.CurFPFeatures. |
688 | PragmaStack<FPOptionsOverride> FpPragmaStack; |
689 | FPOptionsOverride CurFPFeatureOverrides() { |
690 | FPOptionsOverride result; |
691 | if (!FpPragmaStack.hasValue()) { |
692 | result = FPOptionsOverride(); |
693 | } else { |
694 | result = FpPragmaStack.CurrentValue; |
695 | } |
696 | return result; |
697 | } |
698 | |
699 | // RAII object to push / pop sentinel slots for all MS #pragma stacks. |
700 | // Actions should be performed only if we enter / exit a C++ method body. |
701 | class PragmaStackSentinelRAII { |
702 | public: |
703 | PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); |
704 | ~PragmaStackSentinelRAII(); |
705 | |
706 | private: |
707 | Sema &S; |
708 | StringRef SlotLabel; |
709 | bool ShouldAct; |
710 | }; |
711 | |
712 | /// A mapping that describes the nullability we've seen in each header file. |
713 | FileNullabilityMap NullabilityMap; |
714 | |
715 | /// Last section used with #pragma init_seg. |
716 | StringLiteral *CurInitSeg; |
717 | SourceLocation CurInitSegLoc; |
718 | |
719 | /// VisContext - Manages the stack for \#pragma GCC visibility. |
720 | void *VisContext; // Really a "PragmaVisStack*" |
721 | |
722 | /// This an attribute introduced by \#pragma clang attribute. |
723 | struct PragmaAttributeEntry { |
724 | SourceLocation Loc; |
725 | ParsedAttr *Attribute; |
726 | SmallVector<attr::SubjectMatchRule, 4> MatchRules; |
727 | bool IsUsed; |
728 | }; |
729 | |
730 | /// A push'd group of PragmaAttributeEntries. |
731 | struct PragmaAttributeGroup { |
732 | /// The location of the push attribute. |
733 | SourceLocation Loc; |
734 | /// The namespace of this push group. |
735 | const IdentifierInfo *Namespace; |
736 | SmallVector<PragmaAttributeEntry, 2> Entries; |
737 | }; |
738 | |
739 | SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; |
740 | |
741 | /// The declaration that is currently receiving an attribute from the |
742 | /// #pragma attribute stack. |
743 | const Decl *PragmaAttributeCurrentTargetDecl; |
744 | |
745 | /// This represents the last location of a "#pragma clang optimize off" |
746 | /// directive if such a directive has not been closed by an "on" yet. If |
747 | /// optimizations are currently "on", this is set to an invalid location. |
748 | SourceLocation OptimizeOffPragmaLocation; |
749 | |
750 | /// Flag indicating if Sema is building a recovery call expression. |
751 | /// |
752 | /// This flag is used to avoid building recovery call expressions |
753 | /// if Sema is already doing so, which would cause infinite recursions. |
754 | bool IsBuildingRecoveryCallExpr; |
755 | |
756 | /// Used to control the generation of ExprWithCleanups. |
757 | CleanupInfo Cleanup; |
758 | |
759 | /// ExprCleanupObjects - This is the stack of objects requiring |
760 | /// cleanup that are created by the current full expression. |
761 | SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; |
762 | |
763 | /// Store a set of either DeclRefExprs or MemberExprs that contain a reference |
764 | /// to a variable (constant) that may or may not be odr-used in this Expr, and |
765 | /// we won't know until all lvalue-to-rvalue and discarded value conversions |
766 | /// have been applied to all subexpressions of the enclosing full expression. |
767 | /// This is cleared at the end of each full expression. |
768 | using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, |
769 | llvm::SmallPtrSet<Expr *, 4>>; |
770 | MaybeODRUseExprSet MaybeODRUseExprs; |
771 | |
772 | std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; |
773 | |
774 | /// Stack containing information about each of the nested |
775 | /// function, block, and method scopes that are currently active. |
776 | SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; |
777 | |
778 | /// The index of the first FunctionScope that corresponds to the current |
779 | /// context. |
780 | unsigned FunctionScopesStart = 0; |
781 | |
782 | ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { |
783 | return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, |
784 | FunctionScopes.end()); |
785 | } |
786 | |
787 | /// Stack containing information needed when in C++2a an 'auto' is encountered |
788 | /// in a function declaration parameter type specifier in order to invent a |
789 | /// corresponding template parameter in the enclosing abbreviated function |
790 | /// template. This information is also present in LambdaScopeInfo, stored in |
791 | /// the FunctionScopes stack. |
792 | SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; |
793 | |
794 | /// The index of the first InventedParameterInfo that refers to the current |
795 | /// context. |
796 | unsigned InventedParameterInfosStart = 0; |
797 | |
798 | ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { |
799 | return llvm::makeArrayRef(InventedParameterInfos.begin() + |
800 | InventedParameterInfosStart, |
801 | InventedParameterInfos.end()); |
802 | } |
803 | |
804 | typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, |
805 | &ExternalSemaSource::ReadExtVectorDecls, 2, 2> |
806 | ExtVectorDeclsType; |
807 | |
808 | /// ExtVectorDecls - This is a list all the extended vector types. This allows |
809 | /// us to associate a raw vector type with one of the ext_vector type names. |
810 | /// This is only necessary for issuing pretty diagnostics. |
811 | ExtVectorDeclsType ExtVectorDecls; |
812 | |
813 | /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. |
814 | std::unique_ptr<CXXFieldCollector> FieldCollector; |
815 | |
816 | typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; |
817 | |
818 | /// Set containing all declared private fields that are not used. |
819 | NamedDeclSetType UnusedPrivateFields; |
820 | |
821 | /// Set containing all typedefs that are likely unused. |
822 | llvm::SmallSetVector<const TypedefNameDecl *, 4> |
823 | UnusedLocalTypedefNameCandidates; |
824 | |
825 | /// Delete-expressions to be analyzed at the end of translation unit |
826 | /// |
827 | /// This list contains class members, and locations of delete-expressions |
828 | /// that could not be proven as to whether they mismatch with new-expression |
829 | /// used in initializer of the field. |
830 | typedef std::pair<SourceLocation, bool> DeleteExprLoc; |
831 | typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; |
832 | llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; |
833 | |
834 | typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; |
835 | |
836 | /// PureVirtualClassDiagSet - a set of class declarations which we have |
837 | /// emitted a list of pure virtual functions. Used to prevent emitting the |
838 | /// same list more than once. |
839 | std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; |
840 | |
841 | /// ParsingInitForAutoVars - a set of declarations with auto types for which |
842 | /// we are currently parsing the initializer. |
843 | llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; |
844 | |
845 | /// Look for a locally scoped extern "C" declaration by the given name. |
846 | NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); |
847 | |
848 | typedef LazyVector<VarDecl *, ExternalSemaSource, |
849 | &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> |
850 | TentativeDefinitionsType; |
851 | |
852 | /// All the tentative definitions encountered in the TU. |
853 | TentativeDefinitionsType TentativeDefinitions; |
854 | |
855 | /// All the external declarations encoutered and used in the TU. |
856 | SmallVector<VarDecl *, 4> ExternalDeclarations; |
857 | |
858 | typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, |
859 | &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> |
860 | UnusedFileScopedDeclsType; |
861 | |
862 | /// The set of file scoped decls seen so far that have not been used |
863 | /// and must warn if not used. Only contains the first declaration. |
864 | UnusedFileScopedDeclsType UnusedFileScopedDecls; |
865 | |
866 | typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, |
867 | &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> |
868 | DelegatingCtorDeclsType; |
869 | |
870 | /// All the delegating constructors seen so far in the file, used for |
871 | /// cycle detection at the end of the TU. |
872 | DelegatingCtorDeclsType DelegatingCtorDecls; |
873 | |
874 | /// All the overriding functions seen during a class definition |
875 | /// that had their exception spec checks delayed, plus the overridden |
876 | /// function. |
877 | SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> |
878 | DelayedOverridingExceptionSpecChecks; |
879 | |
880 | /// All the function redeclarations seen during a class definition that had |
881 | /// their exception spec checks delayed, plus the prior declaration they |
882 | /// should be checked against. Except during error recovery, the new decl |
883 | /// should always be a friend declaration, as that's the only valid way to |
884 | /// redeclare a special member before its class is complete. |
885 | SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> |
886 | DelayedEquivalentExceptionSpecChecks; |
887 | |
888 | typedef llvm::MapVector<const FunctionDecl *, |
889 | std::unique_ptr<LateParsedTemplate>> |
890 | LateParsedTemplateMapT; |
891 | LateParsedTemplateMapT LateParsedTemplateMap; |
892 | |
893 | /// Callback to the parser to parse templated functions when needed. |
894 | typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); |
895 | typedef void LateTemplateParserCleanupCB(void *P); |
896 | LateTemplateParserCB *LateTemplateParser; |
897 | LateTemplateParserCleanupCB *LateTemplateParserCleanup; |
898 | void *OpaqueParser; |
899 | |
900 | void SetLateTemplateParser(LateTemplateParserCB *LTP, |
901 | LateTemplateParserCleanupCB *LTPCleanup, |
902 | void *P) { |
903 | LateTemplateParser = LTP; |
904 | LateTemplateParserCleanup = LTPCleanup; |
905 | OpaqueParser = P; |
906 | } |
907 | |
908 | class DelayedDiagnostics; |
909 | |
910 | class DelayedDiagnosticsState { |
911 | sema::DelayedDiagnosticPool *SavedPool; |
912 | friend class Sema::DelayedDiagnostics; |
913 | }; |
914 | typedef DelayedDiagnosticsState ParsingDeclState; |
915 | typedef DelayedDiagnosticsState ProcessingContextState; |
916 | |
917 | /// A class which encapsulates the logic for delaying diagnostics |
918 | /// during parsing and other processing. |
919 | class DelayedDiagnostics { |
920 | /// The current pool of diagnostics into which delayed |
921 | /// diagnostics should go. |
922 | sema::DelayedDiagnosticPool *CurPool; |
923 | |
924 | public: |
925 | DelayedDiagnostics() : CurPool(nullptr) {} |
926 | |
927 | /// Adds a delayed diagnostic. |
928 | void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h |
929 | |
930 | /// Determines whether diagnostics should be delayed. |
931 | bool shouldDelayDiagnostics() { return CurPool != nullptr; } |
932 | |
933 | /// Returns the current delayed-diagnostics pool. |
934 | sema::DelayedDiagnosticPool *getCurrentPool() const { |
935 | return CurPool; |
936 | } |
937 | |
938 | /// Enter a new scope. Access and deprecation diagnostics will be |
939 | /// collected in this pool. |
940 | DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { |
941 | DelayedDiagnosticsState state; |
942 | state.SavedPool = CurPool; |
943 | CurPool = &pool; |
944 | return state; |
945 | } |
946 | |
947 | /// Leave a delayed-diagnostic state that was previously pushed. |
948 | /// Do not emit any of the diagnostics. This is performed as part |
949 | /// of the bookkeeping of popping a pool "properly". |
950 | void popWithoutEmitting(DelayedDiagnosticsState state) { |
951 | CurPool = state.SavedPool; |
952 | } |
953 | |
954 | /// Enter a new scope where access and deprecation diagnostics are |
955 | /// not delayed. |
956 | DelayedDiagnosticsState pushUndelayed() { |
957 | DelayedDiagnosticsState state; |
958 | state.SavedPool = CurPool; |
959 | CurPool = nullptr; |
960 | return state; |
961 | } |
962 | |
963 | /// Undo a previous pushUndelayed(). |
964 | void popUndelayed(DelayedDiagnosticsState state) { |
965 | assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail ("CurPool == nullptr", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/Sema/Sema.h" , 965, __PRETTY_FUNCTION__)); |
966 | CurPool = state.SavedPool; |
967 | } |
968 | } DelayedDiagnostics; |
969 | |
970 | /// A RAII object to temporarily push a declaration context. |
971 | class ContextRAII { |
972 | private: |
973 | Sema &S; |
974 | DeclContext *SavedContext; |
975 | ProcessingContextState SavedContextState; |
976 | QualType SavedCXXThisTypeOverride; |
977 | unsigned SavedFunctionScopesStart; |
978 | unsigned SavedInventedParameterInfosStart; |
979 | |
980 | public: |
981 | ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) |
982 | : S(S), SavedContext(S.CurContext), |
983 | SavedContextState(S.DelayedDiagnostics.pushUndelayed()), |
984 | SavedCXXThisTypeOverride(S.CXXThisTypeOverride), |
985 | SavedFunctionScopesStart(S.FunctionScopesStart), |
986 | SavedInventedParameterInfosStart(S.InventedParameterInfosStart) |
987 | { |
988 | assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast <void> (0) : __assert_fail ("ContextToPush && \"pushing null context\"" , "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/Sema/Sema.h" , 988, __PRETTY_FUNCTION__)); |
989 | S.CurContext = ContextToPush; |
990 | if (NewThisContext) |
991 | S.CXXThisTypeOverride = QualType(); |
992 | // Any saved FunctionScopes do not refer to this context. |
993 | S.FunctionScopesStart = S.FunctionScopes.size(); |
994 | S.InventedParameterInfosStart = S.InventedParameterInfos.size(); |
995 | } |
996 | |
997 | void pop() { |
998 | if (!SavedContext) return; |
999 | S.CurContext = SavedContext; |
1000 | S.DelayedDiagnostics.popUndelayed(SavedContextState); |
1001 | S.CXXThisTypeOverride = SavedCXXThisTypeOverride; |
1002 | S.FunctionScopesStart = SavedFunctionScopesStart; |
1003 | S.InventedParameterInfosStart = SavedInventedParameterInfosStart; |
1004 | SavedContext = nullptr; |
1005 | } |
1006 | |
1007 | ~ContextRAII() { |
1008 | pop(); |
1009 | } |
1010 | }; |
1011 | |
1012 | /// Whether the AST is currently being rebuilt to correct immediate |
1013 | /// invocations. Immediate invocation candidates and references to consteval |
1014 | /// functions aren't tracked when this is set. |
1015 | bool RebuildingImmediateInvocation = false; |
1016 | |
1017 | /// Used to change context to isConstantEvaluated without pushing a heavy |
1018 | /// ExpressionEvaluationContextRecord object. |
1019 | bool isConstantEvaluatedOverride; |
1020 | |
1021 | bool isConstantEvaluated() { |
1022 | return ExprEvalContexts.back().isConstantEvaluated() || |
1023 | isConstantEvaluatedOverride; |
1024 | } |
1025 | |
1026 | /// RAII object to handle the state changes required to synthesize |
1027 | /// a function body. |
1028 | class SynthesizedFunctionScope { |
1029 | Sema &S; |
1030 | Sema::ContextRAII SavedContext; |
1031 | bool PushedCodeSynthesisContext = false; |
1032 | |
1033 | public: |
1034 | SynthesizedFunctionScope(Sema &S, DeclContext *DC) |
1035 | : S(S), SavedContext(S, DC) { |
1036 | S.PushFunctionScope(); |
1037 | S.PushExpressionEvaluationContext( |
1038 | Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
1039 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) |
1040 | FD->setWillHaveBody(true); |
1041 | else |
1042 | assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0 ) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/Sema/Sema.h" , 1042, __PRETTY_FUNCTION__)); |
1043 | } |
1044 | |
1045 | void addContextNote(SourceLocation UseLoc) { |
1046 | assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) : __assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/Sema/Sema.h" , 1046, __PRETTY_FUNCTION__)); |
1047 | |
1048 | Sema::CodeSynthesisContext Ctx; |
1049 | Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; |
1050 | Ctx.PointOfInstantiation = UseLoc; |
1051 | Ctx.Entity = cast<Decl>(S.CurContext); |
1052 | S.pushCodeSynthesisContext(Ctx); |
1053 | |
1054 | PushedCodeSynthesisContext = true; |
1055 | } |
1056 | |
1057 | ~SynthesizedFunctionScope() { |
1058 | if (PushedCodeSynthesisContext) |
1059 | S.popCodeSynthesisContext(); |
1060 | if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) |
1061 | FD->setWillHaveBody(false); |
1062 | S.PopExpressionEvaluationContext(); |
1063 | S.PopFunctionScopeInfo(); |
1064 | } |
1065 | }; |
1066 | |
1067 | /// WeakUndeclaredIdentifiers - Identifiers contained in |
1068 | /// \#pragma weak before declared. rare. may alias another |
1069 | /// identifier, declared or undeclared |
1070 | llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; |
1071 | |
1072 | /// ExtnameUndeclaredIdentifiers - Identifiers contained in |
1073 | /// \#pragma redefine_extname before declared. Used in Solaris system headers |
1074 | /// to define functions that occur in multiple standards to call the version |
1075 | /// in the currently selected standard. |
1076 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; |
1077 | |
1078 | |
1079 | /// Load weak undeclared identifiers from the external source. |
1080 | void LoadExternalWeakUndeclaredIdentifiers(); |
1081 | |
1082 | /// WeakTopLevelDecl - Translation-unit scoped declarations generated by |
1083 | /// \#pragma weak during processing of other Decls. |
1084 | /// I couldn't figure out a clean way to generate these in-line, so |
1085 | /// we store them here and handle separately -- which is a hack. |
1086 | /// It would be best to refactor this. |
1087 | SmallVector<Decl*,2> WeakTopLevelDecl; |
1088 | |
1089 | IdentifierResolver IdResolver; |
1090 | |
1091 | /// Translation Unit Scope - useful to Objective-C actions that need |
1092 | /// to lookup file scope declarations in the "ordinary" C decl namespace. |
1093 | /// For example, user-defined classes, built-in "id" type, etc. |
1094 | Scope *TUScope; |
1095 | |
1096 | /// The C++ "std" namespace, where the standard library resides. |
1097 | LazyDeclPtr StdNamespace; |
1098 | |
1099 | /// The C++ "std::bad_alloc" class, which is defined by the C++ |
1100 | /// standard library. |
1101 | LazyDeclPtr StdBadAlloc; |
1102 | |
1103 | /// The C++ "std::align_val_t" enum class, which is defined by the C++ |
1104 | /// standard library. |
1105 | LazyDeclPtr StdAlignValT; |
1106 | |
1107 | /// The C++ "std::experimental" namespace, where the experimental parts |
1108 | /// of the standard library resides. |
1109 | NamespaceDecl *StdExperimentalNamespaceCache; |
1110 | |
1111 | /// The C++ "std::initializer_list" template, which is defined in |
1112 | /// \<initializer_list>. |
1113 | ClassTemplateDecl *StdInitializerList; |
1114 | |
1115 | /// The C++ "std::coroutine_traits" template, which is defined in |
1116 | /// \<coroutine_traits> |
1117 | ClassTemplateDecl *StdCoroutineTraitsCache; |
1118 | |
1119 | /// The C++ "type_info" declaration, which is defined in \<typeinfo>. |
1120 | RecordDecl *CXXTypeInfoDecl; |
1121 | |
1122 | /// The MSVC "_GUID" struct, which is defined in MSVC header files. |
1123 | RecordDecl *MSVCGuidDecl; |
1124 | |
1125 | /// Caches identifiers/selectors for NSFoundation APIs. |
1126 | std::unique_ptr<NSAPI> NSAPIObj; |
1127 | |
1128 | /// The declaration of the Objective-C NSNumber class. |
1129 | ObjCInterfaceDecl *NSNumberDecl; |
1130 | |
1131 | /// The declaration of the Objective-C NSValue class. |
1132 | ObjCInterfaceDecl *NSValueDecl; |
1133 | |
1134 | /// Pointer to NSNumber type (NSNumber *). |
1135 | QualType NSNumberPointer; |
1136 | |
1137 | /// Pointer to NSValue type (NSValue *). |
1138 | QualType NSValuePointer; |
1139 | |
1140 | /// The Objective-C NSNumber methods used to create NSNumber literals. |
1141 | ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; |
1142 | |
1143 | /// The declaration of the Objective-C NSString class. |
1144 | ObjCInterfaceDecl *NSStringDecl; |
1145 | |
1146 | /// Pointer to NSString type (NSString *). |
1147 | QualType NSStringPointer; |
1148 | |
1149 | /// The declaration of the stringWithUTF8String: method. |
1150 | ObjCMethodDecl *StringWithUTF8StringMethod; |
1151 | |
1152 | /// The declaration of the valueWithBytes:objCType: method. |
1153 | ObjCMethodDecl *ValueWithBytesObjCTypeMethod; |
1154 | |
1155 | /// The declaration of the Objective-C NSArray class. |
1156 | ObjCInterfaceDecl *NSArrayDecl; |
1157 | |
1158 | /// The declaration of the arrayWithObjects:count: method. |
1159 | ObjCMethodDecl *ArrayWithObjectsMethod; |
1160 | |
1161 | /// The declaration of the Objective-C NSDictionary class. |
1162 | ObjCInterfaceDecl *NSDictionaryDecl; |
1163 | |
1164 | /// The declaration of the dictionaryWithObjects:forKeys:count: method. |
1165 | ObjCMethodDecl *DictionaryWithObjectsMethod; |
1166 | |
1167 | /// id<NSCopying> type. |
1168 | QualType QIDNSCopying; |
1169 | |
1170 | /// will hold 'respondsToSelector:' |
1171 | Selector RespondsToSelectorSel; |
1172 | |
1173 | /// A flag to remember whether the implicit forms of operator new and delete |
1174 | /// have been declared. |
1175 | bool GlobalNewDeleteDeclared; |
1176 | |
1177 | /// Describes how the expressions currently being parsed are |
1178 | /// evaluated at run-time, if at all. |
1179 | enum class ExpressionEvaluationContext { |
1180 | /// The current expression and its subexpressions occur within an |
1181 | /// unevaluated operand (C++11 [expr]p7), such as the subexpression of |
1182 | /// \c sizeof, where the type of the expression may be significant but |
1183 | /// no code will be generated to evaluate the value of the expression at |
1184 | /// run time. |
1185 | Unevaluated, |
1186 | |
1187 | /// The current expression occurs within a braced-init-list within |
1188 | /// an unevaluated operand. This is mostly like a regular unevaluated |
1189 | /// context, except that we still instantiate constexpr functions that are |
1190 | /// referenced here so that we can perform narrowing checks correctly. |
1191 | UnevaluatedList, |
1192 | |
1193 | /// The current expression occurs within a discarded statement. |
1194 | /// This behaves largely similarly to an unevaluated operand in preventing |
1195 | /// definitions from being required, but not in other ways. |
1196 | DiscardedStatement, |
1197 | |
1198 | /// The current expression occurs within an unevaluated |
1199 | /// operand that unconditionally permits abstract references to |
1200 | /// fields, such as a SIZE operator in MS-style inline assembly. |
1201 | UnevaluatedAbstract, |
1202 | |
1203 | /// The current context is "potentially evaluated" in C++11 terms, |
1204 | /// but the expression is evaluated at compile-time (like the values of |
1205 | /// cases in a switch statement). |
1206 | ConstantEvaluated, |
1207 | |
1208 | /// The current expression is potentially evaluated at run time, |
1209 | /// which means that code may be generated to evaluate the value of the |
1210 | /// expression at run time. |
1211 | PotentiallyEvaluated, |
1212 | |
1213 | /// The current expression is potentially evaluated, but any |
1214 | /// declarations referenced inside that expression are only used if |
1215 | /// in fact the current expression is used. |
1216 | /// |
1217 | /// This value is used when parsing default function arguments, for which |
1218 | /// we would like to provide diagnostics (e.g., passing non-POD arguments |
1219 | /// through varargs) but do not want to mark declarations as "referenced" |
1220 | /// until the default argument is used. |
1221 | PotentiallyEvaluatedIfUsed |
1222 | }; |
1223 | |
1224 | using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; |
1225 | |
1226 | /// Data structure used to record current or nested |
1227 | /// expression evaluation contexts. |
1228 | struct ExpressionEvaluationContextRecord { |
1229 | /// The expression evaluation context. |
1230 | ExpressionEvaluationContext Context; |
1231 | |
1232 | /// Whether the enclosing context needed a cleanup. |
1233 | CleanupInfo ParentCleanup; |
1234 | |
1235 | /// The number of active cleanup objects when we entered |
1236 | /// this expression evaluation context. |
1237 | unsigned NumCleanupObjects; |
1238 | |
1239 | /// The number of typos encountered during this expression evaluation |
1240 | /// context (i.e. the number of TypoExprs created). |
1241 | unsigned NumTypos; |
1242 | |
1243 | MaybeODRUseExprSet SavedMaybeODRUseExprs; |
1244 | |
1245 | /// The lambdas that are present within this context, if it |
1246 | /// is indeed an unevaluated context. |
1247 | SmallVector<LambdaExpr *, 2> Lambdas; |
1248 | |
1249 | /// The declaration that provides context for lambda expressions |
1250 | /// and block literals if the normal declaration context does not |
1251 | /// suffice, e.g., in a default function argument. |
1252 | Decl *ManglingContextDecl; |
1253 | |
1254 | /// If we are processing a decltype type, a set of call expressions |
1255 | /// for which we have deferred checking the completeness of the return type. |
1256 | SmallVector<CallExpr *, 8> DelayedDecltypeCalls; |
1257 | |
1258 | /// If we are processing a decltype type, a set of temporary binding |
1259 | /// expressions for which we have deferred checking the destructor. |
1260 | SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; |
1261 | |
1262 | llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; |
1263 | |
1264 | /// Expressions appearing as the LHS of a volatile assignment in this |
1265 | /// context. We produce a warning for these when popping the context if |
1266 | /// they are not discarded-value expressions nor unevaluated operands. |
1267 | SmallVector<Expr*, 2> VolatileAssignmentLHSs; |
1268 | |
1269 | /// Set of candidates for starting an immediate invocation. |
1270 | llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; |
1271 | |
1272 | /// Set of DeclRefExprs referencing a consteval function when used in a |
1273 | /// context not already known to be immediately invoked. |
1274 | llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; |
1275 | |
1276 | /// \brief Describes whether we are in an expression constext which we have |
1277 | /// to handle differently. |
1278 | enum ExpressionKind { |
1279 | EK_Decltype, EK_TemplateArgument, EK_Other |
1280 | } ExprContext; |
1281 | |
1282 | ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, |
1283 | unsigned NumCleanupObjects, |
1284 | CleanupInfo ParentCleanup, |
1285 | Decl *ManglingContextDecl, |
1286 | ExpressionKind ExprContext) |
1287 | : Context(Context), ParentCleanup(ParentCleanup), |
1288 | NumCleanupObjects(NumCleanupObjects), NumTypos(0), |
1289 | ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} |
1290 | |
1291 | bool isUnevaluated() const { |
1292 | return Context == ExpressionEvaluationContext::Unevaluated || |
1293 | Context == ExpressionEvaluationContext::UnevaluatedAbstract || |
1294 | Context == ExpressionEvaluationContext::UnevaluatedList; |
1295 | } |
1296 | bool isConstantEvaluated() const { |
1297 | return Context == ExpressionEvaluationContext::ConstantEvaluated; |
1298 | } |
1299 | }; |
1300 | |
1301 | /// A stack of expression evaluation contexts. |
1302 | SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; |
1303 | |
1304 | /// Emit a warning for all pending noderef expressions that we recorded. |
1305 | void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); |
1306 | |
1307 | /// Compute the mangling number context for a lambda expression or |
1308 | /// block literal. Also return the extra mangling decl if any. |
1309 | /// |
1310 | /// \param DC - The DeclContext containing the lambda expression or |
1311 | /// block literal. |
1312 | std::tuple<MangleNumberingContext *, Decl *> |
1313 | getCurrentMangleNumberContext(const DeclContext *DC); |
1314 | |
1315 | |
1316 | /// SpecialMemberOverloadResult - The overloading result for a special member |
1317 | /// function. |
1318 | /// |
1319 | /// This is basically a wrapper around PointerIntPair. The lowest bits of the |
1320 | /// integer are used to determine whether overload resolution succeeded. |
1321 | class SpecialMemberOverloadResult { |
1322 | public: |
1323 | enum Kind { |
1324 | NoMemberOrDeleted, |
1325 | Ambiguous, |
1326 | Success |
1327 | }; |
1328 | |
1329 | private: |
1330 | llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; |
1331 | |
1332 | public: |
1333 | SpecialMemberOverloadResult() : Pair() {} |
1334 | SpecialMemberOverloadResult(CXXMethodDecl *MD) |
1335 | : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} |
1336 | |
1337 | CXXMethodDecl *getMethod() const { return Pair.getPointer(); } |
1338 | void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } |
1339 | |
1340 | Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } |
1341 | void setKind(Kind K) { Pair.setInt(K); } |
1342 | }; |
1343 | |
1344 | class SpecialMemberOverloadResultEntry |
1345 | : public llvm::FastFoldingSetNode, |
1346 | public SpecialMemberOverloadResult { |
1347 | public: |
1348 | SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) |
1349 | : FastFoldingSetNode(ID) |
1350 | {} |
1351 | }; |
1352 | |
1353 | /// A cache of special member function overload resolution results |
1354 | /// for C++ records. |
1355 | llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; |
1356 | |
1357 | /// A cache of the flags available in enumerations with the flag_bits |
1358 | /// attribute. |
1359 | mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; |
1360 | |
1361 | /// The kind of translation unit we are processing. |
1362 | /// |
1363 | /// When we're processing a complete translation unit, Sema will perform |
1364 | /// end-of-translation-unit semantic tasks (such as creating |
1365 | /// initializers for tentative definitions in C) once parsing has |
1366 | /// completed. Modules and precompiled headers perform different kinds of |
1367 | /// checks. |
1368 | TranslationUnitKind TUKind; |
1369 | |
1370 | llvm::BumpPtrAllocator BumpAlloc; |
1371 | |
1372 | /// The number of SFINAE diagnostics that have been trapped. |
1373 | unsigned NumSFINAEErrors; |
1374 | |
1375 | typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> |
1376 | UnparsedDefaultArgInstantiationsMap; |
1377 | |
1378 | /// A mapping from parameters with unparsed default arguments to the |
1379 | /// set of instantiations of each parameter. |
1380 | /// |
1381 | /// This mapping is a temporary data structure used when parsing |
1382 | /// nested class templates or nested classes of class templates, |
1383 | /// where we might end up instantiating an inner class before the |
1384 | /// default arguments of its methods have been parsed. |
1385 | UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; |
1386 | |
1387 | // Contains the locations of the beginning of unparsed default |
1388 | // argument locations. |
1389 | llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; |
1390 | |
1391 | /// UndefinedInternals - all the used, undefined objects which require a |
1392 | /// definition in this translation unit. |
1393 | llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; |
1394 | |
1395 | /// Determine if VD, which must be a variable or function, is an external |
1396 | /// symbol that nonetheless can't be referenced from outside this translation |
1397 | /// unit because its type has no linkage and it's not extern "C". |
1398 | bool isExternalWithNoLinkageType(ValueDecl *VD); |
1399 | |
1400 | /// Obtain a sorted list of functions that are undefined but ODR-used. |
1401 | void getUndefinedButUsed( |
1402 | SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); |
1403 | |
1404 | /// Retrieves list of suspicious delete-expressions that will be checked at |
1405 | /// the end of translation unit. |
1406 | const llvm::MapVector<FieldDecl *, DeleteLocs> & |
1407 | getMismatchingDeleteExpressions() const; |
1408 | |
1409 | typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; |
1410 | typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; |
1411 | |
1412 | /// Method Pool - allows efficient lookup when typechecking messages to "id". |
1413 | /// We need to maintain a list, since selectors can have differing signatures |
1414 | /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% |
1415 | /// of selectors are "overloaded"). |
1416 | /// At the head of the list it is recorded whether there were 0, 1, or >= 2 |
1417 | /// methods inside categories with a particular selector. |
1418 | GlobalMethodPool MethodPool; |
1419 | |
1420 | /// Method selectors used in a \@selector expression. Used for implementation |
1421 | /// of -Wselector. |
1422 | llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; |
1423 | |
1424 | /// List of SourceLocations where 'self' is implicitly retained inside a |
1425 | /// block. |
1426 | llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> |
1427 | ImplicitlyRetainedSelfLocs; |
1428 | |
1429 | /// Kinds of C++ special members. |
1430 | enum CXXSpecialMember { |
1431 | CXXDefaultConstructor, |
1432 | CXXCopyConstructor, |
1433 | CXXMoveConstructor, |
1434 | CXXCopyAssignment, |
1435 | CXXMoveAssignment, |
1436 | CXXDestructor, |
1437 | CXXInvalid |
1438 | }; |
1439 | |
1440 | typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> |
1441 | SpecialMemberDecl; |
1442 | |
1443 | /// The C++ special members which we are currently in the process of |
1444 | /// declaring. If this process recursively triggers the declaration of the |
1445 | /// same special member, we should act as if it is not yet declared. |
1446 | llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; |
1447 | |
1448 | /// Kinds of defaulted comparison operator functions. |
1449 | enum class DefaultedComparisonKind : unsigned char { |
1450 | /// This is not a defaultable comparison operator. |
1451 | None, |
1452 | /// This is an operator== that should be implemented as a series of |
1453 | /// subobject comparisons. |
1454 | Equal, |
1455 | /// This is an operator<=> that should be implemented as a series of |
1456 | /// subobject comparisons. |
1457 | ThreeWay, |
1458 | /// This is an operator!= that should be implemented as a rewrite in terms |
1459 | /// of a == comparison. |
1460 | NotEqual, |
1461 | /// This is an <, <=, >, or >= that should be implemented as a rewrite in |
1462 | /// terms of a <=> comparison. |
1463 | Relational, |
1464 | }; |
1465 | |
1466 | /// The function definitions which were renamed as part of typo-correction |
1467 | /// to match their respective declarations. We want to keep track of them |
1468 | /// to ensure that we don't emit a "redefinition" error if we encounter a |
1469 | /// correctly named definition after the renamed definition. |
1470 | llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; |
1471 | |
1472 | /// Stack of types that correspond to the parameter entities that are |
1473 | /// currently being copy-initialized. Can be empty. |
1474 | llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; |
1475 | |
1476 | void ReadMethodPool(Selector Sel); |
1477 | void updateOutOfDateSelector(Selector Sel); |
1478 | |
1479 | /// Private Helper predicate to check for 'self'. |
1480 | bool isSelfExpr(Expr *RExpr); |
1481 | bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); |
1482 | |
1483 | /// Cause the active diagnostic on the DiagosticsEngine to be |
1484 | /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and |
1485 | /// should not be used elsewhere. |
1486 | void EmitCurrentDiagnostic(unsigned DiagID); |
1487 | |
1488 | /// Records and restores the CurFPFeatures state on entry/exit of compound |
1489 | /// statements. |
1490 | class FPFeaturesStateRAII { |
1491 | public: |
1492 | FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { |
1493 | OldOverrides = S.FpPragmaStack.CurrentValue; |
1494 | } |
1495 | ~FPFeaturesStateRAII() { |
1496 | S.CurFPFeatures = OldFPFeaturesState; |
1497 | S.FpPragmaStack.CurrentValue = OldOverrides; |
1498 | } |
1499 | FPOptionsOverride getOverrides() { return OldOverrides; } |
1500 | |
1501 | private: |
1502 | Sema& S; |
1503 | FPOptions OldFPFeaturesState; |
1504 | FPOptionsOverride OldOverrides; |
1505 | }; |
1506 | |
1507 | void addImplicitTypedef(StringRef Name, QualType T); |
1508 | |
1509 | bool WarnedStackExhausted = false; |
1510 | |
1511 | public: |
1512 | Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, |
1513 | TranslationUnitKind TUKind = TU_Complete, |
1514 | CodeCompleteConsumer *CompletionConsumer = nullptr); |
1515 | ~Sema(); |
1516 | |
1517 | /// Perform initialization that occurs after the parser has been |
1518 | /// initialized but before it parses anything. |
1519 | void Initialize(); |
1520 | |
1521 | const LangOptions &getLangOpts() const { return LangOpts; } |
1522 | OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } |
1523 | FPOptions &getCurFPFeatures() { return CurFPFeatures; } |
1524 | |
1525 | DiagnosticsEngine &getDiagnostics() const { return Diags; } |
1526 | SourceManager &getSourceManager() const { return SourceMgr; } |
1527 | Preprocessor &getPreprocessor() const { return PP; } |
1528 | ASTContext &getASTContext() const { return Context; } |
1529 | ASTConsumer &getASTConsumer() const { return Consumer; } |
1530 | ASTMutationListener *getASTMutationListener() const; |
1531 | ExternalSemaSource* getExternalSource() const { return ExternalSource; } |
1532 | |
1533 | ///Registers an external source. If an external source already exists, |
1534 | /// creates a multiplex external source and appends to it. |
1535 | /// |
1536 | ///\param[in] E - A non-null external sema source. |
1537 | /// |
1538 | void addExternalSource(ExternalSemaSource *E); |
1539 | |
1540 | void PrintStats() const; |
1541 | |
1542 | /// Warn that the stack is nearly exhausted. |
1543 | void warnStackExhausted(SourceLocation Loc); |
1544 | |
1545 | /// Run some code with "sufficient" stack space. (Currently, at least 256K is |
1546 | /// guaranteed). Produces a warning if we're low on stack space and allocates |
1547 | /// more in that case. Use this in code that may recurse deeply (for example, |
1548 | /// in template instantiation) to avoid stack overflow. |
1549 | void runWithSufficientStackSpace(SourceLocation Loc, |
1550 | llvm::function_ref<void()> Fn); |
1551 | |
1552 | /// Helper class that creates diagnostics with optional |
1553 | /// template instantiation stacks. |
1554 | /// |
1555 | /// This class provides a wrapper around the basic DiagnosticBuilder |
1556 | /// class that emits diagnostics. ImmediateDiagBuilder is |
1557 | /// responsible for emitting the diagnostic (as DiagnosticBuilder |
1558 | /// does) and, if the diagnostic comes from inside a template |
1559 | /// instantiation, printing the template instantiation stack as |
1560 | /// well. |
1561 | class ImmediateDiagBuilder : public DiagnosticBuilder { |
1562 | Sema &SemaRef; |
1563 | unsigned DiagID; |
1564 | |
1565 | public: |
1566 | ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) |
1567 | : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} |
1568 | ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID) |
1569 | : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} |
1570 | |
1571 | // This is a cunning lie. DiagnosticBuilder actually performs move |
1572 | // construction in its copy constructor (but due to varied uses, it's not |
1573 | // possible to conveniently express this as actual move construction). So |
1574 | // the default copy ctor here is fine, because the base class disables the |
1575 | // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op |
1576 | // in that case anwyay. |
1577 | ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; |
1578 | |
1579 | ~ImmediateDiagBuilder() { |
1580 | // If we aren't active, there is nothing to do. |
1581 | if (!isActive()) return; |
1582 | |
1583 | // Otherwise, we need to emit the diagnostic. First clear the diagnostic |
1584 | // builder itself so it won't emit the diagnostic in its own destructor. |
1585 | // |
1586 | // This seems wasteful, in that as written the DiagnosticBuilder dtor will |
1587 | // do its own needless checks to see if the diagnostic needs to be |
1588 | // emitted. However, because we take care to ensure that the builder |
1589 | // objects never escape, a sufficiently smart compiler will be able to |
1590 | // eliminate that code. |
1591 | Clear(); |
1592 | |
1593 | // Dispatch to Sema to emit the diagnostic. |
1594 | SemaRef.EmitCurrentDiagnostic(DiagID); |
1595 | } |
1596 | |
1597 | /// Teach operator<< to produce an object of the correct type. |
1598 | template <typename T> |
1599 | friend const ImmediateDiagBuilder & |
1600 | operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { |
1601 | const DiagnosticBuilder &BaseDiag = Diag; |
1602 | BaseDiag << Value; |
1603 | return Diag; |
1604 | } |
1605 | |
1606 | // It is necessary to limit this to rvalue reference to avoid calling this |
1607 | // function with a bitfield lvalue argument since non-const reference to |
1608 | // bitfield is not allowed. |
1609 | template <typename T, typename = typename std::enable_if< |
1610 | !std::is_lvalue_reference<T>::value>::type> |
1611 | const ImmediateDiagBuilder &operator<<(T &&V) const { |
1612 | const DiagnosticBuilder &BaseDiag = *this; |
1613 | BaseDiag << std::move(V); |
1614 | return *this; |
1615 | } |
1616 | }; |
1617 | |
1618 | /// A generic diagnostic builder for errors which may or may not be deferred. |
1619 | /// |
1620 | /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) |
1621 | /// which are not allowed to appear inside __device__ functions and are |
1622 | /// allowed to appear in __host__ __device__ functions only if the host+device |
1623 | /// function is never codegen'ed. |
1624 | /// |
1625 | /// To handle this, we use the notion of "deferred diagnostics", where we |
1626 | /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. |
1627 | /// |
1628 | /// This class lets you emit either a regular diagnostic, a deferred |
1629 | /// diagnostic, or no diagnostic at all, according to an argument you pass to |
1630 | /// its constructor, thus simplifying the process of creating these "maybe |
1631 | /// deferred" diagnostics. |
1632 | class SemaDiagnosticBuilder { |
1633 | public: |
1634 | enum Kind { |
1635 | /// Emit no diagnostics. |
1636 | K_Nop, |
1637 | /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). |
1638 | K_Immediate, |
1639 | /// Emit the diagnostic immediately, and, if it's a warning or error, also |
1640 | /// emit a call stack showing how this function can be reached by an a |
1641 | /// priori known-emitted function. |
1642 | K_ImmediateWithCallStack, |
1643 | /// Create a deferred diagnostic, which is emitted only if the function |
1644 | /// it's attached to is codegen'ed. Also emit a call stack as with |
1645 | /// K_ImmediateWithCallStack. |
1646 | K_Deferred |
1647 | }; |
1648 | |
1649 | SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, |
1650 | FunctionDecl *Fn, Sema &S); |
1651 | SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D); |
1652 | SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default; |
1653 | ~SemaDiagnosticBuilder(); |
1654 | |
1655 | bool isImmediate() const { return ImmediateDiag.hasValue(); } |
1656 | |
1657 | /// Convertible to bool: True if we immediately emitted an error, false if |
1658 | /// we didn't emit an error or we created a deferred error. |
1659 | /// |
1660 | /// Example usage: |
1661 | /// |
1662 | /// if (SemaDiagnosticBuilder(...) << foo << bar) |
1663 | /// return ExprError(); |
1664 | /// |
1665 | /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably |
1666 | /// want to use these instead of creating a SemaDiagnosticBuilder yourself. |
1667 | operator bool() const { return isImmediate(); } |
1668 | |
1669 | template <typename T> |
1670 | friend const SemaDiagnosticBuilder & |
1671 | operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) { |
1672 | if (Diag.ImmediateDiag.hasValue()) |
1673 | *Diag.ImmediateDiag << Value; |
1674 | else if (Diag.PartialDiagId.hasValue()) |
1675 | Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second |
1676 | << Value; |
1677 | return Diag; |
1678 | } |
1679 | |
1680 | // It is necessary to limit this to rvalue reference to avoid calling this |
1681 | // function with a bitfield lvalue argument since non-const reference to |
1682 | // bitfield is not allowed. |
1683 | template <typename T, typename = typename std::enable_if< |
1684 | !std::is_lvalue_reference<T>::value>::type> |
1685 | const SemaDiagnosticBuilder &operator<<(T &&V) const { |
1686 | if (ImmediateDiag.hasValue()) |
1687 | *ImmediateDiag << std::move(V); |
1688 | else if (PartialDiagId.hasValue()) |
1689 | S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V); |
1690 | return *this; |
1691 | } |
1692 | |
1693 | friend const SemaDiagnosticBuilder & |
1694 | operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { |
1695 | if (Diag.ImmediateDiag.hasValue()) |
1696 | PD.Emit(*Diag.ImmediateDiag); |
1697 | else if (Diag.PartialDiagId.hasValue()) |
1698 | Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD; |
1699 | return Diag; |
1700 | } |
1701 | |
1702 | void AddFixItHint(const FixItHint &Hint) const { |
1703 | if (ImmediateDiag.hasValue()) |
1704 | ImmediateDiag->AddFixItHint(Hint); |
1705 | else if (PartialDiagId.hasValue()) |
1706 | S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint); |
1707 | } |
1708 | |
1709 | friend ExprResult ExprError(const SemaDiagnosticBuilder &) { |
1710 | return ExprError(); |
1711 | } |
1712 | friend StmtResult StmtError(const SemaDiagnosticBuilder &) { |
1713 | return StmtError(); |
1714 | } |
1715 | operator ExprResult() const { return ExprError(); } |
1716 | operator StmtResult() const { return StmtError(); } |
1717 | operator TypeResult() const { return TypeError(); } |
1718 | operator DeclResult() const { return DeclResult(true); } |
1719 | operator MemInitResult() const { return MemInitResult(true); } |
1720 | |
1721 | private: |
1722 | Sema &S; |
1723 | SourceLocation Loc; |
1724 | unsigned DiagID; |
1725 | FunctionDecl *Fn; |
1726 | bool ShowCallStack; |
1727 | |
1728 | // Invariant: At most one of these Optionals has a value. |
1729 | // FIXME: Switch these to a Variant once that exists. |
1730 | llvm::Optional<ImmediateDiagBuilder> ImmediateDiag; |
1731 | llvm::Optional<unsigned> PartialDiagId; |
1732 | }; |
1733 | |
1734 | /// Is the last error level diagnostic immediate. This is used to determined |
1735 | /// whether the next info diagnostic should be immediate. |
1736 | bool IsLastErrorImmediate = true; |
1737 | |
1738 | /// Emit a diagnostic. |
1739 | SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, |
1740 | bool DeferHint = false); |
1741 | |
1742 | /// Emit a partial diagnostic. |
1743 | SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD, |
1744 | bool DeferHint = false); |
1745 | |
1746 | /// Build a partial diagnostic. |
1747 | PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h |
1748 | |
1749 | /// Whether uncompilable error has occurred. This includes error happens |
1750 | /// in deferred diagnostics. |
1751 | bool hasUncompilableErrorOccurred() const; |
1752 | |
1753 | bool findMacroSpelling(SourceLocation &loc, StringRef name); |
1754 | |
1755 | /// Get a string to suggest for zero-initialization of a type. |
1756 | std::string |
1757 | getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; |
1758 | std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; |
1759 | |
1760 | /// Calls \c Lexer::getLocForEndOfToken() |
1761 | SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); |
1762 | |
1763 | /// Retrieve the module loader associated with the preprocessor. |
1764 | ModuleLoader &getModuleLoader() const; |
1765 | |
1766 | /// Invent a new identifier for parameters of abbreviated templates. |
1767 | IdentifierInfo * |
1768 | InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, |
1769 | unsigned Index); |
1770 | |
1771 | void emitAndClearUnusedLocalTypedefWarnings(); |
1772 | |
1773 | private: |
1774 | /// Function or variable declarations to be checked for whether the deferred |
1775 | /// diagnostics should be emitted. |
1776 | SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags; |
1777 | |
1778 | public: |
1779 | // Emit all deferred diagnostics. |
1780 | void emitDeferredDiags(); |
1781 | |
1782 | enum TUFragmentKind { |
1783 | /// The global module fragment, between 'module;' and a module-declaration. |
1784 | Global, |
1785 | /// A normal translation unit fragment. For a non-module unit, this is the |
1786 | /// entire translation unit. Otherwise, it runs from the module-declaration |
1787 | /// to the private-module-fragment (if any) or the end of the TU (if not). |
1788 | Normal, |
1789 | /// The private module fragment, between 'module :private;' and the end of |
1790 | /// the translation unit. |
1791 | Private |
1792 | }; |
1793 | |
1794 | void ActOnStartOfTranslationUnit(); |
1795 | void ActOnEndOfTranslationUnit(); |
1796 | void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); |
1797 | |
1798 | void CheckDelegatingCtorCycles(); |
1799 | |
1800 | Scope *getScopeForContext(DeclContext *Ctx); |
1801 | |
1802 | void PushFunctionScope(); |
1803 | void PushBlockScope(Scope *BlockScope, BlockDecl *Block); |
1804 | sema::LambdaScopeInfo *PushLambdaScope(); |
1805 | |
1806 | /// This is used to inform Sema what the current TemplateParameterDepth |
1807 | /// is during Parsing. Currently it is used to pass on the depth |
1808 | /// when parsing generic lambda 'auto' parameters. |
1809 | void RecordParsingTemplateParameterDepth(unsigned Depth); |
1810 | |
1811 | void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, |
1812 | RecordDecl *RD, CapturedRegionKind K, |
1813 | unsigned OpenMPCaptureLevel = 0); |
1814 | |
1815 | /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short |
1816 | /// time after they've been popped. |
1817 | class PoppedFunctionScopeDeleter { |
1818 | Sema *Self; |
1819 | |
1820 | public: |
1821 | explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} |
1822 | void operator()(sema::FunctionScopeInfo *Scope) const; |
1823 | }; |
1824 | |
1825 | using PoppedFunctionScopePtr = |
1826 | std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; |
1827 | |
1828 | PoppedFunctionScopePtr |
1829 | PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, |
1830 | const Decl *D = nullptr, |
1831 | QualType BlockType = QualType()); |
1832 | |
1833 | sema::FunctionScopeInfo *getCurFunction() const { |
1834 | return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); |
1835 | } |
1836 | |
1837 | sema::FunctionScopeInfo *getEnclosingFunction() const; |
1838 | |
1839 | void setFunctionHasBranchIntoScope(); |
1840 | void setFunctionHasBranchProtectedScope(); |
1841 | void setFunctionHasIndirectGoto(); |
1842 | |
1843 | void PushCompoundScope(bool IsStmtExpr); |
1844 | void PopCompoundScope(); |
1845 | |
1846 | sema::CompoundScopeInfo &getCurCompoundScope() const; |
1847 | |
1848 | bool hasAnyUnrecoverableErrorsInThisFunction() const; |
1849 | |
1850 | /// Retrieve the current block, if any. |
1851 | sema::BlockScopeInfo *getCurBlock(); |
1852 | |
1853 | /// Get the innermost lambda enclosing the current location, if any. This |
1854 | /// looks through intervening non-lambda scopes such as local functions and |
1855 | /// blocks. |
1856 | sema::LambdaScopeInfo *getEnclosingLambda() const; |
1857 | |
1858 | /// Retrieve the current lambda scope info, if any. |
1859 | /// \param IgnoreNonLambdaCapturingScope true if should find the top-most |
1860 | /// lambda scope info ignoring all inner capturing scopes that are not |
1861 | /// lambda scopes. |
1862 | sema::LambdaScopeInfo * |
1863 | getCurLambda(bool IgnoreNonLambdaCapturingScope = false); |
1864 | |
1865 | /// Retrieve the current generic lambda info, if any. |
1866 | sema::LambdaScopeInfo *getCurGenericLambda(); |
1867 | |
1868 | /// Retrieve the current captured region, if any. |
1869 | sema::CapturedRegionScopeInfo *getCurCapturedRegion(); |
1870 | |
1871 | /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls |
1872 | SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } |
1873 | |
1874 | /// Called before parsing a function declarator belonging to a function |
1875 | /// declaration. |
1876 | void ActOnStartFunctionDeclarationDeclarator(Declarator &D, |
1877 | unsigned TemplateParameterDepth); |
1878 | |
1879 | /// Called after parsing a function declarator belonging to a function |
1880 | /// declaration. |
1881 | void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); |
1882 | |
1883 | void ActOnComment(SourceRange Comment); |
1884 | |
1885 | //===--------------------------------------------------------------------===// |
1886 | // Type Analysis / Processing: SemaType.cpp. |
1887 | // |
1888 | |
1889 | QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, |
1890 | const DeclSpec *DS = nullptr); |
1891 | QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, |
1892 | const DeclSpec *DS = nullptr); |
1893 | QualType BuildPointerType(QualType T, |
1894 | SourceLocation Loc, DeclarationName Entity); |
1895 | QualType BuildReferenceType(QualType T, bool LValueRef, |
1896 | SourceLocation Loc, DeclarationName Entity); |
1897 | QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, |
1898 | Expr *ArraySize, unsigned Quals, |
1899 | SourceRange Brackets, DeclarationName Entity); |
1900 | QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); |
1901 | QualType BuildExtVectorType(QualType T, Expr *ArraySize, |
1902 | SourceLocation AttrLoc); |
1903 | QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, |
1904 | SourceLocation AttrLoc); |
1905 | |
1906 | QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, |
1907 | SourceLocation AttrLoc); |
1908 | |
1909 | /// Same as above, but constructs the AddressSpace index if not provided. |
1910 | QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, |
1911 | SourceLocation AttrLoc); |
1912 | |
1913 | bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); |
1914 | |
1915 | bool CheckFunctionReturnType(QualType T, SourceLocation Loc); |
1916 | |
1917 | /// Build a function type. |
1918 | /// |
1919 | /// This routine checks the function type according to C++ rules and |
1920 | /// under the assumption that the result type and parameter types have |
1921 | /// just been instantiated from a template. It therefore duplicates |
1922 | /// some of the behavior of GetTypeForDeclarator, but in a much |
1923 | /// simpler form that is only suitable for this narrow use case. |
1924 | /// |
1925 | /// \param T The return type of the function. |
1926 | /// |
1927 | /// \param ParamTypes The parameter types of the function. This array |
1928 | /// will be modified to account for adjustments to the types of the |
1929 | /// function parameters. |
1930 | /// |
1931 | /// \param Loc The location of the entity whose type involves this |
1932 | /// function type or, if there is no such entity, the location of the |
1933 | /// type that will have function type. |
1934 | /// |
1935 | /// \param Entity The name of the entity that involves the function |
1936 | /// type, if known. |
1937 | /// |
1938 | /// \param EPI Extra information about the function type. Usually this will |
1939 | /// be taken from an existing function with the same prototype. |
1940 | /// |
1941 | /// \returns A suitable function type, if there are no errors. The |
1942 | /// unqualified type will always be a FunctionProtoType. |
1943 | /// Otherwise, returns a NULL type. |
1944 | QualType BuildFunctionType(QualType T, |
1945 | MutableArrayRef<QualType> ParamTypes, |
1946 | SourceLocation Loc, DeclarationName Entity, |
1947 | const FunctionProtoType::ExtProtoInfo &EPI); |
1948 | |
1949 | QualType BuildMemberPointerType(QualType T, QualType Class, |
1950 | SourceLocation Loc, |
1951 | DeclarationName Entity); |
1952 | QualType BuildBlockPointerType(QualType T, |
1953 | SourceLocation Loc, DeclarationName Entity); |
1954 | QualType BuildParenType(QualType T); |
1955 | QualType BuildAtomicType(QualType T, SourceLocation Loc); |
1956 | QualType BuildReadPipeType(QualType T, |
1957 | SourceLocation Loc); |
1958 | QualType BuildWritePipeType(QualType T, |
1959 | SourceLocation Loc); |
1960 | QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); |
1961 | |
1962 | TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); |
1963 | TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); |
1964 | |
1965 | /// Package the given type and TSI into a ParsedType. |
1966 | ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); |
1967 | DeclarationNameInfo GetNameForDeclarator(Declarator &D); |
1968 | DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); |
1969 | static QualType GetTypeFromParser(ParsedType Ty, |
1970 | TypeSourceInfo **TInfo = nullptr); |
1971 | CanThrowResult canThrow(const Stmt *E); |
1972 | /// Determine whether the callee of a particular function call can throw. |
1973 | /// E, D and Loc are all optional. |
1974 | static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, |
1975 | SourceLocation Loc = SourceLocation()); |
1976 | const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, |
1977 | const FunctionProtoType *FPT); |
1978 | void UpdateExceptionSpec(FunctionDecl *FD, |
1979 | const FunctionProtoType::ExceptionSpecInfo &ESI); |
1980 | bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); |
1981 | bool CheckDistantExceptionSpec(QualType T); |
1982 | bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); |
1983 | bool CheckEquivalentExceptionSpec( |
1984 | const FunctionProtoType *Old, SourceLocation OldLoc, |
1985 | const FunctionProtoType *New, SourceLocation NewLoc); |
1986 | bool CheckEquivalentExceptionSpec( |
1987 | const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, |
1988 | const FunctionProtoType *Old, SourceLocation OldLoc, |
1989 | const FunctionProtoType *New, SourceLocation NewLoc); |
1990 | bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); |
1991 | bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, |
1992 | const PartialDiagnostic &NestedDiagID, |
1993 | const PartialDiagnostic &NoteID, |
1994 | const PartialDiagnostic &NoThrowDiagID, |
1995 | const FunctionProtoType *Superset, |
1996 | SourceLocation SuperLoc, |
1997 | const FunctionProtoType *Subset, |
1998 | SourceLocation SubLoc); |
1999 | bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, |
2000 | const PartialDiagnostic &NoteID, |
2001 | const FunctionProtoType *Target, |
2002 | SourceLocation TargetLoc, |
2003 | const FunctionProtoType *Source, |
2004 | SourceLocation SourceLoc); |
2005 | |
2006 | TypeResult ActOnTypeName(Scope *S, Declarator &D); |
2007 | |
2008 | /// The parser has parsed the context-sensitive type 'instancetype' |
2009 | /// in an Objective-C message declaration. Return the appropriate type. |
2010 | ParsedType ActOnObjCInstanceType(SourceLocation Loc); |
2011 | |
2012 | /// Abstract cl |