| 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/DeclBase.h" |
| 18 | #include "clang/AST/DeclTemplate.h" |
| 19 | #include "clang/AST/DynamicRecursiveASTVisitor.h" |
| 20 | #include "clang/AST/Expr.h" |
| 21 | #include "clang/AST/ExprConcepts.h" |
| 22 | #include "clang/AST/PrettyDeclStackTrace.h" |
| 23 | #include "clang/AST/Type.h" |
| 24 | #include "clang/AST/TypeLoc.h" |
| 25 | #include "clang/AST/TypeVisitor.h" |
| 26 | #include "clang/Basic/LangOptions.h" |
| 27 | #include "clang/Basic/TargetInfo.h" |
| 28 | #include "clang/Sema/DeclSpec.h" |
| 29 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
| 30 | #include "clang/Sema/Initialization.h" |
| 31 | #include "clang/Sema/Sema.h" |
| 32 | #include "clang/Sema/SemaConcept.h" |
| 33 | #include "clang/Sema/SemaInternal.h" |
| 34 | #include "clang/Sema/Template.h" |
| 35 | #include "clang/Sema/TemplateDeduction.h" |
| 36 | #include "llvm/ADT/SmallVectorExtras.h" |
| 37 | #include "llvm/ADT/StringExtras.h" |
| 38 | #include "llvm/Support/ErrorHandling.h" |
| 39 | #include "llvm/Support/SaveAndRestore.h" |
| 40 | #include "llvm/Support/TimeProfiler.h" |
| 41 | #include <optional> |
| 42 | |
| 43 | using namespace clang; |
| 44 | using namespace sema; |
| 45 | |
| 46 | //===----------------------------------------------------------------------===/ |
| 47 | // Template Instantiation Support |
| 48 | //===----------------------------------------------------------------------===/ |
| 49 | |
| 50 | namespace { |
| 51 | namespace TemplateInstArgsHelpers { |
| 52 | struct Response { |
| 53 | const Decl *NextDecl = nullptr; |
| 54 | bool IsDone = false; |
| 55 | bool ClearRelativeToPrimary = true; |
| 56 | static Response Done() { |
| 57 | Response R; |
| 58 | R.IsDone = true; |
| 59 | return R; |
| 60 | } |
| 61 | static Response ChangeDecl(const Decl *ND) { |
| 62 | Response R; |
| 63 | R.NextDecl = ND; |
| 64 | return R; |
| 65 | } |
| 66 | static Response ChangeDecl(const DeclContext *Ctx) { |
| 67 | Response R; |
| 68 | R.NextDecl = Decl::castFromDeclContext(Ctx); |
| 69 | return R; |
| 70 | } |
| 71 | |
| 72 | static Response UseNextDecl(const Decl *CurDecl) { |
| 73 | return ChangeDecl(Ctx: CurDecl->getDeclContext()); |
| 74 | } |
| 75 | |
| 76 | static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) { |
| 77 | Response R = Response::UseNextDecl(CurDecl); |
| 78 | R.ClearRelativeToPrimary = false; |
| 79 | return R; |
| 80 | } |
| 81 | }; |
| 82 | |
| 83 | // Retrieve the primary template for a lambda call operator. It's |
| 84 | // unfortunate that we only have the mappings of call operators rather |
| 85 | // than lambda classes. |
| 86 | const FunctionDecl * |
| 87 | getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) { |
| 88 | if (!isLambdaCallOperator(DC: LambdaCallOperator)) |
| 89 | return LambdaCallOperator; |
| 90 | while (true) { |
| 91 | if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>( |
| 92 | Val: LambdaCallOperator->getDescribedTemplate()); |
| 93 | FTD && FTD->getInstantiatedFromMemberTemplate()) { |
| 94 | LambdaCallOperator = |
| 95 | FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl(); |
| 96 | } else if (LambdaCallOperator->getPrimaryTemplate()) { |
| 97 | // Cases where the lambda operator is instantiated in |
| 98 | // TemplateDeclInstantiator::VisitCXXMethodDecl. |
| 99 | LambdaCallOperator = |
| 100 | LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl(); |
| 101 | } else if (auto *Prev = cast<CXXMethodDecl>(Val: LambdaCallOperator) |
| 102 | ->getInstantiatedFromMemberFunction()) |
| 103 | LambdaCallOperator = Prev; |
| 104 | else |
| 105 | break; |
| 106 | } |
| 107 | return LambdaCallOperator; |
| 108 | } |
| 109 | |
| 110 | struct EnclosingTypeAliasTemplateDetails { |
| 111 | TypeAliasTemplateDecl *Template = nullptr; |
| 112 | TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr; |
| 113 | ArrayRef<TemplateArgument> AssociatedTemplateArguments; |
| 114 | |
| 115 | explicit operator bool() noexcept { return Template; } |
| 116 | }; |
| 117 | |
| 118 | // Find the enclosing type alias template Decl from CodeSynthesisContexts, as |
| 119 | // well as its primary template and instantiating template arguments. |
| 120 | EnclosingTypeAliasTemplateDetails |
| 121 | getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) { |
| 122 | for (auto &CSC : llvm::reverse(C&: SemaRef.CodeSynthesisContexts)) { |
| 123 | if (CSC.Kind != Sema::CodeSynthesisContext::SynthesisKind:: |
| 124 | TypeAliasTemplateInstantiation) |
| 125 | continue; |
| 126 | EnclosingTypeAliasTemplateDetails Result; |
| 127 | auto *TATD = cast<TypeAliasTemplateDecl>(Val: CSC.Entity), |
| 128 | *Next = TATD->getInstantiatedFromMemberTemplate(); |
| 129 | Result = { |
| 130 | /*Template=*/TATD, |
| 131 | /*PrimaryTypeAliasDecl=*/TATD, |
| 132 | /*AssociatedTemplateArguments=*/CSC.template_arguments(), |
| 133 | }; |
| 134 | while (Next) { |
| 135 | Result.PrimaryTypeAliasDecl = Next; |
| 136 | Next = Next->getInstantiatedFromMemberTemplate(); |
| 137 | } |
| 138 | return Result; |
| 139 | } |
| 140 | return {}; |
| 141 | } |
| 142 | |
| 143 | // Check if we are currently inside of a lambda expression that is |
| 144 | // surrounded by a using alias declaration. e.g. |
| 145 | // template <class> using type = decltype([](auto) { ^ }()); |
| 146 | // We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never |
| 147 | // a DeclContext, nor does it have an associated specialization Decl from which |
| 148 | // we could collect these template arguments. |
| 149 | bool isLambdaEnclosedByTypeAliasDecl( |
| 150 | const FunctionDecl *LambdaCallOperator, |
| 151 | const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) { |
| 152 | struct Visitor : DynamicRecursiveASTVisitor { |
| 153 | Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {} |
| 154 | bool VisitLambdaExpr(LambdaExpr *LE) override { |
| 155 | // Return true to bail out of the traversal, implying the Decl contains |
| 156 | // the lambda. |
| 157 | return getPrimaryTemplateOfGenericLambda(LambdaCallOperator: LE->getCallOperator()) != |
| 158 | CallOperator; |
| 159 | } |
| 160 | const FunctionDecl *CallOperator; |
| 161 | }; |
| 162 | |
| 163 | QualType Underlying = |
| 164 | PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType(); |
| 165 | |
| 166 | return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator)) |
| 167 | .TraverseType(T: Underlying); |
| 168 | } |
| 169 | |
| 170 | // Add template arguments from a variable template instantiation. |
| 171 | Response |
| 172 | HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec, |
| 173 | MultiLevelTemplateArgumentList &Result, |
| 174 | bool SkipForSpecialization) { |
| 175 | // For a class-scope explicit specialization, there are no template arguments |
| 176 | // at this level, but there may be enclosing template arguments. |
| 177 | if (VarTemplSpec->isClassScopeExplicitSpecialization()) |
| 178 | return Response::DontClearRelativeToPrimaryNextDecl(CurDecl: VarTemplSpec); |
| 179 | |
| 180 | // We're done when we hit an explicit specialization. |
| 181 | if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization && |
| 182 | !isa<VarTemplatePartialSpecializationDecl>(Val: VarTemplSpec)) |
| 183 | return Response::Done(); |
| 184 | |
| 185 | // If this variable template specialization was instantiated from a |
| 186 | // specialized member that is a variable template, we're done. |
| 187 | assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?" ); |
| 188 | llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *> |
| 189 | Specialized = VarTemplSpec->getSpecializedTemplateOrPartial(); |
| 190 | if (VarTemplatePartialSpecializationDecl *Partial = |
| 191 | dyn_cast<VarTemplatePartialSpecializationDecl *>(Val&: Specialized)) { |
| 192 | if (!SkipForSpecialization) |
| 193 | Result.addOuterTemplateArguments( |
| 194 | AssociatedDecl: Partial, Args: VarTemplSpec->getTemplateInstantiationArgs().asArray(), |
| 195 | /*Final=*/false); |
| 196 | if (Partial->isMemberSpecialization()) |
| 197 | return Response::Done(); |
| 198 | } else { |
| 199 | VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Val&: Specialized); |
| 200 | if (!SkipForSpecialization) |
| 201 | Result.addOuterTemplateArguments( |
| 202 | AssociatedDecl: Tmpl, Args: VarTemplSpec->getTemplateInstantiationArgs().asArray(), |
| 203 | /*Final=*/false); |
| 204 | if (Tmpl->isMemberSpecialization()) |
| 205 | return Response::Done(); |
| 206 | } |
| 207 | return Response::DontClearRelativeToPrimaryNextDecl(CurDecl: VarTemplSpec); |
| 208 | } |
| 209 | |
| 210 | // If we have a template template parameter with translation unit context, |
| 211 | // then we're performing substitution into a default template argument of |
| 212 | // this template template parameter before we've constructed the template |
| 213 | // that will own this template template parameter. In this case, we |
| 214 | // use empty template parameter lists for all of the outer templates |
| 215 | // to avoid performing any substitutions. |
| 216 | Response |
| 217 | HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP, |
| 218 | MultiLevelTemplateArgumentList &Result) { |
| 219 | for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I) |
| 220 | Result.addOuterTemplateArguments(std::nullopt); |
| 221 | return Response::Done(); |
| 222 | } |
| 223 | |
| 224 | Response HandlePartialClassTemplateSpec( |
| 225 | const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec, |
| 226 | MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) { |
| 227 | if (!SkipForSpecialization) |
| 228 | Result.addOuterRetainedLevels(Num: PartialClassTemplSpec->getTemplateDepth()); |
| 229 | return Response::Done(); |
| 230 | } |
| 231 | |
| 232 | // Add template arguments from a class template instantiation. |
| 233 | Response |
| 234 | HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec, |
| 235 | MultiLevelTemplateArgumentList &Result, |
| 236 | bool SkipForSpecialization) { |
| 237 | if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) { |
| 238 | // We're done when we hit an explicit specialization. |
| 239 | if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization && |
| 240 | !isa<ClassTemplatePartialSpecializationDecl>(Val: ClassTemplSpec)) |
| 241 | return Response::Done(); |
| 242 | |
| 243 | if (!SkipForSpecialization) |
| 244 | Result.addOuterTemplateArguments( |
| 245 | AssociatedDecl: const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec), |
| 246 | Args: ClassTemplSpec->getTemplateInstantiationArgs().asArray(), |
| 247 | /*Final=*/false); |
| 248 | |
| 249 | // If this class template specialization was instantiated from a |
| 250 | // specialized member that is a class template, we're done. |
| 251 | assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?" ); |
| 252 | if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization()) |
| 253 | return Response::Done(); |
| 254 | |
| 255 | // If this was instantiated from a partial template specialization, we need |
| 256 | // to get the next level of declaration context from the partial |
| 257 | // specialization, as the ClassTemplateSpecializationDecl's |
| 258 | // DeclContext/LexicalDeclContext will be for the primary template. |
| 259 | if (auto *InstFromPartialTempl = |
| 260 | ClassTemplSpec->getSpecializedTemplateOrPartial() |
| 261 | .dyn_cast<ClassTemplatePartialSpecializationDecl *>()) |
| 262 | return Response::ChangeDecl( |
| 263 | Ctx: InstFromPartialTempl->getLexicalDeclContext()); |
| 264 | } |
| 265 | return Response::UseNextDecl(CurDecl: ClassTemplSpec); |
| 266 | } |
| 267 | |
| 268 | Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function, |
| 269 | MultiLevelTemplateArgumentList &Result, |
| 270 | const FunctionDecl *Pattern, bool RelativeToPrimary, |
| 271 | bool ForConstraintInstantiation, |
| 272 | bool ForDefaultArgumentSubstitution) { |
| 273 | // Add template arguments from a function template specialization. |
| 274 | if (!RelativeToPrimary && |
| 275 | Function->getTemplateSpecializationKindForInstantiation() == |
| 276 | TSK_ExplicitSpecialization) |
| 277 | return Response::Done(); |
| 278 | |
| 279 | if (!RelativeToPrimary && |
| 280 | Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { |
| 281 | // This is an implicit instantiation of an explicit specialization. We |
| 282 | // don't get any template arguments from this function but might get |
| 283 | // some from an enclosing template. |
| 284 | return Response::UseNextDecl(CurDecl: Function); |
| 285 | } else if (const TemplateArgumentList *TemplateArgs = |
| 286 | Function->getTemplateSpecializationArgs()) { |
| 287 | // Add the template arguments for this specialization. |
| 288 | Result.addOuterTemplateArguments(AssociatedDecl: const_cast<FunctionDecl *>(Function), |
| 289 | Args: TemplateArgs->asArray(), |
| 290 | /*Final=*/false); |
| 291 | |
| 292 | if (RelativeToPrimary && |
| 293 | (Function->getTemplateSpecializationKind() == |
| 294 | TSK_ExplicitSpecialization || |
| 295 | (Function->getFriendObjectKind() && |
| 296 | !Function->getPrimaryTemplate()->getFriendObjectKind()))) |
| 297 | return Response::UseNextDecl(CurDecl: Function); |
| 298 | |
| 299 | // If this function was instantiated from a specialized member that is |
| 300 | // a function template, we're done. |
| 301 | assert(Function->getPrimaryTemplate() && "No function template?" ); |
| 302 | if (!ForDefaultArgumentSubstitution && |
| 303 | Function->getPrimaryTemplate()->isMemberSpecialization()) |
| 304 | return Response::Done(); |
| 305 | |
| 306 | // If this function is a generic lambda specialization, we are done. |
| 307 | if (!ForConstraintInstantiation && |
| 308 | isGenericLambdaCallOperatorOrStaticInvokerSpecialization(DC: Function)) |
| 309 | return Response::Done(); |
| 310 | |
| 311 | } else if (auto *Template = Function->getDescribedFunctionTemplate()) { |
| 312 | assert( |
| 313 | (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && |
| 314 | "Outer template not instantiated?" ); |
| 315 | if (ForConstraintInstantiation) { |
| 316 | for (auto &Inst : llvm::reverse(C&: SemaRef.CodeSynthesisContexts)) { |
| 317 | if (Inst.Kind == Sema::CodeSynthesisContext::ConstraintsCheck && |
| 318 | Inst.Entity == Template) { |
| 319 | // After CWG2369, the outer templates are not instantiated when |
| 320 | // checking its associated constraints. So add them back through the |
| 321 | // synthesis context; this is useful for e.g. nested constraints |
| 322 | // involving lambdas. |
| 323 | Result.addOuterTemplateArguments(AssociatedDecl: Template, Args: Inst.template_arguments(), |
| 324 | /*Final=*/false); |
| 325 | break; |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | // If this is a friend or local declaration and it declares an entity at |
| 331 | // namespace scope, take arguments from its lexical parent |
| 332 | // instead of its semantic parent, unless of course the pattern we're |
| 333 | // instantiating actually comes from the file's context! |
| 334 | if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) && |
| 335 | Function->getNonTransparentDeclContext()->isFileContext() && |
| 336 | (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) { |
| 337 | return Response::ChangeDecl(Ctx: Function->getLexicalDeclContext()); |
| 338 | } |
| 339 | |
| 340 | if (ForConstraintInstantiation && Function->getFriendObjectKind()) |
| 341 | return Response::ChangeDecl(Ctx: Function->getLexicalDeclContext()); |
| 342 | return Response::UseNextDecl(CurDecl: Function); |
| 343 | } |
| 344 | |
| 345 | Response HandleFunctionTemplateDecl(Sema &SemaRef, |
| 346 | const FunctionTemplateDecl *FTD, |
| 347 | MultiLevelTemplateArgumentList &Result) { |
| 348 | if (!isa<ClassTemplateSpecializationDecl>(Val: FTD->getDeclContext())) { |
| 349 | Result.addOuterTemplateArguments( |
| 350 | AssociatedDecl: const_cast<FunctionTemplateDecl *>(FTD), |
| 351 | Args: const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs( |
| 352 | Context: SemaRef.Context), |
| 353 | /*Final=*/false); |
| 354 | |
| 355 | NestedNameSpecifier NNS = FTD->getTemplatedDecl()->getQualifier(); |
| 356 | |
| 357 | for (const Type *Ty = NNS.getKind() == NestedNameSpecifier::Kind::Type |
| 358 | ? NNS.getAsType() |
| 359 | : nullptr, |
| 360 | *NextTy = nullptr; |
| 361 | Ty && Ty->isInstantiationDependentType(); |
| 362 | Ty = std::exchange(obj&: NextTy, new_val: nullptr)) { |
| 363 | if (NestedNameSpecifier P = Ty->getPrefix(); |
| 364 | P.getKind() == NestedNameSpecifier::Kind::Type) |
| 365 | NextTy = P.getAsType(); |
| 366 | const auto *TSTy = dyn_cast<TemplateSpecializationType>(Val: Ty); |
| 367 | if (!TSTy) |
| 368 | continue; |
| 369 | |
| 370 | ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments(); |
| 371 | // Prefer template arguments from the injected-class-type if possible. |
| 372 | // For example, |
| 373 | // ```cpp |
| 374 | // template <class... Pack> struct S { |
| 375 | // template <class T> void foo(); |
| 376 | // }; |
| 377 | // template <class... Pack> template <class T> |
| 378 | // ^^^^^^^^^^^^^ InjectedTemplateArgs |
| 379 | // They're of kind TemplateArgument::Pack, not of |
| 380 | // TemplateArgument::Type. |
| 381 | // void S<Pack...>::foo() {} |
| 382 | // ^^^^^^^ |
| 383 | // TSTy->template_arguments() (which are of PackExpansionType) |
| 384 | // ``` |
| 385 | // This meets the contract in |
| 386 | // TreeTransform::TryExpandParameterPacks that the template arguments |
| 387 | // for unexpanded parameters should be of a Pack kind. |
| 388 | if (TSTy->isCurrentInstantiation()) { |
| 389 | auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl(); |
| 390 | if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) |
| 391 | Arguments = CTD->getInjectedTemplateArgs(Context: SemaRef.Context); |
| 392 | else if (auto *Specialization = |
| 393 | dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) |
| 394 | Arguments = Specialization->getTemplateInstantiationArgs().asArray(); |
| 395 | } |
| 396 | Result.addOuterTemplateArguments( |
| 397 | AssociatedDecl: TSTy->getTemplateName().getAsTemplateDecl(), Args: Arguments, |
| 398 | /*Final=*/false); |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | return Response::ChangeDecl(Ctx: FTD->getLexicalDeclContext()); |
| 403 | } |
| 404 | |
| 405 | Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec, |
| 406 | MultiLevelTemplateArgumentList &Result, |
| 407 | ASTContext &Context, |
| 408 | bool ForConstraintInstantiation) { |
| 409 | if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) { |
| 410 | assert( |
| 411 | (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && |
| 412 | "Outer template not instantiated?" ); |
| 413 | if (ClassTemplate->isMemberSpecialization()) |
| 414 | return Response::Done(); |
| 415 | if (ForConstraintInstantiation) |
| 416 | Result.addOuterTemplateArguments( |
| 417 | AssociatedDecl: const_cast<CXXRecordDecl *>(Rec), |
| 418 | Args: ClassTemplate->getInjectedTemplateArgs(Context: SemaRef.Context), |
| 419 | /*Final=*/false); |
| 420 | } |
| 421 | |
| 422 | if (const MemberSpecializationInfo *MSInfo = |
| 423 | Rec->getMemberSpecializationInfo()) |
| 424 | if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) |
| 425 | return Response::Done(); |
| 426 | |
| 427 | bool IsFriend = Rec->getFriendObjectKind() || |
| 428 | (Rec->getDescribedClassTemplate() && |
| 429 | Rec->getDescribedClassTemplate()->getFriendObjectKind()); |
| 430 | if (ForConstraintInstantiation && IsFriend && |
| 431 | Rec->getNonTransparentDeclContext()->isFileContext()) { |
| 432 | return Response::ChangeDecl(Ctx: Rec->getLexicalDeclContext()); |
| 433 | } |
| 434 | |
| 435 | // This is to make sure we pick up the VarTemplateSpecializationDecl or the |
| 436 | // TypeAliasTemplateDecl that this lambda is defined inside of. |
| 437 | if (Rec->isLambda()) { |
| 438 | if (const Decl *LCD = Rec->getLambdaContextDecl()) |
| 439 | return Response::ChangeDecl(ND: LCD); |
| 440 | // Retrieve the template arguments for a using alias declaration. |
| 441 | // This is necessary for constraint checking, since we always keep |
| 442 | // constraints relative to the primary template. |
| 443 | if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef); |
| 444 | ForConstraintInstantiation && TypeAlias) { |
| 445 | if (isLambdaEnclosedByTypeAliasDecl(LambdaCallOperator: Rec->getLambdaCallOperator(), |
| 446 | PrimaryTypeAliasDecl: TypeAlias.PrimaryTypeAliasDecl)) { |
| 447 | Result.addOuterTemplateArguments(AssociatedDecl: TypeAlias.Template, |
| 448 | Args: TypeAlias.AssociatedTemplateArguments, |
| 449 | /*Final=*/false); |
| 450 | // Visit the parent of the current type alias declaration rather than |
| 451 | // the lambda thereof. |
| 452 | // E.g., in the following example: |
| 453 | // struct S { |
| 454 | // template <class> using T = decltype([]<Concept> {} ()); |
| 455 | // }; |
| 456 | // void foo() { |
| 457 | // S::T var; |
| 458 | // } |
| 459 | // The instantiated lambda expression (which we're visiting at 'var') |
| 460 | // has a function DeclContext 'foo' rather than the Record DeclContext |
| 461 | // S. This seems to be an oversight to me that we may want to set a |
| 462 | // Sema Context from the CXXScopeSpec before substituting into T. |
| 463 | return Response::ChangeDecl(Ctx: TypeAlias.Template->getDeclContext()); |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | return Response::UseNextDecl(CurDecl: Rec); |
| 469 | } |
| 470 | |
| 471 | Response HandleImplicitConceptSpecializationDecl( |
| 472 | const ImplicitConceptSpecializationDecl *CSD, |
| 473 | MultiLevelTemplateArgumentList &Result) { |
| 474 | Result.addOuterTemplateArguments( |
| 475 | AssociatedDecl: const_cast<ImplicitConceptSpecializationDecl *>(CSD), |
| 476 | Args: CSD->getTemplateArguments(), |
| 477 | /*Final=*/false); |
| 478 | return Response::UseNextDecl(CurDecl: CSD); |
| 479 | } |
| 480 | |
| 481 | Response HandleGenericDeclContext(const Decl *CurDecl) { |
| 482 | return Response::UseNextDecl(CurDecl); |
| 483 | } |
| 484 | } // namespace TemplateInstArgsHelpers |
| 485 | } // namespace |
| 486 | |
| 487 | MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs( |
| 488 | const NamedDecl *ND, const DeclContext *DC, bool Final, |
| 489 | std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary, |
| 490 | const FunctionDecl *Pattern, bool ForConstraintInstantiation, |
| 491 | bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) { |
| 492 | assert((ND || DC) && "Can't find arguments for a decl if one isn't provided" ); |
| 493 | // Accumulate the set of template argument lists in this structure. |
| 494 | MultiLevelTemplateArgumentList Result; |
| 495 | |
| 496 | using namespace TemplateInstArgsHelpers; |
| 497 | const Decl *CurDecl = ND; |
| 498 | |
| 499 | if (Innermost) { |
| 500 | Result.addOuterTemplateArguments(AssociatedDecl: const_cast<NamedDecl *>(ND), Args: *Innermost, |
| 501 | Final); |
| 502 | // Populate placeholder template arguments for TemplateTemplateParmDecls. |
| 503 | // This is essential for the case e.g. |
| 504 | // |
| 505 | // template <class> concept Concept = false; |
| 506 | // template <template <Concept C> class T> void foo(T<int>) |
| 507 | // |
| 508 | // where parameter C has a depth of 1 but the substituting argument `int` |
| 509 | // has a depth of 0. |
| 510 | if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: CurDecl)) |
| 511 | HandleDefaultTempArgIntoTempTempParam(TTP, Result); |
| 512 | CurDecl = DC ? Decl::castFromDeclContext(DC) |
| 513 | : Response::UseNextDecl(CurDecl).NextDecl; |
| 514 | } else if (!CurDecl) |
| 515 | CurDecl = Decl::castFromDeclContext(DC); |
| 516 | |
| 517 | while (!CurDecl->isFileContextDecl()) { |
| 518 | Response R; |
| 519 | if (const auto *VarTemplSpec = |
| 520 | dyn_cast<VarTemplateSpecializationDecl>(Val: CurDecl)) { |
| 521 | R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization); |
| 522 | } else if (const auto *PartialClassTemplSpec = |
| 523 | dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: CurDecl)) { |
| 524 | R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result, |
| 525 | SkipForSpecialization); |
| 526 | } else if (const auto *ClassTemplSpec = |
| 527 | dyn_cast<ClassTemplateSpecializationDecl>(Val: CurDecl)) { |
| 528 | R = HandleClassTemplateSpec(ClassTemplSpec, Result, |
| 529 | SkipForSpecialization); |
| 530 | } else if (const auto *Function = dyn_cast<FunctionDecl>(Val: CurDecl)) { |
| 531 | R = HandleFunction(SemaRef&: *this, Function, Result, Pattern, RelativeToPrimary, |
| 532 | ForConstraintInstantiation, |
| 533 | ForDefaultArgumentSubstitution); |
| 534 | } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: CurDecl)) { |
| 535 | R = HandleRecordDecl(SemaRef&: *this, Rec, Result, Context, |
| 536 | ForConstraintInstantiation); |
| 537 | } else if (const auto *CSD = |
| 538 | dyn_cast<ImplicitConceptSpecializationDecl>(Val: CurDecl)) { |
| 539 | R = HandleImplicitConceptSpecializationDecl(CSD, Result); |
| 540 | } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: CurDecl)) { |
| 541 | R = HandleFunctionTemplateDecl(SemaRef&: *this, FTD, Result); |
| 542 | } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(Val: CurDecl)) { |
| 543 | R = Response::ChangeDecl(Ctx: CTD->getLexicalDeclContext()); |
| 544 | } else if (!isa<DeclContext>(Val: CurDecl)) { |
| 545 | R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl); |
| 546 | if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: CurDecl)) { |
| 547 | R = HandleDefaultTempArgIntoTempTempParam(TTP, Result); |
| 548 | } |
| 549 | } else { |
| 550 | R = HandleGenericDeclContext(CurDecl); |
| 551 | } |
| 552 | |
| 553 | if (R.IsDone) |
| 554 | return Result; |
| 555 | if (R.ClearRelativeToPrimary) |
| 556 | RelativeToPrimary = false; |
| 557 | assert(R.NextDecl); |
| 558 | CurDecl = R.NextDecl; |
| 559 | } |
| 560 | return Result; |
| 561 | } |
| 562 | |
| 563 | bool Sema::CodeSynthesisContext::isInstantiationRecord() const { |
| 564 | switch (Kind) { |
| 565 | case TemplateInstantiation: |
| 566 | case ExceptionSpecInstantiation: |
| 567 | case DefaultTemplateArgumentInstantiation: |
| 568 | case DefaultFunctionArgumentInstantiation: |
| 569 | case ExplicitTemplateArgumentSubstitution: |
| 570 | case DeducedTemplateArgumentSubstitution: |
| 571 | case PriorTemplateArgumentSubstitution: |
| 572 | case ConstraintsCheck: |
| 573 | case NestedRequirementConstraintsCheck: |
| 574 | case ExpansionStmtInstantiation: |
| 575 | return true; |
| 576 | |
| 577 | case RequirementInstantiation: |
| 578 | case RequirementParameterInstantiation: |
| 579 | case DefaultTemplateArgumentChecking: |
| 580 | case DeclaringSpecialMember: |
| 581 | case DeclaringImplicitEqualityComparison: |
| 582 | case DefiningSynthesizedFunction: |
| 583 | case ExceptionSpecEvaluation: |
| 584 | case ConstraintSubstitution: |
| 585 | case ParameterMappingSubstitution: |
| 586 | case RewritingOperatorAsSpaceship: |
| 587 | case InitializingStructuredBinding: |
| 588 | case MarkingClassDllexported: |
| 589 | case BuildingBuiltinDumpStructCall: |
| 590 | case LambdaExpressionSubstitution: |
| 591 | case BuildingDeductionGuides: |
| 592 | case TypeAliasTemplateInstantiation: |
| 593 | case PartialOrderingTTP: |
| 594 | case SYCLKernelLaunchLookup: |
| 595 | case SYCLKernelLaunchOverloadResolution: |
| 596 | return false; |
| 597 | |
| 598 | // This function should never be called when Kind's value is Memoization. |
| 599 | case Memoization: |
| 600 | break; |
| 601 | } |
| 602 | |
| 603 | llvm_unreachable("Invalid SynthesisKind!" ); |
| 604 | } |
| 605 | |
| 606 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 607 | Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, |
| 608 | SourceLocation PointOfInstantiation, SourceRange InstantiationRange, |
| 609 | Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs) |
| 610 | : SemaRef(SemaRef) { |
| 611 | // Don't allow further instantiation if a fatal error and an uncompilable |
| 612 | // error have occurred. Any diagnostics we might have raised will not be |
| 613 | // visible, and we do not need to construct a correct AST. |
| 614 | if (SemaRef.Diags.hasFatalErrorOccurred() && |
| 615 | SemaRef.hasUncompilableErrorOccurred()) { |
| 616 | Invalid = true; |
| 617 | return; |
| 618 | } |
| 619 | |
| 620 | CodeSynthesisContext Inst; |
| 621 | Inst.Kind = Kind; |
| 622 | Inst.PointOfInstantiation = PointOfInstantiation; |
| 623 | Inst.Entity = Entity; |
| 624 | Inst.Template = Template; |
| 625 | Inst.TemplateArgs = TemplateArgs.data(); |
| 626 | Inst.NumTemplateArgs = TemplateArgs.size(); |
| 627 | Inst.InstantiationRange = InstantiationRange; |
| 628 | Inst.InConstraintSubstitution = |
| 629 | Inst.Kind == CodeSynthesisContext::ConstraintSubstitution; |
| 630 | Inst.InParameterMappingSubstitution = |
| 631 | Inst.Kind == CodeSynthesisContext::ParameterMappingSubstitution; |
| 632 | if (!SemaRef.CodeSynthesisContexts.empty()) { |
| 633 | Inst.InConstraintSubstitution |= |
| 634 | SemaRef.CodeSynthesisContexts.back().InConstraintSubstitution; |
| 635 | Inst.InParameterMappingSubstitution |= |
| 636 | SemaRef.CodeSynthesisContexts.back().InParameterMappingSubstitution; |
| 637 | } |
| 638 | |
| 639 | Invalid = SemaRef.pushCodeSynthesisContext(Ctx: Inst); |
| 640 | } |
| 641 | |
| 642 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 643 | Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, |
| 644 | SourceRange InstantiationRange) |
| 645 | : InstantiatingTemplate(SemaRef, |
| 646 | CodeSynthesisContext::TemplateInstantiation, |
| 647 | PointOfInstantiation, InstantiationRange, Entity) {} |
| 648 | |
| 649 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 650 | Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, |
| 651 | ExceptionSpecification, SourceRange InstantiationRange) |
| 652 | : InstantiatingTemplate( |
| 653 | SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation, |
| 654 | PointOfInstantiation, InstantiationRange, Entity) {} |
| 655 | |
| 656 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 657 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, |
| 658 | TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, |
| 659 | SourceRange InstantiationRange) |
| 660 | : InstantiatingTemplate( |
| 661 | SemaRef, |
| 662 | CodeSynthesisContext::DefaultTemplateArgumentInstantiation, |
| 663 | PointOfInstantiation, InstantiationRange, getAsNamedDecl(P: Param), |
| 664 | Template, TemplateArgs) {} |
| 665 | |
| 666 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 667 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 668 | FunctionTemplateDecl *FunctionTemplate, |
| 669 | ArrayRef<TemplateArgument> TemplateArgs, |
| 670 | CodeSynthesisContext::SynthesisKind Kind, SourceRange InstantiationRange) |
| 671 | : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation, |
| 672 | InstantiationRange, FunctionTemplate, nullptr, |
| 673 | TemplateArgs) { |
| 674 | assert(Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || |
| 675 | Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution || |
| 676 | Kind == CodeSynthesisContext::BuildingDeductionGuides); |
| 677 | } |
| 678 | |
| 679 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 680 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, |
| 681 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
| 682 | : InstantiatingTemplate( |
| 683 | SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution, |
| 684 | PointOfInstantiation, InstantiationRange, Template, nullptr, |
| 685 | TemplateArgs) {} |
| 686 | |
| 687 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 688 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 689 | ClassTemplatePartialSpecializationDecl *PartialSpec, |
| 690 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
| 691 | : InstantiatingTemplate( |
| 692 | SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution, |
| 693 | PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, |
| 694 | TemplateArgs) {} |
| 695 | |
| 696 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 697 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 698 | VarTemplatePartialSpecializationDecl *PartialSpec, |
| 699 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
| 700 | : InstantiatingTemplate( |
| 701 | SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution, |
| 702 | PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, |
| 703 | TemplateArgs) {} |
| 704 | |
| 705 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 706 | Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, |
| 707 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
| 708 | : InstantiatingTemplate( |
| 709 | SemaRef, |
| 710 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation, |
| 711 | PointOfInstantiation, InstantiationRange, Param, nullptr, |
| 712 | TemplateArgs) {} |
| 713 | |
| 714 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 715 | Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, |
| 716 | NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, |
| 717 | SourceRange InstantiationRange) |
| 718 | : InstantiatingTemplate( |
| 719 | SemaRef, |
| 720 | CodeSynthesisContext::PriorTemplateArgumentSubstitution, |
| 721 | PointOfInstantiation, InstantiationRange, Param, Template, |
| 722 | TemplateArgs) {} |
| 723 | |
| 724 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 725 | Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, |
| 726 | TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, |
| 727 | SourceRange InstantiationRange) |
| 728 | : InstantiatingTemplate( |
| 729 | SemaRef, |
| 730 | CodeSynthesisContext::PriorTemplateArgumentSubstitution, |
| 731 | PointOfInstantiation, InstantiationRange, Param, Template, |
| 732 | TemplateArgs) {} |
| 733 | |
| 734 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 735 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 736 | TypeAliasTemplateDecl *Entity, ArrayRef<TemplateArgument> TemplateArgs, |
| 737 | SourceRange InstantiationRange) |
| 738 | : InstantiatingTemplate( |
| 739 | SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation, |
| 740 | PointOfInstantiation, InstantiationRange, /*Entity=*/Entity, |
| 741 | /*Template=*/nullptr, TemplateArgs) {} |
| 742 | |
| 743 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 744 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, |
| 745 | NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, |
| 746 | SourceRange InstantiationRange) |
| 747 | : InstantiatingTemplate( |
| 748 | SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking, |
| 749 | PointOfInstantiation, InstantiationRange, Param, Template, |
| 750 | TemplateArgs) {} |
| 751 | |
| 752 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 753 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 754 | concepts::Requirement *Req, SourceRange InstantiationRange) |
| 755 | : InstantiatingTemplate( |
| 756 | SemaRef, CodeSynthesisContext::RequirementInstantiation, |
| 757 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, |
| 758 | /*Template=*/nullptr, /*TemplateArgs=*/{}) {} |
| 759 | |
| 760 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 761 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 762 | CXXExpansionStmtPattern *ExpansionStmt, ArrayRef<TemplateArgument> TArgs, |
| 763 | SourceRange InstantiationRange) |
| 764 | : InstantiatingTemplate( |
| 765 | SemaRef, CodeSynthesisContext::ExpansionStmtInstantiation, |
| 766 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, |
| 767 | /*Template=*/nullptr, /*TemplateArgs=*/TArgs) {} |
| 768 | |
| 769 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 770 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 771 | concepts::NestedRequirement *Req, ConstraintsCheck, |
| 772 | SourceRange InstantiationRange) |
| 773 | : InstantiatingTemplate( |
| 774 | SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck, |
| 775 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, |
| 776 | /*Template=*/nullptr, /*TemplateArgs=*/{}) {} |
| 777 | |
| 778 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 779 | Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE, |
| 780 | SourceRange InstantiationRange) |
| 781 | : InstantiatingTemplate( |
| 782 | SemaRef, CodeSynthesisContext::RequirementParameterInstantiation, |
| 783 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, |
| 784 | /*Template=*/nullptr, /*TemplateArgs=*/{}) {} |
| 785 | |
| 786 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 787 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 788 | ConstraintsCheck, NamedDecl *Template, |
| 789 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
| 790 | : InstantiatingTemplate( |
| 791 | SemaRef, CodeSynthesisContext::ConstraintsCheck, |
| 792 | PointOfInstantiation, InstantiationRange, Template, nullptr, |
| 793 | TemplateArgs) {} |
| 794 | |
| 795 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 796 | Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, |
| 797 | NamedDecl *Template, SourceRange InstantiationRange) |
| 798 | : InstantiatingTemplate( |
| 799 | SemaRef, CodeSynthesisContext::ConstraintSubstitution, |
| 800 | PointOfInstantiation, InstantiationRange, Template, nullptr, {}) {} |
| 801 | |
| 802 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 803 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
| 804 | ParameterMappingSubstitution, NamedDecl *Template, |
| 805 | SourceRange InstantiationRange) |
| 806 | : InstantiatingTemplate( |
| 807 | SemaRef, CodeSynthesisContext::ParameterMappingSubstitution, |
| 808 | PointOfInstantiation, InstantiationRange, Template) {} |
| 809 | |
| 810 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 811 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity, |
| 812 | BuildingDeductionGuidesTag, SourceRange InstantiationRange) |
| 813 | : InstantiatingTemplate( |
| 814 | SemaRef, CodeSynthesisContext::BuildingDeductionGuides, |
| 815 | PointOfInstantiation, InstantiationRange, Entity) {} |
| 816 | |
| 817 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
| 818 | Sema &SemaRef, SourceLocation ArgLoc, PartialOrderingTTP, |
| 819 | TemplateDecl *PArg, SourceRange InstantiationRange) |
| 820 | : InstantiatingTemplate(SemaRef, CodeSynthesisContext::PartialOrderingTTP, |
| 821 | ArgLoc, InstantiationRange, PArg) {} |
| 822 | |
| 823 | bool Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) { |
| 824 | if (!Ctx.isInstantiationRecord()) { |
| 825 | ++NonInstantiationEntries; |
| 826 | } else { |
| 827 | assert(SemaRef.NonInstantiationEntries <= |
| 828 | SemaRef.CodeSynthesisContexts.size()); |
| 829 | if ((SemaRef.CodeSynthesisContexts.size() - |
| 830 | SemaRef.NonInstantiationEntries) > |
| 831 | SemaRef.getLangOpts().InstantiationDepth) { |
| 832 | SemaRef.Diag(Loc: Ctx.PointOfInstantiation, |
| 833 | DiagID: diag::err_template_recursion_depth_exceeded) |
| 834 | << SemaRef.getLangOpts().InstantiationDepth << Ctx.InstantiationRange; |
| 835 | SemaRef.Diag(Loc: Ctx.PointOfInstantiation, |
| 836 | DiagID: diag::note_template_recursion_depth) |
| 837 | << SemaRef.getLangOpts().InstantiationDepth; |
| 838 | return true; |
| 839 | } |
| 840 | } |
| 841 | |
| 842 | CodeSynthesisContexts.push_back(Elt: Ctx); |
| 843 | |
| 844 | // Check to see if we're low on stack space. We can't do anything about this |
| 845 | // from here, but we can at least warn the user. |
| 846 | StackHandler.warnOnStackNearlyExhausted(Loc: Ctx.PointOfInstantiation); |
| 847 | return false; |
| 848 | } |
| 849 | |
| 850 | void Sema::popCodeSynthesisContext() { |
| 851 | auto &Active = CodeSynthesisContexts.back(); |
| 852 | if (!Active.isInstantiationRecord()) { |
| 853 | assert(NonInstantiationEntries > 0); |
| 854 | --NonInstantiationEntries; |
| 855 | } |
| 856 | |
| 857 | // Name lookup no longer looks in this template's defining module. |
| 858 | assert(CodeSynthesisContexts.size() >= |
| 859 | CodeSynthesisContextLookupModules.size() && |
| 860 | "forgot to remove a lookup module for a template instantiation" ); |
| 861 | if (CodeSynthesisContexts.size() == |
| 862 | CodeSynthesisContextLookupModules.size()) { |
| 863 | if (Module *M = CodeSynthesisContextLookupModules.back()) |
| 864 | LookupModulesCache.erase(V: M); |
| 865 | CodeSynthesisContextLookupModules.pop_back(); |
| 866 | } |
| 867 | |
| 868 | // If we've left the code synthesis context for the current context stack, |
| 869 | // stop remembering that we've emitted that stack. |
| 870 | if (CodeSynthesisContexts.size() == |
| 871 | LastEmittedCodeSynthesisContextDepth) |
| 872 | LastEmittedCodeSynthesisContextDepth = 0; |
| 873 | |
| 874 | CodeSynthesisContexts.pop_back(); |
| 875 | } |
| 876 | |
| 877 | void Sema::InstantiatingTemplate::Clear() { |
| 878 | if (!Invalid) { |
| 879 | SemaRef.popCodeSynthesisContext(); |
| 880 | Invalid = true; |
| 881 | } |
| 882 | } |
| 883 | |
| 884 | static std::string convertCallArgsToString(Sema &S, |
| 885 | llvm::ArrayRef<const Expr *> Args) { |
| 886 | std::string Result; |
| 887 | llvm::raw_string_ostream OS(Result); |
| 888 | llvm::ListSeparator Comma; |
| 889 | for (const Expr *Arg : Args) { |
| 890 | OS << Comma; |
| 891 | Arg->IgnoreParens()->printPretty(OS, Helper: nullptr, |
| 892 | Policy: S.Context.getPrintingPolicy()); |
| 893 | } |
| 894 | return Result; |
| 895 | } |
| 896 | |
| 897 | static std::string |
| 898 | convertCallArgsValueCategoryAndTypeToString(Sema &S, |
| 899 | llvm::ArrayRef<const Expr *> Args) { |
| 900 | std::string Result; |
| 901 | llvm::raw_string_ostream OS(Result); |
| 902 | llvm::ListSeparator Comma; |
| 903 | OS << "(" ; |
| 904 | for (const Expr *Arg : Args) { |
| 905 | ExprValueKind EVK = Arg->getValueKind(); |
| 906 | const char *ValueCategory = |
| 907 | (EVK == VK_LValue ? "lvalue" |
| 908 | : (EVK == VK_XValue ? "xvalue" : "prvalue" )); |
| 909 | OS << Comma << ValueCategory << " of type '" ; |
| 910 | Arg->getType().print(OS, Policy: S.getPrintingPolicy()); |
| 911 | OS << "'" ; |
| 912 | } |
| 913 | OS << ")" ; |
| 914 | return Result; |
| 915 | } |
| 916 | |
| 917 | void Sema::PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc) { |
| 918 | // Determine which template instantiations to skip, if any. |
| 919 | unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart; |
| 920 | unsigned Limit = Diags.getTemplateBacktraceLimit(); |
| 921 | if (Limit && Limit < CodeSynthesisContexts.size()) { |
| 922 | SkipStart = Limit / 2 + Limit % 2; |
| 923 | SkipEnd = CodeSynthesisContexts.size() - Limit / 2; |
| 924 | } |
| 925 | |
| 926 | // FIXME: In all of these cases, we need to show the template arguments |
| 927 | unsigned InstantiationIdx = 0; |
| 928 | for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator |
| 929 | Active = CodeSynthesisContexts.rbegin(), |
| 930 | ActiveEnd = CodeSynthesisContexts.rend(); |
| 931 | Active != ActiveEnd; |
| 932 | ++Active, ++InstantiationIdx) { |
| 933 | // Skip this instantiation? |
| 934 | if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) { |
| 935 | if (InstantiationIdx == SkipStart) { |
| 936 | // Note that we're skipping instantiations. |
| 937 | DiagFunc(Active->PointOfInstantiation, |
| 938 | PDiag(DiagID: diag::note_instantiation_contexts_suppressed) |
| 939 | << unsigned(CodeSynthesisContexts.size() - Limit)); |
| 940 | } |
| 941 | continue; |
| 942 | } |
| 943 | |
| 944 | switch (Active->Kind) { |
| 945 | case CodeSynthesisContext::TemplateInstantiation: { |
| 946 | Decl *D = Active->Entity; |
| 947 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D)) { |
| 948 | unsigned DiagID = diag::note_template_member_class_here; |
| 949 | if (isa<ClassTemplateSpecializationDecl>(Val: Record)) |
| 950 | DiagID = diag::note_template_class_instantiation_here; |
| 951 | DiagFunc(Active->PointOfInstantiation, |
| 952 | PDiag(DiagID) << Record << Active->InstantiationRange); |
| 953 | } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D)) { |
| 954 | unsigned DiagID; |
| 955 | if (Function->getPrimaryTemplate()) |
| 956 | DiagID = diag::note_function_template_spec_here; |
| 957 | else |
| 958 | DiagID = diag::note_template_member_function_here; |
| 959 | DiagFunc(Active->PointOfInstantiation, |
| 960 | PDiag(DiagID) << Function << Active->InstantiationRange); |
| 961 | } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
| 962 | DiagFunc(Active->PointOfInstantiation, |
| 963 | PDiag(DiagID: VD->isStaticDataMember() |
| 964 | ? diag::note_template_static_data_member_def_here |
| 965 | : diag::note_template_variable_def_here) |
| 966 | << VD << Active->InstantiationRange); |
| 967 | } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: D)) { |
| 968 | DiagFunc(Active->PointOfInstantiation, |
| 969 | PDiag(DiagID: diag::note_template_enum_def_here) |
| 970 | << ED << Active->InstantiationRange); |
| 971 | } else if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: D)) { |
| 972 | DiagFunc(Active->PointOfInstantiation, |
| 973 | PDiag(DiagID: diag::note_template_nsdmi_here) |
| 974 | << FD << Active->InstantiationRange); |
| 975 | } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) { |
| 976 | DiagFunc(Active->PointOfInstantiation, |
| 977 | PDiag(DiagID: diag::note_template_class_instantiation_here) |
| 978 | << CTD << Active->InstantiationRange); |
| 979 | } |
| 980 | break; |
| 981 | } |
| 982 | |
| 983 | case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: { |
| 984 | TemplateDecl *Template = cast<TemplateDecl>(Val: Active->Template); |
| 985 | SmallString<128> TemplateArgsStr; |
| 986 | llvm::raw_svector_ostream OS(TemplateArgsStr); |
| 987 | Template->printName(OS, Policy: getPrintingPolicy()); |
| 988 | printTemplateArgumentList(OS, Args: Active->template_arguments(), |
| 989 | Policy: getPrintingPolicy()); |
| 990 | DiagFunc(Active->PointOfInstantiation, |
| 991 | PDiag(DiagID: diag::note_default_arg_instantiation_here) |
| 992 | << OS.str() << Active->InstantiationRange); |
| 993 | break; |
| 994 | } |
| 995 | |
| 996 | case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: { |
| 997 | FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Val: Active->Entity); |
| 998 | DiagFunc(Active->PointOfInstantiation, |
| 999 | PDiag(DiagID: diag::note_explicit_template_arg_substitution_here) |
| 1000 | << FnTmpl |
| 1001 | << getTemplateArgumentBindingsText( |
| 1002 | Params: FnTmpl->getTemplateParameters(), Args: Active->TemplateArgs, |
| 1003 | NumArgs: Active->NumTemplateArgs) |
| 1004 | << Active->InstantiationRange); |
| 1005 | break; |
| 1006 | } |
| 1007 | |
| 1008 | case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: { |
| 1009 | if (FunctionTemplateDecl *FnTmpl = |
| 1010 | dyn_cast<FunctionTemplateDecl>(Val: Active->Entity)) { |
| 1011 | DiagFunc( |
| 1012 | Active->PointOfInstantiation, |
| 1013 | PDiag(DiagID: diag::note_function_template_deduction_instantiation_here) |
| 1014 | << FnTmpl |
| 1015 | << getTemplateArgumentBindingsText( |
| 1016 | Params: FnTmpl->getTemplateParameters(), Args: Active->TemplateArgs, |
| 1017 | NumArgs: Active->NumTemplateArgs) |
| 1018 | << Active->InstantiationRange); |
| 1019 | } else { |
| 1020 | bool IsVar = isa<VarTemplateDecl>(Val: Active->Entity) || |
| 1021 | isa<VarTemplateSpecializationDecl>(Val: Active->Entity); |
| 1022 | bool IsTemplate = false; |
| 1023 | TemplateParameterList *Params; |
| 1024 | if (auto *D = dyn_cast<TemplateDecl>(Val: Active->Entity)) { |
| 1025 | IsTemplate = true; |
| 1026 | Params = D->getTemplateParameters(); |
| 1027 | } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>( |
| 1028 | Val: Active->Entity)) { |
| 1029 | Params = D->getTemplateParameters(); |
| 1030 | } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>( |
| 1031 | Val: Active->Entity)) { |
| 1032 | Params = D->getTemplateParameters(); |
| 1033 | } else { |
| 1034 | llvm_unreachable("unexpected template kind" ); |
| 1035 | } |
| 1036 | |
| 1037 | DiagFunc(Active->PointOfInstantiation, |
| 1038 | PDiag(DiagID: diag::note_deduced_template_arg_substitution_here) |
| 1039 | << IsVar << IsTemplate << cast<NamedDecl>(Val: Active->Entity) |
| 1040 | << getTemplateArgumentBindingsText(Params, |
| 1041 | Args: Active->TemplateArgs, |
| 1042 | NumArgs: Active->NumTemplateArgs) |
| 1043 | << Active->InstantiationRange); |
| 1044 | } |
| 1045 | break; |
| 1046 | } |
| 1047 | |
| 1048 | case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: { |
| 1049 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: Active->Entity); |
| 1050 | FunctionDecl *FD = cast<FunctionDecl>(Val: Param->getDeclContext()); |
| 1051 | |
| 1052 | SmallString<128> TemplateArgsStr; |
| 1053 | llvm::raw_svector_ostream OS(TemplateArgsStr); |
| 1054 | FD->printName(OS, Policy: getPrintingPolicy()); |
| 1055 | printTemplateArgumentList(OS, Args: Active->template_arguments(), |
| 1056 | Policy: getPrintingPolicy()); |
| 1057 | DiagFunc(Active->PointOfInstantiation, |
| 1058 | PDiag(DiagID: diag::note_default_function_arg_instantiation_here) |
| 1059 | << OS.str() << Active->InstantiationRange); |
| 1060 | break; |
| 1061 | } |
| 1062 | |
| 1063 | case CodeSynthesisContext::PriorTemplateArgumentSubstitution: { |
| 1064 | NamedDecl *Parm = cast<NamedDecl>(Val: Active->Entity); |
| 1065 | std::string Name; |
| 1066 | if (!Parm->getName().empty()) |
| 1067 | Name = std::string(" '" ) + Parm->getName().str() + "'" ; |
| 1068 | |
| 1069 | TemplateParameterList *TemplateParams = nullptr; |
| 1070 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: Active->Template)) |
| 1071 | TemplateParams = Template->getTemplateParameters(); |
| 1072 | else |
| 1073 | TemplateParams = |
| 1074 | cast<ClassTemplatePartialSpecializationDecl>(Val: Active->Template) |
| 1075 | ->getTemplateParameters(); |
| 1076 | DiagFunc(Active->PointOfInstantiation, |
| 1077 | PDiag(DiagID: diag::note_prior_template_arg_substitution) |
| 1078 | << isa<TemplateTemplateParmDecl>(Val: Parm) << Name |
| 1079 | << getTemplateArgumentBindingsText(Params: TemplateParams, |
| 1080 | Args: Active->TemplateArgs, |
| 1081 | NumArgs: Active->NumTemplateArgs) |
| 1082 | << Active->InstantiationRange); |
| 1083 | break; |
| 1084 | } |
| 1085 | |
| 1086 | case CodeSynthesisContext::DefaultTemplateArgumentChecking: { |
| 1087 | TemplateParameterList *TemplateParams = nullptr; |
| 1088 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: Active->Template)) |
| 1089 | TemplateParams = Template->getTemplateParameters(); |
| 1090 | else |
| 1091 | TemplateParams = |
| 1092 | cast<ClassTemplatePartialSpecializationDecl>(Val: Active->Template) |
| 1093 | ->getTemplateParameters(); |
| 1094 | |
| 1095 | DiagFunc(Active->PointOfInstantiation, |
| 1096 | PDiag(DiagID: diag::note_template_default_arg_checking) |
| 1097 | << getTemplateArgumentBindingsText(Params: TemplateParams, |
| 1098 | Args: Active->TemplateArgs, |
| 1099 | NumArgs: Active->NumTemplateArgs) |
| 1100 | << Active->InstantiationRange); |
| 1101 | break; |
| 1102 | } |
| 1103 | |
| 1104 | case CodeSynthesisContext::ExceptionSpecEvaluation: |
| 1105 | DiagFunc(Active->PointOfInstantiation, |
| 1106 | PDiag(DiagID: diag::note_evaluating_exception_spec_here) |
| 1107 | << cast<FunctionDecl>(Val: Active->Entity)); |
| 1108 | break; |
| 1109 | |
| 1110 | case CodeSynthesisContext::ExceptionSpecInstantiation: |
| 1111 | DiagFunc(Active->PointOfInstantiation, |
| 1112 | PDiag(DiagID: diag::note_template_exception_spec_instantiation_here) |
| 1113 | << cast<FunctionDecl>(Val: Active->Entity) |
| 1114 | << Active->InstantiationRange); |
| 1115 | break; |
| 1116 | |
| 1117 | case CodeSynthesisContext::RequirementInstantiation: |
| 1118 | DiagFunc(Active->PointOfInstantiation, |
| 1119 | PDiag(DiagID: diag::note_template_requirement_instantiation_here) |
| 1120 | << Active->InstantiationRange); |
| 1121 | break; |
| 1122 | case CodeSynthesisContext::RequirementParameterInstantiation: |
| 1123 | DiagFunc(Active->PointOfInstantiation, |
| 1124 | PDiag(DiagID: diag::note_template_requirement_params_instantiation_here) |
| 1125 | << Active->InstantiationRange); |
| 1126 | break; |
| 1127 | |
| 1128 | case CodeSynthesisContext::NestedRequirementConstraintsCheck: |
| 1129 | DiagFunc(Active->PointOfInstantiation, |
| 1130 | PDiag(DiagID: diag::note_nested_requirement_here) |
| 1131 | << Active->InstantiationRange); |
| 1132 | break; |
| 1133 | |
| 1134 | case CodeSynthesisContext::DeclaringSpecialMember: |
| 1135 | DiagFunc(Active->PointOfInstantiation, |
| 1136 | PDiag(DiagID: diag::note_in_declaration_of_implicit_special_member) |
| 1137 | << cast<CXXRecordDecl>(Val: Active->Entity) |
| 1138 | << Active->SpecialMember); |
| 1139 | break; |
| 1140 | |
| 1141 | case CodeSynthesisContext::DeclaringImplicitEqualityComparison: |
| 1142 | DiagFunc( |
| 1143 | Active->Entity->getLocation(), |
| 1144 | PDiag(DiagID: diag::note_in_declaration_of_implicit_equality_comparison)); |
| 1145 | break; |
| 1146 | |
| 1147 | case CodeSynthesisContext::DefiningSynthesizedFunction: { |
| 1148 | // FIXME: For synthesized functions that are not defaulted, |
| 1149 | // produce a note. |
| 1150 | auto *FD = dyn_cast<FunctionDecl>(Val: Active->Entity); |
| 1151 | // Note: if FD is nullptr currently setting DFK to DefaultedFunctionKind() |
| 1152 | // will ensure that DFK.isComparison() is false. This is important because |
| 1153 | // we will uncondtionally dereference FD in the else if. |
| 1154 | FunctionDecl::DefaultedFunctionKind DFK = |
| 1155 | FD ? FD->getDefaultedFunctionKind() |
| 1156 | : FunctionDecl::DefaultedFunctionKind(); |
| 1157 | if (DFK.isSpecialMember()) { |
| 1158 | auto *MD = cast<CXXMethodDecl>(Val: FD); |
| 1159 | DiagFunc(Active->PointOfInstantiation, |
| 1160 | PDiag(DiagID: diag::note_member_synthesized_at) |
| 1161 | << MD->isExplicitlyDefaulted() << DFK.asSpecialMember() |
| 1162 | << Context.getCanonicalTagType(TD: MD->getParent())); |
| 1163 | } else if (DFK.isComparison()) { |
| 1164 | QualType RecordType = FD->getParamDecl(i: 0) |
| 1165 | ->getType() |
| 1166 | .getNonReferenceType() |
| 1167 | .getUnqualifiedType(); |
| 1168 | DiagFunc(Active->PointOfInstantiation, |
| 1169 | PDiag(DiagID: diag::note_comparison_synthesized_at) |
| 1170 | << (int)DFK.asComparison() << RecordType); |
| 1171 | } |
| 1172 | break; |
| 1173 | } |
| 1174 | |
| 1175 | case CodeSynthesisContext::RewritingOperatorAsSpaceship: |
| 1176 | DiagFunc(Active->Entity->getLocation(), |
| 1177 | PDiag(DiagID: diag::note_rewriting_operator_as_spaceship)); |
| 1178 | break; |
| 1179 | |
| 1180 | case CodeSynthesisContext::InitializingStructuredBinding: |
| 1181 | DiagFunc(Active->PointOfInstantiation, |
| 1182 | PDiag(DiagID: diag::note_in_binding_decl_init) |
| 1183 | << cast<BindingDecl>(Val: Active->Entity)); |
| 1184 | break; |
| 1185 | |
| 1186 | case CodeSynthesisContext::MarkingClassDllexported: |
| 1187 | DiagFunc(Active->PointOfInstantiation, |
| 1188 | PDiag(DiagID: diag::note_due_to_dllexported_class) |
| 1189 | << cast<CXXRecordDecl>(Val: Active->Entity) |
| 1190 | << !getLangOpts().CPlusPlus11); |
| 1191 | break; |
| 1192 | |
| 1193 | case CodeSynthesisContext::BuildingBuiltinDumpStructCall: |
| 1194 | DiagFunc(Active->PointOfInstantiation, |
| 1195 | PDiag(DiagID: diag::note_building_builtin_dump_struct_call) |
| 1196 | << convertCallArgsToString( |
| 1197 | S&: *this, Args: llvm::ArrayRef(Active->CallArgs, |
| 1198 | Active->NumCallArgs))); |
| 1199 | break; |
| 1200 | |
| 1201 | case CodeSynthesisContext::Memoization: |
| 1202 | break; |
| 1203 | |
| 1204 | case CodeSynthesisContext::LambdaExpressionSubstitution: |
| 1205 | DiagFunc(Active->PointOfInstantiation, |
| 1206 | PDiag(DiagID: diag::note_lambda_substitution_here)); |
| 1207 | break; |
| 1208 | case CodeSynthesisContext::ConstraintsCheck: { |
| 1209 | unsigned DiagID = 0; |
| 1210 | if (!Active->Entity) { |
| 1211 | DiagFunc(Active->PointOfInstantiation, |
| 1212 | PDiag(DiagID: diag::note_nested_requirement_here) |
| 1213 | << Active->InstantiationRange); |
| 1214 | break; |
| 1215 | } |
| 1216 | if (isa<ConceptDecl>(Val: Active->Entity)) |
| 1217 | DiagID = diag::note_concept_specialization_here; |
| 1218 | else if (isa<TemplateDecl>(Val: Active->Entity)) |
| 1219 | DiagID = diag::note_checking_constraints_for_template_id_here; |
| 1220 | else if (isa<VarTemplatePartialSpecializationDecl>(Val: Active->Entity)) |
| 1221 | DiagID = diag::note_checking_constraints_for_var_spec_id_here; |
| 1222 | else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Active->Entity)) |
| 1223 | DiagID = diag::note_checking_constraints_for_class_spec_id_here; |
| 1224 | else { |
| 1225 | assert(isa<FunctionDecl>(Active->Entity)); |
| 1226 | DiagID = diag::note_checking_constraints_for_function_here; |
| 1227 | } |
| 1228 | SmallString<128> TemplateArgsStr; |
| 1229 | llvm::raw_svector_ostream OS(TemplateArgsStr); |
| 1230 | cast<NamedDecl>(Val: Active->Entity)->printName(OS, Policy: getPrintingPolicy()); |
| 1231 | if (!isa<FunctionDecl>(Val: Active->Entity)) { |
| 1232 | printTemplateArgumentList(OS, Args: Active->template_arguments(), |
| 1233 | Policy: getPrintingPolicy()); |
| 1234 | } |
| 1235 | DiagFunc(Active->PointOfInstantiation, |
| 1236 | PDiag(DiagID) << OS.str() << Active->InstantiationRange); |
| 1237 | break; |
| 1238 | } |
| 1239 | case CodeSynthesisContext::ConstraintSubstitution: |
| 1240 | DiagFunc(Active->PointOfInstantiation, |
| 1241 | PDiag(DiagID: diag::note_constraint_substitution_here) |
| 1242 | << Active->InstantiationRange); |
| 1243 | break; |
| 1244 | case CodeSynthesisContext::ParameterMappingSubstitution: |
| 1245 | DiagFunc(Active->PointOfInstantiation, |
| 1246 | PDiag(DiagID: diag::note_parameter_mapping_substitution_here) |
| 1247 | << Active->InstantiationRange); |
| 1248 | break; |
| 1249 | case CodeSynthesisContext::BuildingDeductionGuides: |
| 1250 | DiagFunc(Active->PointOfInstantiation, |
| 1251 | PDiag(DiagID: diag::note_building_deduction_guide_here)); |
| 1252 | break; |
| 1253 | case CodeSynthesisContext::TypeAliasTemplateInstantiation: |
| 1254 | // Workaround for a workaround: don't produce a note if we are merely |
| 1255 | // instantiating some other template which contains this alias template. |
| 1256 | // This would be redundant either with the error itself, or some other |
| 1257 | // context note attached to it. |
| 1258 | if (Active->NumTemplateArgs == 0) |
| 1259 | break; |
| 1260 | DiagFunc(Active->PointOfInstantiation, |
| 1261 | PDiag(DiagID: diag::note_template_type_alias_instantiation_here) |
| 1262 | << cast<TypeAliasTemplateDecl>(Val: Active->Entity) |
| 1263 | << Active->InstantiationRange); |
| 1264 | break; |
| 1265 | case CodeSynthesisContext::PartialOrderingTTP: |
| 1266 | DiagFunc(Active->PointOfInstantiation, |
| 1267 | PDiag(DiagID: diag::note_template_arg_template_params_mismatch)); |
| 1268 | if (SourceLocation ParamLoc = Active->Entity->getLocation(); |
| 1269 | ParamLoc.isValid()) |
| 1270 | DiagFunc(ParamLoc, PDiag(DiagID: diag::note_template_prev_declaration) |
| 1271 | << /*isTemplateTemplateParam=*/true |
| 1272 | << Active->InstantiationRange); |
| 1273 | break; |
| 1274 | case CodeSynthesisContext::SYCLKernelLaunchLookup: { |
| 1275 | const auto *SKEPAttr = |
| 1276 | Active->Entity->getAttr<SYCLKernelEntryPointAttr>(); |
| 1277 | assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute" ); |
| 1278 | assert(!SKEPAttr->isInvalidAttr() && |
| 1279 | "sycl_kernel_entry_point attribute is invalid" ); |
| 1280 | DiagFunc(SKEPAttr->getLocation(), PDiag(DiagID: diag::note_sycl_runtime_defect)); |
| 1281 | DiagFunc(SKEPAttr->getLocation(), |
| 1282 | PDiag(DiagID: diag::note_sycl_kernel_launch_lookup_here) |
| 1283 | << SKEPAttr->getKernelName()); |
| 1284 | break; |
| 1285 | } |
| 1286 | case CodeSynthesisContext::SYCLKernelLaunchOverloadResolution: { |
| 1287 | const auto *SKEPAttr = |
| 1288 | Active->Entity->getAttr<SYCLKernelEntryPointAttr>(); |
| 1289 | assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute" ); |
| 1290 | assert(!SKEPAttr->isInvalidAttr() && |
| 1291 | "sycl_kernel_entry_point attribute is invalid" ); |
| 1292 | DiagFunc(SKEPAttr->getLocation(), PDiag(DiagID: diag::note_sycl_runtime_defect)); |
| 1293 | DiagFunc(SKEPAttr->getLocation(), |
| 1294 | PDiag(DiagID: diag::note_sycl_kernel_launch_overload_resolution_here) |
| 1295 | << SKEPAttr->getKernelName() |
| 1296 | << convertCallArgsValueCategoryAndTypeToString( |
| 1297 | S&: *this, Args: llvm::ArrayRef(Active->CallArgs, |
| 1298 | Active->NumCallArgs))); |
| 1299 | break; |
| 1300 | } |
| 1301 | case CodeSynthesisContext::ExpansionStmtInstantiation: |
| 1302 | Diags.Report(Loc: Active->PointOfInstantiation, |
| 1303 | DiagID: diag::note_expansion_stmt_instantiation_here); |
| 1304 | } |
| 1305 | } |
| 1306 | } |
| 1307 | |
| 1308 | //===----------------------------------------------------------------------===/ |
| 1309 | // Template Instantiation for Types |
| 1310 | //===----------------------------------------------------------------------===/ |
| 1311 | namespace { |
| 1312 | |
| 1313 | class TemplateInstantiator : public TreeTransform<TemplateInstantiator> { |
| 1314 | const MultiLevelTemplateArgumentList &TemplateArgs; |
| 1315 | SourceLocation Loc; |
| 1316 | DeclarationName Entity; |
| 1317 | // Whether to evaluate the C++20 constraints or simply substitute into them. |
| 1318 | bool EvaluateConstraints = true; |
| 1319 | bool EvaluateLambdaConstraint = false; |
| 1320 | // Whether Substitution was Incomplete, that is, we tried to substitute in |
| 1321 | // any user provided template arguments which were null. |
| 1322 | bool IsIncomplete = false; |
| 1323 | // Whether an incomplete substituion should be treated as an error. |
| 1324 | bool BailOutOnIncomplete; |
| 1325 | |
| 1326 | std::optional<llvm::FoldingSetNodeID> TemplateArgsHashValue; |
| 1327 | |
| 1328 | // CWG2770: Function parameters should be instantiated when they are |
| 1329 | // needed by a satisfaction check of an atomic constraint or |
| 1330 | // (recursively) by another function parameter. |
| 1331 | bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm); |
| 1332 | |
| 1333 | public: |
| 1334 | typedef TreeTransform<TemplateInstantiator> inherited; |
| 1335 | |
| 1336 | TemplateInstantiator(Sema &SemaRef, |
| 1337 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 1338 | SourceLocation Loc, DeclarationName Entity, |
| 1339 | bool BailOutOnIncomplete = false) |
| 1340 | : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), |
| 1341 | Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) { |
| 1342 | assert((!SemaRef.CodeSynthesisContexts.empty() || |
| 1343 | SemaRef.isSFINAEContext()) && |
| 1344 | "Cannot perform an instantiation without some context on the " |
| 1345 | "instantiation stack" ); |
| 1346 | } |
| 1347 | |
| 1348 | void setEvaluateConstraints(bool B) { |
| 1349 | EvaluateConstraints = B; |
| 1350 | } |
| 1351 | bool getEvaluateConstraints() { |
| 1352 | return EvaluateConstraints; |
| 1353 | } |
| 1354 | |
| 1355 | inline static struct ForParameterMappingSubstitution_t { |
| 1356 | } ForParameterMappingSubstitution; |
| 1357 | |
| 1358 | inline static struct ForConstraintSubstitution_t { |
| 1359 | } ForConstraintSubstitution; |
| 1360 | |
| 1361 | TemplateInstantiator(ForParameterMappingSubstitution_t, Sema &SemaRef, |
| 1362 | SourceLocation Loc, |
| 1363 | const MultiLevelTemplateArgumentList &TemplateArgs) |
| 1364 | : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), |
| 1365 | EvaluateLambdaConstraint(true), BailOutOnIncomplete(false) { |
| 1366 | if (!SemaRef.CurrentCachedTemplateArgs) |
| 1367 | return; |
| 1368 | auto &V = TemplateArgsHashValue.emplace(); |
| 1369 | for (auto &Level : TemplateArgs) |
| 1370 | for (auto &Arg : Level.Args) |
| 1371 | Arg.Profile(ID&: V, Context: SemaRef.Context); |
| 1372 | } |
| 1373 | |
| 1374 | TemplateInstantiator(ForConstraintSubstitution_t, Sema &SemaRef, |
| 1375 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 1376 | SourceLocation Loc, DeclarationName Entity, |
| 1377 | bool BailOutOnIncomplete = false) |
| 1378 | : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), |
| 1379 | EvaluateLambdaConstraint(true), BailOutOnIncomplete(false) {} |
| 1380 | |
| 1381 | /// Determine whether the given type \p T has already been |
| 1382 | /// transformed. |
| 1383 | /// |
| 1384 | /// For the purposes of template instantiation, a type has already been |
| 1385 | /// transformed if it is NULL or if it is not dependent. |
| 1386 | bool AlreadyTransformed(QualType T); |
| 1387 | |
| 1388 | /// Returns the location of the entity being instantiated, if known. |
| 1389 | SourceLocation getBaseLocation() { return Loc; } |
| 1390 | |
| 1391 | /// Returns the name of the entity being instantiated, if any. |
| 1392 | DeclarationName getBaseEntity() { return Entity; } |
| 1393 | |
| 1394 | /// Returns whether any substitution so far was incomplete. |
| 1395 | bool getIsIncomplete() const { return IsIncomplete; } |
| 1396 | |
| 1397 | /// Sets the "base" location and entity when that |
| 1398 | /// information is known based on another transformation. |
| 1399 | void setBase(SourceLocation Loc, DeclarationName Entity) { |
| 1400 | this->Loc = Loc; |
| 1401 | this->Entity = Entity; |
| 1402 | } |
| 1403 | |
| 1404 | unsigned TransformTemplateDepth(unsigned Depth) { |
| 1405 | return TemplateArgs.getNewDepth(OldDepth: Depth); |
| 1406 | } |
| 1407 | |
| 1408 | bool TryExpandParameterPacks(SourceLocation EllipsisLoc, |
| 1409 | SourceRange PatternRange, |
| 1410 | ArrayRef<UnexpandedParameterPack> Unexpanded, |
| 1411 | bool FailOnPackProducingTemplates, |
| 1412 | bool &ShouldExpand, bool &RetainExpansion, |
| 1413 | UnsignedOrNone &NumExpansions) { |
| 1414 | if (SemaRef.CurrentInstantiationScope && |
| 1415 | (SemaRef.inConstraintSubstitution() || |
| 1416 | SemaRef.inParameterMappingSubstitution())) { |
| 1417 | for (UnexpandedParameterPack ParmPack : Unexpanded) { |
| 1418 | NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>(); |
| 1419 | if (auto *PVD = dyn_cast_if_present<ParmVarDecl>(Val: VD); |
| 1420 | PVD && maybeInstantiateFunctionParameterToScope(OldParm: PVD)) |
| 1421 | return true; |
| 1422 | } |
| 1423 | } |
| 1424 | |
| 1425 | return getSema().CheckParameterPacksForExpansion( |
| 1426 | EllipsisLoc, PatternRange, Unexpanded, TemplateArgs, |
| 1427 | FailOnPackProducingTemplates, ShouldExpand, RetainExpansion, |
| 1428 | NumExpansions); |
| 1429 | } |
| 1430 | |
| 1431 | void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { |
| 1432 | SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(D: Pack); |
| 1433 | } |
| 1434 | |
| 1435 | TemplateArgument ForgetPartiallySubstitutedPack() { |
| 1436 | TemplateArgument Result; |
| 1437 | if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope |
| 1438 | ->getPartiallySubstitutedPack()) { |
| 1439 | MultiLevelTemplateArgumentList &TemplateArgs = |
| 1440 | const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); |
| 1441 | unsigned Depth, Index; |
| 1442 | std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack); |
| 1443 | if (TemplateArgs.hasTemplateArgument(Depth, Index)) { |
| 1444 | Result = TemplateArgs(Depth, Index); |
| 1445 | TemplateArgs.setArgument(Depth, Index, Arg: TemplateArgument()); |
| 1446 | } else { |
| 1447 | IsIncomplete = true; |
| 1448 | if (BailOutOnIncomplete) |
| 1449 | return TemplateArgument(); |
| 1450 | } |
| 1451 | } |
| 1452 | |
| 1453 | return Result; |
| 1454 | } |
| 1455 | |
| 1456 | void RememberPartiallySubstitutedPack(TemplateArgument Arg) { |
| 1457 | if (Arg.isNull()) |
| 1458 | return; |
| 1459 | |
| 1460 | if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope |
| 1461 | ->getPartiallySubstitutedPack()) { |
| 1462 | MultiLevelTemplateArgumentList &TemplateArgs = |
| 1463 | const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); |
| 1464 | unsigned Depth, Index; |
| 1465 | std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack); |
| 1466 | TemplateArgs.setArgument(Depth, Index, Arg); |
| 1467 | } |
| 1468 | } |
| 1469 | |
| 1470 | MultiLevelTemplateArgumentList ForgetSubstitution() { |
| 1471 | MultiLevelTemplateArgumentList New; |
| 1472 | New.addOuterRetainedLevels(Num: this->TemplateArgs.getNumLevels()); |
| 1473 | |
| 1474 | MultiLevelTemplateArgumentList Old = |
| 1475 | const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); |
| 1476 | const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) = |
| 1477 | std::move(New); |
| 1478 | return Old; |
| 1479 | } |
| 1480 | |
| 1481 | void RememberSubstitution(MultiLevelTemplateArgumentList Old) { |
| 1482 | const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) = |
| 1483 | std::move(Old); |
| 1484 | } |
| 1485 | |
| 1486 | TemplateArgument |
| 1487 | getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) { |
| 1488 | if (TA.getKind() != TemplateArgument::Pack) |
| 1489 | return TA; |
| 1490 | if (SemaRef.ArgPackSubstIndex) |
| 1491 | return SemaRef.getPackSubstitutedTemplateArgument(Arg: TA); |
| 1492 | assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() && |
| 1493 | "unexpected pack arguments in template rewrite" ); |
| 1494 | TemplateArgument Arg = *TA.pack_begin(); |
| 1495 | if (Arg.isPackExpansion()) |
| 1496 | Arg = Arg.getPackExpansionPattern(); |
| 1497 | return Arg; |
| 1498 | } |
| 1499 | |
| 1500 | /// Transform the given declaration by instantiating a reference to |
| 1501 | /// this declaration. |
| 1502 | Decl *TransformDecl(SourceLocation Loc, Decl *D); |
| 1503 | |
| 1504 | void transformAttrs(Decl *Old, Decl *New) { |
| 1505 | SemaRef.InstantiateAttrs(TemplateArgs, Pattern: Old, Inst: New); |
| 1506 | } |
| 1507 | |
| 1508 | void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) { |
| 1509 | if (Old->isParameterPack() && |
| 1510 | (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) { |
| 1511 | SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(D: Old); |
| 1512 | for (auto *New : NewDecls) |
| 1513 | SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg( |
| 1514 | D: Old, Inst: cast<VarDecl>(Val: New)); |
| 1515 | return; |
| 1516 | } |
| 1517 | |
| 1518 | assert(NewDecls.size() == 1 && |
| 1519 | "should only have multiple expansions for a pack" ); |
| 1520 | Decl *New = NewDecls.front(); |
| 1521 | |
| 1522 | // If we've instantiated the call operator of a lambda or the call |
| 1523 | // operator template of a generic lambda, update the "instantiation of" |
| 1524 | // information. |
| 1525 | auto *NewMD = dyn_cast<CXXMethodDecl>(Val: New); |
| 1526 | if (NewMD && isLambdaCallOperator(MD: NewMD)) { |
| 1527 | auto *OldMD = dyn_cast<CXXMethodDecl>(Val: Old); |
| 1528 | if (auto *NewTD = NewMD->getDescribedFunctionTemplate()) |
| 1529 | NewTD->setInstantiatedFromMemberTemplate( |
| 1530 | OldMD->getDescribedFunctionTemplate()); |
| 1531 | else |
| 1532 | NewMD->setInstantiationOfMemberFunction(FD: OldMD, |
| 1533 | TSK: TSK_ImplicitInstantiation); |
| 1534 | } |
| 1535 | |
| 1536 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: Old, Inst: New); |
| 1537 | |
| 1538 | // We recreated a local declaration, but not by instantiating it. There |
| 1539 | // may be pending dependent diagnostics to produce. |
| 1540 | if (auto *DC = dyn_cast<DeclContext>(Val: Old); |
| 1541 | DC && DC->isDependentContext() && DC->isFunctionOrMethod()) |
| 1542 | SemaRef.PerformDependentDiagnostics(Pattern: DC, TemplateArgs); |
| 1543 | } |
| 1544 | |
| 1545 | /// Transform the definition of the given declaration by |
| 1546 | /// instantiating it. |
| 1547 | Decl *TransformDefinition(SourceLocation Loc, Decl *D); |
| 1548 | |
| 1549 | /// Transform the first qualifier within a scope by instantiating the |
| 1550 | /// declaration. |
| 1551 | NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc); |
| 1552 | |
| 1553 | bool TransformExceptionSpec(SourceLocation Loc, |
| 1554 | FunctionProtoType::ExceptionSpecInfo &ESI, |
| 1555 | SmallVectorImpl<QualType> &Exceptions, |
| 1556 | bool &Changed); |
| 1557 | |
| 1558 | /// Rebuild the exception declaration and register the declaration |
| 1559 | /// as an instantiated local. |
| 1560 | VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, |
| 1561 | TypeSourceInfo *Declarator, |
| 1562 | SourceLocation StartLoc, |
| 1563 | SourceLocation NameLoc, |
| 1564 | IdentifierInfo *Name); |
| 1565 | |
| 1566 | /// Rebuild the Objective-C exception declaration and register the |
| 1567 | /// declaration as an instantiated local. |
| 1568 | VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, |
| 1569 | TypeSourceInfo *TSInfo, QualType T); |
| 1570 | |
| 1571 | TemplateName |
| 1572 | TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc, |
| 1573 | SourceLocation TemplateKWLoc, TemplateName Name, |
| 1574 | SourceLocation NameLoc, |
| 1575 | QualType ObjectType = QualType(), |
| 1576 | NamedDecl *FirstQualifierInScope = nullptr, |
| 1577 | bool AllowInjectedClassName = false); |
| 1578 | |
| 1579 | const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA); |
| 1580 | const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA); |
| 1581 | const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH); |
| 1582 | const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS, |
| 1583 | const Stmt *InstS, |
| 1584 | const NoInlineAttr *A); |
| 1585 | const AlwaysInlineAttr * |
| 1586 | TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS, |
| 1587 | const AlwaysInlineAttr *A); |
| 1588 | const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA); |
| 1589 | const OpenACCRoutineDeclAttr * |
| 1590 | TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A); |
| 1591 | ExprResult TransformPredefinedExpr(PredefinedExpr *E); |
| 1592 | ExprResult TransformDeclRefExpr(DeclRefExpr *E); |
| 1593 | ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E); |
| 1594 | |
| 1595 | ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E, |
| 1596 | NonTypeTemplateParmDecl *D); |
| 1597 | |
| 1598 | /// Rebuild a DeclRefExpr for a VarDecl reference. |
| 1599 | ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc); |
| 1600 | |
| 1601 | /// Transform a reference to a function or init-capture parameter pack. |
| 1602 | ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD); |
| 1603 | |
| 1604 | /// Transform a FunctionParmPackExpr which was built when we couldn't |
| 1605 | /// expand a function parameter pack reference which refers to an expanded |
| 1606 | /// pack. |
| 1607 | ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E); |
| 1608 | |
| 1609 | QualType TransformFunctionProtoType(TypeLocBuilder &TLB, |
| 1610 | FunctionProtoTypeLoc TL) { |
| 1611 | // Call the base version; it will forward to our overridden version below. |
| 1612 | return inherited::TransformFunctionProtoType(TLB, TL); |
| 1613 | } |
| 1614 | |
| 1615 | QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) { |
| 1616 | auto Type = inherited::TransformTagType(TLB, TL); |
| 1617 | if (!Type.isNull()) |
| 1618 | return Type; |
| 1619 | // Special case for transforming a deduction guide, we return a |
| 1620 | // transformed TemplateSpecializationType. |
| 1621 | // FIXME: Why is this hack necessary? |
| 1622 | if (const auto *ICNT = dyn_cast<InjectedClassNameType>(Val: TL.getTypePtr()); |
| 1623 | ICNT && SemaRef.CodeSynthesisContexts.back().Kind == |
| 1624 | Sema::CodeSynthesisContext::BuildingDeductionGuides) { |
| 1625 | Type = inherited::TransformType( |
| 1626 | T: ICNT->getDecl()->getCanonicalTemplateSpecializationType( |
| 1627 | Ctx: SemaRef.Context)); |
| 1628 | TLB.pushTrivial(Context&: SemaRef.Context, T: Type, Loc: TL.getNameLoc()); |
| 1629 | } |
| 1630 | return Type; |
| 1631 | } |
| 1632 | |
| 1633 | // Override the default version to handle a rewrite-template-arg-pack case |
| 1634 | // for building a deduction guide, and to cache substitution results in |
| 1635 | // concepts checking. |
| 1636 | bool TransformTemplateArgument(const TemplateArgumentLoc &Input, |
| 1637 | TemplateArgumentLoc &Output, |
| 1638 | bool Uneval = false) { |
| 1639 | const TemplateArgument &Arg = Input.getArgument(); |
| 1640 | if (auto *Cache = SemaRef.CurrentCachedTemplateArgs; |
| 1641 | Cache && TemplateArgsHashValue) { |
| 1642 | llvm::FoldingSetNodeID ID = *TemplateArgsHashValue; |
| 1643 | ID.AddInteger(I: SemaRef.ArgPackSubstIndex.toInternalRepresentation()); |
| 1644 | // FIXME: We may have better performance if we profile Arg without |
| 1645 | // sugars. |
| 1646 | Arg.Profile(ID, Context: SemaRef.Context); |
| 1647 | // FIXME: Ideally, we should only cache and restore the TemplateArgument |
| 1648 | // and rebuild the uncached TypeLoc separately in place. |
| 1649 | // We choose to accept loss of TypeLoc fidelity in cases where TypeLocs |
| 1650 | // are less critical for performance trade-off: currently, this is only |
| 1651 | // applied to concept substitutions and their valid template arguments. |
| 1652 | if (auto Iter = Cache->find(Val: ID); Iter != Cache->end()) { |
| 1653 | Output = Iter->second; |
| 1654 | return false; |
| 1655 | } |
| 1656 | bool Ret = inherited::TransformTemplateArgument(Input, Output, Uneval); |
| 1657 | if (!Ret) |
| 1658 | Cache->insert(KV: {ID, Output}); |
| 1659 | return Ret; |
| 1660 | } |
| 1661 | switch (Arg.getKind()) { |
| 1662 | case TemplateArgument::Pack: { |
| 1663 | std::vector<TemplateArgument> TArgs; |
| 1664 | assert(SemaRef.CodeSynthesisContexts.empty() || |
| 1665 | SemaRef.CodeSynthesisContexts.back().Kind == |
| 1666 | Sema::CodeSynthesisContext::BuildingDeductionGuides); |
| 1667 | // Literally rewrite the template argument pack, instead of unpacking |
| 1668 | // it. |
| 1669 | for (auto &pack : Arg.getPackAsArray()) { |
| 1670 | TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc( |
| 1671 | Arg: pack, NTTPType: QualType(), Loc: SourceLocation{}); |
| 1672 | TemplateArgumentLoc Output; |
| 1673 | if (TransformTemplateArgument(Input, Output, Uneval)) |
| 1674 | return true; // fails |
| 1675 | TArgs.push_back(x: Output.getArgument()); |
| 1676 | } |
| 1677 | Output = SemaRef.getTrivialTemplateArgumentLoc( |
| 1678 | Arg: TemplateArgument(llvm::ArrayRef(TArgs).copy(A&: SemaRef.Context)), |
| 1679 | NTTPType: QualType(), Loc: SourceLocation{}); |
| 1680 | return false; |
| 1681 | } |
| 1682 | default: |
| 1683 | break; |
| 1684 | } |
| 1685 | return inherited::TransformTemplateArgument(Input, Output, Uneval); |
| 1686 | } |
| 1687 | |
| 1688 | using TreeTransform::TransformTemplateSpecializationType; |
| 1689 | QualType |
| 1690 | TransformTemplateSpecializationType(TypeLocBuilder &TLB, |
| 1691 | TemplateSpecializationTypeLoc TL) { |
| 1692 | auto *T = TL.getTypePtr(); |
| 1693 | if (!getSema().ArgPackSubstIndex || !T->isSugared() || |
| 1694 | !isPackProducingBuiltinTemplateName(N: T->getTemplateName())) |
| 1695 | return TreeTransform::TransformTemplateSpecializationType(TLB, TL); |
| 1696 | // Look through sugar to get to the SubstBuiltinTemplatePackType that we |
| 1697 | // need to substitute into. |
| 1698 | |
| 1699 | // `TransformType` code below will handle picking the element from a pack |
| 1700 | // with the index `ArgPackSubstIndex`. |
| 1701 | // FIXME: add ability to represent sugarred type for N-th element of a |
| 1702 | // builtin pack and produce the sugar here. |
| 1703 | QualType R = TransformType(T: T->desugar()); |
| 1704 | TLB.pushTrivial(Context&: getSema().getASTContext(), T: R, Loc: TL.getBeginLoc()); |
| 1705 | return R; |
| 1706 | } |
| 1707 | |
| 1708 | UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution( |
| 1709 | ArrayRef<TemplateArgument> PackArgs) { |
| 1710 | // Don't do this when rewriting template parameters for CTAD: |
| 1711 | // 1) The heuristic needs the unpacked Subst* nodes to figure out the |
| 1712 | // expanded size, but this never applies since Subst* nodes are not |
| 1713 | // created in rewrite scenarios. |
| 1714 | // |
| 1715 | // 2) The heuristic substitutes into the pattern with pack expansion |
| 1716 | // suppressed, which does not meet the requirements for argument |
| 1717 | // rewriting when template arguments include a non-pack matching against |
| 1718 | // a pack, particularly when rewriting an alias CTAD. |
| 1719 | if (TemplateArgs.isRewrite()) |
| 1720 | return std::nullopt; |
| 1721 | |
| 1722 | return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs); |
| 1723 | } |
| 1724 | |
| 1725 | template<typename Fn> |
| 1726 | QualType TransformFunctionProtoType(TypeLocBuilder &TLB, |
| 1727 | FunctionProtoTypeLoc TL, |
| 1728 | CXXRecordDecl *ThisContext, |
| 1729 | Qualifiers ThisTypeQuals, |
| 1730 | Fn TransformExceptionSpec); |
| 1731 | |
| 1732 | ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm, |
| 1733 | int indexAdjustment, |
| 1734 | UnsignedOrNone NumExpansions, |
| 1735 | bool ExpectParameterPack); |
| 1736 | |
| 1737 | using inherited::TransformTemplateTypeParmType; |
| 1738 | /// Transforms a template type parameter type by performing |
| 1739 | /// substitution of the corresponding template type argument. |
| 1740 | QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, |
| 1741 | TemplateTypeParmTypeLoc TL, |
| 1742 | bool SuppressObjCLifetime); |
| 1743 | |
| 1744 | QualType BuildSubstTemplateTypeParmType( |
| 1745 | TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final, |
| 1746 | Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, |
| 1747 | TemplateArgument Arg, SourceLocation NameLoc); |
| 1748 | |
| 1749 | /// Transforms an already-substituted template type parameter pack |
| 1750 | /// into either itself (if we aren't substituting into its pack expansion) |
| 1751 | /// or the appropriate substituted argument. |
| 1752 | using inherited::TransformSubstTemplateTypeParmPackType; |
| 1753 | QualType |
| 1754 | TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB, |
| 1755 | SubstTemplateTypeParmPackTypeLoc TL, |
| 1756 | bool SuppressObjCLifetime); |
| 1757 | QualType |
| 1758 | TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB, |
| 1759 | SubstBuiltinTemplatePackTypeLoc TL); |
| 1760 | |
| 1761 | CXXRecordDecl::LambdaDependencyKind |
| 1762 | ComputeLambdaDependency(LambdaScopeInfo *LSI) { |
| 1763 | if (auto TypeAlias = |
| 1764 | TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl( |
| 1765 | SemaRef&: getSema()); |
| 1766 | TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl( |
| 1767 | LambdaCallOperator: LSI->CallOperator, PrimaryTypeAliasDecl: TypeAlias.PrimaryTypeAliasDecl)) { |
| 1768 | unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth(); |
| 1769 | if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels()) |
| 1770 | return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent; |
| 1771 | for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments) |
| 1772 | if (TA.isDependent()) |
| 1773 | return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent; |
| 1774 | } |
| 1775 | if (auto *CD = dyn_cast_if_present<ImplicitConceptSpecializationDecl>( |
| 1776 | Val: LSI->Lambda->getLambdaContextDecl())) { |
| 1777 | if (llvm::any_of(Range: CD->getTemplateArguments(), |
| 1778 | P: [](const auto &TA) { return TA.isDependent(); })) |
| 1779 | return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent; |
| 1780 | } |
| 1781 | return inherited::ComputeLambdaDependency(LSI); |
| 1782 | } |
| 1783 | |
| 1784 | ExprResult TransformLambdaConstraint(Expr *AC) { |
| 1785 | if (AC && EvaluateLambdaConstraint) |
| 1786 | return TransformExpr(E: const_cast<Expr *>(AC)); |
| 1787 | |
| 1788 | return AC; |
| 1789 | } |
| 1790 | |
| 1791 | ExprResult TransformLambdaExpr(LambdaExpr *E) { |
| 1792 | // Do not rebuild lambdas to avoid creating a new type. |
| 1793 | // Lambdas have already been processed inside their eval contexts. |
| 1794 | if (SemaRef.RebuildingImmediateInvocation) |
| 1795 | return E; |
| 1796 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true, |
| 1797 | /*InstantiatingLambdaOrBlock=*/true); |
| 1798 | llvm::SaveAndRestore RAII(EvaluateConstraints, EvaluateLambdaConstraint); |
| 1799 | |
| 1800 | return inherited::TransformLambdaExpr(E); |
| 1801 | } |
| 1802 | |
| 1803 | ExprResult TransformBlockExpr(BlockExpr *E) { |
| 1804 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true, |
| 1805 | /*InstantiatingLambdaOrBlock=*/true); |
| 1806 | return inherited::TransformBlockExpr(E); |
| 1807 | } |
| 1808 | |
| 1809 | ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, |
| 1810 | LambdaScopeInfo *LSI) { |
| 1811 | CXXMethodDecl *MD = LSI->CallOperator; |
| 1812 | for (ParmVarDecl *PVD : MD->parameters()) { |
| 1813 | assert(PVD && "null in a parameter list" ); |
| 1814 | if (!PVD->hasDefaultArg()) |
| 1815 | continue; |
| 1816 | Expr *UninstExpr = PVD->getUninstantiatedDefaultArg(); |
| 1817 | // FIXME: Obtain the source location for the '=' token. |
| 1818 | SourceLocation EqualLoc = UninstExpr->getBeginLoc(); |
| 1819 | if (SemaRef.SubstDefaultArgument(Loc: EqualLoc, Param: PVD, TemplateArgs)) { |
| 1820 | // If substitution fails, the default argument is set to a |
| 1821 | // RecoveryExpr that wraps the uninstantiated default argument so |
| 1822 | // that downstream diagnostics are omitted. |
| 1823 | ExprResult ErrorResult = SemaRef.CreateRecoveryExpr( |
| 1824 | Begin: UninstExpr->getBeginLoc(), End: UninstExpr->getEndLoc(), SubExprs: {UninstExpr}, |
| 1825 | T: UninstExpr->getType()); |
| 1826 | if (ErrorResult.isUsable()) |
| 1827 | PVD->setDefaultArg(ErrorResult.get()); |
| 1828 | } |
| 1829 | } |
| 1830 | return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI); |
| 1831 | } |
| 1832 | |
| 1833 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { |
| 1834 | // Currently, we instantiate the body when instantiating the lambda |
| 1835 | // expression. However, `EvaluateConstraints` is disabled during the |
| 1836 | // instantiation of the lambda expression, causing the instantiation |
| 1837 | // failure of the return type requirement in the body. If p0588r1 is fully |
| 1838 | // implemented, the body will be lazily instantiated, and this problem |
| 1839 | // will not occur. Here, `EvaluateConstraints` is temporarily set to |
| 1840 | // `true` to temporarily fix this issue. |
| 1841 | // FIXME: This temporary fix can be removed after fully implementing |
| 1842 | // p0588r1. |
| 1843 | llvm::SaveAndRestore _(EvaluateConstraints, true); |
| 1844 | return inherited::TransformLambdaBody(E, S: Body); |
| 1845 | } |
| 1846 | |
| 1847 | ExprResult TransformRequiresExpr(RequiresExpr *E) { |
| 1848 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); |
| 1849 | ExprResult TransReq = inherited::TransformRequiresExpr(E); |
| 1850 | if (TransReq.isInvalid()) |
| 1851 | return TransReq; |
| 1852 | assert(TransReq.get() != E && |
| 1853 | "Do not change value of isSatisfied for the existing expression. " |
| 1854 | "Create a new expression instead." ); |
| 1855 | if (E->getBody()->isDependentContext()) { |
| 1856 | Sema::SFINAETrap Trap(SemaRef); |
| 1857 | // We recreate the RequiresExpr body, but not by instantiating it. |
| 1858 | // Produce pending diagnostics for dependent access check. |
| 1859 | SemaRef.PerformDependentDiagnostics(Pattern: E->getBody(), TemplateArgs); |
| 1860 | // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis. |
| 1861 | if (Trap.hasErrorOccurred()) |
| 1862 | TransReq.getAs<RequiresExpr>()->setSatisfied(false); |
| 1863 | } |
| 1864 | return TransReq; |
| 1865 | } |
| 1866 | |
| 1867 | bool TransformRequiresExprRequirements( |
| 1868 | ArrayRef<concepts::Requirement *> Reqs, |
| 1869 | SmallVectorImpl<concepts::Requirement *> &Transformed) { |
| 1870 | bool SatisfactionDetermined = false; |
| 1871 | for (concepts::Requirement *Req : Reqs) { |
| 1872 | concepts::Requirement *TransReq = nullptr; |
| 1873 | if (!SatisfactionDetermined) { |
| 1874 | if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Val: Req)) |
| 1875 | TransReq = TransformTypeRequirement(Req: TypeReq); |
| 1876 | else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Val: Req)) |
| 1877 | TransReq = TransformExprRequirement(Req: ExprReq); |
| 1878 | else |
| 1879 | TransReq = TransformNestedRequirement( |
| 1880 | Req: cast<concepts::NestedRequirement>(Val: Req)); |
| 1881 | if (!TransReq) |
| 1882 | return true; |
| 1883 | if (!TransReq->isDependent() && !TransReq->isSatisfied()) |
| 1884 | // [expr.prim.req]p6 |
| 1885 | // [...] The substitution and semantic constraint checking |
| 1886 | // proceeds in lexical order and stops when a condition that |
| 1887 | // determines the result of the requires-expression is |
| 1888 | // encountered. [..] |
| 1889 | SatisfactionDetermined = true; |
| 1890 | } else |
| 1891 | TransReq = Req; |
| 1892 | Transformed.push_back(Elt: TransReq); |
| 1893 | } |
| 1894 | return false; |
| 1895 | } |
| 1896 | |
| 1897 | TemplateParameterList *TransformTemplateParameterList( |
| 1898 | TemplateParameterList *OrigTPL) { |
| 1899 | if (!OrigTPL || !OrigTPL->size()) return OrigTPL; |
| 1900 | |
| 1901 | DeclContext *Owner = OrigTPL->getParam(Idx: 0)->getDeclContext(); |
| 1902 | TemplateDeclInstantiator DeclInstantiator(getSema(), |
| 1903 | /* DeclContext *Owner */ Owner, |
| 1904 | TemplateArgs); |
| 1905 | DeclInstantiator.setEvaluateConstraints(EvaluateConstraints); |
| 1906 | return DeclInstantiator.SubstTemplateParams(List: OrigTPL); |
| 1907 | } |
| 1908 | |
| 1909 | concepts::TypeRequirement * |
| 1910 | TransformTypeRequirement(concepts::TypeRequirement *Req); |
| 1911 | concepts::ExprRequirement * |
| 1912 | TransformExprRequirement(concepts::ExprRequirement *Req); |
| 1913 | concepts::NestedRequirement * |
| 1914 | TransformNestedRequirement(concepts::NestedRequirement *Req); |
| 1915 | ExprResult TransformRequiresTypeParams( |
| 1916 | SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE, |
| 1917 | RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params, |
| 1918 | SmallVectorImpl<QualType> &PTypes, |
| 1919 | SmallVectorImpl<ParmVarDecl *> &TransParams, |
| 1920 | Sema::ExtParameterInfoBuilder &PInfos); |
| 1921 | |
| 1922 | ExprResult TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) { |
| 1923 | ExprResult Ret = inherited::TransformCXXDynamicCastExpr(E); |
| 1924 | if (Ret.isInvalid()) |
| 1925 | return Ret; |
| 1926 | QualType T = Ret.get()->getType(); |
| 1927 | if (const auto *PT = T->getAsCanonical<PointerType>()) |
| 1928 | T = PT->getPointeeType(); |
| 1929 | auto *DestDecl = T->getAsCXXRecordDecl(); |
| 1930 | if (DestDecl && DestDecl->isEffectivelyFinal()) |
| 1931 | getSema().MarkVTableUsed(Loc: Ret.get()->getExprLoc(), Class: DestDecl); |
| 1932 | return Ret; |
| 1933 | } |
| 1934 | }; |
| 1935 | } |
| 1936 | |
| 1937 | bool TemplateInstantiator::AlreadyTransformed(QualType T) { |
| 1938 | if (T.isNull()) |
| 1939 | return true; |
| 1940 | |
| 1941 | if (T->isInstantiationDependentType() || T->isVariablyModifiedType() || |
| 1942 | T->containsUnexpandedParameterPack()) |
| 1943 | return false; |
| 1944 | |
| 1945 | getSema().MarkDeclarationsReferencedInType(Loc, T); |
| 1946 | return true; |
| 1947 | } |
| 1948 | |
| 1949 | Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) { |
| 1950 | if (!D) |
| 1951 | return nullptr; |
| 1952 | |
| 1953 | if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: D)) { |
| 1954 | if (TTP->getDepth() < TemplateArgs.getNumLevels()) { |
| 1955 | // If the corresponding template argument is NULL or non-existent, it's |
| 1956 | // because we are performing instantiation from explicitly-specified |
| 1957 | // template arguments in a function template, but there were some |
| 1958 | // arguments left unspecified. |
| 1959 | if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(), |
| 1960 | Index: TTP->getPosition())) { |
| 1961 | IsIncomplete = true; |
| 1962 | return BailOutOnIncomplete ? nullptr : D; |
| 1963 | } |
| 1964 | |
| 1965 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); |
| 1966 | |
| 1967 | if (TTP->isParameterPack()) { |
| 1968 | assert(Arg.getKind() == TemplateArgument::Pack && |
| 1969 | "Missing argument pack" ); |
| 1970 | Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg); |
| 1971 | } |
| 1972 | |
| 1973 | TemplateName Template = Arg.getAsTemplate(); |
| 1974 | assert(!Template.isNull() && Template.getAsTemplateDecl() && |
| 1975 | "Wrong kind of template template argument" ); |
| 1976 | return Template.getAsTemplateDecl(); |
| 1977 | } |
| 1978 | |
| 1979 | // Fall through to find the instantiated declaration for this template |
| 1980 | // template parameter. |
| 1981 | } |
| 1982 | |
| 1983 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: D); |
| 1984 | PVD && SemaRef.CurrentInstantiationScope && |
| 1985 | (SemaRef.inConstraintSubstitution() || |
| 1986 | SemaRef.inParameterMappingSubstitution()) && |
| 1987 | maybeInstantiateFunctionParameterToScope(OldParm: PVD)) |
| 1988 | return nullptr; |
| 1989 | |
| 1990 | if (isa<CXXExpansionStmtDecl>(Val: D)) { |
| 1991 | assert(SemaRef.CurrentInstantiationScope); |
| 1992 | return cast<Decl *>( |
| 1993 | Val&: *SemaRef.CurrentInstantiationScope->findInstantiationOf(D)); |
| 1994 | } |
| 1995 | |
| 1996 | return SemaRef.FindInstantiatedDecl(Loc, D: cast<NamedDecl>(Val: D), TemplateArgs); |
| 1997 | } |
| 1998 | |
| 1999 | bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope( |
| 2000 | ParmVarDecl *OldParm) { |
| 2001 | if (SemaRef.CurrentInstantiationScope->getInstantiationOfIfExists(D: OldParm)) |
| 2002 | return false; |
| 2003 | |
| 2004 | if (!OldParm->isParameterPack()) |
| 2005 | return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0, |
| 2006 | /*NumExpansions=*/std::nullopt, |
| 2007 | /*ExpectParameterPack=*/false); |
| 2008 | |
| 2009 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
| 2010 | |
| 2011 | // Find the parameter packs that could be expanded. |
| 2012 | TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc(); |
| 2013 | PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>(); |
| 2014 | TypeLoc Pattern = ExpansionTL.getPatternLoc(); |
| 2015 | SemaRef.collectUnexpandedParameterPacks(TL: Pattern, Unexpanded); |
| 2016 | assert(!Unexpanded.empty() && "Pack expansion without parameter packs?" ); |
| 2017 | |
| 2018 | bool ShouldExpand = false; |
| 2019 | bool RetainExpansion = false; |
| 2020 | UnsignedOrNone OrigNumExpansions = |
| 2021 | ExpansionTL.getTypePtr()->getNumExpansions(); |
| 2022 | UnsignedOrNone NumExpansions = OrigNumExpansions; |
| 2023 | if (TryExpandParameterPacks(EllipsisLoc: ExpansionTL.getEllipsisLoc(), |
| 2024 | PatternRange: Pattern.getSourceRange(), Unexpanded, |
| 2025 | /*FailOnPackProducingTemplates=*/true, |
| 2026 | ShouldExpand, RetainExpansion, NumExpansions)) |
| 2027 | return true; |
| 2028 | |
| 2029 | assert(ShouldExpand && !RetainExpansion && |
| 2030 | "Shouldn't preserve pack expansion when evaluating constraints" ); |
| 2031 | ExpandingFunctionParameterPack(Pack: OldParm); |
| 2032 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
| 2033 | Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I); |
| 2034 | if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0, |
| 2035 | /*NumExpansions=*/OrigNumExpansions, |
| 2036 | /*ExpectParameterPack=*/false)) |
| 2037 | return true; |
| 2038 | } |
| 2039 | return false; |
| 2040 | } |
| 2041 | |
| 2042 | Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) { |
| 2043 | Decl *Inst = getSema().SubstDecl(D, Owner: getSema().CurContext, TemplateArgs); |
| 2044 | if (!Inst) |
| 2045 | return nullptr; |
| 2046 | |
| 2047 | getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst); |
| 2048 | return Inst; |
| 2049 | } |
| 2050 | |
| 2051 | bool TemplateInstantiator::TransformExceptionSpec( |
| 2052 | SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, |
| 2053 | SmallVectorImpl<QualType> &Exceptions, bool &Changed) { |
| 2054 | if (ESI.Type == EST_Uninstantiated) { |
| 2055 | ESI.instantiate(); |
| 2056 | Changed = true; |
| 2057 | } |
| 2058 | return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed); |
| 2059 | } |
| 2060 | |
| 2061 | NamedDecl * |
| 2062 | TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, |
| 2063 | SourceLocation Loc) { |
| 2064 | // If the first part of the nested-name-specifier was a template type |
| 2065 | // parameter, instantiate that type parameter down to a tag type. |
| 2066 | if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(Val: D)) { |
| 2067 | const TemplateTypeParmType *TTP |
| 2068 | = cast<TemplateTypeParmType>(Val: getSema().Context.getTypeDeclType(Decl: TTPD)); |
| 2069 | |
| 2070 | if (TTP->getDepth() < TemplateArgs.getNumLevels()) { |
| 2071 | // FIXME: This needs testing w/ member access expressions. |
| 2072 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex()); |
| 2073 | |
| 2074 | if (TTP->isParameterPack()) { |
| 2075 | assert(Arg.getKind() == TemplateArgument::Pack && |
| 2076 | "Missing argument pack" ); |
| 2077 | |
| 2078 | if (!getSema().ArgPackSubstIndex) |
| 2079 | return nullptr; |
| 2080 | |
| 2081 | Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg); |
| 2082 | } |
| 2083 | |
| 2084 | QualType T = Arg.getAsType(); |
| 2085 | if (T.isNull()) |
| 2086 | return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D)); |
| 2087 | |
| 2088 | if (const TagType *Tag = T->getAs<TagType>()) |
| 2089 | return Tag->getDecl(); |
| 2090 | |
| 2091 | // The resulting type is not a tag; complain. |
| 2092 | getSema().Diag(Loc, DiagID: diag::err_nested_name_spec_non_tag) << T; |
| 2093 | return nullptr; |
| 2094 | } |
| 2095 | } |
| 2096 | |
| 2097 | return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D)); |
| 2098 | } |
| 2099 | |
| 2100 | VarDecl * |
| 2101 | TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, |
| 2102 | TypeSourceInfo *Declarator, |
| 2103 | SourceLocation StartLoc, |
| 2104 | SourceLocation NameLoc, |
| 2105 | IdentifierInfo *Name) { |
| 2106 | VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator, |
| 2107 | StartLoc, IdLoc: NameLoc, Id: Name); |
| 2108 | if (Var) |
| 2109 | getSema().CurrentInstantiationScope->InstantiatedLocal(D: ExceptionDecl, Inst: Var); |
| 2110 | return Var; |
| 2111 | } |
| 2112 | |
| 2113 | VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, |
| 2114 | TypeSourceInfo *TSInfo, |
| 2115 | QualType T) { |
| 2116 | VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TInfo: TSInfo, T); |
| 2117 | if (Var) |
| 2118 | getSema().CurrentInstantiationScope->InstantiatedLocal(D: ExceptionDecl, Inst: Var); |
| 2119 | return Var; |
| 2120 | } |
| 2121 | |
| 2122 | TemplateName TemplateInstantiator::TransformTemplateName( |
| 2123 | NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc, |
| 2124 | TemplateName Name, SourceLocation NameLoc, QualType ObjectType, |
| 2125 | NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) { |
| 2126 | if (Name.getKind() == TemplateName::Template) { |
| 2127 | assert(!QualifierLoc && "Unexpected qualifier" ); |
| 2128 | if (auto *TTP = |
| 2129 | dyn_cast<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()); |
| 2130 | TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) { |
| 2131 | // If the corresponding template argument is NULL or non-existent, it's |
| 2132 | // because we are performing instantiation from explicitly-specified |
| 2133 | // template arguments in a function template, but there were some |
| 2134 | // arguments left unspecified. |
| 2135 | if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(), |
| 2136 | Index: TTP->getPosition())) { |
| 2137 | IsIncomplete = true; |
| 2138 | return BailOutOnIncomplete ? TemplateName() : Name; |
| 2139 | } |
| 2140 | |
| 2141 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); |
| 2142 | |
| 2143 | if (TemplateArgs.isRewrite()) { |
| 2144 | // We're rewriting the template parameter as a reference to another |
| 2145 | // template parameter. |
| 2146 | Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg); |
| 2147 | assert(Arg.getKind() == TemplateArgument::Template && |
| 2148 | "unexpected nontype template argument kind in template rewrite" ); |
| 2149 | return Arg.getAsTemplate(); |
| 2150 | } |
| 2151 | |
| 2152 | auto [AssociatedDecl, Final] = |
| 2153 | TemplateArgs.getAssociatedDecl(Depth: TTP->getDepth()); |
| 2154 | UnsignedOrNone PackIndex = std::nullopt; |
| 2155 | if (TTP->isParameterPack()) { |
| 2156 | assert(Arg.getKind() == TemplateArgument::Pack && |
| 2157 | "Missing argument pack" ); |
| 2158 | |
| 2159 | if (!getSema().ArgPackSubstIndex) { |
| 2160 | // We have the template argument pack to substitute, but we're not |
| 2161 | // actually expanding the enclosing pack expansion yet. So, just |
| 2162 | // keep the entire argument pack. |
| 2163 | return getSema().Context.getSubstTemplateTemplateParmPack( |
| 2164 | ArgPack: Arg, AssociatedDecl, Index: TTP->getIndex(), Final); |
| 2165 | } |
| 2166 | |
| 2167 | PackIndex = SemaRef.getPackIndex(Pack: Arg); |
| 2168 | Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg); |
| 2169 | } |
| 2170 | |
| 2171 | TemplateName Template = Arg.getAsTemplate(); |
| 2172 | assert(!Template.isNull() && "Null template template argument" ); |
| 2173 | return getSema().Context.getSubstTemplateTemplateParm( |
| 2174 | replacement: Template, AssociatedDecl, Index: TTP->getIndex(), PackIndex, Final); |
| 2175 | } |
| 2176 | } |
| 2177 | |
| 2178 | if (SubstTemplateTemplateParmPackStorage *SubstPack |
| 2179 | = Name.getAsSubstTemplateTemplateParmPack()) { |
| 2180 | if (!getSema().ArgPackSubstIndex) |
| 2181 | return Name; |
| 2182 | |
| 2183 | TemplateArgument Pack = SubstPack->getArgumentPack(); |
| 2184 | TemplateName Template = |
| 2185 | SemaRef.getPackSubstitutedTemplateArgument(Arg: Pack).getAsTemplate(); |
| 2186 | return getSema().Context.getSubstTemplateTemplateParm( |
| 2187 | replacement: Template, AssociatedDecl: SubstPack->getAssociatedDecl(), Index: SubstPack->getIndex(), |
| 2188 | PackIndex: SemaRef.getPackIndex(Pack), Final: SubstPack->getFinal()); |
| 2189 | } |
| 2190 | |
| 2191 | return inherited::TransformTemplateName( |
| 2192 | QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType, |
| 2193 | FirstQualifierInScope, AllowInjectedClassName); |
| 2194 | } |
| 2195 | |
| 2196 | ExprResult |
| 2197 | TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) { |
| 2198 | if (!E->isTypeDependent()) |
| 2199 | return E; |
| 2200 | |
| 2201 | return getSema().BuildPredefinedExpr(Loc: E->getLocation(), IK: E->getIdentKind()); |
| 2202 | } |
| 2203 | |
| 2204 | ExprResult |
| 2205 | TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, |
| 2206 | NonTypeTemplateParmDecl *NTTP) { |
| 2207 | if (TemplateArgs.retainInnerDepths() && |
| 2208 | NTTP->getDepth() >= TemplateArgs.getNumLevels()) |
| 2209 | return E; |
| 2210 | // If the corresponding template argument is NULL or non-existent, it's |
| 2211 | // because we are performing instantiation from explicitly-specified |
| 2212 | // template arguments in a function template, but there were some |
| 2213 | // arguments left unspecified. |
| 2214 | if (!TemplateArgs.hasTemplateArgument(Depth: NTTP->getDepth(), |
| 2215 | Index: NTTP->getPosition())) { |
| 2216 | IsIncomplete = true; |
| 2217 | return BailOutOnIncomplete ? ExprError() : E; |
| 2218 | } |
| 2219 | |
| 2220 | TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition()); |
| 2221 | |
| 2222 | if (TemplateArgs.isRewrite()) { |
| 2223 | // We're rewriting the template parameter as a reference to another |
| 2224 | // template parameter. |
| 2225 | Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg); |
| 2226 | assert(Arg.getKind() == TemplateArgument::Expression && |
| 2227 | "unexpected nontype template argument kind in template rewrite" ); |
| 2228 | // FIXME: This can lead to the same subexpression appearing multiple times |
| 2229 | // in a complete expression. |
| 2230 | return Arg.getAsExpr(); |
| 2231 | } |
| 2232 | |
| 2233 | QualType ParamType = NTTP->isExpandedParameterPack() |
| 2234 | ? NTTP->getExpansionType(I: *SemaRef.ArgPackSubstIndex) |
| 2235 | : NTTP->isParameterPack() && SemaRef.ArgPackSubstIndex |
| 2236 | ? NTTP->getType().getNonPackExpansionType() |
| 2237 | : NTTP->getType(); |
| 2238 | ParamType = SemaRef.SubstType(T: ParamType, TemplateArgs, Loc: E->getLocation(), |
| 2239 | Entity: NTTP->getDeclName()); |
| 2240 | assert(!ParamType.isNull() && "Shouldn't substitute to an invalid type" ); |
| 2241 | |
| 2242 | auto [AssociatedDecl, Final] = |
| 2243 | TemplateArgs.getAssociatedDecl(Depth: NTTP->getDepth()); |
| 2244 | UnsignedOrNone PackIndex = std::nullopt; |
| 2245 | if (NTTP->isParameterPack() || |
| 2246 | // In concept parameter mapping for fold expressions, packs that aren't |
| 2247 | // expanded in place are treated as having non-pack dependency, so that |
| 2248 | // a PackExpansionType won't prevent expanding the packs outside the |
| 2249 | // TreeTransform. However, we still need to unpack the arguments during |
| 2250 | // any template argument substitution, so we also check its FoundDecl. |
| 2251 | (E->getFoundDecl() && E->getFoundDecl() != E->getDecl() && |
| 2252 | E->getFoundDecl()->isParameterPack())) { |
| 2253 | assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack" ); |
| 2254 | |
| 2255 | if (!getSema().ArgPackSubstIndex) { |
| 2256 | // We have an argument pack, but we can't select a particular argument |
| 2257 | // out of it yet. Therefore, we'll build an expression to hold on to that |
| 2258 | // argument pack. |
| 2259 | QualType ExprType = ParamType.getNonLValueExprType(Context: SemaRef.Context); |
| 2260 | if (ParamType->isRecordType()) |
| 2261 | ExprType.addConst(); |
| 2262 | return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr( |
| 2263 | ExprType, ParamType->isReferenceType() ? VK_LValue : VK_PRValue, |
| 2264 | E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final); |
| 2265 | } |
| 2266 | PackIndex = SemaRef.getPackIndex(Pack: Arg); |
| 2267 | Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg); |
| 2268 | } |
| 2269 | return SemaRef.BuildSubstNonTypeTemplateParmExpr( |
| 2270 | AssociatedDecl, Index: NTTP->getPosition(), ParamType, loc: E->getLocation(), Replacement: Arg, |
| 2271 | PackIndex, Final); |
| 2272 | } |
| 2273 | |
| 2274 | const AnnotateAttr * |
| 2275 | TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) { |
| 2276 | SmallVector<Expr *> Args; |
| 2277 | for (Expr *Arg : AA->args()) { |
| 2278 | ExprResult Res = getDerived().TransformExpr(E: Arg); |
| 2279 | if (Res.isUsable()) |
| 2280 | Args.push_back(Elt: Res.get()); |
| 2281 | } |
| 2282 | return AnnotateAttr::CreateImplicit(Ctx&: getSema().Context, Annotation: AA->getAnnotation(), |
| 2283 | Args: Args.data(), ArgsSize: Args.size(), Range: AA->getRange()); |
| 2284 | } |
| 2285 | |
| 2286 | const CXXAssumeAttr * |
| 2287 | TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) { |
| 2288 | ExprResult Res = getDerived().TransformExpr(E: AA->getAssumption()); |
| 2289 | if (!Res.isUsable()) |
| 2290 | return AA; |
| 2291 | |
| 2292 | if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) { |
| 2293 | Res = getSema().BuildCXXAssumeExpr(Assumption: Res.get(), AttrName: AA->getAttrName(), |
| 2294 | Range: AA->getRange()); |
| 2295 | if (!Res.isUsable()) |
| 2296 | return AA; |
| 2297 | } |
| 2298 | |
| 2299 | return CXXAssumeAttr::CreateImplicit(Ctx&: getSema().Context, Assumption: Res.get(), |
| 2300 | Range: AA->getRange()); |
| 2301 | } |
| 2302 | |
| 2303 | const LoopHintAttr * |
| 2304 | TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) { |
| 2305 | ExprResult TransformedExprResult = getDerived().TransformExpr(E: LH->getValue()); |
| 2306 | if (!TransformedExprResult.isUsable() || |
| 2307 | TransformedExprResult.get() == LH->getValue()) |
| 2308 | return LH; |
| 2309 | Expr *TransformedExpr = TransformedExprResult.get(); |
| 2310 | |
| 2311 | // Generate error if there is a problem with the value. |
| 2312 | if (getSema().CheckLoopHintExpr(E: TransformedExpr, Loc: LH->getLocation(), |
| 2313 | /*AllowZero=*/LH->getSemanticSpelling() == |
| 2314 | LoopHintAttr::Pragma_unroll)) |
| 2315 | return LH; |
| 2316 | |
| 2317 | LoopHintAttr::OptionType Option = LH->getOption(); |
| 2318 | LoopHintAttr::LoopHintState State = LH->getState(); |
| 2319 | |
| 2320 | // Since C++ does not have partial instantiation, we would expect a |
| 2321 | // transformed loop hint expression to not be value dependent. However, at |
| 2322 | // the time of writing, the use of a generic lambda inside a template |
| 2323 | // triggers a double instantiation, so we must protect against this event. |
| 2324 | // This provision may become unneeded in the future. |
| 2325 | if (Option == LoopHintAttr::UnrollCount && |
| 2326 | !TransformedExpr->isValueDependent()) { |
| 2327 | llvm::APSInt ValueAPS = |
| 2328 | TransformedExpr->EvaluateKnownConstInt(Ctx: getSema().getASTContext()); |
| 2329 | // The values of 0 and 1 block any unrolling of the loop (also see |
| 2330 | // handleLoopHintAttr in SemaStmtAttr). |
| 2331 | if (ValueAPS.isZero() || ValueAPS.isOne()) { |
| 2332 | Option = LoopHintAttr::Unroll; |
| 2333 | State = LoopHintAttr::Disable; |
| 2334 | } |
| 2335 | } |
| 2336 | |
| 2337 | // Create new LoopHintValueAttr with integral expression in place of the |
| 2338 | // non-type template parameter. |
| 2339 | return LoopHintAttr::CreateImplicit(Ctx&: getSema().Context, Option, State, |
| 2340 | Value: TransformedExpr, CommonInfo: *LH); |
| 2341 | } |
| 2342 | const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr( |
| 2343 | const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) { |
| 2344 | if (!A || getSema().CheckNoInlineAttr(OrigSt: OrigS, CurSt: InstS, A: *A)) |
| 2345 | return nullptr; |
| 2346 | |
| 2347 | return A; |
| 2348 | } |
| 2349 | const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr( |
| 2350 | const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) { |
| 2351 | if (!A || getSema().CheckAlwaysInlineAttr(OrigSt: OrigS, CurSt: InstS, A: *A)) |
| 2352 | return nullptr; |
| 2353 | |
| 2354 | return A; |
| 2355 | } |
| 2356 | |
| 2357 | const CodeAlignAttr * |
| 2358 | TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) { |
| 2359 | Expr *TransformedExpr = getDerived().TransformExpr(E: CA->getAlignment()).get(); |
| 2360 | return getSema().BuildCodeAlignAttr(CI: *CA, E: TransformedExpr); |
| 2361 | } |
| 2362 | const OpenACCRoutineDeclAttr * |
| 2363 | TemplateInstantiator::TransformOpenACCRoutineDeclAttr( |
| 2364 | const OpenACCRoutineDeclAttr *A) { |
| 2365 | llvm_unreachable("RoutineDecl should only be a declaration attribute, as it " |
| 2366 | "applies to a Function Decl (and a few places for VarDecl)" ); |
| 2367 | } |
| 2368 | |
| 2369 | ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD, |
| 2370 | SourceLocation Loc) { |
| 2371 | DeclarationNameInfo NameInfo(PD->getDeclName(), Loc); |
| 2372 | return getSema().BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo, D: PD); |
| 2373 | } |
| 2374 | |
| 2375 | ExprResult |
| 2376 | TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) { |
| 2377 | if (getSema().ArgPackSubstIndex) { |
| 2378 | // We can expand this parameter pack now. |
| 2379 | ValueDecl *D = E->getExpansion(I: *getSema().ArgPackSubstIndex); |
| 2380 | ValueDecl *VD = cast_or_null<ValueDecl>(Val: TransformDecl(Loc: E->getExprLoc(), D)); |
| 2381 | if (!VD) |
| 2382 | return ExprError(); |
| 2383 | return RebuildVarDeclRefExpr(PD: VD, Loc: E->getExprLoc()); |
| 2384 | } |
| 2385 | |
| 2386 | QualType T = TransformType(T: E->getType()); |
| 2387 | if (T.isNull()) |
| 2388 | return ExprError(); |
| 2389 | |
| 2390 | // Transform each of the parameter expansions into the corresponding |
| 2391 | // parameters in the instantiation of the function decl. |
| 2392 | SmallVector<ValueDecl *, 8> Vars; |
| 2393 | Vars.reserve(N: E->getNumExpansions()); |
| 2394 | for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end(); |
| 2395 | I != End; ++I) { |
| 2396 | ValueDecl *D = cast_or_null<ValueDecl>(Val: TransformDecl(Loc: E->getExprLoc(), D: *I)); |
| 2397 | if (!D) |
| 2398 | return ExprError(); |
| 2399 | Vars.push_back(Elt: D); |
| 2400 | } |
| 2401 | |
| 2402 | auto *PackExpr = |
| 2403 | FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: E->getParameterPack(), |
| 2404 | NameLoc: E->getParameterPackLocation(), Params: Vars); |
| 2405 | getSema().MarkFunctionParmPackReferenced(E: PackExpr); |
| 2406 | return PackExpr; |
| 2407 | } |
| 2408 | |
| 2409 | ExprResult |
| 2410 | TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E, |
| 2411 | ValueDecl *PD) { |
| 2412 | typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; |
| 2413 | llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found = |
| 2414 | getSema().CurrentInstantiationScope->getInstantiationOfIfExists(D: PD); |
| 2415 | |
| 2416 | // This can happen when instantiating an expansion statement that contains |
| 2417 | // a pack (e.g. `template for (auto x : {{ts...}})`). |
| 2418 | if (!Found) |
| 2419 | return E; |
| 2420 | |
| 2421 | Decl *TransformedDecl; |
| 2422 | if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: *Found)) { |
| 2423 | // If this is a reference to a function parameter pack which we can |
| 2424 | // substitute but can't yet expand, build a FunctionParmPackExpr for it. |
| 2425 | if (!getSema().ArgPackSubstIndex) { |
| 2426 | QualType T = TransformType(T: E->getType()); |
| 2427 | if (T.isNull()) |
| 2428 | return ExprError(); |
| 2429 | auto *PackExpr = FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: PD, |
| 2430 | NameLoc: E->getExprLoc(), Params: *Pack); |
| 2431 | getSema().MarkFunctionParmPackReferenced(E: PackExpr); |
| 2432 | return PackExpr; |
| 2433 | } |
| 2434 | |
| 2435 | TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex]; |
| 2436 | } else { |
| 2437 | TransformedDecl = cast<Decl *>(Val&: *Found); |
| 2438 | } |
| 2439 | |
| 2440 | // We have either an unexpanded pack or a specific expansion. |
| 2441 | return RebuildVarDeclRefExpr(PD: cast<ValueDecl>(Val: TransformedDecl), |
| 2442 | Loc: E->getExprLoc()); |
| 2443 | } |
| 2444 | |
| 2445 | ExprResult |
| 2446 | TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { |
| 2447 | NamedDecl *D = E->getDecl(); |
| 2448 | |
| 2449 | // Handle references to non-type template parameters and non-type template |
| 2450 | // parameter packs. |
| 2451 | if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: D)) { |
| 2452 | if (NTTP->getDepth() < TemplateArgs.getNumLevels()) |
| 2453 | return TransformTemplateParmRefExpr(E, NTTP); |
| 2454 | |
| 2455 | // We have a non-type template parameter that isn't fully substituted; |
| 2456 | // FindInstantiatedDecl will find it in the local instantiation scope. |
| 2457 | } |
| 2458 | |
| 2459 | // Handle references to function parameter packs. |
| 2460 | if (VarDecl *PD = dyn_cast<VarDecl>(Val: D)) |
| 2461 | if (PD->isParameterPack()) { |
| 2462 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: PD); |
| 2463 | PVD && SemaRef.CurrentInstantiationScope && |
| 2464 | (SemaRef.inConstraintSubstitution() || |
| 2465 | SemaRef.inParameterMappingSubstitution()) && |
| 2466 | maybeInstantiateFunctionParameterToScope(OldParm: PVD)) |
| 2467 | return ExprError(); |
| 2468 | |
| 2469 | return TransformFunctionParmPackRefExpr(E, PD); |
| 2470 | } |
| 2471 | |
| 2472 | return inherited::TransformDeclRefExpr(E); |
| 2473 | } |
| 2474 | |
| 2475 | ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr( |
| 2476 | CXXDefaultArgExpr *E) { |
| 2477 | assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())-> |
| 2478 | getDescribedFunctionTemplate() && |
| 2479 | "Default arg expressions are never formed in dependent cases." ); |
| 2480 | return SemaRef.BuildCXXDefaultArgExpr( |
| 2481 | CallLoc: E->getUsedLocation(), FD: cast<FunctionDecl>(Val: E->getParam()->getDeclContext()), |
| 2482 | Param: E->getParam()); |
| 2483 | } |
| 2484 | |
| 2485 | template<typename Fn> |
| 2486 | QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB, |
| 2487 | FunctionProtoTypeLoc TL, |
| 2488 | CXXRecordDecl *ThisContext, |
| 2489 | Qualifiers ThisTypeQuals, |
| 2490 | Fn TransformExceptionSpec) { |
| 2491 | // If this is a lambda or block, the transformation MUST be done in the |
| 2492 | // CurrentInstantiationScope since it introduces a mapping of |
| 2493 | // the original to the newly created transformed parameters. |
| 2494 | // |
| 2495 | // In that case, TemplateInstantiator::TransformLambdaExpr will |
| 2496 | // have already pushed a scope for this prototype, so don't create |
| 2497 | // a second one. |
| 2498 | LocalInstantiationScope *Current = getSema().CurrentInstantiationScope; |
| 2499 | std::optional<LocalInstantiationScope> Scope; |
| 2500 | if (!Current || !Current->isLambdaOrBlock()) |
| 2501 | Scope.emplace(args&: SemaRef, /*CombineWithOuterScope=*/args: true); |
| 2502 | |
| 2503 | return inherited::TransformFunctionProtoType( |
| 2504 | TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec); |
| 2505 | } |
| 2506 | |
| 2507 | ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam( |
| 2508 | ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions, |
| 2509 | bool ExpectParameterPack) { |
| 2510 | auto NewParm = SemaRef.SubstParmVarDecl( |
| 2511 | D: OldParm, TemplateArgs, indexAdjustment, NumExpansions, |
| 2512 | ExpectParameterPack, EvaluateConstraints); |
| 2513 | if (NewParm && SemaRef.getLangOpts().OpenCL) |
| 2514 | SemaRef.deduceOpenCLAddressSpace(decl: NewParm); |
| 2515 | return NewParm; |
| 2516 | } |
| 2517 | |
| 2518 | QualType TemplateInstantiator::BuildSubstTemplateTypeParmType( |
| 2519 | TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final, |
| 2520 | Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, |
| 2521 | TemplateArgument Arg, SourceLocation NameLoc) { |
| 2522 | QualType Replacement = Arg.getAsType(); |
| 2523 | |
| 2524 | // If the template parameter had ObjC lifetime qualifiers, |
| 2525 | // then any such qualifiers on the replacement type are ignored. |
| 2526 | if (SuppressObjCLifetime) { |
| 2527 | Qualifiers RQs; |
| 2528 | RQs = Replacement.getQualifiers(); |
| 2529 | RQs.removeObjCLifetime(); |
| 2530 | Replacement = |
| 2531 | SemaRef.Context.getQualifiedType(T: Replacement.getUnqualifiedType(), Qs: RQs); |
| 2532 | } |
| 2533 | |
| 2534 | // TODO: only do this uniquing once, at the start of instantiation. |
| 2535 | QualType Result = getSema().Context.getSubstTemplateTypeParmType( |
| 2536 | Replacement, AssociatedDecl, Index, PackIndex, Final); |
| 2537 | SubstTemplateTypeParmTypeLoc NewTL = |
| 2538 | TLB.push<SubstTemplateTypeParmTypeLoc>(T: Result); |
| 2539 | NewTL.setNameLoc(NameLoc); |
| 2540 | return Result; |
| 2541 | } |
| 2542 | |
| 2543 | QualType |
| 2544 | TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, |
| 2545 | TemplateTypeParmTypeLoc TL, |
| 2546 | bool SuppressObjCLifetime) { |
| 2547 | const TemplateTypeParmType *T = TL.getTypePtr(); |
| 2548 | if (T->getDepth() < TemplateArgs.getNumLevels()) { |
| 2549 | // Replace the template type parameter with its corresponding |
| 2550 | // template argument. |
| 2551 | |
| 2552 | // If the corresponding template argument is NULL or doesn't exist, it's |
| 2553 | // because we are performing instantiation from explicitly-specified |
| 2554 | // template arguments in a function template class, but there were some |
| 2555 | // arguments left unspecified. |
| 2556 | if (!TemplateArgs.hasTemplateArgument(Depth: T->getDepth(), Index: T->getIndex())) { |
| 2557 | IsIncomplete = true; |
| 2558 | if (BailOutOnIncomplete) |
| 2559 | return QualType(); |
| 2560 | |
| 2561 | TemplateTypeParmTypeLoc NewTL |
| 2562 | = TLB.push<TemplateTypeParmTypeLoc>(T: TL.getType()); |
| 2563 | NewTL.setNameLoc(TL.getNameLoc()); |
| 2564 | return TL.getType(); |
| 2565 | } |
| 2566 | |
| 2567 | TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex()); |
| 2568 | |
| 2569 | if (TemplateArgs.isRewrite()) { |
| 2570 | // We're rewriting the template parameter as a reference to another |
| 2571 | // template parameter. |
| 2572 | Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg); |
| 2573 | assert(Arg.getKind() == TemplateArgument::Type && |
| 2574 | "unexpected nontype template argument kind in template rewrite" ); |
| 2575 | QualType NewT = Arg.getAsType(); |
| 2576 | TLB.pushTrivial(Context&: SemaRef.Context, T: NewT, Loc: TL.getNameLoc()); |
| 2577 | return NewT; |
| 2578 | } |
| 2579 | |
| 2580 | auto [AssociatedDecl, Final] = |
| 2581 | TemplateArgs.getAssociatedDecl(Depth: T->getDepth()); |
| 2582 | UnsignedOrNone PackIndex = std::nullopt; |
| 2583 | if (T->isParameterPack() || |
| 2584 | // In concept parameter mapping for fold expressions, packs that aren't |
| 2585 | // expanded in place are treated as having non-pack dependency, so that |
| 2586 | // a PackExpansionType won't prevent expanding the packs outside the |
| 2587 | // TreeTransform. However, we still need to unpack the arguments during |
| 2588 | // any template argument substitution, so we check the associated |
| 2589 | // declaration instead. |
| 2590 | (T->getDecl() && T->getDecl()->isTemplateParameterPack())) { |
| 2591 | assert(Arg.getKind() == TemplateArgument::Pack && |
| 2592 | "Missing argument pack" ); |
| 2593 | |
| 2594 | if (!getSema().ArgPackSubstIndex) { |
| 2595 | // We have the template argument pack, but we're not expanding the |
| 2596 | // enclosing pack expansion yet. Just save the template argument |
| 2597 | // pack for later substitution. |
| 2598 | QualType Result = getSema().Context.getSubstTemplateTypeParmPackType( |
| 2599 | AssociatedDecl, Index: T->getIndex(), Final, ArgPack: Arg); |
| 2600 | SubstTemplateTypeParmPackTypeLoc NewTL |
| 2601 | = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result); |
| 2602 | NewTL.setNameLoc(TL.getNameLoc()); |
| 2603 | return Result; |
| 2604 | } |
| 2605 | |
| 2606 | // PackIndex starts from last element. |
| 2607 | PackIndex = SemaRef.getPackIndex(Pack: Arg); |
| 2608 | Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg); |
| 2609 | } |
| 2610 | |
| 2611 | assert(Arg.getKind() == TemplateArgument::Type && |
| 2612 | "Template argument kind mismatch" ); |
| 2613 | |
| 2614 | return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final, |
| 2615 | AssociatedDecl, Index: T->getIndex(), |
| 2616 | PackIndex, Arg, NameLoc: TL.getNameLoc()); |
| 2617 | } |
| 2618 | |
| 2619 | // The template type parameter comes from an inner template (e.g., |
| 2620 | // the template parameter list of a member template inside the |
| 2621 | // template we are instantiating). Create a new template type |
| 2622 | // parameter with the template "level" reduced by one. |
| 2623 | TemplateTypeParmDecl *NewTTPDecl = nullptr; |
| 2624 | if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl()) |
| 2625 | NewTTPDecl = cast_or_null<TemplateTypeParmDecl>( |
| 2626 | Val: TransformDecl(Loc: TL.getNameLoc(), D: OldTTPDecl)); |
| 2627 | QualType Result = getSema().Context.getTemplateTypeParmType( |
| 2628 | Depth: T->getDepth() - (TemplateArgs.retainInnerDepths() |
| 2629 | ? 0 |
| 2630 | : TemplateArgs.getNumSubstitutedLevels()), |
| 2631 | Index: T->getIndex(), ParameterPack: T->isParameterPack(), ParmDecl: NewTTPDecl); |
| 2632 | TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(T: Result); |
| 2633 | NewTL.setNameLoc(TL.getNameLoc()); |
| 2634 | return Result; |
| 2635 | } |
| 2636 | |
| 2637 | QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType( |
| 2638 | TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL, |
| 2639 | bool SuppressObjCLifetime) { |
| 2640 | const SubstTemplateTypeParmPackType *T = TL.getTypePtr(); |
| 2641 | |
| 2642 | Decl *NewReplaced = TransformDecl(Loc: TL.getNameLoc(), D: T->getAssociatedDecl()); |
| 2643 | |
| 2644 | if (!getSema().ArgPackSubstIndex) { |
| 2645 | // We aren't expanding the parameter pack, so just return ourselves. |
| 2646 | QualType Result = TL.getType(); |
| 2647 | if (NewReplaced != T->getAssociatedDecl()) |
| 2648 | Result = getSema().Context.getSubstTemplateTypeParmPackType( |
| 2649 | AssociatedDecl: NewReplaced, Index: T->getIndex(), Final: T->getFinal(), ArgPack: T->getArgumentPack()); |
| 2650 | SubstTemplateTypeParmPackTypeLoc NewTL = |
| 2651 | TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result); |
| 2652 | NewTL.setNameLoc(TL.getNameLoc()); |
| 2653 | return Result; |
| 2654 | } |
| 2655 | |
| 2656 | TemplateArgument Pack = T->getArgumentPack(); |
| 2657 | TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg: Pack); |
| 2658 | return BuildSubstTemplateTypeParmType( |
| 2659 | TLB, SuppressObjCLifetime, Final: T->getFinal(), AssociatedDecl: NewReplaced, Index: T->getIndex(), |
| 2660 | PackIndex: SemaRef.getPackIndex(Pack), Arg, NameLoc: TL.getNameLoc()); |
| 2661 | } |
| 2662 | |
| 2663 | QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType( |
| 2664 | TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) { |
| 2665 | if (!getSema().ArgPackSubstIndex) |
| 2666 | return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL); |
| 2667 | TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument( |
| 2668 | Arg: TL.getTypePtr()->getArgumentPack()); |
| 2669 | TLB.pushTrivial(Context&: SemaRef.getASTContext(), T: Result.getAsType(), |
| 2670 | Loc: TL.getBeginLoc()); |
| 2671 | return Result.getAsType(); |
| 2672 | } |
| 2673 | |
| 2674 | static concepts::Requirement::SubstitutionDiagnostic * |
| 2675 | createSubstDiag(Sema &S, TemplateDeductionInfo &Info, |
| 2676 | Sema::EntityPrinter Printer) { |
| 2677 | SmallString<128> Message; |
| 2678 | SourceLocation ErrorLoc; |
| 2679 | if (Info.hasSFINAEDiagnostic()) { |
| 2680 | PartialDiagnosticAt PDA(SourceLocation(), |
| 2681 | PartialDiagnostic::NullDiagnostic{}); |
| 2682 | Info.takeSFINAEDiagnostic(PD&: PDA); |
| 2683 | PDA.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: Message); |
| 2684 | ErrorLoc = PDA.first; |
| 2685 | } else { |
| 2686 | ErrorLoc = Info.getLocation(); |
| 2687 | } |
| 2688 | SmallString<128> Entity; |
| 2689 | llvm::raw_svector_ostream OS(Entity); |
| 2690 | Printer(OS); |
| 2691 | const ASTContext &C = S.Context; |
| 2692 | return new (C) concepts::Requirement::SubstitutionDiagnostic{ |
| 2693 | .SubstitutedEntity: C.backupStr(S: Entity), .DiagLoc: ErrorLoc, .DiagMessage: C.backupStr(S: Message)}; |
| 2694 | } |
| 2695 | |
| 2696 | concepts::Requirement::SubstitutionDiagnostic * |
| 2697 | Sema::createSubstDiagAt(SourceLocation Location, EntityPrinter Printer) { |
| 2698 | SmallString<128> Entity; |
| 2699 | llvm::raw_svector_ostream OS(Entity); |
| 2700 | Printer(OS); |
| 2701 | const ASTContext &C = Context; |
| 2702 | return new (C) concepts::Requirement::SubstitutionDiagnostic{ |
| 2703 | /*SubstitutedEntity=*/C.backupStr(S: Entity), |
| 2704 | /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()}; |
| 2705 | } |
| 2706 | |
| 2707 | ExprResult TemplateInstantiator::TransformRequiresTypeParams( |
| 2708 | SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE, |
| 2709 | RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params, |
| 2710 | SmallVectorImpl<QualType> &PTypes, |
| 2711 | SmallVectorImpl<ParmVarDecl *> &TransParams, |
| 2712 | Sema::ExtParameterInfoBuilder &PInfos) { |
| 2713 | |
| 2714 | TemplateDeductionInfo Info(KWLoc); |
| 2715 | Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, RE, |
| 2716 | SourceRange{KWLoc, RBraceLoc}); |
| 2717 | Sema::SFINAETrap Trap(SemaRef, Info); |
| 2718 | |
| 2719 | unsigned ErrorIdx; |
| 2720 | if (getDerived().TransformFunctionTypeParams( |
| 2721 | Loc: KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, OutParamTypes&: PTypes, |
| 2722 | PVars: &TransParams, PInfos, LastParamTransformed: &ErrorIdx) || |
| 2723 | Trap.hasErrorOccurred()) { |
| 2724 | SmallVector<concepts::Requirement *, 4> TransReqs; |
| 2725 | ParmVarDecl *FailedDecl = Params[ErrorIdx]; |
| 2726 | // Add a 'failed' Requirement to contain the error that caused the failure |
| 2727 | // here. |
| 2728 | TransReqs.push_back(Elt: RebuildTypeRequirement(SubstDiag: createSubstDiag( |
| 2729 | S&: SemaRef, Info, Printer: [&](llvm::raw_ostream &OS) { OS << *FailedDecl; }))); |
| 2730 | return getDerived().RebuildRequiresExpr(RequiresKWLoc: KWLoc, Body, LParenLoc: RE->getLParenLoc(), |
| 2731 | LocalParameters: TransParams, RParenLoc: RE->getRParenLoc(), |
| 2732 | Requirements: TransReqs, ClosingBraceLoc: RBraceLoc); |
| 2733 | } |
| 2734 | |
| 2735 | return ExprResult{}; |
| 2736 | } |
| 2737 | |
| 2738 | concepts::TypeRequirement * |
| 2739 | TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) { |
| 2740 | if (!Req->isDependent() && !AlwaysRebuild()) |
| 2741 | return Req; |
| 2742 | if (Req->isSubstitutionFailure()) { |
| 2743 | if (AlwaysRebuild()) |
| 2744 | return RebuildTypeRequirement( |
| 2745 | SubstDiag: Req->getSubstitutionDiagnostic()); |
| 2746 | return Req; |
| 2747 | } |
| 2748 | |
| 2749 | TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc()); |
| 2750 | Sema::SFINAETrap Trap(SemaRef, Info); |
| 2751 | Sema::InstantiatingTemplate TypeInst( |
| 2752 | SemaRef, Req->getType()->getTypeLoc().getBeginLoc(), Req, |
| 2753 | Req->getType()->getTypeLoc().getSourceRange()); |
| 2754 | if (TypeInst.isInvalid()) |
| 2755 | return nullptr; |
| 2756 | TypeSourceInfo *TransType = TransformType(TSI: Req->getType()); |
| 2757 | if (!TransType || Trap.hasErrorOccurred()) |
| 2758 | return RebuildTypeRequirement(SubstDiag: createSubstDiag(S&: SemaRef, Info, |
| 2759 | Printer: [&] (llvm::raw_ostream& OS) { |
| 2760 | Req->getType()->getType().print(OS, Policy: SemaRef.getPrintingPolicy()); |
| 2761 | })); |
| 2762 | return RebuildTypeRequirement(T: TransType); |
| 2763 | } |
| 2764 | |
| 2765 | concepts::ExprRequirement * |
| 2766 | TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) { |
| 2767 | if (!Req->isDependent() && !AlwaysRebuild()) |
| 2768 | return Req; |
| 2769 | |
| 2770 | llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> |
| 2771 | TransExpr; |
| 2772 | if (Req->isExprSubstitutionFailure()) |
| 2773 | TransExpr = Req->getExprSubstitutionDiagnostic(); |
| 2774 | else { |
| 2775 | Expr *E = Req->getExpr(); |
| 2776 | TemplateDeductionInfo Info(E->getBeginLoc()); |
| 2777 | Sema::SFINAETrap Trap(SemaRef, Info); |
| 2778 | Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, |
| 2779 | E->getSourceRange()); |
| 2780 | if (ExprInst.isInvalid()) |
| 2781 | return nullptr; |
| 2782 | ExprResult TransExprRes = TransformExpr(E); |
| 2783 | if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() && |
| 2784 | TransExprRes.get()->hasPlaceholderType()) |
| 2785 | TransExprRes = SemaRef.CheckPlaceholderExpr(E: TransExprRes.get()); |
| 2786 | if (TransExprRes.isInvalid() || Trap.hasErrorOccurred()) |
| 2787 | TransExpr = createSubstDiag(S&: SemaRef, Info, Printer: [&](llvm::raw_ostream &OS) { |
| 2788 | E->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy()); |
| 2789 | }); |
| 2790 | else |
| 2791 | TransExpr = TransExprRes.get(); |
| 2792 | } |
| 2793 | |
| 2794 | std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq; |
| 2795 | const auto &RetReq = Req->getReturnTypeRequirement(); |
| 2796 | if (RetReq.isEmpty()) |
| 2797 | TransRetReq.emplace(); |
| 2798 | else if (RetReq.isSubstitutionFailure()) |
| 2799 | TransRetReq.emplace(args: RetReq.getSubstitutionDiagnostic()); |
| 2800 | else if (RetReq.isTypeConstraint()) { |
| 2801 | TemplateParameterList *OrigTPL = |
| 2802 | RetReq.getTypeConstraintTemplateParameterList(); |
| 2803 | TemplateDeductionInfo Info(OrigTPL->getTemplateLoc()); |
| 2804 | Sema::SFINAETrap Trap(SemaRef, Info); |
| 2805 | Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), Req, |
| 2806 | OrigTPL->getSourceRange()); |
| 2807 | if (TPLInst.isInvalid()) |
| 2808 | return nullptr; |
| 2809 | TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL); |
| 2810 | if (!TPL || Trap.hasErrorOccurred()) |
| 2811 | TransRetReq.emplace(args: createSubstDiag(S&: SemaRef, Info, |
| 2812 | Printer: [&] (llvm::raw_ostream& OS) { |
| 2813 | RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint() |
| 2814 | ->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy()); |
| 2815 | })); |
| 2816 | else { |
| 2817 | TPLInst.Clear(); |
| 2818 | TransRetReq.emplace(args&: TPL); |
| 2819 | } |
| 2820 | } |
| 2821 | assert(TransRetReq && "All code paths leading here must set TransRetReq" ); |
| 2822 | if (Expr *E = TransExpr.dyn_cast<Expr *>()) |
| 2823 | return RebuildExprRequirement(E, IsSimple: Req->isSimple(), NoexceptLoc: Req->getNoexceptLoc(), |
| 2824 | Ret: std::move(*TransRetReq)); |
| 2825 | return RebuildExprRequirement( |
| 2826 | SubstDiag: cast<concepts::Requirement::SubstitutionDiagnostic *>(Val&: TransExpr), |
| 2827 | IsSimple: Req->isSimple(), NoexceptLoc: Req->getNoexceptLoc(), Ret: std::move(*TransRetReq)); |
| 2828 | } |
| 2829 | |
| 2830 | concepts::NestedRequirement * |
| 2831 | TemplateInstantiator::TransformNestedRequirement( |
| 2832 | concepts::NestedRequirement *Req) { |
| 2833 | |
| 2834 | ASTContext &C = SemaRef.Context; |
| 2835 | |
| 2836 | ConstraintSatisfaction Satisfaction; |
| 2837 | |
| 2838 | auto NestedReqWithDiag = [&C, this](Expr *E, |
| 2839 | ConstraintSatisfaction Satisfaction) { |
| 2840 | Satisfaction.IsSatisfied = false; |
| 2841 | SmallString<128> Entity; |
| 2842 | llvm::raw_svector_ostream OS(Entity); |
| 2843 | E->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy()); |
| 2844 | return new (C) concepts::NestedRequirement( |
| 2845 | SemaRef.Context, C.backupStr(S: Entity), std::move(Satisfaction)); |
| 2846 | }; |
| 2847 | |
| 2848 | if (Req->hasInvalidConstraint()) { |
| 2849 | if (AlwaysRebuild()) |
| 2850 | return RebuildNestedRequirement(InvalidConstraintEntity: Req->getInvalidConstraintEntity(), |
| 2851 | Satisfaction: Req->getConstraintSatisfaction()); |
| 2852 | return Req; |
| 2853 | } |
| 2854 | |
| 2855 | Expr *Constraint = Req->getConstraintExpr(); |
| 2856 | |
| 2857 | if (!getEvaluateConstraints()) { |
| 2858 | ExprResult TransConstraint = TransformExpr(E: Req->getConstraintExpr()); |
| 2859 | if (TransConstraint.isInvalid() || !TransConstraint.get()) |
| 2860 | return nullptr; |
| 2861 | if (TransConstraint.get()->isInstantiationDependent()) |
| 2862 | return new (SemaRef.Context) |
| 2863 | concepts::NestedRequirement(TransConstraint.get()); |
| 2864 | ConstraintSatisfaction Satisfaction; |
| 2865 | return new (SemaRef.Context) concepts::NestedRequirement( |
| 2866 | SemaRef.Context, TransConstraint.get(), Satisfaction); |
| 2867 | } |
| 2868 | |
| 2869 | bool Success; |
| 2870 | Expr *NewConstraint; |
| 2871 | { |
| 2872 | EnterExpressionEvaluationContext ( |
| 2873 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
| 2874 | Sema::InstantiatingTemplate ConstrInst( |
| 2875 | SemaRef, Constraint->getBeginLoc(), Req, |
| 2876 | Sema::InstantiatingTemplate::ConstraintsCheck(), |
| 2877 | Constraint->getSourceRange()); |
| 2878 | |
| 2879 | if (ConstrInst.isInvalid()) |
| 2880 | return nullptr; |
| 2881 | |
| 2882 | Success = !SemaRef.CheckConstraintSatisfaction( |
| 2883 | Entity: Req, AssociatedConstraints: AssociatedConstraint(Constraint), TemplateArgLists: TemplateArgs, |
| 2884 | TemplateIDRange: Constraint->getSourceRange(), Satisfaction, |
| 2885 | /*TopLevelConceptId=*/nullptr, ConvertedExpr: &NewConstraint); |
| 2886 | } |
| 2887 | |
| 2888 | if (!Success || Satisfaction.HasSubstitutionFailure()) |
| 2889 | return NestedReqWithDiag(Constraint, Satisfaction); |
| 2890 | |
| 2891 | // FIXME: const correctness |
| 2892 | // MLTAL might be dependent. |
| 2893 | if (!NewConstraint) { |
| 2894 | if (!Satisfaction.IsSatisfied) |
| 2895 | return NestedReqWithDiag(Constraint, Satisfaction); |
| 2896 | |
| 2897 | NewConstraint = Constraint; |
| 2898 | } |
| 2899 | return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction); |
| 2900 | } |
| 2901 | |
| 2902 | TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T, |
| 2903 | const MultiLevelTemplateArgumentList &Args, |
| 2904 | SourceLocation Loc, DeclarationName Entity, |
| 2905 | bool AllowDeducedTST) { |
| 2906 | if (!T->getType()->isInstantiationDependentType() && |
| 2907 | !T->getType()->isVariablyModifiedType()) |
| 2908 | return T; |
| 2909 | |
| 2910 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); |
| 2911 | return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(TSI: T) |
| 2912 | : Instantiator.TransformType(TSI: T); |
| 2913 | } |
| 2914 | |
| 2915 | TypeSourceInfo *Sema::SubstType(TypeLoc TL, |
| 2916 | const MultiLevelTemplateArgumentList &Args, |
| 2917 | SourceLocation Loc, DeclarationName Entity) { |
| 2918 | if (TL.getType().isNull()) |
| 2919 | return nullptr; |
| 2920 | |
| 2921 | if (!TL.getType()->isInstantiationDependentType() && |
| 2922 | !TL.getType()->isVariablyModifiedType()) { |
| 2923 | // FIXME: Make a copy of the TypeLoc data here, so that we can |
| 2924 | // return a new TypeSourceInfo. Inefficient! |
| 2925 | TypeLocBuilder TLB; |
| 2926 | TLB.pushFullCopy(L: TL); |
| 2927 | return TLB.getTypeSourceInfo(Context, T: TL.getType()); |
| 2928 | } |
| 2929 | |
| 2930 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); |
| 2931 | TypeLocBuilder TLB; |
| 2932 | TLB.reserve(Requested: TL.getFullDataSize()); |
| 2933 | QualType Result = Instantiator.TransformType(TLB, T: TL); |
| 2934 | if (Result.isNull()) |
| 2935 | return nullptr; |
| 2936 | |
| 2937 | return TLB.getTypeSourceInfo(Context, T: Result); |
| 2938 | } |
| 2939 | |
| 2940 | /// Deprecated form of the above. |
| 2941 | QualType Sema::SubstType(QualType T, |
| 2942 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 2943 | SourceLocation Loc, DeclarationName Entity, |
| 2944 | bool *IsIncompleteSubstitution) { |
| 2945 | // If T is not a dependent type or a variably-modified type, there |
| 2946 | // is nothing to do. |
| 2947 | if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType()) |
| 2948 | return T; |
| 2949 | |
| 2950 | TemplateInstantiator Instantiator( |
| 2951 | *this, TemplateArgs, Loc, Entity, |
| 2952 | /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr); |
| 2953 | QualType QT = Instantiator.TransformType(T); |
| 2954 | if (IsIncompleteSubstitution && Instantiator.getIsIncomplete()) |
| 2955 | *IsIncompleteSubstitution = true; |
| 2956 | return QT; |
| 2957 | } |
| 2958 | |
| 2959 | static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) { |
| 2960 | if (T->getType()->isInstantiationDependentType() || |
| 2961 | T->getType()->isVariablyModifiedType()) |
| 2962 | return true; |
| 2963 | |
| 2964 | TypeLoc TL = T->getTypeLoc().IgnoreParens(); |
| 2965 | if (!TL.getAs<FunctionProtoTypeLoc>()) |
| 2966 | return false; |
| 2967 | |
| 2968 | FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>(); |
| 2969 | for (ParmVarDecl *P : FP.getParams()) { |
| 2970 | // This must be synthesized from a typedef. |
| 2971 | if (!P) continue; |
| 2972 | |
| 2973 | // If there are any parameters, a new TypeSourceInfo that refers to the |
| 2974 | // instantiated parameters must be built. |
| 2975 | return true; |
| 2976 | } |
| 2977 | |
| 2978 | return false; |
| 2979 | } |
| 2980 | |
| 2981 | TypeSourceInfo *Sema::SubstFunctionDeclType( |
| 2982 | TypeSourceInfo *T, const MultiLevelTemplateArgumentList &Args, |
| 2983 | SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, |
| 2984 | Qualifiers ThisTypeQuals, bool EvaluateConstraints) { |
| 2985 | if (!NeedsInstantiationAsFunctionType(T)) |
| 2986 | return T; |
| 2987 | |
| 2988 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); |
| 2989 | Instantiator.setEvaluateConstraints(EvaluateConstraints); |
| 2990 | |
| 2991 | TypeLocBuilder TLB; |
| 2992 | |
| 2993 | TypeLoc TL = T->getTypeLoc(); |
| 2994 | TLB.reserve(Requested: TL.getFullDataSize()); |
| 2995 | |
| 2996 | QualType Result; |
| 2997 | |
| 2998 | if (FunctionProtoTypeLoc Proto = |
| 2999 | TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) { |
| 3000 | // Instantiate the type, other than its exception specification. The |
| 3001 | // exception specification is instantiated in InitFunctionInstantiation |
| 3002 | // once we've built the FunctionDecl. |
| 3003 | // FIXME: Set the exception specification to EST_Uninstantiated here, |
| 3004 | // instead of rebuilding the function type again later. |
| 3005 | Result = Instantiator.TransformFunctionProtoType( |
| 3006 | TLB, TL: Proto, ThisContext, ThisTypeQuals, |
| 3007 | TransformExceptionSpec: [](FunctionProtoType::ExceptionSpecInfo &ESI, |
| 3008 | bool &Changed) { return false; }); |
| 3009 | } else { |
| 3010 | Result = Instantiator.TransformType(TLB, T: TL); |
| 3011 | } |
| 3012 | // When there are errors resolving types, clang may use IntTy as a fallback, |
| 3013 | // breaking our assumption that function declarations have function types. |
| 3014 | if (Result.isNull() || !Result->isFunctionType()) |
| 3015 | return nullptr; |
| 3016 | |
| 3017 | return TLB.getTypeSourceInfo(Context, T: Result); |
| 3018 | } |
| 3019 | |
| 3020 | bool Sema::SubstExceptionSpec(SourceLocation Loc, |
| 3021 | FunctionProtoType::ExceptionSpecInfo &ESI, |
| 3022 | SmallVectorImpl<QualType> &ExceptionStorage, |
| 3023 | const MultiLevelTemplateArgumentList &Args) { |
| 3024 | bool Changed = false; |
| 3025 | TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName()); |
| 3026 | return Instantiator.TransformExceptionSpec(Loc, ESI, Exceptions&: ExceptionStorage, |
| 3027 | Changed); |
| 3028 | } |
| 3029 | |
| 3030 | void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, |
| 3031 | const MultiLevelTemplateArgumentList &Args) { |
| 3032 | FunctionProtoType::ExceptionSpecInfo ESI = |
| 3033 | Proto->getExtProtoInfo().ExceptionSpec; |
| 3034 | |
| 3035 | SmallVector<QualType, 4> ExceptionStorage; |
| 3036 | if (SubstExceptionSpec(Loc: New->getTypeSourceInfo()->getTypeLoc().getEndLoc(), |
| 3037 | ESI, ExceptionStorage, Args)) |
| 3038 | // On error, recover by dropping the exception specification. |
| 3039 | ESI.Type = EST_None; |
| 3040 | |
| 3041 | UpdateExceptionSpec(FD: New, ESI); |
| 3042 | } |
| 3043 | |
| 3044 | namespace { |
| 3045 | |
| 3046 | struct GetContainedInventedTypeParmVisitor : |
| 3047 | public TypeVisitor<GetContainedInventedTypeParmVisitor, |
| 3048 | TemplateTypeParmDecl *> { |
| 3049 | using TypeVisitor<GetContainedInventedTypeParmVisitor, |
| 3050 | TemplateTypeParmDecl *>::Visit; |
| 3051 | |
| 3052 | TemplateTypeParmDecl *Visit(QualType T) { |
| 3053 | if (T.isNull()) |
| 3054 | return nullptr; |
| 3055 | return Visit(T: T.getTypePtr()); |
| 3056 | } |
| 3057 | // The deduced type itself. |
| 3058 | TemplateTypeParmDecl *VisitTemplateTypeParmType( |
| 3059 | const TemplateTypeParmType *T) { |
| 3060 | if (!T->getDecl() || !T->getDecl()->isImplicit()) |
| 3061 | return nullptr; |
| 3062 | return T->getDecl(); |
| 3063 | } |
| 3064 | |
| 3065 | // Only these types can contain 'auto' types, and subsequently be replaced |
| 3066 | // by references to invented parameters. |
| 3067 | |
| 3068 | TemplateTypeParmDecl *VisitPointerType(const PointerType *T) { |
| 3069 | return Visit(T: T->getPointeeType()); |
| 3070 | } |
| 3071 | |
| 3072 | TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) { |
| 3073 | return Visit(T: T->getPointeeType()); |
| 3074 | } |
| 3075 | |
| 3076 | TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) { |
| 3077 | return Visit(T: T->getPointeeTypeAsWritten()); |
| 3078 | } |
| 3079 | |
| 3080 | TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) { |
| 3081 | return Visit(T: T->getPointeeType()); |
| 3082 | } |
| 3083 | |
| 3084 | TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) { |
| 3085 | return Visit(T: T->getElementType()); |
| 3086 | } |
| 3087 | |
| 3088 | TemplateTypeParmDecl *VisitDependentSizedExtVectorType( |
| 3089 | const DependentSizedExtVectorType *T) { |
| 3090 | return Visit(T: T->getElementType()); |
| 3091 | } |
| 3092 | |
| 3093 | TemplateTypeParmDecl *VisitVectorType(const VectorType *T) { |
| 3094 | return Visit(T: T->getElementType()); |
| 3095 | } |
| 3096 | |
| 3097 | TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) { |
| 3098 | return VisitFunctionType(T); |
| 3099 | } |
| 3100 | |
| 3101 | TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) { |
| 3102 | return Visit(T: T->getReturnType()); |
| 3103 | } |
| 3104 | |
| 3105 | TemplateTypeParmDecl *VisitParenType(const ParenType *T) { |
| 3106 | return Visit(T: T->getInnerType()); |
| 3107 | } |
| 3108 | |
| 3109 | TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) { |
| 3110 | return Visit(T: T->getModifiedType()); |
| 3111 | } |
| 3112 | |
| 3113 | TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) { |
| 3114 | return Visit(T: T->getUnderlyingType()); |
| 3115 | } |
| 3116 | |
| 3117 | TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) { |
| 3118 | return Visit(T: T->getOriginalType()); |
| 3119 | } |
| 3120 | |
| 3121 | TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) { |
| 3122 | return Visit(T: T->getPattern()); |
| 3123 | } |
| 3124 | }; |
| 3125 | |
| 3126 | } // namespace |
| 3127 | |
| 3128 | bool Sema::SubstTypeConstraint( |
| 3129 | TemplateTypeParmDecl *Inst, const TypeConstraint *TC, |
| 3130 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3131 | bool EvaluateConstraints) { |
| 3132 | const ASTTemplateArgumentListInfo *TemplArgInfo = |
| 3133 | TC->getTemplateArgsAsWritten(); |
| 3134 | |
| 3135 | if (!EvaluateConstraints) { |
| 3136 | UnsignedOrNone Index = TC->getArgPackSubstIndex(); |
| 3137 | bool ContainsUnexpandedPack = |
| 3138 | TemplArgInfo && |
| 3139 | llvm::any_of( |
| 3140 | Range: TemplArgInfo->arguments(), P: [](const TemplateArgumentLoc &TA) { |
| 3141 | return TA.getArgument().containsUnexpandedParameterPack(); |
| 3142 | }); |
| 3143 | if (!Index && ContainsUnexpandedPack) |
| 3144 | Index = SemaRef.ArgPackSubstIndex; |
| 3145 | Inst->setTypeConstraint(CR: TC->getConceptReference(), |
| 3146 | ImmediatelyDeclaredConstraint: TC->getImmediatelyDeclaredConstraint(), ArgPackSubstIndex: Index); |
| 3147 | return false; |
| 3148 | } |
| 3149 | |
| 3150 | TemplateArgumentListInfo InstArgs; |
| 3151 | |
| 3152 | if (TemplArgInfo) { |
| 3153 | InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc); |
| 3154 | InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc); |
| 3155 | if (SubstTemplateArguments(Args: TemplArgInfo->arguments(), TemplateArgs, |
| 3156 | Outputs&: InstArgs)) |
| 3157 | return true; |
| 3158 | } |
| 3159 | return AttachTypeConstraint( |
| 3160 | NS: TC->getNestedNameSpecifierLoc(), NameInfo: TC->getConceptNameInfo(), |
| 3161 | NamedConcept: TC->getNamedConcept(), |
| 3162 | /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), TemplateArgs: &InstArgs, ConstrainedParameter: Inst, |
| 3163 | EllipsisLoc: Inst->isParameterPack() |
| 3164 | ? cast<CXXFoldExpr>(Val: TC->getImmediatelyDeclaredConstraint()) |
| 3165 | ->getEllipsisLoc() |
| 3166 | : SourceLocation()); |
| 3167 | } |
| 3168 | |
| 3169 | ParmVarDecl * |
| 3170 | Sema::SubstParmVarDecl(ParmVarDecl *OldParm, |
| 3171 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3172 | int indexAdjustment, UnsignedOrNone NumExpansions, |
| 3173 | bool ExpectParameterPack, bool EvaluateConstraint) { |
| 3174 | TypeSourceInfo *OldTSI = OldParm->getTypeSourceInfo(); |
| 3175 | TypeSourceInfo *NewTSI = nullptr; |
| 3176 | |
| 3177 | TypeLoc OldTL = OldTSI->getTypeLoc(); |
| 3178 | if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) { |
| 3179 | |
| 3180 | // We have a function parameter pack. Substitute into the pattern of the |
| 3181 | // expansion. |
| 3182 | NewTSI = SubstType(TL: ExpansionTL.getPatternLoc(), Args: TemplateArgs, |
| 3183 | Loc: OldParm->getLocation(), Entity: OldParm->getDeclName()); |
| 3184 | if (!NewTSI) |
| 3185 | return nullptr; |
| 3186 | |
| 3187 | if (NewTSI->getType()->containsUnexpandedParameterPack()) { |
| 3188 | // We still have unexpanded parameter packs, which means that |
| 3189 | // our function parameter is still a function parameter pack. |
| 3190 | // Therefore, make its type a pack expansion type. |
| 3191 | NewTSI = CheckPackExpansion(Pattern: NewTSI, EllipsisLoc: ExpansionTL.getEllipsisLoc(), |
| 3192 | NumExpansions); |
| 3193 | } else if (ExpectParameterPack) { |
| 3194 | // We expected to get a parameter pack but didn't (because the type |
| 3195 | // itself is not a pack expansion type), so complain. This can occur when |
| 3196 | // the substitution goes through an alias template that "loses" the |
| 3197 | // pack expansion. |
| 3198 | Diag(Loc: OldParm->getLocation(), |
| 3199 | DiagID: diag::err_function_parameter_pack_without_parameter_packs) |
| 3200 | << NewTSI->getType(); |
| 3201 | return nullptr; |
| 3202 | } |
| 3203 | } else { |
| 3204 | NewTSI = SubstType(T: OldTSI, Args: TemplateArgs, Loc: OldParm->getLocation(), |
| 3205 | Entity: OldParm->getDeclName()); |
| 3206 | } |
| 3207 | |
| 3208 | if (!NewTSI) |
| 3209 | return nullptr; |
| 3210 | |
| 3211 | if (NewTSI->getType()->isVoidType()) { |
| 3212 | Diag(Loc: OldParm->getLocation(), DiagID: diag::err_param_with_void_type); |
| 3213 | return nullptr; |
| 3214 | } |
| 3215 | |
| 3216 | // In abbreviated templates, TemplateTypeParmDecls with possible |
| 3217 | // TypeConstraints are created when the parameter list is originally parsed. |
| 3218 | // The TypeConstraints can therefore reference other functions parameters in |
| 3219 | // the abbreviated function template, which is why we must instantiate them |
| 3220 | // here, when the instantiated versions of those referenced parameters are in |
| 3221 | // scope. |
| 3222 | if (TemplateTypeParmDecl *TTP = |
| 3223 | GetContainedInventedTypeParmVisitor().Visit(T: OldTSI->getType())) { |
| 3224 | if (const TypeConstraint *TC = TTP->getTypeConstraint()) { |
| 3225 | auto *Inst = cast_or_null<TemplateTypeParmDecl>( |
| 3226 | Val: FindInstantiatedDecl(Loc: TTP->getLocation(), D: TTP, TemplateArgs)); |
| 3227 | // We will first get here when instantiating the abbreviated function |
| 3228 | // template's described function, but we might also get here later. |
| 3229 | // Make sure we do not instantiate the TypeConstraint more than once. |
| 3230 | if (Inst && !Inst->getTypeConstraint()) { |
| 3231 | if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraints: EvaluateConstraint)) |
| 3232 | return nullptr; |
| 3233 | } |
| 3234 | } |
| 3235 | } |
| 3236 | |
| 3237 | ParmVarDecl *NewParm = CheckParameter( |
| 3238 | DC: Context.getTranslationUnitDecl(), StartLoc: OldParm->getInnerLocStart(), |
| 3239 | NameLoc: OldParm->getLocation(), Name: OldParm->getIdentifier(), T: NewTSI->getType(), |
| 3240 | TSInfo: NewTSI, SC: OldParm->getStorageClass()); |
| 3241 | if (!NewParm) |
| 3242 | return nullptr; |
| 3243 | |
| 3244 | // Mark the (new) default argument as uninstantiated (if any). |
| 3245 | if (OldParm->hasUninstantiatedDefaultArg()) { |
| 3246 | Expr *Arg = OldParm->getUninstantiatedDefaultArg(); |
| 3247 | NewParm->setUninstantiatedDefaultArg(Arg); |
| 3248 | } else if (OldParm->hasUnparsedDefaultArg()) { |
| 3249 | NewParm->setUnparsedDefaultArg(); |
| 3250 | UnparsedDefaultArgInstantiations[OldParm].push_back(NewVal: NewParm); |
| 3251 | } else if (Expr *Arg = OldParm->getDefaultArg()) { |
| 3252 | // Default arguments cannot be substituted until the declaration context |
| 3253 | // for the associated function or lambda capture class is available. |
| 3254 | // This is necessary for cases like the following where construction of |
| 3255 | // the lambda capture class for the outer lambda is dependent on the |
| 3256 | // parameter types but where the default argument is dependent on the |
| 3257 | // outer lambda's declaration context. |
| 3258 | // template <typename T> |
| 3259 | // auto f() { |
| 3260 | // return [](T = []{ return T{}; }()) { return 0; }; |
| 3261 | // } |
| 3262 | NewParm->setUninstantiatedDefaultArg(Arg); |
| 3263 | } |
| 3264 | |
| 3265 | NewParm->setExplicitObjectParameterLoc( |
| 3266 | OldParm->getExplicitObjectParamThisLoc()); |
| 3267 | NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg()); |
| 3268 | |
| 3269 | if (OldParm->isParameterPack() && !NewParm->isParameterPack()) { |
| 3270 | // Add the new parameter to the instantiated parameter pack. |
| 3271 | CurrentInstantiationScope->InstantiatedLocalPackArg(D: OldParm, Inst: NewParm); |
| 3272 | } else { |
| 3273 | // Introduce an Old -> New mapping |
| 3274 | CurrentInstantiationScope->InstantiatedLocal(D: OldParm, Inst: NewParm); |
| 3275 | } |
| 3276 | |
| 3277 | // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext |
| 3278 | // can be anything, is this right ? |
| 3279 | NewParm->setDeclContext(CurContext); |
| 3280 | |
| 3281 | NewParm->setScopeInfo(scopeDepth: OldParm->getFunctionScopeDepth(), |
| 3282 | parameterIndex: OldParm->getFunctionScopeIndex() + indexAdjustment); |
| 3283 | |
| 3284 | InstantiateAttrs(TemplateArgs, Pattern: OldParm, Inst: NewParm); |
| 3285 | |
| 3286 | NewParm->deduceParmAddressSpace(Ctxt: Context); |
| 3287 | |
| 3288 | return NewParm; |
| 3289 | } |
| 3290 | |
| 3291 | bool Sema::SubstParmTypes( |
| 3292 | SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, |
| 3293 | const FunctionProtoType::ExtParameterInfo *ExtParamInfos, |
| 3294 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3295 | SmallVectorImpl<QualType> &ParamTypes, |
| 3296 | SmallVectorImpl<ParmVarDecl *> *OutParams, |
| 3297 | ExtParameterInfoBuilder &ParamInfos) { |
| 3298 | TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, |
| 3299 | DeclarationName()); |
| 3300 | return Instantiator.TransformFunctionTypeParams( |
| 3301 | Loc, Params, ParamTypes: nullptr, ParamInfos: ExtParamInfos, PTypes&: ParamTypes, PVars: OutParams, PInfos&: ParamInfos); |
| 3302 | } |
| 3303 | |
| 3304 | bool Sema::SubstDefaultArgument( |
| 3305 | SourceLocation Loc, |
| 3306 | ParmVarDecl *Param, |
| 3307 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3308 | bool ForCallExpr) { |
| 3309 | FunctionDecl *FD = cast<FunctionDecl>(Val: Param->getDeclContext()); |
| 3310 | Expr *PatternExpr = Param->getUninstantiatedDefaultArg(); |
| 3311 | |
| 3312 | RecursiveInstGuard AlreadyInstantiating( |
| 3313 | *this, Param, RecursiveInstGuard::Kind::DefaultArgument); |
| 3314 | if (AlreadyInstantiating) { |
| 3315 | Param->setInvalidDecl(); |
| 3316 | return Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) |
| 3317 | << FD << PatternExpr->getSourceRange(); |
| 3318 | } |
| 3319 | |
| 3320 | EnterExpressionEvaluationContext EvalContext( |
| 3321 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); |
| 3322 | NonSFINAEContext _(*this); |
| 3323 | InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost()); |
| 3324 | if (Inst.isInvalid()) |
| 3325 | return true; |
| 3326 | |
| 3327 | ExprResult Result; |
| 3328 | // C++ [dcl.fct.default]p5: |
| 3329 | // The names in the [default argument] expression are bound, and |
| 3330 | // the semantic constraints are checked, at the point where the |
| 3331 | // default argument expression appears. |
| 3332 | ContextRAII SavedContext(*this, FD); |
| 3333 | { |
| 3334 | std::optional<LocalInstantiationScope> LIS; |
| 3335 | |
| 3336 | if (ForCallExpr) { |
| 3337 | // When instantiating a default argument due to use in a call expression, |
| 3338 | // an instantiation scope that includes the parameters of the callee is |
| 3339 | // required to satisfy references from the default argument. For example: |
| 3340 | // template<typename T> void f(T a, int = decltype(a)()); |
| 3341 | // void g() { f(0); } |
| 3342 | LIS.emplace(args&: *this); |
| 3343 | FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern( |
| 3344 | /*ForDefinition*/ false); |
| 3345 | if (addInstantiatedParametersToScope(Function: FD, PatternDecl: PatternFD, Scope&: *LIS, TemplateArgs)) |
| 3346 | return true; |
| 3347 | } |
| 3348 | |
| 3349 | runWithSufficientStackSpace(Loc, Fn: [&] { |
| 3350 | Result = SubstInitializer(E: PatternExpr, TemplateArgs, |
| 3351 | /*DirectInit*/ CXXDirectInit: false); |
| 3352 | }); |
| 3353 | } |
| 3354 | if (Result.isInvalid()) |
| 3355 | return true; |
| 3356 | |
| 3357 | if (ForCallExpr) { |
| 3358 | // Check the expression as an initializer for the parameter. |
| 3359 | InitializedEntity Entity |
| 3360 | = InitializedEntity::InitializeParameter(Context, Parm: Param); |
| 3361 | InitializationKind Kind = InitializationKind::CreateCopy( |
| 3362 | InitLoc: Param->getLocation(), |
| 3363 | /*FIXME:EqualLoc*/ EqualLoc: PatternExpr->getBeginLoc()); |
| 3364 | Expr *ResultE = Result.getAs<Expr>(); |
| 3365 | |
| 3366 | InitializationSequence InitSeq(*this, Entity, Kind, ResultE); |
| 3367 | Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: ResultE); |
| 3368 | if (Result.isInvalid()) |
| 3369 | return true; |
| 3370 | |
| 3371 | Result = |
| 3372 | ActOnFinishFullExpr(Expr: Result.getAs<Expr>(), CC: Param->getOuterLocStart(), |
| 3373 | /*DiscardedValue*/ false); |
| 3374 | } else { |
| 3375 | // FIXME: Obtain the source location for the '=' token. |
| 3376 | SourceLocation EqualLoc = PatternExpr->getBeginLoc(); |
| 3377 | Result = ConvertParamDefaultArgument(Param, DefaultArg: Result.getAs<Expr>(), EqualLoc); |
| 3378 | } |
| 3379 | if (Result.isInvalid()) |
| 3380 | return true; |
| 3381 | |
| 3382 | // Remember the instantiated default argument. |
| 3383 | Param->setDefaultArg(Result.getAs<Expr>()); |
| 3384 | |
| 3385 | return false; |
| 3386 | } |
| 3387 | |
| 3388 | // See TreeTransform::PreparePackForExpansion for the relevant comment. |
| 3389 | // This function implements the same concept for base specifiers. |
| 3390 | static bool |
| 3391 | PreparePackForExpansion(Sema &S, const CXXBaseSpecifier &Base, |
| 3392 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3393 | TypeSourceInfo *&Out, UnexpandedInfo &Info) { |
| 3394 | SourceRange BaseSourceRange = Base.getSourceRange(); |
| 3395 | SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc(); |
| 3396 | Info.Ellipsis = Base.getEllipsisLoc(); |
| 3397 | auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc]( |
| 3398 | TypeSourceInfo *BaseTypeInfo, |
| 3399 | bool IsLateExpansionAttempt, UnexpandedInfo &Info) { |
| 3400 | // This is a pack expansion. See whether we should expand it now, or |
| 3401 | // wait until later. |
| 3402 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
| 3403 | S.collectUnexpandedParameterPacks(TL: BaseTypeInfo->getTypeLoc(), Unexpanded); |
| 3404 | if (IsLateExpansionAttempt) { |
| 3405 | // Request expansion only when there is an opportunity to expand a pack |
| 3406 | // that required a substituion first. |
| 3407 | bool SawPackTypes = |
| 3408 | llvm::any_of(Range&: Unexpanded, P: [](UnexpandedParameterPack P) { |
| 3409 | return P.first.dyn_cast<const SubstBuiltinTemplatePackType *>(); |
| 3410 | }); |
| 3411 | if (!SawPackTypes) { |
| 3412 | Info.Expand = false; |
| 3413 | return false; |
| 3414 | } |
| 3415 | } |
| 3416 | |
| 3417 | // Determine whether the set of unexpanded parameter packs can and should be |
| 3418 | // expanded. |
| 3419 | Info.Expand = false; |
| 3420 | Info.RetainExpansion = false; |
| 3421 | Info.NumExpansions = std::nullopt; |
| 3422 | return S.CheckParameterPacksForExpansion( |
| 3423 | EllipsisLoc: BaseEllipsisLoc, PatternRange: BaseSourceRange, Unexpanded, TemplateArgs, |
| 3424 | /*FailOnPackProducingTemplates=*/false, ShouldExpand&: Info.Expand, |
| 3425 | RetainExpansion&: Info.RetainExpansion, NumExpansions&: Info.NumExpansions); |
| 3426 | }; |
| 3427 | |
| 3428 | if (ComputeInfo(Base.getTypeSourceInfo(), false, Info)) |
| 3429 | return true; |
| 3430 | |
| 3431 | if (Info.Expand) { |
| 3432 | Out = Base.getTypeSourceInfo(); |
| 3433 | return false; |
| 3434 | } |
| 3435 | |
| 3436 | // The resulting base specifier will (still) be a pack expansion. |
| 3437 | { |
| 3438 | Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt); |
| 3439 | Out = S.SubstType(T: Base.getTypeSourceInfo(), Args: TemplateArgs, |
| 3440 | Loc: BaseSourceRange.getBegin(), Entity: DeclarationName()); |
| 3441 | } |
| 3442 | if (!Out->getType()->containsUnexpandedParameterPack()) |
| 3443 | return false; |
| 3444 | |
| 3445 | // Some packs will learn their length after substitution. |
| 3446 | // We may need to request their expansion. |
| 3447 | if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info)) |
| 3448 | return true; |
| 3449 | if (Info.Expand) |
| 3450 | Info.ExpandUnderForgetSubstitions = true; |
| 3451 | return false; |
| 3452 | } |
| 3453 | |
| 3454 | bool |
| 3455 | Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, |
| 3456 | CXXRecordDecl *Pattern, |
| 3457 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 3458 | bool Invalid = false; |
| 3459 | SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; |
| 3460 | for (const auto &Base : Pattern->bases()) { |
| 3461 | if (!Base.getType()->isInstantiationDependentType()) { |
| 3462 | if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) { |
| 3463 | if (RD->isInvalidDecl()) |
| 3464 | Instantiation->setInvalidDecl(); |
| 3465 | } |
| 3466 | InstantiatedBases.push_back(Elt: new (Context) CXXBaseSpecifier(Base)); |
| 3467 | continue; |
| 3468 | } |
| 3469 | |
| 3470 | SourceLocation EllipsisLoc; |
| 3471 | TypeSourceInfo *BaseTypeLoc = nullptr; |
| 3472 | if (Base.isPackExpansion()) { |
| 3473 | UnexpandedInfo Info; |
| 3474 | if (PreparePackForExpansion(S&: *this, Base, TemplateArgs, Out&: BaseTypeLoc, |
| 3475 | Info)) { |
| 3476 | Invalid = true; |
| 3477 | continue; |
| 3478 | } |
| 3479 | |
| 3480 | // If we should expand this pack expansion now, do so. |
| 3481 | MultiLevelTemplateArgumentList EmptyList; |
| 3482 | const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs; |
| 3483 | if (Info.ExpandUnderForgetSubstitions) |
| 3484 | ArgsForSubst = &EmptyList; |
| 3485 | |
| 3486 | if (Info.Expand) { |
| 3487 | for (unsigned I = 0; I != *Info.NumExpansions; ++I) { |
| 3488 | Sema::ArgPackSubstIndexRAII SubstIndex(*this, I); |
| 3489 | |
| 3490 | TypeSourceInfo *Expanded = |
| 3491 | SubstType(T: BaseTypeLoc, Args: *ArgsForSubst, |
| 3492 | Loc: Base.getSourceRange().getBegin(), Entity: DeclarationName()); |
| 3493 | if (!Expanded) { |
| 3494 | Invalid = true; |
| 3495 | continue; |
| 3496 | } |
| 3497 | |
| 3498 | if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier( |
| 3499 | Class: Instantiation, SpecifierRange: Base.getSourceRange(), Virtual: Base.isVirtual(), |
| 3500 | Access: Base.getAccessSpecifierAsWritten(), TInfo: Expanded, |
| 3501 | EllipsisLoc: SourceLocation())) |
| 3502 | InstantiatedBases.push_back(Elt: InstantiatedBase); |
| 3503 | else |
| 3504 | Invalid = true; |
| 3505 | } |
| 3506 | |
| 3507 | continue; |
| 3508 | } |
| 3509 | |
| 3510 | // The resulting base specifier will (still) be a pack expansion. |
| 3511 | EllipsisLoc = Base.getEllipsisLoc(); |
| 3512 | Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt); |
| 3513 | BaseTypeLoc = |
| 3514 | SubstType(T: BaseTypeLoc, Args: *ArgsForSubst, |
| 3515 | Loc: Base.getSourceRange().getBegin(), Entity: DeclarationName()); |
| 3516 | } else { |
| 3517 | BaseTypeLoc = SubstType(T: Base.getTypeSourceInfo(), |
| 3518 | Args: TemplateArgs, |
| 3519 | Loc: Base.getSourceRange().getBegin(), |
| 3520 | Entity: DeclarationName()); |
| 3521 | } |
| 3522 | |
| 3523 | if (!BaseTypeLoc) { |
| 3524 | Invalid = true; |
| 3525 | continue; |
| 3526 | } |
| 3527 | |
| 3528 | if (CXXBaseSpecifier *InstantiatedBase |
| 3529 | = CheckBaseSpecifier(Class: Instantiation, |
| 3530 | SpecifierRange: Base.getSourceRange(), |
| 3531 | Virtual: Base.isVirtual(), |
| 3532 | Access: Base.getAccessSpecifierAsWritten(), |
| 3533 | TInfo: BaseTypeLoc, |
| 3534 | EllipsisLoc)) |
| 3535 | InstantiatedBases.push_back(Elt: InstantiatedBase); |
| 3536 | else |
| 3537 | Invalid = true; |
| 3538 | } |
| 3539 | |
| 3540 | if (!Invalid && AttachBaseSpecifiers(Class: Instantiation, Bases: InstantiatedBases)) |
| 3541 | Invalid = true; |
| 3542 | |
| 3543 | return Invalid; |
| 3544 | } |
| 3545 | |
| 3546 | // Defined via #include from SemaTemplateInstantiateDecl.cpp |
| 3547 | namespace clang { |
| 3548 | namespace sema { |
| 3549 | Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, |
| 3550 | const MultiLevelTemplateArgumentList &TemplateArgs); |
| 3551 | Attr *instantiateTemplateAttributeForDecl( |
| 3552 | const Attr *At, ASTContext &C, Sema &S, |
| 3553 | const MultiLevelTemplateArgumentList &TemplateArgs); |
| 3554 | } |
| 3555 | } |
| 3556 | |
| 3557 | bool Sema::InstantiateClass(SourceLocation PointOfInstantiation, |
| 3558 | CXXRecordDecl *Instantiation, |
| 3559 | CXXRecordDecl *Pattern, |
| 3560 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3561 | TemplateSpecializationKind TSK, bool Complain) { |
| 3562 | #ifndef NDEBUG |
| 3563 | RecursiveInstGuard AlreadyInstantiating(*this, Instantiation, |
| 3564 | RecursiveInstGuard::Kind::Template); |
| 3565 | assert(!AlreadyInstantiating && "should have been caught by caller" ); |
| 3566 | #endif |
| 3567 | |
| 3568 | return InstantiateClassImpl(PointOfInstantiation, Instantiation, Pattern, |
| 3569 | TemplateArgs, TSK, Complain); |
| 3570 | } |
| 3571 | |
| 3572 | bool Sema::InstantiateClassImpl( |
| 3573 | SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, |
| 3574 | CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3575 | TemplateSpecializationKind TSK, bool Complain) { |
| 3576 | |
| 3577 | CXXRecordDecl *PatternDef |
| 3578 | = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition()); |
| 3579 | if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation, |
| 3580 | InstantiatedFromMember: Instantiation->getInstantiatedFromMemberClass(), |
| 3581 | Pattern, PatternDef, TSK, Complain)) |
| 3582 | return true; |
| 3583 | |
| 3584 | llvm::TimeTraceScope TimeScope("InstantiateClass" , [&]() { |
| 3585 | llvm::TimeTraceMetadata M; |
| 3586 | llvm::raw_string_ostream OS(M.Detail); |
| 3587 | Instantiation->getNameForDiagnostic(OS, Policy: getPrintingPolicy(), |
| 3588 | /*Qualified=*/true); |
| 3589 | if (llvm::isTimeTraceVerbose()) { |
| 3590 | auto Loc = SourceMgr.getExpansionLoc(Loc: Instantiation->getLocation()); |
| 3591 | M.File = SourceMgr.getFilename(SpellingLoc: Loc); |
| 3592 | M.Line = SourceMgr.getExpansionLineNumber(Loc); |
| 3593 | } |
| 3594 | return M; |
| 3595 | }); |
| 3596 | |
| 3597 | Pattern = PatternDef; |
| 3598 | |
| 3599 | // Record the point of instantiation. |
| 3600 | if (MemberSpecializationInfo *MSInfo |
| 3601 | = Instantiation->getMemberSpecializationInfo()) { |
| 3602 | MSInfo->setTemplateSpecializationKind(TSK); |
| 3603 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
| 3604 | } else if (ClassTemplateSpecializationDecl *Spec |
| 3605 | = dyn_cast<ClassTemplateSpecializationDecl>(Val: Instantiation)) { |
| 3606 | Spec->setTemplateSpecializationKind(TSK); |
| 3607 | Spec->setPointOfInstantiation(PointOfInstantiation); |
| 3608 | } |
| 3609 | |
| 3610 | NonSFINAEContext _(*this); |
| 3611 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); |
| 3612 | if (Inst.isInvalid()) |
| 3613 | return true; |
| 3614 | PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), |
| 3615 | "instantiating class definition" ); |
| 3616 | |
| 3617 | // Enter the scope of this instantiation. We don't use |
| 3618 | // PushDeclContext because we don't have a scope. |
| 3619 | ContextRAII SavedContext(*this, Instantiation); |
| 3620 | EnterExpressionEvaluationContext EvalContext( |
| 3621 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
| 3622 | |
| 3623 | // If this is an instantiation of a local class, merge this local |
| 3624 | // instantiation scope with the enclosing scope. Otherwise, every |
| 3625 | // instantiation of a class has its own local instantiation scope. |
| 3626 | bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod(); |
| 3627 | LocalInstantiationScope Scope(*this, MergeWithParentScope); |
| 3628 | |
| 3629 | // Some class state isn't processed immediately but delayed till class |
| 3630 | // instantiation completes. We may not be ready to handle any delayed state |
| 3631 | // already on the stack as it might correspond to a different class, so save |
| 3632 | // it now and put it back later. |
| 3633 | SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this); |
| 3634 | |
| 3635 | // Pull attributes from the pattern onto the instantiation. |
| 3636 | InstantiateAttrs(TemplateArgs, Pattern, Inst: Instantiation); |
| 3637 | |
| 3638 | // Start the definition of this instantiation. |
| 3639 | Instantiation->startDefinition(); |
| 3640 | |
| 3641 | // The instantiation is visible here, even if it was first declared in an |
| 3642 | // unimported module. |
| 3643 | Instantiation->setVisibleDespiteOwningModule(); |
| 3644 | |
| 3645 | // FIXME: This loses the as-written tag kind for an explicit instantiation. |
| 3646 | Instantiation->setTagKind(Pattern->getTagKind()); |
| 3647 | |
| 3648 | // Do substitution on the base class specifiers. |
| 3649 | if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs)) |
| 3650 | Instantiation->setInvalidDecl(); |
| 3651 | |
| 3652 | TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); |
| 3653 | Instantiator.setEvaluateConstraints(false); |
| 3654 | SmallVector<Decl*, 4> Fields; |
| 3655 | // Delay instantiation of late parsed attributes. |
| 3656 | LateInstantiatedAttrVec LateAttrs; |
| 3657 | Instantiator.enableLateAttributeInstantiation(LA: &LateAttrs); |
| 3658 | |
| 3659 | bool MightHaveConstexprVirtualFunctions = false; |
| 3660 | for (auto *Member : Pattern->decls()) { |
| 3661 | // Don't instantiate members not belonging in this semantic context. |
| 3662 | // e.g. for: |
| 3663 | // @code |
| 3664 | // template <int i> class A { |
| 3665 | // class B *g; |
| 3666 | // }; |
| 3667 | // @endcode |
| 3668 | // 'class B' has the template as lexical context but semantically it is |
| 3669 | // introduced in namespace scope. |
| 3670 | if (Member->getDeclContext() != Pattern) |
| 3671 | continue; |
| 3672 | |
| 3673 | // BlockDecls can appear in a default-member-initializer. They must be the |
| 3674 | // child of a BlockExpr, so we only know how to instantiate them from there. |
| 3675 | // Similarly, lambda closure types are recreated when instantiating the |
| 3676 | // corresponding LambdaExpr. |
| 3677 | if (isa<BlockDecl>(Val: Member) || |
| 3678 | (isa<CXXRecordDecl>(Val: Member) && cast<CXXRecordDecl>(Val: Member)->isLambda())) |
| 3679 | continue; |
| 3680 | |
| 3681 | if (Member->isInvalidDecl()) { |
| 3682 | Instantiation->setInvalidDecl(); |
| 3683 | // Drop invalid members to prevent cascading diagnostic errors. |
| 3684 | // We make an exception for VarTemplateDecl because the primary template |
| 3685 | // is required for partial specialization lookup. Keeping it is safe from |
| 3686 | // cascading errors due to the parser's type recovery. |
| 3687 | if (!isa<VarTemplateDecl>(Val: Member)) |
| 3688 | continue; |
| 3689 | } |
| 3690 | |
| 3691 | Decl *NewMember = Instantiator.Visit(D: Member); |
| 3692 | if (NewMember) { |
| 3693 | if (FieldDecl *Field = dyn_cast<FieldDecl>(Val: NewMember)) { |
| 3694 | Fields.push_back(Elt: Field); |
| 3695 | } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Val: NewMember)) { |
| 3696 | // C++11 [temp.inst]p1: The implicit instantiation of a class template |
| 3697 | // specialization causes the implicit instantiation of the definitions |
| 3698 | // of unscoped member enumerations. |
| 3699 | // Record a point of instantiation for this implicit instantiation. |
| 3700 | if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() && |
| 3701 | Enum->isCompleteDefinition()) { |
| 3702 | MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo(); |
| 3703 | assert(MSInfo && "no spec info for member enum specialization" ); |
| 3704 | MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation); |
| 3705 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
| 3706 | } |
| 3707 | } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(Val: NewMember)) { |
| 3708 | if (SA->isFailed()) { |
| 3709 | // A static_assert failed. Bail out; instantiating this |
| 3710 | // class is probably not meaningful. |
| 3711 | Instantiation->setInvalidDecl(); |
| 3712 | break; |
| 3713 | } |
| 3714 | } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewMember)) { |
| 3715 | if (MD->isConstexpr() && !MD->getFriendObjectKind() && |
| 3716 | (MD->isVirtualAsWritten() || Instantiation->getNumBases())) |
| 3717 | MightHaveConstexprVirtualFunctions = true; |
| 3718 | } |
| 3719 | |
| 3720 | if (Member->isInvalidDecl()) |
| 3721 | NewMember->setInvalidDecl(); |
| 3722 | |
| 3723 | if (NewMember->isInvalidDecl()) |
| 3724 | Instantiation->setInvalidDecl(); |
| 3725 | } else { |
| 3726 | // FIXME: Eventually, a NULL return will mean that one of the |
| 3727 | // instantiations was a semantic disaster, and we'll want to mark the |
| 3728 | // declaration invalid. |
| 3729 | // For now, we expect to skip some members that we can't yet handle. |
| 3730 | } |
| 3731 | } |
| 3732 | |
| 3733 | // Finish checking fields. |
| 3734 | ActOnFields(S: nullptr, RecLoc: Instantiation->getLocation(), TagDecl: Instantiation, Fields, |
| 3735 | LBrac: SourceLocation(), RBrac: SourceLocation(), AttrList: ParsedAttributesView()); |
| 3736 | CheckCompletedCXXClass(S: nullptr, Record: Instantiation); |
| 3737 | |
| 3738 | // Default arguments are parsed, if not instantiated. We can go instantiate |
| 3739 | // default arg exprs for default constructors if necessary now. Unless we're |
| 3740 | // parsing a class, in which case wait until that's finished. |
| 3741 | if (ParsingClassDepth == 0) |
| 3742 | ActOnFinishCXXNonNestedClass(); |
| 3743 | |
| 3744 | // Instantiate late parsed attributes, and attach them to their decls. |
| 3745 | // See Sema::InstantiateAttrs |
| 3746 | for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(), |
| 3747 | E = LateAttrs.end(); I != E; ++I) { |
| 3748 | assert(CurrentInstantiationScope == Instantiator.getStartingScope()); |
| 3749 | CurrentInstantiationScope = I->Scope; |
| 3750 | |
| 3751 | // Allow 'this' within late-parsed attributes. |
| 3752 | auto *ND = cast<NamedDecl>(Val: I->NewDecl); |
| 3753 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: ND->getDeclContext()); |
| 3754 | CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(), |
| 3755 | ND->isCXXInstanceMember()); |
| 3756 | |
| 3757 | Attr *NewAttr = |
| 3758 | instantiateTemplateAttribute(At: I->TmplAttr, C&: Context, S&: *this, TemplateArgs); |
| 3759 | if (NewAttr && checkInstantiatedThreadSafetyAttrs(D: I->NewDecl, A: NewAttr)) |
| 3760 | I->NewDecl->addAttr(A: NewAttr); |
| 3761 | LocalInstantiationScope::deleteScopes(Scope: I->Scope, |
| 3762 | Outermost: Instantiator.getStartingScope()); |
| 3763 | } |
| 3764 | Instantiator.disableLateAttributeInstantiation(); |
| 3765 | LateAttrs.clear(); |
| 3766 | |
| 3767 | ActOnFinishDelayedMemberInitializers(Record: Instantiation); |
| 3768 | |
| 3769 | // FIXME: We should do something similar for explicit instantiations so they |
| 3770 | // end up in the right module. |
| 3771 | if (TSK == TSK_ImplicitInstantiation) { |
| 3772 | Instantiation->setLocation(Pattern->getLocation()); |
| 3773 | Instantiation->setLocStart(Pattern->getInnerLocStart()); |
| 3774 | Instantiation->setBraceRange(Pattern->getBraceRange()); |
| 3775 | } |
| 3776 | |
| 3777 | if (!Instantiation->isInvalidDecl()) { |
| 3778 | // Perform any dependent diagnostics from the pattern. |
| 3779 | if (Pattern->isDependentContext()) |
| 3780 | PerformDependentDiagnostics(Pattern, TemplateArgs); |
| 3781 | |
| 3782 | // Instantiate any out-of-line class template partial |
| 3783 | // specializations now. |
| 3784 | for (TemplateDeclInstantiator::delayed_partial_spec_iterator |
| 3785 | P = Instantiator.delayed_partial_spec_begin(), |
| 3786 | PEnd = Instantiator.delayed_partial_spec_end(); |
| 3787 | P != PEnd; ++P) { |
| 3788 | if (!Instantiator.InstantiateClassTemplatePartialSpecialization( |
| 3789 | ClassTemplate: P->first, PartialSpec: P->second)) { |
| 3790 | Instantiation->setInvalidDecl(); |
| 3791 | break; |
| 3792 | } |
| 3793 | } |
| 3794 | |
| 3795 | // Instantiate any out-of-line variable template partial |
| 3796 | // specializations now. |
| 3797 | for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator |
| 3798 | P = Instantiator.delayed_var_partial_spec_begin(), |
| 3799 | PEnd = Instantiator.delayed_var_partial_spec_end(); |
| 3800 | P != PEnd; ++P) { |
| 3801 | if (!Instantiator.InstantiateVarTemplatePartialSpecialization( |
| 3802 | VarTemplate: P->first, PartialSpec: P->second)) { |
| 3803 | Instantiation->setInvalidDecl(); |
| 3804 | break; |
| 3805 | } |
| 3806 | } |
| 3807 | } |
| 3808 | |
| 3809 | Instantiation->setIsHLSLBuiltinRecord(Pattern->isHLSLBuiltinRecord()); |
| 3810 | |
| 3811 | // Exit the scope of this instantiation. |
| 3812 | SavedContext.pop(); |
| 3813 | |
| 3814 | if (!Instantiation->isInvalidDecl()) { |
| 3815 | // Always emit the vtable for an explicit instantiation definition |
| 3816 | // of a polymorphic class template specialization. Otherwise, eagerly |
| 3817 | // instantiate only constexpr virtual functions in preparation for their use |
| 3818 | // in constant evaluation. |
| 3819 | if (TSK == TSK_ExplicitInstantiationDefinition) |
| 3820 | MarkVTableUsed(Loc: PointOfInstantiation, Class: Instantiation, DefinitionRequired: true); |
| 3821 | else if (MightHaveConstexprVirtualFunctions) |
| 3822 | MarkVirtualMembersReferenced(Loc: PointOfInstantiation, RD: Instantiation, |
| 3823 | /*ConstexprOnly*/ true); |
| 3824 | } |
| 3825 | |
| 3826 | Consumer.HandleTagDeclDefinition(D: Instantiation); |
| 3827 | |
| 3828 | return Instantiation->isInvalidDecl(); |
| 3829 | } |
| 3830 | |
| 3831 | bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation, |
| 3832 | EnumDecl *Instantiation, EnumDecl *Pattern, |
| 3833 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 3834 | TemplateSpecializationKind TSK) { |
| 3835 | #ifndef NDEBUG |
| 3836 | RecursiveInstGuard AlreadyInstantiating(*this, Instantiation, |
| 3837 | RecursiveInstGuard::Kind::Template); |
| 3838 | assert(!AlreadyInstantiating && "should have been caught by caller" ); |
| 3839 | #endif |
| 3840 | |
| 3841 | EnumDecl *PatternDef = Pattern->getDefinition(); |
| 3842 | if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation, |
| 3843 | InstantiatedFromMember: Instantiation->getInstantiatedFromMemberEnum(), |
| 3844 | Pattern, PatternDef, TSK,/*Complain*/true)) |
| 3845 | return true; |
| 3846 | Pattern = PatternDef; |
| 3847 | |
| 3848 | // Record the point of instantiation. |
| 3849 | if (MemberSpecializationInfo *MSInfo |
| 3850 | = Instantiation->getMemberSpecializationInfo()) { |
| 3851 | MSInfo->setTemplateSpecializationKind(TSK); |
| 3852 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
| 3853 | } |
| 3854 | |
| 3855 | NonSFINAEContext _(*this); |
| 3856 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); |
| 3857 | if (Inst.isInvalid()) |
| 3858 | return true; |
| 3859 | PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), |
| 3860 | "instantiating enum definition" ); |
| 3861 | |
| 3862 | // The instantiation is visible here, even if it was first declared in an |
| 3863 | // unimported module. |
| 3864 | Instantiation->setVisibleDespiteOwningModule(); |
| 3865 | |
| 3866 | // Enter the scope of this instantiation. We don't use |
| 3867 | // PushDeclContext because we don't have a scope. |
| 3868 | ContextRAII SavedContext(*this, Instantiation); |
| 3869 | EnterExpressionEvaluationContext EvalContext( |
| 3870 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
| 3871 | |
| 3872 | LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true); |
| 3873 | |
| 3874 | // Pull attributes from the pattern onto the instantiation. |
| 3875 | InstantiateAttrs(TemplateArgs, Pattern, Inst: Instantiation); |
| 3876 | |
| 3877 | TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); |
| 3878 | Instantiator.InstantiateEnumDefinition(Enum: Instantiation, Pattern); |
| 3879 | |
| 3880 | // Exit the scope of this instantiation. |
| 3881 | SavedContext.pop(); |
| 3882 | |
| 3883 | return Instantiation->isInvalidDecl(); |
| 3884 | } |
| 3885 | |
| 3886 | bool Sema::InstantiateInClassInitializer( |
| 3887 | SourceLocation PointOfInstantiation, FieldDecl *Instantiation, |
| 3888 | FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 3889 | // If there is no initializer, we don't need to do anything. |
| 3890 | if (!Pattern->hasInClassInitializer()) |
| 3891 | return false; |
| 3892 | |
| 3893 | assert(Instantiation->getInClassInitStyle() == |
| 3894 | Pattern->getInClassInitStyle() && |
| 3895 | "pattern and instantiation disagree about init style" ); |
| 3896 | |
| 3897 | RecursiveInstGuard AlreadyInstantiating(*this, Instantiation, |
| 3898 | RecursiveInstGuard::Kind::Template); |
| 3899 | if (AlreadyInstantiating) |
| 3900 | // Error out if we hit an instantiation cycle for this initializer. |
| 3901 | return Diag(Loc: PointOfInstantiation, |
| 3902 | DiagID: diag::err_default_member_initializer_cycle) |
| 3903 | << Instantiation; |
| 3904 | |
| 3905 | // Error out if we haven't parsed the initializer of the pattern yet because |
| 3906 | // we are waiting for the closing brace of the outer class. |
| 3907 | Expr *OldInit = Pattern->getInClassInitializer(); |
| 3908 | if (!OldInit) { |
| 3909 | RecordDecl *PatternRD = Pattern->getParent(); |
| 3910 | RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext(); |
| 3911 | Diag(Loc: PointOfInstantiation, |
| 3912 | DiagID: diag::err_default_member_initializer_not_yet_parsed) |
| 3913 | << OutermostClass << Pattern; |
| 3914 | Diag(Loc: Pattern->getEndLoc(), |
| 3915 | DiagID: diag::note_default_member_initializer_not_yet_parsed); |
| 3916 | return true; |
| 3917 | } |
| 3918 | |
| 3919 | NonSFINAEContext _(*this); |
| 3920 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); |
| 3921 | if (Inst.isInvalid()) |
| 3922 | return true; |
| 3923 | PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), |
| 3924 | "instantiating default member init" ); |
| 3925 | |
| 3926 | // Enter the scope of this instantiation. We don't use PushDeclContext because |
| 3927 | // we don't have a scope. |
| 3928 | ContextRAII SavedContext(*this, Instantiation->getParent()); |
| 3929 | EnterExpressionEvaluationContext EvalContext( |
| 3930 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, |
| 3931 | Instantiation); |
| 3932 | ExprEvalContexts.back().DelayedDefaultInitializationContext = { |
| 3933 | PointOfInstantiation, Instantiation, CurContext}; |
| 3934 | |
| 3935 | LocalInstantiationScope Scope(*this, true); |
| 3936 | |
| 3937 | // Instantiate the initializer. |
| 3938 | ActOnStartCXXInClassMemberInitializer(); |
| 3939 | CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers()); |
| 3940 | |
| 3941 | ExprResult NewInit = SubstInitializer(E: OldInit, TemplateArgs, |
| 3942 | /*CXXDirectInit=*/false); |
| 3943 | Expr *Init = NewInit.get(); |
| 3944 | assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class" ); |
| 3945 | ActOnFinishCXXInClassMemberInitializer( |
| 3946 | VarDecl: Instantiation, EqualLoc: Init ? Init->getBeginLoc() : SourceLocation(), Init); |
| 3947 | |
| 3948 | if (auto *L = getASTMutationListener()) |
| 3949 | L->DefaultMemberInitializerInstantiated(D: Instantiation); |
| 3950 | |
| 3951 | // Return true if the in-class initializer is still missing. |
| 3952 | return !Instantiation->getInClassInitializer(); |
| 3953 | } |
| 3954 | |
| 3955 | namespace { |
| 3956 | /// A partial specialization whose template arguments have matched |
| 3957 | /// a given template-id. |
| 3958 | struct PartialSpecMatchResult { |
| 3959 | ClassTemplatePartialSpecializationDecl *Partial; |
| 3960 | TemplateArgumentList *Args; |
| 3961 | }; |
| 3962 | } |
| 3963 | |
| 3964 | bool Sema::usesPartialOrExplicitSpecialization( |
| 3965 | SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) { |
| 3966 | if (ClassTemplateSpec->getTemplateSpecializationKind() == |
| 3967 | TSK_ExplicitSpecialization) |
| 3968 | return true; |
| 3969 | |
| 3970 | SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
| 3971 | ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate(); |
| 3972 | CTD->getPartialSpecializations(PS&: PartialSpecs); |
| 3973 | for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) { |
| 3974 | // C++ [temp.spec.partial.member]p2: |
| 3975 | // If the primary member template is explicitly specialized for a given |
| 3976 | // (implicit) specialization of the enclosing class template, the partial |
| 3977 | // specializations of the member template are ignored for this |
| 3978 | // specialization of the enclosing class template. If a partial |
| 3979 | // specialization of the member template is explicitly specialized for a |
| 3980 | // given (implicit) specialization of the enclosing class template, the |
| 3981 | // primary member template and its other partial specializations are still |
| 3982 | // considered for this specialization of the enclosing class template. |
| 3983 | if (CTD->isMemberSpecialization() && !CTPSD->isMemberSpecialization()) |
| 3984 | continue; |
| 3985 | |
| 3986 | TemplateDeductionInfo Info(Loc); |
| 3987 | if (DeduceTemplateArguments(Partial: CTPSD, |
| 3988 | TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(), |
| 3989 | Info) == TemplateDeductionResult::Success) |
| 3990 | return true; |
| 3991 | } |
| 3992 | |
| 3993 | return false; |
| 3994 | } |
| 3995 | |
| 3996 | /// Get the instantiation pattern to use to instantiate the definition of a |
| 3997 | /// given ClassTemplateSpecializationDecl (either the pattern of the primary |
| 3998 | /// template or of a partial specialization). |
| 3999 | static ActionResult<CXXRecordDecl *> getPatternForClassTemplateSpecialization( |
| 4000 | Sema &S, SourceLocation PointOfInstantiation, |
| 4001 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
| 4002 | TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) { |
| 4003 | std::optional<Sema::NonSFINAEContext> NSC(S); |
| 4004 | Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec); |
| 4005 | if (Inst.isInvalid()) |
| 4006 | return {/*Invalid=*/true}; |
| 4007 | |
| 4008 | llvm::PointerUnion<ClassTemplateDecl *, |
| 4009 | ClassTemplatePartialSpecializationDecl *> |
| 4010 | Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); |
| 4011 | if (!isa<ClassTemplatePartialSpecializationDecl *>(Val: Specialized)) { |
| 4012 | // Find best matching specialization. |
| 4013 | ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); |
| 4014 | |
| 4015 | // C++ [temp.class.spec.match]p1: |
| 4016 | // When a class template is used in a context that requires an |
| 4017 | // instantiation of the class, it is necessary to determine |
| 4018 | // whether the instantiation is to be generated using the primary |
| 4019 | // template or one of the partial specializations. This is done by |
| 4020 | // matching the template arguments of the class template |
| 4021 | // specialization with the template argument lists of the partial |
| 4022 | // specializations. |
| 4023 | typedef PartialSpecMatchResult MatchResult; |
| 4024 | SmallVector<MatchResult, 4> Matched, ; |
| 4025 | SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
| 4026 | Template->getPartialSpecializations(PS&: PartialSpecs); |
| 4027 | TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation); |
| 4028 | for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) { |
| 4029 | // C++ [temp.spec.partial.member]p2: |
| 4030 | // If the primary member template is explicitly specialized for a given |
| 4031 | // (implicit) specialization of the enclosing class template, the |
| 4032 | // partial specializations of the member template are ignored for this |
| 4033 | // specialization of the enclosing class template. If a partial |
| 4034 | // specialization of the member template is explicitly specialized for a |
| 4035 | // given (implicit) specialization of the enclosing class template, the |
| 4036 | // primary member template and its other partial specializations are |
| 4037 | // still considered for this specialization of the enclosing class |
| 4038 | // template. |
| 4039 | if (Template->isMemberSpecialization() && |
| 4040 | !Partial->isMemberSpecialization()) |
| 4041 | continue; |
| 4042 | |
| 4043 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
| 4044 | if (TemplateDeductionResult Result = S.DeduceTemplateArguments( |
| 4045 | Partial, TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(), Info); |
| 4046 | Result != TemplateDeductionResult::Success) { |
| 4047 | // Store the failed-deduction information for use in diagnostics, later. |
| 4048 | // TODO: Actually use the failed-deduction info? |
| 4049 | FailedCandidates.addCandidate().set( |
| 4050 | Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial, |
| 4051 | Info: MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info)); |
| 4052 | (void)Result; |
| 4053 | } else { |
| 4054 | auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched; |
| 4055 | List.push_back(Elt: MatchResult{.Partial: Partial, .Args: Info.takeCanonical()}); |
| 4056 | } |
| 4057 | } |
| 4058 | if (Matched.empty() && PrimaryStrictPackMatch) |
| 4059 | Matched = std::move(ExtraMatched); |
| 4060 | |
| 4061 | // If we're dealing with a member template where the template parameters |
| 4062 | // have been instantiated, this provides the original template parameters |
| 4063 | // from which the member template's parameters were instantiated. |
| 4064 | |
| 4065 | if (Matched.size() >= 1) { |
| 4066 | SmallVectorImpl<MatchResult>::iterator Best = Matched.begin(); |
| 4067 | if (Matched.size() == 1) { |
| 4068 | // -- If exactly one matching specialization is found, the |
| 4069 | // instantiation is generated from that specialization. |
| 4070 | // We don't need to do anything for this. |
| 4071 | } else { |
| 4072 | // -- If more than one matching specialization is found, the |
| 4073 | // partial order rules (14.5.4.2) are used to determine |
| 4074 | // whether one of the specializations is more specialized |
| 4075 | // than the others. If none of the specializations is more |
| 4076 | // specialized than all of the other matching |
| 4077 | // specializations, then the use of the class template is |
| 4078 | // ambiguous and the program is ill-formed. |
| 4079 | for (SmallVectorImpl<MatchResult>::iterator P = Best + 1, |
| 4080 | PEnd = Matched.end(); |
| 4081 | P != PEnd; ++P) { |
| 4082 | if (S.getMoreSpecializedPartialSpecialization( |
| 4083 | PS1: P->Partial, PS2: Best->Partial, Loc: PointOfInstantiation) == |
| 4084 | P->Partial) |
| 4085 | Best = P; |
| 4086 | } |
| 4087 | |
| 4088 | // Determine if the best partial specialization is more specialized than |
| 4089 | // the others. |
| 4090 | bool Ambiguous = false; |
| 4091 | for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), |
| 4092 | PEnd = Matched.end(); |
| 4093 | P != PEnd; ++P) { |
| 4094 | if (P != Best && S.getMoreSpecializedPartialSpecialization( |
| 4095 | PS1: P->Partial, PS2: Best->Partial, |
| 4096 | Loc: PointOfInstantiation) != Best->Partial) { |
| 4097 | Ambiguous = true; |
| 4098 | break; |
| 4099 | } |
| 4100 | } |
| 4101 | |
| 4102 | if (Ambiguous) { |
| 4103 | // Partial ordering did not produce a clear winner. Complain. |
| 4104 | Inst.Clear(); |
| 4105 | NSC.reset(); |
| 4106 | S.Diag(Loc: PointOfInstantiation, |
| 4107 | DiagID: diag::err_partial_spec_ordering_ambiguous) |
| 4108 | << ClassTemplateSpec; |
| 4109 | |
| 4110 | // Print the matching partial specializations. |
| 4111 | for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), |
| 4112 | PEnd = Matched.end(); |
| 4113 | P != PEnd; ++P) |
| 4114 | S.Diag(Loc: P->Partial->getLocation(), DiagID: diag::note_partial_spec_match) |
| 4115 | << S.getTemplateArgumentBindingsText( |
| 4116 | Params: P->Partial->getTemplateParameters(), Args: *P->Args); |
| 4117 | |
| 4118 | return {/*Invalid=*/true}; |
| 4119 | } |
| 4120 | } |
| 4121 | |
| 4122 | ClassTemplateSpec->setInstantiationOf(PartialSpec: Best->Partial, TemplateArgs: Best->Args); |
| 4123 | } else { |
| 4124 | // -- If no matches are found, the instantiation is generated |
| 4125 | // from the primary template. |
| 4126 | } |
| 4127 | } |
| 4128 | |
| 4129 | CXXRecordDecl *Pattern = nullptr; |
| 4130 | Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); |
| 4131 | if (auto *PartialSpec = |
| 4132 | Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { |
| 4133 | // Instantiate using the best class template partial specialization. |
| 4134 | while (PartialSpec->getInstantiatedFromMember()) { |
| 4135 | // If we've found an explicit specialization of this class template, |
| 4136 | // stop here and use that as the pattern. |
| 4137 | if (PartialSpec->isMemberSpecialization()) |
| 4138 | break; |
| 4139 | |
| 4140 | PartialSpec = PartialSpec->getInstantiatedFromMember(); |
| 4141 | } |
| 4142 | Pattern = PartialSpec; |
| 4143 | } else { |
| 4144 | ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); |
| 4145 | while (Template->getInstantiatedFromMemberTemplate()) { |
| 4146 | // If we've found an explicit specialization of this class template, |
| 4147 | // stop here and use that as the pattern. |
| 4148 | if (Template->isMemberSpecialization()) |
| 4149 | break; |
| 4150 | |
| 4151 | Template = Template->getInstantiatedFromMemberTemplate(); |
| 4152 | } |
| 4153 | Pattern = Template->getTemplatedDecl(); |
| 4154 | } |
| 4155 | |
| 4156 | return Pattern; |
| 4157 | } |
| 4158 | |
| 4159 | bool Sema::InstantiateClassTemplateSpecialization( |
| 4160 | SourceLocation PointOfInstantiation, |
| 4161 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
| 4162 | TemplateSpecializationKind TSK, bool Complain, |
| 4163 | bool PrimaryStrictPackMatch) { |
| 4164 | // Perform the actual instantiation on the canonical declaration. |
| 4165 | ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( |
| 4166 | Val: ClassTemplateSpec->getCanonicalDecl()); |
| 4167 | if (ClassTemplateSpec->isInvalidDecl()) |
| 4168 | return true; |
| 4169 | |
| 4170 | Sema::RecursiveInstGuard AlreadyInstantiating( |
| 4171 | *this, ClassTemplateSpec, Sema::RecursiveInstGuard::Kind::Template); |
| 4172 | if (AlreadyInstantiating) |
| 4173 | return false; |
| 4174 | |
| 4175 | bool HadAvaibilityWarning = |
| 4176 | ShouldDiagnoseAvailabilityOfDecl(D: ClassTemplateSpec, Message: nullptr, ClassReceiver: nullptr) |
| 4177 | .first != AR_Available; |
| 4178 | |
| 4179 | ActionResult<CXXRecordDecl *> Pattern = |
| 4180 | getPatternForClassTemplateSpecialization(S&: *this, PointOfInstantiation, |
| 4181 | ClassTemplateSpec, TSK, |
| 4182 | PrimaryStrictPackMatch); |
| 4183 | |
| 4184 | if (!Pattern.isUsable()) |
| 4185 | return Pattern.isInvalid(); |
| 4186 | |
| 4187 | // Deduction has picked the pattern this specialization will be instantiated |
| 4188 | // from, which may be a declaration an external AST source has yet to define. |
| 4189 | if (!Pattern.get()->isCompleteDefinition() && |
| 4190 | Pattern.get()->hasExternalLexicalStorage()) |
| 4191 | if (ExternalASTSource *Source = Context.getExternalSource()) |
| 4192 | Source->CompleteType(Tag: Pattern.get()); |
| 4193 | |
| 4194 | bool Err = InstantiateClassImpl( |
| 4195 | PointOfInstantiation, Instantiation: ClassTemplateSpec, Pattern: Pattern.get(), |
| 4196 | TemplateArgs: getTemplateInstantiationArgs(ND: ClassTemplateSpec), TSK, Complain); |
| 4197 | |
| 4198 | // If we haven't already warn on avaibility, consider the avaibility |
| 4199 | // attributes of the partial specialization. |
| 4200 | // Note that - because we need to have deduced the partial specialization - |
| 4201 | // We can only emit these warnings when the specialization is instantiated. |
| 4202 | if (!Err && !HadAvaibilityWarning) { |
| 4203 | assert(ClassTemplateSpec->getTemplateSpecializationKind() != |
| 4204 | TSK_Undeclared); |
| 4205 | DiagnoseAvailabilityOfDecl(D: ClassTemplateSpec, Locs: PointOfInstantiation); |
| 4206 | } |
| 4207 | return Err; |
| 4208 | } |
| 4209 | |
| 4210 | void |
| 4211 | Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, |
| 4212 | CXXRecordDecl *Instantiation, |
| 4213 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4214 | TemplateSpecializationKind TSK) { |
| 4215 | // FIXME: We need to notify the ASTMutationListener that we did all of these |
| 4216 | // things, in case we have an explicit instantiation definition in a PCM, a |
| 4217 | // module, or preamble, and the declaration is in an imported AST. |
| 4218 | assert( |
| 4219 | (TSK == TSK_ExplicitInstantiationDefinition || |
| 4220 | TSK == TSK_ExplicitInstantiationDeclaration || |
| 4221 | (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && |
| 4222 | "Unexpected template specialization kind!" ); |
| 4223 | for (auto *D : Instantiation->decls()) { |
| 4224 | bool SuppressNew = false; |
| 4225 | if (auto *Function = dyn_cast<FunctionDecl>(Val: D)) { |
| 4226 | if (FunctionDecl *Pattern = |
| 4227 | Function->getInstantiatedFromMemberFunction()) { |
| 4228 | |
| 4229 | if (Function->getTrailingRequiresClause()) { |
| 4230 | ConstraintSatisfaction Satisfaction; |
| 4231 | if (CheckFunctionConstraints(FD: Function, Satisfaction) || |
| 4232 | !Satisfaction.IsSatisfied) { |
| 4233 | continue; |
| 4234 | } |
| 4235 | } |
| 4236 | |
| 4237 | if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>()) |
| 4238 | continue; |
| 4239 | |
| 4240 | TemplateSpecializationKind PrevTSK = |
| 4241 | Function->getTemplateSpecializationKind(); |
| 4242 | if (PrevTSK == TSK_ExplicitSpecialization) |
| 4243 | continue; |
| 4244 | |
| 4245 | if (CheckSpecializationInstantiationRedecl( |
| 4246 | NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, PrevDecl: Function, PrevTSK, |
| 4247 | PrevPtOfInstantiation: Function->getPointOfInstantiation(), SuppressNew) || |
| 4248 | SuppressNew) |
| 4249 | continue; |
| 4250 | |
| 4251 | // C++11 [temp.explicit]p8: |
| 4252 | // An explicit instantiation definition that names a class template |
| 4253 | // specialization explicitly instantiates the class template |
| 4254 | // specialization and is only an explicit instantiation definition |
| 4255 | // of members whose definition is visible at the point of |
| 4256 | // instantiation. |
| 4257 | if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined()) |
| 4258 | continue; |
| 4259 | |
| 4260 | Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
| 4261 | |
| 4262 | if (Function->isDefined()) { |
| 4263 | // Let the ASTConsumer know that this function has been explicitly |
| 4264 | // instantiated now, and its linkage might have changed. |
| 4265 | Consumer.HandleTopLevelDecl(D: DeclGroupRef(Function)); |
| 4266 | } else if (TSK == TSK_ExplicitInstantiationDefinition) { |
| 4267 | InstantiateFunctionDefinition(PointOfInstantiation, Function); |
| 4268 | } else if (TSK == TSK_ImplicitInstantiation) { |
| 4269 | PendingLocalImplicitInstantiations.push_back( |
| 4270 | x: std::make_pair(x&: Function, y&: PointOfInstantiation)); |
| 4271 | } |
| 4272 | } |
| 4273 | } else if (auto *Var = dyn_cast<VarDecl>(Val: D)) { |
| 4274 | if (isa<VarTemplateSpecializationDecl>(Val: Var)) |
| 4275 | continue; |
| 4276 | |
| 4277 | if (Var->isStaticDataMember()) { |
| 4278 | if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>()) |
| 4279 | continue; |
| 4280 | |
| 4281 | MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); |
| 4282 | assert(MSInfo && "No member specialization information?" ); |
| 4283 | if (MSInfo->getTemplateSpecializationKind() |
| 4284 | == TSK_ExplicitSpecialization) |
| 4285 | continue; |
| 4286 | |
| 4287 | if (CheckSpecializationInstantiationRedecl(NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, |
| 4288 | PrevDecl: Var, |
| 4289 | PrevTSK: MSInfo->getTemplateSpecializationKind(), |
| 4290 | PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(), |
| 4291 | SuppressNew) || |
| 4292 | SuppressNew) |
| 4293 | continue; |
| 4294 | |
| 4295 | if (TSK == TSK_ExplicitInstantiationDefinition) { |
| 4296 | // C++0x [temp.explicit]p8: |
| 4297 | // An explicit instantiation definition that names a class template |
| 4298 | // specialization explicitly instantiates the class template |
| 4299 | // specialization and is only an explicit instantiation definition |
| 4300 | // of members whose definition is visible at the point of |
| 4301 | // instantiation. |
| 4302 | if (!Var->getInstantiatedFromStaticDataMember()->getDefinition()) |
| 4303 | continue; |
| 4304 | |
| 4305 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
| 4306 | InstantiateVariableDefinition(PointOfInstantiation, Var); |
| 4307 | } else { |
| 4308 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
| 4309 | } |
| 4310 | } |
| 4311 | } else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) { |
| 4312 | if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>()) |
| 4313 | continue; |
| 4314 | |
| 4315 | // Always skip the injected-class-name, along with any |
| 4316 | // redeclarations of nested classes, since both would cause us |
| 4317 | // to try to instantiate the members of a class twice. |
| 4318 | // Skip closure types; they'll get instantiated when we instantiate |
| 4319 | // the corresponding lambda-expression. |
| 4320 | if (Record->isInjectedClassName() || Record->getPreviousDecl() || |
| 4321 | Record->isLambda()) |
| 4322 | continue; |
| 4323 | |
| 4324 | MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); |
| 4325 | assert(MSInfo && "No member specialization information?" ); |
| 4326 | |
| 4327 | if (MSInfo->getTemplateSpecializationKind() |
| 4328 | == TSK_ExplicitSpecialization) |
| 4329 | continue; |
| 4330 | |
| 4331 | if (Context.getTargetInfo().getTriple().isOSWindows() && |
| 4332 | TSK == TSK_ExplicitInstantiationDeclaration) { |
| 4333 | // On Windows, explicit instantiation decl of the outer class doesn't |
| 4334 | // affect the inner class. Typically extern template declarations are |
| 4335 | // used in combination with dll import/export annotations, but those |
| 4336 | // are not propagated from the outer class templates to inner classes. |
| 4337 | // Therefore, do not instantiate inner classes on this platform, so |
| 4338 | // that users don't end up with undefined symbols during linking. |
| 4339 | continue; |
| 4340 | } |
| 4341 | |
| 4342 | if (CheckSpecializationInstantiationRedecl(NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, |
| 4343 | PrevDecl: Record, |
| 4344 | PrevTSK: MSInfo->getTemplateSpecializationKind(), |
| 4345 | PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(), |
| 4346 | SuppressNew) || |
| 4347 | SuppressNew) |
| 4348 | continue; |
| 4349 | |
| 4350 | CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); |
| 4351 | assert(Pattern && "Missing instantiated-from-template information" ); |
| 4352 | |
| 4353 | if (!Record->getDefinition()) { |
| 4354 | if (!Pattern->getDefinition()) { |
| 4355 | // C++0x [temp.explicit]p8: |
| 4356 | // An explicit instantiation definition that names a class template |
| 4357 | // specialization explicitly instantiates the class template |
| 4358 | // specialization and is only an explicit instantiation definition |
| 4359 | // of members whose definition is visible at the point of |
| 4360 | // instantiation. |
| 4361 | if (TSK == TSK_ExplicitInstantiationDeclaration) { |
| 4362 | MSInfo->setTemplateSpecializationKind(TSK); |
| 4363 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
| 4364 | } |
| 4365 | |
| 4366 | continue; |
| 4367 | } |
| 4368 | |
| 4369 | InstantiateClass(PointOfInstantiation, Instantiation: Record, Pattern, |
| 4370 | TemplateArgs, |
| 4371 | TSK); |
| 4372 | } else { |
| 4373 | if (TSK == TSK_ExplicitInstantiationDefinition && |
| 4374 | Record->getTemplateSpecializationKind() == |
| 4375 | TSK_ExplicitInstantiationDeclaration) { |
| 4376 | Record->setTemplateSpecializationKind(TSK); |
| 4377 | MarkVTableUsed(Loc: PointOfInstantiation, Class: Record, DefinitionRequired: true); |
| 4378 | } |
| 4379 | } |
| 4380 | |
| 4381 | Pattern = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition()); |
| 4382 | if (Pattern) |
| 4383 | InstantiateClassMembers(PointOfInstantiation, Instantiation: Pattern, TemplateArgs, |
| 4384 | TSK); |
| 4385 | } else if (auto *Enum = dyn_cast<EnumDecl>(Val: D)) { |
| 4386 | MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo(); |
| 4387 | assert(MSInfo && "No member specialization information?" ); |
| 4388 | |
| 4389 | if (MSInfo->getTemplateSpecializationKind() |
| 4390 | == TSK_ExplicitSpecialization) |
| 4391 | continue; |
| 4392 | |
| 4393 | if (CheckSpecializationInstantiationRedecl( |
| 4394 | NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, PrevDecl: Enum, |
| 4395 | PrevTSK: MSInfo->getTemplateSpecializationKind(), |
| 4396 | PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(), SuppressNew) || |
| 4397 | SuppressNew) |
| 4398 | continue; |
| 4399 | |
| 4400 | if (Enum->getDefinition()) |
| 4401 | continue; |
| 4402 | |
| 4403 | EnumDecl *Pattern = Enum->getTemplateInstantiationPattern(); |
| 4404 | assert(Pattern && "Missing instantiated-from-template information" ); |
| 4405 | |
| 4406 | if (TSK == TSK_ExplicitInstantiationDefinition) { |
| 4407 | if (!Pattern->getDefinition()) |
| 4408 | continue; |
| 4409 | |
| 4410 | InstantiateEnum(PointOfInstantiation, Instantiation: Enum, Pattern, TemplateArgs, TSK); |
| 4411 | } else { |
| 4412 | MSInfo->setTemplateSpecializationKind(TSK); |
| 4413 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
| 4414 | } |
| 4415 | } else if (auto *Field = dyn_cast<FieldDecl>(Val: D)) { |
| 4416 | // No need to instantiate in-class initializers during explicit |
| 4417 | // instantiation. |
| 4418 | if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) { |
| 4419 | // Handle local classes which could have substituted template params. |
| 4420 | CXXRecordDecl *ClassPattern = |
| 4421 | Instantiation->isLocalClass() |
| 4422 | ? Instantiation->getInstantiatedFromMemberClass() |
| 4423 | : Instantiation->getTemplateInstantiationPattern(); |
| 4424 | |
| 4425 | DeclContext::lookup_result Lookup = |
| 4426 | ClassPattern->lookup(Name: Field->getDeclName()); |
| 4427 | FieldDecl *Pattern = Lookup.find_first<FieldDecl>(); |
| 4428 | assert(Pattern); |
| 4429 | InstantiateInClassInitializer(PointOfInstantiation, Instantiation: Field, Pattern, |
| 4430 | TemplateArgs); |
| 4431 | } |
| 4432 | } |
| 4433 | } |
| 4434 | } |
| 4435 | |
| 4436 | void |
| 4437 | Sema::InstantiateClassTemplateSpecializationMembers( |
| 4438 | SourceLocation PointOfInstantiation, |
| 4439 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
| 4440 | TemplateSpecializationKind TSK) { |
| 4441 | // C++0x [temp.explicit]p7: |
| 4442 | // An explicit instantiation that names a class template |
| 4443 | // specialization is an explicit instantion of the same kind |
| 4444 | // (declaration or definition) of each of its members (not |
| 4445 | // including members inherited from base classes) that has not |
| 4446 | // been previously explicitly specialized in the translation unit |
| 4447 | // containing the explicit instantiation, except as described |
| 4448 | // below. |
| 4449 | InstantiateClassMembers(PointOfInstantiation, Instantiation: ClassTemplateSpec, |
| 4450 | TemplateArgs: getTemplateInstantiationArgs(ND: ClassTemplateSpec), |
| 4451 | TSK); |
| 4452 | } |
| 4453 | |
| 4454 | StmtResult |
| 4455 | Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4456 | if (!S) |
| 4457 | return S; |
| 4458 | |
| 4459 | TemplateInstantiator Instantiator(*this, TemplateArgs, |
| 4460 | SourceLocation(), |
| 4461 | DeclarationName()); |
| 4462 | return Instantiator.TransformStmt(S); |
| 4463 | } |
| 4464 | |
| 4465 | bool Sema::SubstTemplateArgument( |
| 4466 | const TemplateArgumentLoc &Input, |
| 4467 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4468 | TemplateArgumentLoc &Output, SourceLocation Loc, |
| 4469 | const DeclarationName &Entity) { |
| 4470 | TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity); |
| 4471 | return Instantiator.TransformTemplateArgument(Input, Output); |
| 4472 | } |
| 4473 | |
| 4474 | bool Sema::SubstTemplateArguments( |
| 4475 | ArrayRef<TemplateArgumentLoc> Args, |
| 4476 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4477 | TemplateArgumentListInfo &Out) { |
| 4478 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
| 4479 | DeclarationName()); |
| 4480 | return Instantiator.TransformTemplateArguments(First: Args.begin(), Last: Args.end(), Outputs&: Out); |
| 4481 | } |
| 4482 | |
| 4483 | bool Sema::SubstTemplateArgumentsInParameterMapping( |
| 4484 | ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc, |
| 4485 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4486 | TemplateArgumentListInfo &Out) { |
| 4487 | TemplateInstantiator Instantiator( |
| 4488 | TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc, |
| 4489 | TemplateArgs); |
| 4490 | return Instantiator.TransformTemplateArguments(First: Args.begin(), Last: Args.end(), Outputs&: Out); |
| 4491 | } |
| 4492 | |
| 4493 | ExprResult |
| 4494 | Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4495 | if (!E) |
| 4496 | return E; |
| 4497 | |
| 4498 | TemplateInstantiator Instantiator(*this, TemplateArgs, |
| 4499 | SourceLocation(), |
| 4500 | DeclarationName()); |
| 4501 | return Instantiator.TransformExpr(E); |
| 4502 | } |
| 4503 | |
| 4504 | ExprResult |
| 4505 | Sema::SubstCXXIdExpr(Expr *E, |
| 4506 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4507 | if (!E) |
| 4508 | return E; |
| 4509 | |
| 4510 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
| 4511 | DeclarationName()); |
| 4512 | return Instantiator.TransformAddressOfOperand(E); |
| 4513 | } |
| 4514 | |
| 4515 | ExprResult |
| 4516 | Sema::SubstConstraintExpr(Expr *E, |
| 4517 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4518 | if (!E) |
| 4519 | return E; |
| 4520 | |
| 4521 | TemplateInstantiator Instantiator( |
| 4522 | TemplateInstantiator::ForConstraintSubstitution, *this, TemplateArgs, |
| 4523 | SourceLocation(), DeclarationName()); |
| 4524 | return Instantiator.TransformExpr(E); |
| 4525 | } |
| 4526 | |
| 4527 | ExprResult Sema::SubstConstraintExprWithoutSatisfaction( |
| 4528 | Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4529 | if (!E) |
| 4530 | return E; |
| 4531 | |
| 4532 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
| 4533 | DeclarationName()); |
| 4534 | Instantiator.setEvaluateConstraints(false); |
| 4535 | return Instantiator.TransformExpr(E); |
| 4536 | } |
| 4537 | |
| 4538 | ExprResult Sema::SubstConceptTemplateArguments( |
| 4539 | const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr, |
| 4540 | const MultiLevelTemplateArgumentList &MLTAL) { |
| 4541 | assert(isSFINAEContext()); |
| 4542 | |
| 4543 | TemplateInstantiator Instantiator(*this, MLTAL, SourceLocation(), |
| 4544 | DeclarationName()); |
| 4545 | const ASTTemplateArgumentListInfo *ArgsAsWritten = |
| 4546 | CSE->getTemplateArgsAsWritten(); |
| 4547 | TemplateArgumentListInfo SubstArgs(ArgsAsWritten->getLAngleLoc(), |
| 4548 | ArgsAsWritten->getRAngleLoc()); |
| 4549 | |
| 4550 | if (Instantiator.TransformConceptTemplateArguments( |
| 4551 | First: ArgsAsWritten->getTemplateArgs(), |
| 4552 | Last: ArgsAsWritten->getTemplateArgs() + |
| 4553 | ArgsAsWritten->getNumTemplateArgs(), |
| 4554 | Outputs&: SubstArgs)) |
| 4555 | return true; |
| 4556 | |
| 4557 | llvm::SmallVector<TemplateArgument, 4> NewArgList = llvm::map_to_vector( |
| 4558 | C: SubstArgs.arguments(), |
| 4559 | F: [](const TemplateArgumentLoc &Loc) { return Loc.getArgument(); }); |
| 4560 | |
| 4561 | MultiLevelTemplateArgumentList MLTALForConstraint = |
| 4562 | getTemplateInstantiationArgs( |
| 4563 | ND: CSE->getConceptDecl(), DC: CSE->getConceptDecl()->getLexicalDeclContext(), |
| 4564 | /*Final=*/false, |
| 4565 | /*Innermost=*/NewArgList, |
| 4566 | /*RelativeToPrimary=*/true, |
| 4567 | /*Pattern=*/nullptr, |
| 4568 | /*ForConstraintInstantiation=*/true); |
| 4569 | |
| 4570 | // Rebuild a constraint, only substituting non-dependent concept names |
| 4571 | // and nothing else. |
| 4572 | // Given C<SomeType, SomeValue, SomeConceptName, SomeDependentConceptName>. |
| 4573 | // only SomeConceptName is substituted, in the constraint expression of C. |
| 4574 | struct ConstraintExprTransformer : TreeTransform<ConstraintExprTransformer> { |
| 4575 | using Base = TreeTransform<ConstraintExprTransformer>; |
| 4576 | MultiLevelTemplateArgumentList &MLTAL; |
| 4577 | |
| 4578 | ConstraintExprTransformer(Sema &SemaRef, |
| 4579 | MultiLevelTemplateArgumentList &MLTAL) |
| 4580 | : TreeTransform(SemaRef), MLTAL(MLTAL) {} |
| 4581 | |
| 4582 | ExprResult TransformExpr(Expr *E) { |
| 4583 | if (!E) |
| 4584 | return E; |
| 4585 | switch (E->getStmtClass()) { |
| 4586 | case Stmt::BinaryOperatorClass: |
| 4587 | case Stmt::ConceptSpecializationExprClass: |
| 4588 | case Stmt::ParenExprClass: |
| 4589 | case Stmt::UnresolvedLookupExprClass: |
| 4590 | case Stmt::DependentTemplateIdExprClass: |
| 4591 | return Base::TransformExpr(E); |
| 4592 | default: |
| 4593 | break; |
| 4594 | } |
| 4595 | return E; |
| 4596 | } |
| 4597 | |
| 4598 | // Rebuild both branches of a conjunction / disjunction |
| 4599 | // even if there is a substitution failure in one of |
| 4600 | // the branch. |
| 4601 | ExprResult TransformBinaryOperator(BinaryOperator *E) { |
| 4602 | if (!(E->getOpcode() == BinaryOperatorKind::BO_LAnd || |
| 4603 | E->getOpcode() == BinaryOperatorKind::BO_LOr)) |
| 4604 | return E; |
| 4605 | |
| 4606 | ExprResult LHS = TransformExpr(E: E->getLHS()); |
| 4607 | ExprResult RHS = TransformExpr(E: E->getRHS()); |
| 4608 | |
| 4609 | if (LHS.get() == E->getLHS() && RHS.get() == E->getRHS()) |
| 4610 | return E; |
| 4611 | |
| 4612 | return BinaryOperator::Create(C: SemaRef.Context, lhs: LHS.get(), rhs: RHS.get(), |
| 4613 | opc: E->getOpcode(), ResTy: SemaRef.Context.BoolTy, |
| 4614 | VK: VK_PRValue, OK: OK_Ordinary, |
| 4615 | opLoc: E->getOperatorLoc(), FPFeatures: FPOptionsOverride{}); |
| 4616 | } |
| 4617 | |
| 4618 | bool TransformTemplateArgument(const TemplateArgumentLoc &Input, |
| 4619 | TemplateArgumentLoc &Output, |
| 4620 | bool Uneval = false) { |
| 4621 | if (Input.getArgument().isConceptOrConceptTemplateParameter()) |
| 4622 | return Base::TransformTemplateArgument(Input, Output, Uneval); |
| 4623 | |
| 4624 | Output = Input; |
| 4625 | return false; |
| 4626 | } |
| 4627 | |
| 4628 | ExprResult RebuildConceptSpecialization(ConceptDecl *ResolvedConcept, |
| 4629 | SourceLocation NameLoc, |
| 4630 | SourceLocation LAngleLoc, |
| 4631 | SourceLocation RAngleLoc, |
| 4632 | const TemplateArgumentLoc *Args, |
| 4633 | unsigned NumArgs) { |
| 4634 | TemplateArgumentListInfo TransArgs(LAngleLoc, RAngleLoc); |
| 4635 | if (TransformTemplateArguments(Inputs: Args, NumInputs: NumArgs, Outputs&: TransArgs)) |
| 4636 | return ExprError(); |
| 4637 | |
| 4638 | CXXScopeSpec SS; |
| 4639 | DeclarationNameInfo NameInfo(ResolvedConcept->getDeclName(), NameLoc); |
| 4640 | return SemaRef.CheckConceptTemplateId(SS, TemplateKWLoc: SourceLocation(), ConceptNameInfo: NameInfo, |
| 4641 | FoundDecl: ResolvedConcept, NamedConcept: ResolvedConcept, |
| 4642 | TemplateArgs: &TransArgs, DoCheckConstraintSatisfaction: false); |
| 4643 | } |
| 4644 | |
| 4645 | ExprResult TransformDependentTemplateIdExpr(DependentTemplateIdExpr *E) { |
| 4646 | if (!E->isConceptReference()) |
| 4647 | return E; |
| 4648 | |
| 4649 | TemplateTemplateParmDecl *TTP = E->getParameter(); |
| 4650 | unsigned Depth = TTP->getDepth(); |
| 4651 | unsigned Pos = TTP->getPosition(); |
| 4652 | if (!MLTAL.hasTemplateArgument(Depth, Index: Pos)) |
| 4653 | return E; |
| 4654 | |
| 4655 | TemplateArgument Arg = MLTAL(Depth, Pos); |
| 4656 | if (PackIndexingTemplateStorage *PI = |
| 4657 | E->getTemplateName().getAsPackIndexingTemplate()) { |
| 4658 | UnsignedOrNone Index = PI->getSelectedIndex(); |
| 4659 | if (Arg.getKind() != TemplateArgument::Pack || !Index || |
| 4660 | *Index >= Arg.pack_size()) |
| 4661 | return E; |
| 4662 | Arg = Arg.getPackAsArray()[*Index]; |
| 4663 | } |
| 4664 | if (Arg.getKind() != TemplateArgument::Template) |
| 4665 | return E; |
| 4666 | ConceptDecl *ResolvedConcept = dyn_cast_if_present<ConceptDecl>( |
| 4667 | Val: Arg.getAsTemplate().getAsTemplateDecl()); |
| 4668 | if (!ResolvedConcept) |
| 4669 | return E; |
| 4670 | |
| 4671 | return RebuildConceptSpecialization(ResolvedConcept, NameLoc: E->getNameLoc(), |
| 4672 | LAngleLoc: E->getLAngleLoc(), RAngleLoc: E->getRAngleLoc(), |
| 4673 | Args: E->template_arguments().data(), |
| 4674 | NumArgs: E->getNumTemplateArgs()); |
| 4675 | } |
| 4676 | }; |
| 4677 | |
| 4678 | ConstraintExprTransformer Transformer(*this, MLTALForConstraint); |
| 4679 | ExprResult Res = |
| 4680 | Transformer.TransformExpr(E: const_cast<Expr *>(ConstraintExpr)); |
| 4681 | return Res; |
| 4682 | } |
| 4683 | |
| 4684 | ExprResult Sema::SubstInitializer(Expr *Init, |
| 4685 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4686 | bool CXXDirectInit) { |
| 4687 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
| 4688 | DeclarationName()); |
| 4689 | return Instantiator.TransformInitializer(Init, NotCopyInit: CXXDirectInit); |
| 4690 | } |
| 4691 | |
| 4692 | bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, |
| 4693 | const MultiLevelTemplateArgumentList &TemplateArgs, |
| 4694 | SmallVectorImpl<Expr *> &Outputs) { |
| 4695 | if (Exprs.empty()) |
| 4696 | return false; |
| 4697 | |
| 4698 | TemplateInstantiator Instantiator(*this, TemplateArgs, |
| 4699 | SourceLocation(), |
| 4700 | DeclarationName()); |
| 4701 | return Instantiator.TransformExprs(Inputs: Exprs.data(), NumInputs: Exprs.size(), |
| 4702 | IsCall, Outputs); |
| 4703 | } |
| 4704 | |
| 4705 | NestedNameSpecifierLoc |
| 4706 | Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, |
| 4707 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4708 | if (!NNS) |
| 4709 | return NestedNameSpecifierLoc(); |
| 4710 | |
| 4711 | TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(), |
| 4712 | DeclarationName()); |
| 4713 | return Instantiator.TransformNestedNameSpecifierLoc(NNS); |
| 4714 | } |
| 4715 | |
| 4716 | DeclarationNameInfo |
| 4717 | Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, |
| 4718 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4719 | TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(), |
| 4720 | NameInfo.getName()); |
| 4721 | return Instantiator.TransformDeclarationNameInfo(NameInfo); |
| 4722 | } |
| 4723 | |
| 4724 | TemplateName |
| 4725 | Sema::SubstTemplateName(SourceLocation TemplateKWLoc, |
| 4726 | NestedNameSpecifierLoc &QualifierLoc, TemplateName Name, |
| 4727 | SourceLocation NameLoc, |
| 4728 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
| 4729 | TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc, |
| 4730 | DeclarationName()); |
| 4731 | return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name, |
| 4732 | NameLoc); |
| 4733 | } |
| 4734 | |
| 4735 | static const Decl *getCanonicalParmVarDecl(const Decl *D) { |
| 4736 | // When storing ParmVarDecls in the local instantiation scope, we always |
| 4737 | // want to use the ParmVarDecl from the canonical function declaration, |
| 4738 | // since the map is then valid for any redeclaration or definition of that |
| 4739 | // function. |
| 4740 | if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: D)) { |
| 4741 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) { |
| 4742 | unsigned i = PV->getFunctionScopeIndex(); |
| 4743 | // This parameter might be from a freestanding function type within the |
| 4744 | // function and isn't necessarily referring to one of FD's parameters. |
| 4745 | if (i < FD->getNumParams() && FD->getParamDecl(i) == PV) |
| 4746 | return FD->getCanonicalDecl()->getParamDecl(i); |
| 4747 | } |
| 4748 | } |
| 4749 | return D; |
| 4750 | } |
| 4751 | |
| 4752 | llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> * |
| 4753 | LocalInstantiationScope::getInstantiationOfIfExists(const Decl *D) { |
| 4754 | D = getCanonicalParmVarDecl(D); |
| 4755 | for (LocalInstantiationScope *Current = this; Current; |
| 4756 | Current = Current->Outer) { |
| 4757 | |
| 4758 | // Check if we found something within this scope. |
| 4759 | const Decl *CheckD = D; |
| 4760 | do { |
| 4761 | LocalDeclsMap::iterator Found = Current->LocalDecls.find(Val: CheckD); |
| 4762 | if (Found != Current->LocalDecls.end()) |
| 4763 | return &Found->second; |
| 4764 | |
| 4765 | // If this is a tag declaration, it's possible that we need to look for |
| 4766 | // a previous declaration. |
| 4767 | if (const TagDecl *Tag = dyn_cast<TagDecl>(Val: CheckD)) |
| 4768 | CheckD = Tag->getPreviousDecl(); |
| 4769 | else |
| 4770 | CheckD = nullptr; |
| 4771 | } while (CheckD); |
| 4772 | |
| 4773 | // If we aren't combined with our outer scope, we're done. |
| 4774 | if (!Current->CombineWithOuterScope) |
| 4775 | break; |
| 4776 | } |
| 4777 | |
| 4778 | return nullptr; |
| 4779 | } |
| 4780 | |
| 4781 | llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> * |
| 4782 | LocalInstantiationScope::findInstantiationOf(const Decl *D) { |
| 4783 | auto *Result = getInstantiationOfIfExists(D); |
| 4784 | if (Result) |
| 4785 | return Result; |
| 4786 | // If we're performing a partial substitution during template argument |
| 4787 | // deduction, we may not have values for template parameters yet. |
| 4788 | if (isa<NonTypeTemplateParmDecl>(Val: D) || isa<TemplateTypeParmDecl>(Val: D) || |
| 4789 | isa<TemplateTemplateParmDecl>(Val: D)) |
| 4790 | return nullptr; |
| 4791 | |
| 4792 | // Local types referenced prior to definition may require instantiation. |
| 4793 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D)) |
| 4794 | if (RD->isLocalClass()) |
| 4795 | return nullptr; |
| 4796 | |
| 4797 | // Enumeration types referenced prior to definition may appear as a result of |
| 4798 | // error recovery. |
| 4799 | if (isa<EnumDecl>(Val: D)) |
| 4800 | return nullptr; |
| 4801 | |
| 4802 | // Materialized typedefs/type alias for implicit deduction guides may require |
| 4803 | // instantiation. |
| 4804 | if (isa<TypedefNameDecl>(Val: D) && |
| 4805 | isa<CXXDeductionGuideDecl>(Val: D->getDeclContext())) |
| 4806 | return nullptr; |
| 4807 | |
| 4808 | // If we didn't find the decl, then we either have a sema bug, or we have a |
| 4809 | // forward reference to a label declaration. Return null to indicate that |
| 4810 | // we have an uninstantiated label. |
| 4811 | assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope" ); |
| 4812 | return nullptr; |
| 4813 | } |
| 4814 | |
| 4815 | void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) { |
| 4816 | D = getCanonicalParmVarDecl(D); |
| 4817 | llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; |
| 4818 | if (Stored.isNull()) { |
| 4819 | #ifndef NDEBUG |
| 4820 | // It should not be present in any surrounding scope either. |
| 4821 | LocalInstantiationScope *Current = this; |
| 4822 | while (Current->CombineWithOuterScope && Current->Outer) { |
| 4823 | Current = Current->Outer; |
| 4824 | assert(!Current->LocalDecls.contains(D) && |
| 4825 | "Instantiated local in inner and outer scopes" ); |
| 4826 | } |
| 4827 | #endif |
| 4828 | Stored = Inst; |
| 4829 | } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: Stored)) { |
| 4830 | Pack->push_back(Elt: cast<ValueDecl>(Val: Inst)); |
| 4831 | } else { |
| 4832 | assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local" ); |
| 4833 | } |
| 4834 | } |
| 4835 | |
| 4836 | void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D, |
| 4837 | VarDecl *Inst) { |
| 4838 | D = getCanonicalParmVarDecl(D); |
| 4839 | DeclArgumentPack *Pack = cast<DeclArgumentPack *>(Val&: LocalDecls[D]); |
| 4840 | Pack->push_back(Elt: Inst); |
| 4841 | } |
| 4842 | |
| 4843 | void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) { |
| 4844 | #ifndef NDEBUG |
| 4845 | // This should be the first time we've been told about this decl. |
| 4846 | for (LocalInstantiationScope *Current = this; |
| 4847 | Current && Current->CombineWithOuterScope; Current = Current->Outer) |
| 4848 | assert(!Current->LocalDecls.contains(D) && |
| 4849 | "Creating local pack after instantiation of local" ); |
| 4850 | #endif |
| 4851 | |
| 4852 | D = getCanonicalParmVarDecl(D); |
| 4853 | llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; |
| 4854 | DeclArgumentPack *Pack = new DeclArgumentPack; |
| 4855 | Stored = Pack; |
| 4856 | ArgumentPacks.push_back(Elt: Pack); |
| 4857 | } |
| 4858 | |
| 4859 | bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) { |
| 4860 | for (DeclArgumentPack *Pack : ArgumentPacks) |
| 4861 | if (llvm::is_contained(Range&: *Pack, Element: D)) |
| 4862 | return true; |
| 4863 | return false; |
| 4864 | } |
| 4865 | |
| 4866 | void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, |
| 4867 | const TemplateArgument *ExplicitArgs, |
| 4868 | unsigned NumExplicitArgs) { |
| 4869 | assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && |
| 4870 | "Already have a partially-substituted pack" ); |
| 4871 | assert((!PartiallySubstitutedPack |
| 4872 | || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && |
| 4873 | "Wrong number of arguments in partially-substituted pack" ); |
| 4874 | PartiallySubstitutedPack = Pack; |
| 4875 | ArgsInPartiallySubstitutedPack = ExplicitArgs; |
| 4876 | NumArgsInPartiallySubstitutedPack = NumExplicitArgs; |
| 4877 | } |
| 4878 | |
| 4879 | NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack( |
| 4880 | const TemplateArgument **ExplicitArgs, |
| 4881 | unsigned *NumExplicitArgs) const { |
| 4882 | if (ExplicitArgs) |
| 4883 | *ExplicitArgs = nullptr; |
| 4884 | if (NumExplicitArgs) |
| 4885 | *NumExplicitArgs = 0; |
| 4886 | |
| 4887 | for (const LocalInstantiationScope *Current = this; Current; |
| 4888 | Current = Current->Outer) { |
| 4889 | if (Current->PartiallySubstitutedPack) { |
| 4890 | if (ExplicitArgs) |
| 4891 | *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack; |
| 4892 | if (NumExplicitArgs) |
| 4893 | *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack; |
| 4894 | |
| 4895 | return Current->PartiallySubstitutedPack; |
| 4896 | } |
| 4897 | |
| 4898 | if (!Current->CombineWithOuterScope) |
| 4899 | break; |
| 4900 | } |
| 4901 | |
| 4902 | return nullptr; |
| 4903 | } |
| 4904 | |