1 //===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements C++ template argument deduction. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Sema/TemplateDeduction.h" 14 #include "TreeTransform.h" 15 #include "TypeLocBuilder.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclAccessPair.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NestedNameSpecifier.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TemplateBase.h" 29 #include "clang/AST/TemplateName.h" 30 #include "clang/AST/Type.h" 31 #include "clang/AST/TypeLoc.h" 32 #include "clang/AST/UnresolvedSet.h" 33 #include "clang/Basic/AddressSpaces.h" 34 #include "clang/Basic/ExceptionSpecificationType.h" 35 #include "clang/Basic/LLVM.h" 36 #include "clang/Basic/LangOptions.h" 37 #include "clang/Basic/PartialDiagnostic.h" 38 #include "clang/Basic/SourceLocation.h" 39 #include "clang/Basic/Specifiers.h" 40 #include "clang/Sema/Ownership.h" 41 #include "clang/Sema/Sema.h" 42 #include "clang/Sema/Template.h" 43 #include "llvm/ADT/APInt.h" 44 #include "llvm/ADT/APSInt.h" 45 #include "llvm/ADT/ArrayRef.h" 46 #include "llvm/ADT/DenseMap.h" 47 #include "llvm/ADT/FoldingSet.h" 48 #include "llvm/ADT/Optional.h" 49 #include "llvm/ADT/SmallBitVector.h" 50 #include "llvm/ADT/SmallPtrSet.h" 51 #include "llvm/ADT/SmallVector.h" 52 #include "llvm/Support/Casting.h" 53 #include "llvm/Support/Compiler.h" 54 #include "llvm/Support/ErrorHandling.h" 55 #include <algorithm> 56 #include <cassert> 57 #include <tuple> 58 #include <utility> 59 60 namespace clang { 61 62 /// Various flags that control template argument deduction. 63 /// 64 /// These flags can be bitwise-OR'd together. 65 enum TemplateDeductionFlags { 66 /// No template argument deduction flags, which indicates the 67 /// strictest results for template argument deduction (as used for, e.g., 68 /// matching class template partial specializations). 69 TDF_None = 0, 70 71 /// Within template argument deduction from a function call, we are 72 /// matching with a parameter type for which the original parameter was 73 /// a reference. 74 TDF_ParamWithReferenceType = 0x1, 75 76 /// Within template argument deduction from a function call, we 77 /// are matching in a case where we ignore cv-qualifiers. 78 TDF_IgnoreQualifiers = 0x02, 79 80 /// Within template argument deduction from a function call, 81 /// we are matching in a case where we can perform template argument 82 /// deduction from a template-id of a derived class of the argument type. 83 TDF_DerivedClass = 0x04, 84 85 /// Allow non-dependent types to differ, e.g., when performing 86 /// template argument deduction from a function call where conversions 87 /// may apply. 88 TDF_SkipNonDependent = 0x08, 89 90 /// Whether we are performing template argument deduction for 91 /// parameters and arguments in a top-level template argument 92 TDF_TopLevelParameterTypeList = 0x10, 93 94 /// Within template argument deduction from overload resolution per 95 /// C++ [over.over] allow matching function types that are compatible in 96 /// terms of noreturn and default calling convention adjustments, or 97 /// similarly matching a declared template specialization against a 98 /// possible template, per C++ [temp.deduct.decl]. In either case, permit 99 /// deduction where the parameter is a function type that can be converted 100 /// to the argument type. 101 TDF_AllowCompatibleFunctionType = 0x20, 102 103 /// Within template argument deduction for a conversion function, we are 104 /// matching with an argument type for which the original argument was 105 /// a reference. 106 TDF_ArgWithReferenceType = 0x40, 107 }; 108 } 109 110 using namespace clang; 111 using namespace sema; 112 113 /// Compare two APSInts, extending and switching the sign as 114 /// necessary to compare their values regardless of underlying type. 115 static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) { 116 if (Y.getBitWidth() > X.getBitWidth()) 117 X = X.extend(Y.getBitWidth()); 118 else if (Y.getBitWidth() < X.getBitWidth()) 119 Y = Y.extend(X.getBitWidth()); 120 121 // If there is a signedness mismatch, correct it. 122 if (X.isSigned() != Y.isSigned()) { 123 // If the signed value is negative, then the values cannot be the same. 124 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative())) 125 return false; 126 127 Y.setIsSigned(true); 128 X.setIsSigned(true); 129 } 130 131 return X == Y; 132 } 133 134 static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch( 135 Sema &S, TemplateParameterList *TemplateParams, QualType Param, 136 QualType Arg, TemplateDeductionInfo &Info, 137 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF, 138 bool PartialOrdering = false, bool DeducedFromArrayBound = false); 139 140 static Sema::TemplateDeductionResult 141 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, 142 ArrayRef<TemplateArgument> Ps, 143 ArrayRef<TemplateArgument> As, 144 TemplateDeductionInfo &Info, 145 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 146 bool NumberOfArgumentsMustMatch); 147 148 static void MarkUsedTemplateParameters(ASTContext &Ctx, 149 const TemplateArgument &TemplateArg, 150 bool OnlyDeduced, unsigned Depth, 151 llvm::SmallBitVector &Used); 152 153 static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 154 bool OnlyDeduced, unsigned Level, 155 llvm::SmallBitVector &Deduced); 156 157 /// If the given expression is of a form that permits the deduction 158 /// of a non-type template parameter, return the declaration of that 159 /// non-type template parameter. 160 static const NonTypeTemplateParmDecl * 161 getDeducedParameterFromExpr(const Expr *E, unsigned Depth) { 162 // If we are within an alias template, the expression may have undergone 163 // any number of parameter substitutions already. 164 while (true) { 165 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E)) 166 E = IC->getSubExpr(); 167 else if (const auto *CE = dyn_cast<ConstantExpr>(E)) 168 E = CE->getSubExpr(); 169 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) 170 E = Subst->getReplacement(); 171 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) { 172 // Look through implicit copy construction from an lvalue of the same type. 173 if (CCE->getParenOrBraceRange().isValid()) 174 break; 175 // Note, there could be default arguments. 176 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg"); 177 E = CCE->getArg(0); 178 } else 179 break; 180 } 181 182 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 183 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) 184 if (NTTP->getDepth() == Depth) 185 return NTTP; 186 187 return nullptr; 188 } 189 190 static const NonTypeTemplateParmDecl * 191 getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) { 192 return getDeducedParameterFromExpr(E, Info.getDeducedDepth()); 193 } 194 195 /// Determine whether two declaration pointers refer to the same 196 /// declaration. 197 static bool isSameDeclaration(Decl *X, Decl *Y) { 198 if (NamedDecl *NX = dyn_cast<NamedDecl>(X)) 199 X = NX->getUnderlyingDecl(); 200 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y)) 201 Y = NY->getUnderlyingDecl(); 202 203 return X->getCanonicalDecl() == Y->getCanonicalDecl(); 204 } 205 206 /// Verify that the given, deduced template arguments are compatible. 207 /// 208 /// \returns The deduced template argument, or a NULL template argument if 209 /// the deduced template arguments were incompatible. 210 static DeducedTemplateArgument 211 checkDeducedTemplateArguments(ASTContext &Context, 212 const DeducedTemplateArgument &X, 213 const DeducedTemplateArgument &Y) { 214 // We have no deduction for one or both of the arguments; they're compatible. 215 if (X.isNull()) 216 return Y; 217 if (Y.isNull()) 218 return X; 219 220 // If we have two non-type template argument values deduced for the same 221 // parameter, they must both match the type of the parameter, and thus must 222 // match each other's type. As we're only keeping one of them, we must check 223 // for that now. The exception is that if either was deduced from an array 224 // bound, the type is permitted to differ. 225 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) { 226 QualType XType = X.getNonTypeTemplateArgumentType(); 227 if (!XType.isNull()) { 228 QualType YType = Y.getNonTypeTemplateArgumentType(); 229 if (YType.isNull() || !Context.hasSameType(XType, YType)) 230 return DeducedTemplateArgument(); 231 } 232 } 233 234 switch (X.getKind()) { 235 case TemplateArgument::Null: 236 llvm_unreachable("Non-deduced template arguments handled above"); 237 238 case TemplateArgument::Type: 239 // If two template type arguments have the same type, they're compatible. 240 if (Y.getKind() == TemplateArgument::Type && 241 Context.hasSameType(X.getAsType(), Y.getAsType())) 242 return X; 243 244 // If one of the two arguments was deduced from an array bound, the other 245 // supersedes it. 246 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound()) 247 return X.wasDeducedFromArrayBound() ? Y : X; 248 249 // The arguments are not compatible. 250 return DeducedTemplateArgument(); 251 252 case TemplateArgument::Integral: 253 // If we deduced a constant in one case and either a dependent expression or 254 // declaration in another case, keep the integral constant. 255 // If both are integral constants with the same value, keep that value. 256 if (Y.getKind() == TemplateArgument::Expression || 257 Y.getKind() == TemplateArgument::Declaration || 258 (Y.getKind() == TemplateArgument::Integral && 259 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral()))) 260 return X.wasDeducedFromArrayBound() ? Y : X; 261 262 // All other combinations are incompatible. 263 return DeducedTemplateArgument(); 264 265 case TemplateArgument::Template: 266 if (Y.getKind() == TemplateArgument::Template && 267 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate())) 268 return X; 269 270 // All other combinations are incompatible. 271 return DeducedTemplateArgument(); 272 273 case TemplateArgument::TemplateExpansion: 274 if (Y.getKind() == TemplateArgument::TemplateExpansion && 275 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(), 276 Y.getAsTemplateOrTemplatePattern())) 277 return X; 278 279 // All other combinations are incompatible. 280 return DeducedTemplateArgument(); 281 282 case TemplateArgument::Expression: { 283 if (Y.getKind() != TemplateArgument::Expression) 284 return checkDeducedTemplateArguments(Context, Y, X); 285 286 // Compare the expressions for equality 287 llvm::FoldingSetNodeID ID1, ID2; 288 X.getAsExpr()->Profile(ID1, Context, true); 289 Y.getAsExpr()->Profile(ID2, Context, true); 290 if (ID1 == ID2) 291 return X.wasDeducedFromArrayBound() ? Y : X; 292 293 // Differing dependent expressions are incompatible. 294 return DeducedTemplateArgument(); 295 } 296 297 case TemplateArgument::Declaration: 298 assert(!X.wasDeducedFromArrayBound()); 299 300 // If we deduced a declaration and a dependent expression, keep the 301 // declaration. 302 if (Y.getKind() == TemplateArgument::Expression) 303 return X; 304 305 // If we deduced a declaration and an integral constant, keep the 306 // integral constant and whichever type did not come from an array 307 // bound. 308 if (Y.getKind() == TemplateArgument::Integral) { 309 if (Y.wasDeducedFromArrayBound()) 310 return TemplateArgument(Context, Y.getAsIntegral(), 311 X.getParamTypeForDecl()); 312 return Y; 313 } 314 315 // If we deduced two declarations, make sure that they refer to the 316 // same declaration. 317 if (Y.getKind() == TemplateArgument::Declaration && 318 isSameDeclaration(X.getAsDecl(), Y.getAsDecl())) 319 return X; 320 321 // All other combinations are incompatible. 322 return DeducedTemplateArgument(); 323 324 case TemplateArgument::NullPtr: 325 // If we deduced a null pointer and a dependent expression, keep the 326 // null pointer. 327 if (Y.getKind() == TemplateArgument::Expression) 328 return X; 329 330 // If we deduced a null pointer and an integral constant, keep the 331 // integral constant. 332 if (Y.getKind() == TemplateArgument::Integral) 333 return Y; 334 335 // If we deduced two null pointers, they are the same. 336 if (Y.getKind() == TemplateArgument::NullPtr) 337 return X; 338 339 // All other combinations are incompatible. 340 return DeducedTemplateArgument(); 341 342 case TemplateArgument::Pack: { 343 if (Y.getKind() != TemplateArgument::Pack || 344 X.pack_size() != Y.pack_size()) 345 return DeducedTemplateArgument(); 346 347 llvm::SmallVector<TemplateArgument, 8> NewPack; 348 for (TemplateArgument::pack_iterator XA = X.pack_begin(), 349 XAEnd = X.pack_end(), 350 YA = Y.pack_begin(); 351 XA != XAEnd; ++XA, ++YA) { 352 TemplateArgument Merged = checkDeducedTemplateArguments( 353 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()), 354 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound())); 355 if (Merged.isNull() && !(XA->isNull() && YA->isNull())) 356 return DeducedTemplateArgument(); 357 NewPack.push_back(Merged); 358 } 359 360 return DeducedTemplateArgument( 361 TemplateArgument::CreatePackCopy(Context, NewPack), 362 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound()); 363 } 364 } 365 366 llvm_unreachable("Invalid TemplateArgument Kind!"); 367 } 368 369 /// Deduce the value of the given non-type template parameter 370 /// as the given deduced template argument. All non-type template parameter 371 /// deduction is funneled through here. 372 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument( 373 Sema &S, TemplateParameterList *TemplateParams, 374 const NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced, 375 QualType ValueType, TemplateDeductionInfo &Info, 376 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 377 assert(NTTP->getDepth() == Info.getDeducedDepth() && 378 "deducing non-type template argument with wrong depth"); 379 380 DeducedTemplateArgument Result = checkDeducedTemplateArguments( 381 S.Context, Deduced[NTTP->getIndex()], NewDeduced); 382 if (Result.isNull()) { 383 Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP); 384 Info.FirstArg = Deduced[NTTP->getIndex()]; 385 Info.SecondArg = NewDeduced; 386 return Sema::TDK_Inconsistent; 387 } 388 389 Deduced[NTTP->getIndex()] = Result; 390 if (!S.getLangOpts().CPlusPlus17) 391 return Sema::TDK_Success; 392 393 if (NTTP->isExpandedParameterPack()) 394 // FIXME: We may still need to deduce parts of the type here! But we 395 // don't have any way to find which slice of the type to use, and the 396 // type stored on the NTTP itself is nonsense. Perhaps the type of an 397 // expanded NTTP should be a pack expansion type? 398 return Sema::TDK_Success; 399 400 // Get the type of the parameter for deduction. If it's a (dependent) array 401 // or function type, we will not have decayed it yet, so do that now. 402 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType()); 403 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType)) 404 ParamType = Expansion->getPattern(); 405 406 // FIXME: It's not clear how deduction of a parameter of reference 407 // type from an argument (of non-reference type) should be performed. 408 // For now, we just remove reference types from both sides and let 409 // the final check for matching types sort out the mess. 410 ValueType = ValueType.getNonReferenceType(); 411 if (ParamType->isReferenceType()) 412 ParamType = ParamType.getNonReferenceType(); 413 else 414 // Top-level cv-qualifiers are irrelevant for a non-reference type. 415 ValueType = ValueType.getUnqualifiedType(); 416 417 return DeduceTemplateArgumentsByTypeMatch( 418 S, TemplateParams, ParamType, ValueType, Info, Deduced, 419 TDF_SkipNonDependent, /*PartialOrdering=*/false, 420 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound()); 421 } 422 423 /// Deduce the value of the given non-type template parameter 424 /// from the given integral constant. 425 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument( 426 Sema &S, TemplateParameterList *TemplateParams, 427 const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value, 428 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info, 429 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 430 return DeduceNonTypeTemplateArgument( 431 S, TemplateParams, NTTP, 432 DeducedTemplateArgument(S.Context, Value, ValueType, 433 DeducedFromArrayBound), 434 ValueType, Info, Deduced); 435 } 436 437 /// Deduce the value of the given non-type template parameter 438 /// from the given null pointer template argument type. 439 static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument( 440 Sema &S, TemplateParameterList *TemplateParams, 441 const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType, 442 TemplateDeductionInfo &Info, 443 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 444 Expr *Value = S.ImpCastExprToType( 445 new (S.Context) CXXNullPtrLiteralExpr(S.Context.NullPtrTy, 446 NTTP->getLocation()), 447 NullPtrType, 448 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer 449 : CK_NullToPointer) 450 .get(); 451 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 452 DeducedTemplateArgument(Value), 453 Value->getType(), Info, Deduced); 454 } 455 456 /// Deduce the value of the given non-type template parameter 457 /// from the given type- or value-dependent expression. 458 /// 459 /// \returns true if deduction succeeded, false otherwise. 460 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument( 461 Sema &S, TemplateParameterList *TemplateParams, 462 const NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info, 463 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 464 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 465 DeducedTemplateArgument(Value), 466 Value->getType(), Info, Deduced); 467 } 468 469 /// Deduce the value of the given non-type template parameter 470 /// from the given declaration. 471 /// 472 /// \returns true if deduction succeeded, false otherwise. 473 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument( 474 Sema &S, TemplateParameterList *TemplateParams, 475 const NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T, 476 TemplateDeductionInfo &Info, 477 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 478 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr; 479 TemplateArgument New(D, T); 480 return DeduceNonTypeTemplateArgument( 481 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced); 482 } 483 484 static Sema::TemplateDeductionResult 485 DeduceTemplateArguments(Sema &S, 486 TemplateParameterList *TemplateParams, 487 TemplateName Param, 488 TemplateName Arg, 489 TemplateDeductionInfo &Info, 490 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 491 TemplateDecl *ParamDecl = Param.getAsTemplateDecl(); 492 if (!ParamDecl) { 493 // The parameter type is dependent and is not a template template parameter, 494 // so there is nothing that we can deduce. 495 return Sema::TDK_Success; 496 } 497 498 if (TemplateTemplateParmDecl *TempParam 499 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) { 500 // If we're not deducing at this depth, there's nothing to deduce. 501 if (TempParam->getDepth() != Info.getDeducedDepth()) 502 return Sema::TDK_Success; 503 504 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg)); 505 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 506 Deduced[TempParam->getIndex()], 507 NewDeduced); 508 if (Result.isNull()) { 509 Info.Param = TempParam; 510 Info.FirstArg = Deduced[TempParam->getIndex()]; 511 Info.SecondArg = NewDeduced; 512 return Sema::TDK_Inconsistent; 513 } 514 515 Deduced[TempParam->getIndex()] = Result; 516 return Sema::TDK_Success; 517 } 518 519 // Verify that the two template names are equivalent. 520 if (S.Context.hasSameTemplateName(Param, Arg)) 521 return Sema::TDK_Success; 522 523 // Mismatch of non-dependent template parameter to argument. 524 Info.FirstArg = TemplateArgument(Param); 525 Info.SecondArg = TemplateArgument(Arg); 526 return Sema::TDK_NonDeducedMismatch; 527 } 528 529 /// Deduce the template arguments by comparing the template parameter 530 /// type (which is a template-id) with the template argument type. 531 /// 532 /// \param S the Sema 533 /// 534 /// \param TemplateParams the template parameters that we are deducing 535 /// 536 /// \param P the parameter type 537 /// 538 /// \param A the argument type 539 /// 540 /// \param Info information about the template argument deduction itself 541 /// 542 /// \param Deduced the deduced template arguments 543 /// 544 /// \returns the result of template argument deduction so far. Note that a 545 /// "success" result means that template argument deduction has not yet failed, 546 /// but it may still fail, later, for other reasons. 547 static Sema::TemplateDeductionResult 548 DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams, 549 const QualType P, QualType A, 550 TemplateDeductionInfo &Info, 551 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 552 QualType UP = P; 553 if (const auto *IP = P->getAs<InjectedClassNameType>()) 554 UP = IP->getInjectedSpecializationType(); 555 // FIXME: Try to preserve type sugar here, which is hard 556 // because of the unresolved template arguments. 557 const auto *TP = UP.getCanonicalType()->castAs<TemplateSpecializationType>(); 558 ArrayRef<TemplateArgument> PResolved = TP->template_arguments(); 559 560 QualType UA = A; 561 // Treat an injected-class-name as its underlying template-id. 562 if (const auto *Injected = A->getAs<InjectedClassNameType>()) 563 UA = Injected->getInjectedSpecializationType(); 564 565 // Check whether the template argument is a dependent template-id. 566 // FIXME: Should not lose sugar here. 567 if (const auto *SA = 568 dyn_cast<TemplateSpecializationType>(UA.getCanonicalType())) { 569 // Perform template argument deduction for the template name. 570 if (auto Result = 571 DeduceTemplateArguments(S, TemplateParams, TP->getTemplateName(), 572 SA->getTemplateName(), Info, Deduced)) 573 return Result; 574 // Perform template argument deduction on each template 575 // argument. Ignore any missing/extra arguments, since they could be 576 // filled in by default arguments. 577 return DeduceTemplateArguments(S, TemplateParams, PResolved, 578 SA->template_arguments(), Info, Deduced, 579 /*NumberOfArgumentsMustMatch=*/false); 580 } 581 582 // If the argument type is a class template specialization, we 583 // perform template argument deduction using its template 584 // arguments. 585 const auto *RA = UA->getAs<RecordType>(); 586 const auto *SA = 587 RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr; 588 if (!SA) { 589 Info.FirstArg = TemplateArgument(P); 590 Info.SecondArg = TemplateArgument(A); 591 return Sema::TDK_NonDeducedMismatch; 592 } 593 594 // Perform template argument deduction for the template name. 595 if (auto Result = DeduceTemplateArguments( 596 S, TemplateParams, TP->getTemplateName(), 597 TemplateName(SA->getSpecializedTemplate()), Info, Deduced)) 598 return Result; 599 600 // Perform template argument deduction for the template arguments. 601 return DeduceTemplateArguments(S, TemplateParams, PResolved, 602 SA->getTemplateArgs().asArray(), Info, Deduced, 603 /*NumberOfArgumentsMustMatch=*/true); 604 } 605 606 static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T) { 607 assert(T->isCanonicalUnqualified()); 608 609 switch (T->getTypeClass()) { 610 case Type::TypeOfExpr: 611 case Type::TypeOf: 612 case Type::DependentName: 613 case Type::Decltype: 614 case Type::UnresolvedUsing: 615 case Type::TemplateTypeParm: 616 return true; 617 618 case Type::ConstantArray: 619 case Type::IncompleteArray: 620 case Type::VariableArray: 621 case Type::DependentSizedArray: 622 return IsPossiblyOpaquelyQualifiedTypeInternal( 623 cast<ArrayType>(T)->getElementType().getTypePtr()); 624 625 default: 626 return false; 627 } 628 } 629 630 /// Determines whether the given type is an opaque type that 631 /// might be more qualified when instantiated. 632 static bool IsPossiblyOpaquelyQualifiedType(QualType T) { 633 return IsPossiblyOpaquelyQualifiedTypeInternal( 634 T->getCanonicalTypeInternal().getTypePtr()); 635 } 636 637 /// Helper function to build a TemplateParameter when we don't 638 /// know its type statically. 639 static TemplateParameter makeTemplateParameter(Decl *D) { 640 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D)) 641 return TemplateParameter(TTP); 642 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) 643 return TemplateParameter(NTTP); 644 645 return TemplateParameter(cast<TemplateTemplateParmDecl>(D)); 646 } 647 648 /// A pack that we're currently deducing. 649 struct clang::DeducedPack { 650 // The index of the pack. 651 unsigned Index; 652 653 // The old value of the pack before we started deducing it. 654 DeducedTemplateArgument Saved; 655 656 // A deferred value of this pack from an inner deduction, that couldn't be 657 // deduced because this deduction hadn't happened yet. 658 DeducedTemplateArgument DeferredDeduction; 659 660 // The new value of the pack. 661 SmallVector<DeducedTemplateArgument, 4> New; 662 663 // The outer deduction for this pack, if any. 664 DeducedPack *Outer = nullptr; 665 666 DeducedPack(unsigned Index) : Index(Index) {} 667 }; 668 669 namespace { 670 671 /// A scope in which we're performing pack deduction. 672 class PackDeductionScope { 673 public: 674 /// Prepare to deduce the packs named within Pattern. 675 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams, 676 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 677 TemplateDeductionInfo &Info, TemplateArgument Pattern) 678 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) { 679 unsigned NumNamedPacks = addPacks(Pattern); 680 finishConstruction(NumNamedPacks); 681 } 682 683 /// Prepare to directly deduce arguments of the parameter with index \p Index. 684 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams, 685 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 686 TemplateDeductionInfo &Info, unsigned Index) 687 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) { 688 addPack(Index); 689 finishConstruction(1); 690 } 691 692 private: 693 void addPack(unsigned Index) { 694 // Save the deduced template argument for the parameter pack expanded 695 // by this pack expansion, then clear out the deduction. 696 DeducedPack Pack(Index); 697 Pack.Saved = Deduced[Index]; 698 Deduced[Index] = TemplateArgument(); 699 700 // FIXME: What if we encounter multiple packs with different numbers of 701 // pre-expanded expansions? (This should already have been diagnosed 702 // during substitution.) 703 if (Optional<unsigned> ExpandedPackExpansions = 704 getExpandedPackSize(TemplateParams->getParam(Index))) 705 FixedNumExpansions = ExpandedPackExpansions; 706 707 Packs.push_back(Pack); 708 } 709 710 unsigned addPacks(TemplateArgument Pattern) { 711 // Compute the set of template parameter indices that correspond to 712 // parameter packs expanded by the pack expansion. 713 llvm::SmallBitVector SawIndices(TemplateParams->size()); 714 llvm::SmallVector<TemplateArgument, 4> ExtraDeductions; 715 716 auto AddPack = [&](unsigned Index) { 717 if (SawIndices[Index]) 718 return; 719 SawIndices[Index] = true; 720 addPack(Index); 721 722 // Deducing a parameter pack that is a pack expansion also constrains the 723 // packs appearing in that parameter to have the same deduced arity. Also, 724 // in C++17 onwards, deducing a non-type template parameter deduces its 725 // type, so we need to collect the pending deduced values for those packs. 726 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>( 727 TemplateParams->getParam(Index))) { 728 if (!NTTP->isExpandedParameterPack()) 729 if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType())) 730 ExtraDeductions.push_back(Expansion->getPattern()); 731 } 732 // FIXME: Also collect the unexpanded packs in any type and template 733 // parameter packs that are pack expansions. 734 }; 735 736 auto Collect = [&](TemplateArgument Pattern) { 737 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 738 S.collectUnexpandedParameterPacks(Pattern, Unexpanded); 739 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 740 unsigned Depth, Index; 741 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]); 742 if (Depth == Info.getDeducedDepth()) 743 AddPack(Index); 744 } 745 }; 746 747 // Look for unexpanded packs in the pattern. 748 Collect(Pattern); 749 assert(!Packs.empty() && "Pack expansion without unexpanded packs?"); 750 751 unsigned NumNamedPacks = Packs.size(); 752 753 // Also look for unexpanded packs that are indirectly deduced by deducing 754 // the sizes of the packs in this pattern. 755 while (!ExtraDeductions.empty()) 756 Collect(ExtraDeductions.pop_back_val()); 757 758 return NumNamedPacks; 759 } 760 761 void finishConstruction(unsigned NumNamedPacks) { 762 // Dig out the partially-substituted pack, if there is one. 763 const TemplateArgument *PartialPackArgs = nullptr; 764 unsigned NumPartialPackArgs = 0; 765 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u); 766 if (auto *Scope = S.CurrentInstantiationScope) 767 if (auto *Partial = Scope->getPartiallySubstitutedPack( 768 &PartialPackArgs, &NumPartialPackArgs)) 769 PartialPackDepthIndex = getDepthAndIndex(Partial); 770 771 // This pack expansion will have been partially or fully expanded if 772 // it only names explicitly-specified parameter packs (including the 773 // partially-substituted one, if any). 774 bool IsExpanded = true; 775 for (unsigned I = 0; I != NumNamedPacks; ++I) { 776 if (Packs[I].Index >= Info.getNumExplicitArgs()) { 777 IsExpanded = false; 778 IsPartiallyExpanded = false; 779 break; 780 } 781 if (PartialPackDepthIndex == 782 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) { 783 IsPartiallyExpanded = true; 784 } 785 } 786 787 // Skip over the pack elements that were expanded into separate arguments. 788 // If we partially expanded, this is the number of partial arguments. 789 if (IsPartiallyExpanded) 790 PackElements += NumPartialPackArgs; 791 else if (IsExpanded) 792 PackElements += *FixedNumExpansions; 793 794 for (auto &Pack : Packs) { 795 if (Info.PendingDeducedPacks.size() > Pack.Index) 796 Pack.Outer = Info.PendingDeducedPacks[Pack.Index]; 797 else 798 Info.PendingDeducedPacks.resize(Pack.Index + 1); 799 Info.PendingDeducedPacks[Pack.Index] = &Pack; 800 801 if (PartialPackDepthIndex == 802 std::make_pair(Info.getDeducedDepth(), Pack.Index)) { 803 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs); 804 // We pre-populate the deduced value of the partially-substituted 805 // pack with the specified value. This is not entirely correct: the 806 // value is supposed to have been substituted, not deduced, but the 807 // cases where this is observable require an exact type match anyway. 808 // 809 // FIXME: If we could represent a "depth i, index j, pack elem k" 810 // parameter, we could substitute the partially-substituted pack 811 // everywhere and avoid this. 812 if (!IsPartiallyExpanded) 813 Deduced[Pack.Index] = Pack.New[PackElements]; 814 } 815 } 816 } 817 818 public: 819 ~PackDeductionScope() { 820 for (auto &Pack : Packs) 821 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer; 822 } 823 824 /// Determine whether this pack has already been partially expanded into a 825 /// sequence of (prior) function parameters / template arguments. 826 bool isPartiallyExpanded() { return IsPartiallyExpanded; } 827 828 /// Determine whether this pack expansion scope has a known, fixed arity. 829 /// This happens if it involves a pack from an outer template that has 830 /// (notionally) already been expanded. 831 bool hasFixedArity() { return FixedNumExpansions.has_value(); } 832 833 /// Determine whether the next element of the argument is still part of this 834 /// pack. This is the case unless the pack is already expanded to a fixed 835 /// length. 836 bool hasNextElement() { 837 return !FixedNumExpansions || *FixedNumExpansions > PackElements; 838 } 839 840 /// Move to deducing the next element in each pack that is being deduced. 841 void nextPackElement() { 842 // Capture the deduced template arguments for each parameter pack expanded 843 // by this pack expansion, add them to the list of arguments we've deduced 844 // for that pack, then clear out the deduced argument. 845 for (auto &Pack : Packs) { 846 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index]; 847 if (!Pack.New.empty() || !DeducedArg.isNull()) { 848 while (Pack.New.size() < PackElements) 849 Pack.New.push_back(DeducedTemplateArgument()); 850 if (Pack.New.size() == PackElements) 851 Pack.New.push_back(DeducedArg); 852 else 853 Pack.New[PackElements] = DeducedArg; 854 DeducedArg = Pack.New.size() > PackElements + 1 855 ? Pack.New[PackElements + 1] 856 : DeducedTemplateArgument(); 857 } 858 } 859 ++PackElements; 860 } 861 862 /// Finish template argument deduction for a set of argument packs, 863 /// producing the argument packs and checking for consistency with prior 864 /// deductions. 865 Sema::TemplateDeductionResult finish() { 866 // Build argument packs for each of the parameter packs expanded by this 867 // pack expansion. 868 for (auto &Pack : Packs) { 869 // Put back the old value for this pack. 870 Deduced[Pack.Index] = Pack.Saved; 871 872 // Always make sure the size of this pack is correct, even if we didn't 873 // deduce any values for it. 874 // 875 // FIXME: This isn't required by the normative wording, but substitution 876 // and post-substitution checking will always fail if the arity of any 877 // pack is not equal to the number of elements we processed. (Either that 878 // or something else has gone *very* wrong.) We're permitted to skip any 879 // hard errors from those follow-on steps by the intent (but not the 880 // wording) of C++ [temp.inst]p8: 881 // 882 // If the function selected by overload resolution can be determined 883 // without instantiating a class template definition, it is unspecified 884 // whether that instantiation actually takes place 885 Pack.New.resize(PackElements); 886 887 // Build or find a new value for this pack. 888 DeducedTemplateArgument NewPack; 889 if (Pack.New.empty()) { 890 // If we deduced an empty argument pack, create it now. 891 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack()); 892 } else { 893 TemplateArgument *ArgumentPack = 894 new (S.Context) TemplateArgument[Pack.New.size()]; 895 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack); 896 NewPack = DeducedTemplateArgument( 897 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())), 898 // FIXME: This is wrong, it's possible that some pack elements are 899 // deduced from an array bound and others are not: 900 // template<typename ...T, T ...V> void g(const T (&...p)[V]); 901 // g({1, 2, 3}, {{}, {}}); 902 // ... should deduce T = {int, size_t (from array bound)}. 903 Pack.New[0].wasDeducedFromArrayBound()); 904 } 905 906 // Pick where we're going to put the merged pack. 907 DeducedTemplateArgument *Loc; 908 if (Pack.Outer) { 909 if (Pack.Outer->DeferredDeduction.isNull()) { 910 // Defer checking this pack until we have a complete pack to compare 911 // it against. 912 Pack.Outer->DeferredDeduction = NewPack; 913 continue; 914 } 915 Loc = &Pack.Outer->DeferredDeduction; 916 } else { 917 Loc = &Deduced[Pack.Index]; 918 } 919 920 // Check the new pack matches any previous value. 921 DeducedTemplateArgument OldPack = *Loc; 922 DeducedTemplateArgument Result = 923 checkDeducedTemplateArguments(S.Context, OldPack, NewPack); 924 925 // If we deferred a deduction of this pack, check that one now too. 926 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) { 927 OldPack = Result; 928 NewPack = Pack.DeferredDeduction; 929 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack); 930 } 931 932 NamedDecl *Param = TemplateParams->getParam(Pack.Index); 933 if (Result.isNull()) { 934 Info.Param = makeTemplateParameter(Param); 935 Info.FirstArg = OldPack; 936 Info.SecondArg = NewPack; 937 return Sema::TDK_Inconsistent; 938 } 939 940 // If we have a pre-expanded pack and we didn't deduce enough elements 941 // for it, fail deduction. 942 if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) { 943 if (*Expansions != PackElements) { 944 Info.Param = makeTemplateParameter(Param); 945 Info.FirstArg = Result; 946 return Sema::TDK_IncompletePack; 947 } 948 } 949 950 *Loc = Result; 951 } 952 953 return Sema::TDK_Success; 954 } 955 956 private: 957 Sema &S; 958 TemplateParameterList *TemplateParams; 959 SmallVectorImpl<DeducedTemplateArgument> &Deduced; 960 TemplateDeductionInfo &Info; 961 unsigned PackElements = 0; 962 bool IsPartiallyExpanded = false; 963 /// The number of expansions, if we have a fully-expanded pack in this scope. 964 Optional<unsigned> FixedNumExpansions; 965 966 SmallVector<DeducedPack, 2> Packs; 967 }; 968 969 } // namespace 970 971 /// Deduce the template arguments by comparing the list of parameter 972 /// types to the list of argument types, as in the parameter-type-lists of 973 /// function types (C++ [temp.deduct.type]p10). 974 /// 975 /// \param S The semantic analysis object within which we are deducing 976 /// 977 /// \param TemplateParams The template parameters that we are deducing 978 /// 979 /// \param Params The list of parameter types 980 /// 981 /// \param NumParams The number of types in \c Params 982 /// 983 /// \param Args The list of argument types 984 /// 985 /// \param NumArgs The number of types in \c Args 986 /// 987 /// \param Info information about the template argument deduction itself 988 /// 989 /// \param Deduced the deduced template arguments 990 /// 991 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 992 /// how template argument deduction is performed. 993 /// 994 /// \param PartialOrdering If true, we are performing template argument 995 /// deduction for during partial ordering for a call 996 /// (C++0x [temp.deduct.partial]). 997 /// 998 /// \returns the result of template argument deduction so far. Note that a 999 /// "success" result means that template argument deduction has not yet failed, 1000 /// but it may still fail, later, for other reasons. 1001 static Sema::TemplateDeductionResult 1002 DeduceTemplateArguments(Sema &S, 1003 TemplateParameterList *TemplateParams, 1004 const QualType *Params, unsigned NumParams, 1005 const QualType *Args, unsigned NumArgs, 1006 TemplateDeductionInfo &Info, 1007 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 1008 unsigned TDF, 1009 bool PartialOrdering = false) { 1010 // C++0x [temp.deduct.type]p10: 1011 // Similarly, if P has a form that contains (T), then each parameter type 1012 // Pi of the respective parameter-type- list of P is compared with the 1013 // corresponding parameter type Ai of the corresponding parameter-type-list 1014 // of A. [...] 1015 unsigned ArgIdx = 0, ParamIdx = 0; 1016 for (; ParamIdx != NumParams; ++ParamIdx) { 1017 // Check argument types. 1018 const PackExpansionType *Expansion 1019 = dyn_cast<PackExpansionType>(Params[ParamIdx]); 1020 if (!Expansion) { 1021 // Simple case: compare the parameter and argument types at this point. 1022 1023 // Make sure we have an argument. 1024 if (ArgIdx >= NumArgs) 1025 return Sema::TDK_MiscellaneousDeductionFailure; 1026 1027 if (isa<PackExpansionType>(Args[ArgIdx])) { 1028 // C++0x [temp.deduct.type]p22: 1029 // If the original function parameter associated with A is a function 1030 // parameter pack and the function parameter associated with P is not 1031 // a function parameter pack, then template argument deduction fails. 1032 return Sema::TDK_MiscellaneousDeductionFailure; 1033 } 1034 1035 if (Sema::TemplateDeductionResult Result = 1036 DeduceTemplateArgumentsByTypeMatch( 1037 S, TemplateParams, Params[ParamIdx].getUnqualifiedType(), 1038 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF, 1039 PartialOrdering, 1040 /*DeducedFromArrayBound=*/false)) 1041 return Result; 1042 1043 ++ArgIdx; 1044 continue; 1045 } 1046 1047 // C++0x [temp.deduct.type]p10: 1048 // If the parameter-declaration corresponding to Pi is a function 1049 // parameter pack, then the type of its declarator- id is compared with 1050 // each remaining parameter type in the parameter-type-list of A. Each 1051 // comparison deduces template arguments for subsequent positions in the 1052 // template parameter packs expanded by the function parameter pack. 1053 1054 QualType Pattern = Expansion->getPattern(); 1055 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern); 1056 1057 // A pack scope with fixed arity is not really a pack any more, so is not 1058 // a non-deduced context. 1059 if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) { 1060 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) { 1061 // Deduce template arguments from the pattern. 1062 if (Sema::TemplateDeductionResult Result = 1063 DeduceTemplateArgumentsByTypeMatch( 1064 S, TemplateParams, Pattern.getUnqualifiedType(), 1065 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF, 1066 PartialOrdering, /*DeducedFromArrayBound=*/false)) 1067 return Result; 1068 1069 PackScope.nextPackElement(); 1070 } 1071 } else { 1072 // C++0x [temp.deduct.type]p5: 1073 // The non-deduced contexts are: 1074 // - A function parameter pack that does not occur at the end of the 1075 // parameter-declaration-clause. 1076 // 1077 // FIXME: There is no wording to say what we should do in this case. We 1078 // choose to resolve this by applying the same rule that is applied for a 1079 // function call: that is, deduce all contained packs to their 1080 // explicitly-specified values (or to <> if there is no such value). 1081 // 1082 // This is seemingly-arbitrarily different from the case of a template-id 1083 // with a non-trailing pack-expansion in its arguments, which renders the 1084 // entire template-argument-list a non-deduced context. 1085 1086 // If the parameter type contains an explicitly-specified pack that we 1087 // could not expand, skip the number of parameters notionally created 1088 // by the expansion. 1089 Optional<unsigned> NumExpansions = Expansion->getNumExpansions(); 1090 if (NumExpansions && !PackScope.isPartiallyExpanded()) { 1091 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs; 1092 ++I, ++ArgIdx) 1093 PackScope.nextPackElement(); 1094 } 1095 } 1096 1097 // Build argument packs for each of the parameter packs expanded by this 1098 // pack expansion. 1099 if (auto Result = PackScope.finish()) 1100 return Result; 1101 } 1102 1103 // Make sure we don't have any extra arguments. 1104 if (ArgIdx < NumArgs) 1105 return Sema::TDK_MiscellaneousDeductionFailure; 1106 1107 return Sema::TDK_Success; 1108 } 1109 1110 /// Determine whether the parameter has qualifiers that the argument 1111 /// lacks. Put another way, determine whether there is no way to add 1112 /// a deduced set of qualifiers to the ParamType that would result in 1113 /// its qualifiers matching those of the ArgType. 1114 static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, 1115 QualType ArgType) { 1116 Qualifiers ParamQs = ParamType.getQualifiers(); 1117 Qualifiers ArgQs = ArgType.getQualifiers(); 1118 1119 if (ParamQs == ArgQs) 1120 return false; 1121 1122 // Mismatched (but not missing) Objective-C GC attributes. 1123 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() && 1124 ParamQs.hasObjCGCAttr()) 1125 return true; 1126 1127 // Mismatched (but not missing) address spaces. 1128 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() && 1129 ParamQs.hasAddressSpace()) 1130 return true; 1131 1132 // Mismatched (but not missing) Objective-C lifetime qualifiers. 1133 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() && 1134 ParamQs.hasObjCLifetime()) 1135 return true; 1136 1137 // CVR qualifiers inconsistent or a superset. 1138 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0; 1139 } 1140 1141 /// Compare types for equality with respect to possibly compatible 1142 /// function types (noreturn adjustment, implicit calling conventions). If any 1143 /// of parameter and argument is not a function, just perform type comparison. 1144 /// 1145 /// \param P the template parameter type. 1146 /// 1147 /// \param A the argument type. 1148 bool Sema::isSameOrCompatibleFunctionType(QualType P, QualType A) { 1149 const FunctionType *PF = P->getAs<FunctionType>(), 1150 *AF = A->getAs<FunctionType>(); 1151 1152 // Just compare if not functions. 1153 if (!PF || !AF) 1154 return Context.hasSameType(P, A); 1155 1156 // Noreturn and noexcept adjustment. 1157 QualType AdjustedParam; 1158 if (IsFunctionConversion(P, A, AdjustedParam)) 1159 return Context.hasSameType(AdjustedParam, A); 1160 1161 // FIXME: Compatible calling conventions. 1162 1163 return Context.hasSameType(P, A); 1164 } 1165 1166 /// Get the index of the first template parameter that was originally from the 1167 /// innermost template-parameter-list. This is 0 except when we concatenate 1168 /// the template parameter lists of a class template and a constructor template 1169 /// when forming an implicit deduction guide. 1170 static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) { 1171 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl()); 1172 if (!Guide || !Guide->isImplicit()) 1173 return 0; 1174 return Guide->getDeducedTemplate()->getTemplateParameters()->size(); 1175 } 1176 1177 /// Determine whether a type denotes a forwarding reference. 1178 static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) { 1179 // C++1z [temp.deduct.call]p3: 1180 // A forwarding reference is an rvalue reference to a cv-unqualified 1181 // template parameter that does not represent a template parameter of a 1182 // class template. 1183 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) { 1184 if (ParamRef->getPointeeType().getQualifiers()) 1185 return false; 1186 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>(); 1187 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex; 1188 } 1189 return false; 1190 } 1191 1192 static CXXRecordDecl *getCanonicalRD(QualType T) { 1193 return cast<CXXRecordDecl>( 1194 T->castAs<RecordType>()->getDecl()->getCanonicalDecl()); 1195 } 1196 1197 /// Attempt to deduce the template arguments by checking the base types 1198 /// according to (C++20 [temp.deduct.call] p4b3. 1199 /// 1200 /// \param S the semantic analysis object within which we are deducing. 1201 /// 1202 /// \param RD the top level record object we are deducing against. 1203 /// 1204 /// \param TemplateParams the template parameters that we are deducing. 1205 /// 1206 /// \param P the template specialization parameter type. 1207 /// 1208 /// \param Info information about the template argument deduction itself. 1209 /// 1210 /// \param Deduced the deduced template arguments. 1211 /// 1212 /// \returns the result of template argument deduction with the bases. "invalid" 1213 /// means no matches, "success" found a single item, and the 1214 /// "MiscellaneousDeductionFailure" result happens when the match is ambiguous. 1215 static Sema::TemplateDeductionResult 1216 DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD, 1217 TemplateParameterList *TemplateParams, QualType P, 1218 TemplateDeductionInfo &Info, 1219 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 1220 // C++14 [temp.deduct.call] p4b3: 1221 // If P is a class and P has the form simple-template-id, then the 1222 // transformed A can be a derived class of the deduced A. Likewise if 1223 // P is a pointer to a class of the form simple-template-id, the 1224 // transformed A can be a pointer to a derived class pointed to by the 1225 // deduced A. However, if there is a class C that is a (direct or 1226 // indirect) base class of D and derived (directly or indirectly) from a 1227 // class B and that would be a valid deduced A, the deduced A cannot be 1228 // B or pointer to B, respectively. 1229 // 1230 // These alternatives are considered only if type deduction would 1231 // otherwise fail. If they yield more than one possible deduced A, the 1232 // type deduction fails. 1233 1234 // Use a breadth-first search through the bases to collect the set of 1235 // successful matches. Visited contains the set of nodes we have already 1236 // visited, while ToVisit is our stack of records that we still need to 1237 // visit. Matches contains a list of matches that have yet to be 1238 // disqualified. 1239 llvm::SmallPtrSet<const CXXRecordDecl *, 8> Visited; 1240 SmallVector<QualType, 8> ToVisit; 1241 // We iterate over this later, so we have to use MapVector to ensure 1242 // determinism. 1243 llvm::MapVector<const CXXRecordDecl *, 1244 SmallVector<DeducedTemplateArgument, 8>> 1245 Matches; 1246 1247 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) { 1248 for (const auto &Base : RD->bases()) { 1249 QualType T = Base.getType(); 1250 assert(T->isRecordType() && "Base class that isn't a record?"); 1251 if (Visited.insert(::getCanonicalRD(T)).second) 1252 ToVisit.push_back(T); 1253 } 1254 }; 1255 1256 // Set up the loop by adding all the bases. 1257 AddBases(RD); 1258 1259 // Search each path of bases until we either run into a successful match 1260 // (where all bases of it are invalid), or we run out of bases. 1261 while (!ToVisit.empty()) { 1262 QualType NextT = ToVisit.pop_back_val(); 1263 1264 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(), 1265 Deduced.end()); 1266 TemplateDeductionInfo BaseInfo(TemplateDeductionInfo::ForBase, Info); 1267 Sema::TemplateDeductionResult BaseResult = DeduceTemplateSpecArguments( 1268 S, TemplateParams, P, NextT, BaseInfo, DeducedCopy); 1269 1270 // If this was a successful deduction, add it to the list of matches, 1271 // otherwise we need to continue searching its bases. 1272 const CXXRecordDecl *RD = ::getCanonicalRD(NextT); 1273 if (BaseResult == Sema::TDK_Success) 1274 Matches.insert({RD, DeducedCopy}); 1275 else 1276 AddBases(RD); 1277 } 1278 1279 // At this point, 'Matches' contains a list of seemingly valid bases, however 1280 // in the event that we have more than 1 match, it is possible that the base 1281 // of one of the matches might be disqualified for being a base of another 1282 // valid match. We can count on cyclical instantiations being invalid to 1283 // simplify the disqualifications. That is, if A & B are both matches, and B 1284 // inherits from A (disqualifying A), we know that A cannot inherit from B. 1285 if (Matches.size() > 1) { 1286 Visited.clear(); 1287 for (const auto &Match : Matches) 1288 AddBases(Match.first); 1289 1290 // We can give up once we have a single item (or have run out of things to 1291 // search) since cyclical inheritance isn't valid. 1292 while (Matches.size() > 1 && !ToVisit.empty()) { 1293 const CXXRecordDecl *RD = ::getCanonicalRD(ToVisit.pop_back_val()); 1294 Matches.erase(RD); 1295 1296 // Always add all bases, since the inheritance tree can contain 1297 // disqualifications for multiple matches. 1298 AddBases(RD); 1299 } 1300 } 1301 1302 if (Matches.empty()) 1303 return Sema::TDK_Invalid; 1304 if (Matches.size() > 1) 1305 return Sema::TDK_MiscellaneousDeductionFailure; 1306 1307 std::swap(Matches.front().second, Deduced); 1308 return Sema::TDK_Success; 1309 } 1310 1311 /// Deduce the template arguments by comparing the parameter type and 1312 /// the argument type (C++ [temp.deduct.type]). 1313 /// 1314 /// \param S the semantic analysis object within which we are deducing 1315 /// 1316 /// \param TemplateParams the template parameters that we are deducing 1317 /// 1318 /// \param P the parameter type 1319 /// 1320 /// \param A the argument type 1321 /// 1322 /// \param Info information about the template argument deduction itself 1323 /// 1324 /// \param Deduced the deduced template arguments 1325 /// 1326 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 1327 /// how template argument deduction is performed. 1328 /// 1329 /// \param PartialOrdering Whether we're performing template argument deduction 1330 /// in the context of partial ordering (C++0x [temp.deduct.partial]). 1331 /// 1332 /// \returns the result of template argument deduction so far. Note that a 1333 /// "success" result means that template argument deduction has not yet failed, 1334 /// but it may still fail, later, for other reasons. 1335 static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch( 1336 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A, 1337 TemplateDeductionInfo &Info, 1338 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF, 1339 bool PartialOrdering, bool DeducedFromArrayBound) { 1340 1341 // If the argument type is a pack expansion, look at its pattern. 1342 // This isn't explicitly called out 1343 if (const auto *AExp = dyn_cast<PackExpansionType>(A)) 1344 A = AExp->getPattern(); 1345 assert(!isa<PackExpansionType>(A.getCanonicalType())); 1346 1347 if (PartialOrdering) { 1348 // C++11 [temp.deduct.partial]p5: 1349 // Before the partial ordering is done, certain transformations are 1350 // performed on the types used for partial ordering: 1351 // - If P is a reference type, P is replaced by the type referred to. 1352 const ReferenceType *PRef = P->getAs<ReferenceType>(); 1353 if (PRef) 1354 P = PRef->getPointeeType(); 1355 1356 // - If A is a reference type, A is replaced by the type referred to. 1357 const ReferenceType *ARef = A->getAs<ReferenceType>(); 1358 if (ARef) 1359 A = A->getPointeeType(); 1360 1361 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) { 1362 // C++11 [temp.deduct.partial]p9: 1363 // If, for a given type, deduction succeeds in both directions (i.e., 1364 // the types are identical after the transformations above) and both 1365 // P and A were reference types [...]: 1366 // - if [one type] was an lvalue reference and [the other type] was 1367 // not, [the other type] is not considered to be at least as 1368 // specialized as [the first type] 1369 // - if [one type] is more cv-qualified than [the other type], 1370 // [the other type] is not considered to be at least as specialized 1371 // as [the first type] 1372 // Objective-C ARC adds: 1373 // - [one type] has non-trivial lifetime, [the other type] has 1374 // __unsafe_unretained lifetime, and the types are otherwise 1375 // identical 1376 // 1377 // A is "considered to be at least as specialized" as P iff deduction 1378 // succeeds, so we model this as a deduction failure. Note that 1379 // [the first type] is P and [the other type] is A here; the standard 1380 // gets this backwards. 1381 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers(); 1382 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) || 1383 PQuals.isStrictSupersetOf(AQuals) || 1384 (PQuals.hasNonTrivialObjCLifetime() && 1385 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone && 1386 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) { 1387 Info.FirstArg = TemplateArgument(P); 1388 Info.SecondArg = TemplateArgument(A); 1389 return Sema::TDK_NonDeducedMismatch; 1390 } 1391 } 1392 Qualifiers DiscardedQuals; 1393 // C++11 [temp.deduct.partial]p7: 1394 // Remove any top-level cv-qualifiers: 1395 // - If P is a cv-qualified type, P is replaced by the cv-unqualified 1396 // version of P. 1397 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals); 1398 // - If A is a cv-qualified type, A is replaced by the cv-unqualified 1399 // version of A. 1400 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals); 1401 } else { 1402 // C++0x [temp.deduct.call]p4 bullet 1: 1403 // - If the original P is a reference type, the deduced A (i.e., the type 1404 // referred to by the reference) can be more cv-qualified than the 1405 // transformed A. 1406 if (TDF & TDF_ParamWithReferenceType) { 1407 Qualifiers Quals; 1408 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals); 1409 Quals.setCVRQualifiers(Quals.getCVRQualifiers() & A.getCVRQualifiers()); 1410 P = S.Context.getQualifiedType(UnqualP, Quals); 1411 } 1412 1413 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) { 1414 // C++0x [temp.deduct.type]p10: 1415 // If P and A are function types that originated from deduction when 1416 // taking the address of a function template (14.8.2.2) or when deducing 1417 // template arguments from a function declaration (14.8.2.6) and Pi and 1418 // Ai are parameters of the top-level parameter-type-list of P and A, 1419 // respectively, Pi is adjusted if it is a forwarding reference and Ai 1420 // is an lvalue reference, in 1421 // which case the type of Pi is changed to be the template parameter 1422 // type (i.e., T&& is changed to simply T). [ Note: As a result, when 1423 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be 1424 // deduced as X&. - end note ] 1425 TDF &= ~TDF_TopLevelParameterTypeList; 1426 if (isForwardingReference(P, /*FirstInnerIndex=*/0) && 1427 A->isLValueReferenceType()) 1428 P = P->getPointeeType(); 1429 } 1430 } 1431 1432 // C++ [temp.deduct.type]p9: 1433 // A template type argument T, a template template argument TT or a 1434 // template non-type argument i can be deduced if P and A have one of 1435 // the following forms: 1436 // 1437 // T 1438 // cv-list T 1439 if (const auto *TTP = P->getAs<TemplateTypeParmType>()) { 1440 // Just skip any attempts to deduce from a placeholder type or a parameter 1441 // at a different depth. 1442 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth()) 1443 return Sema::TDK_Success; 1444 1445 unsigned Index = TTP->getIndex(); 1446 1447 // If the argument type is an array type, move the qualifiers up to the 1448 // top level, so they can be matched with the qualifiers on the parameter. 1449 if (A->isArrayType()) { 1450 Qualifiers Quals; 1451 A = S.Context.getUnqualifiedArrayType(A, Quals); 1452 if (Quals) 1453 A = S.Context.getQualifiedType(A, Quals); 1454 } 1455 1456 // The argument type can not be less qualified than the parameter 1457 // type. 1458 if (!(TDF & TDF_IgnoreQualifiers) && 1459 hasInconsistentOrSupersetQualifiersOf(P, A)) { 1460 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1461 Info.FirstArg = TemplateArgument(P); 1462 Info.SecondArg = TemplateArgument(A); 1463 return Sema::TDK_Underqualified; 1464 } 1465 1466 // Do not match a function type with a cv-qualified type. 1467 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584 1468 if (A->isFunctionType() && P.hasQualifiers()) 1469 return Sema::TDK_NonDeducedMismatch; 1470 1471 assert(TTP->getDepth() == Info.getDeducedDepth() && 1472 "saw template type parameter with wrong depth"); 1473 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy && 1474 "Unresolved overloaded function"); 1475 QualType DeducedType = A; 1476 1477 // Remove any qualifiers on the parameter from the deduced type. 1478 // We checked the qualifiers for consistency above. 1479 Qualifiers DeducedQs = DeducedType.getQualifiers(); 1480 Qualifiers ParamQs = P.getQualifiers(); 1481 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers()); 1482 if (ParamQs.hasObjCGCAttr()) 1483 DeducedQs.removeObjCGCAttr(); 1484 if (ParamQs.hasAddressSpace()) 1485 DeducedQs.removeAddressSpace(); 1486 if (ParamQs.hasObjCLifetime()) 1487 DeducedQs.removeObjCLifetime(); 1488 1489 // Objective-C ARC: 1490 // If template deduction would produce a lifetime qualifier on a type 1491 // that is not a lifetime type, template argument deduction fails. 1492 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() && 1493 !DeducedType->isDependentType()) { 1494 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1495 Info.FirstArg = TemplateArgument(P); 1496 Info.SecondArg = TemplateArgument(A); 1497 return Sema::TDK_Underqualified; 1498 } 1499 1500 // Objective-C ARC: 1501 // If template deduction would produce an argument type with lifetime type 1502 // but no lifetime qualifier, the __strong lifetime qualifier is inferred. 1503 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() && 1504 !DeducedQs.hasObjCLifetime()) 1505 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong); 1506 1507 DeducedType = 1508 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs); 1509 1510 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound); 1511 DeducedTemplateArgument Result = 1512 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced); 1513 if (Result.isNull()) { 1514 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1515 Info.FirstArg = Deduced[Index]; 1516 Info.SecondArg = NewDeduced; 1517 return Sema::TDK_Inconsistent; 1518 } 1519 1520 Deduced[Index] = Result; 1521 return Sema::TDK_Success; 1522 } 1523 1524 // Set up the template argument deduction information for a failure. 1525 Info.FirstArg = TemplateArgument(P); 1526 Info.SecondArg = TemplateArgument(A); 1527 1528 // If the parameter is an already-substituted template parameter 1529 // pack, do nothing: we don't know which of its arguments to look 1530 // at, so we have to wait until all of the parameter packs in this 1531 // expansion have arguments. 1532 if (P->getAs<SubstTemplateTypeParmPackType>()) 1533 return Sema::TDK_Success; 1534 1535 // Check the cv-qualifiers on the parameter and argument types. 1536 if (!(TDF & TDF_IgnoreQualifiers)) { 1537 if (TDF & TDF_ParamWithReferenceType) { 1538 if (hasInconsistentOrSupersetQualifiersOf(P, A)) 1539 return Sema::TDK_NonDeducedMismatch; 1540 } else if (TDF & TDF_ArgWithReferenceType) { 1541 // C++ [temp.deduct.conv]p4: 1542 // If the original A is a reference type, A can be more cv-qualified 1543 // than the deduced A 1544 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers())) 1545 return Sema::TDK_NonDeducedMismatch; 1546 1547 // Strip out all extra qualifiers from the argument to figure out the 1548 // type we're converting to, prior to the qualification conversion. 1549 Qualifiers Quals; 1550 A = S.Context.getUnqualifiedArrayType(A, Quals); 1551 A = S.Context.getQualifiedType(A, P.getQualifiers()); 1552 } else if (!IsPossiblyOpaquelyQualifiedType(P)) { 1553 if (P.getCVRQualifiers() != A.getCVRQualifiers()) 1554 return Sema::TDK_NonDeducedMismatch; 1555 } 1556 } 1557 1558 // If the parameter type is not dependent, there is nothing to deduce. 1559 if (!P->isDependentType()) { 1560 if (TDF & TDF_SkipNonDependent) 1561 return Sema::TDK_Success; 1562 if ((TDF & TDF_IgnoreQualifiers) ? S.Context.hasSameUnqualifiedType(P, A) 1563 : S.Context.hasSameType(P, A)) 1564 return Sema::TDK_Success; 1565 if (TDF & TDF_AllowCompatibleFunctionType && 1566 S.isSameOrCompatibleFunctionType(P, A)) 1567 return Sema::TDK_Success; 1568 if (!(TDF & TDF_IgnoreQualifiers)) 1569 return Sema::TDK_NonDeducedMismatch; 1570 // Otherwise, when ignoring qualifiers, the types not having the same 1571 // unqualified type does not mean they do not match, so in this case we 1572 // must keep going and analyze with a non-dependent parameter type. 1573 } 1574 1575 switch (P.getCanonicalType()->getTypeClass()) { 1576 // Non-canonical types cannot appear here. 1577 #define NON_CANONICAL_TYPE(Class, Base) \ 1578 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class); 1579 #define TYPE(Class, Base) 1580 #include "clang/AST/TypeNodes.inc" 1581 1582 case Type::TemplateTypeParm: 1583 case Type::SubstTemplateTypeParmPack: 1584 llvm_unreachable("Type nodes handled above"); 1585 1586 case Type::Auto: 1587 // FIXME: Implement deduction in dependent case. 1588 if (P->isDependentType()) 1589 return Sema::TDK_Success; 1590 LLVM_FALLTHROUGH; 1591 case Type::Builtin: 1592 case Type::VariableArray: 1593 case Type::Vector: 1594 case Type::FunctionNoProto: 1595 case Type::Record: 1596 case Type::Enum: 1597 case Type::ObjCObject: 1598 case Type::ObjCInterface: 1599 case Type::ObjCObjectPointer: 1600 case Type::BitInt: 1601 return (TDF & TDF_SkipNonDependent) || 1602 ((TDF & TDF_IgnoreQualifiers) 1603 ? S.Context.hasSameUnqualifiedType(P, A) 1604 : S.Context.hasSameType(P, A)) 1605 ? Sema::TDK_Success 1606 : Sema::TDK_NonDeducedMismatch; 1607 1608 // _Complex T [placeholder extension] 1609 case Type::Complex: { 1610 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>(); 1611 if (!CA) 1612 return Sema::TDK_NonDeducedMismatch; 1613 return DeduceTemplateArgumentsByTypeMatch( 1614 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info, 1615 Deduced, TDF); 1616 } 1617 1618 // _Atomic T [extension] 1619 case Type::Atomic: { 1620 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>(); 1621 if (!AA) 1622 return Sema::TDK_NonDeducedMismatch; 1623 return DeduceTemplateArgumentsByTypeMatch( 1624 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info, 1625 Deduced, TDF); 1626 } 1627 1628 // T * 1629 case Type::Pointer: { 1630 QualType PointeeType; 1631 if (const auto *PA = A->getAs<PointerType>()) { 1632 PointeeType = PA->getPointeeType(); 1633 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) { 1634 PointeeType = PA->getPointeeType(); 1635 } else { 1636 return Sema::TDK_NonDeducedMismatch; 1637 } 1638 return DeduceTemplateArgumentsByTypeMatch( 1639 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(), 1640 PointeeType, Info, Deduced, 1641 TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass)); 1642 } 1643 1644 // T & 1645 case Type::LValueReference: { 1646 const auto *RP = P->castAs<LValueReferenceType>(), 1647 *RA = A->getAs<LValueReferenceType>(); 1648 if (!RA) 1649 return Sema::TDK_NonDeducedMismatch; 1650 1651 return DeduceTemplateArgumentsByTypeMatch( 1652 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info, 1653 Deduced, 0); 1654 } 1655 1656 // T && [C++0x] 1657 case Type::RValueReference: { 1658 const auto *RP = P->castAs<RValueReferenceType>(), 1659 *RA = A->getAs<RValueReferenceType>(); 1660 if (!RA) 1661 return Sema::TDK_NonDeducedMismatch; 1662 1663 return DeduceTemplateArgumentsByTypeMatch( 1664 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info, 1665 Deduced, 0); 1666 } 1667 1668 // T [] (implied, but not stated explicitly) 1669 case Type::IncompleteArray: { 1670 const auto *IAA = S.Context.getAsIncompleteArrayType(A); 1671 if (!IAA) 1672 return Sema::TDK_NonDeducedMismatch; 1673 1674 return DeduceTemplateArgumentsByTypeMatch( 1675 S, TemplateParams, 1676 S.Context.getAsIncompleteArrayType(P)->getElementType(), 1677 IAA->getElementType(), Info, Deduced, TDF & TDF_IgnoreQualifiers); 1678 } 1679 1680 // T [integer-constant] 1681 case Type::ConstantArray: { 1682 const auto *CAA = S.Context.getAsConstantArrayType(A), 1683 *CAP = S.Context.getAsConstantArrayType(P); 1684 assert(CAP); 1685 if (!CAA || CAA->getSize() != CAP->getSize()) 1686 return Sema::TDK_NonDeducedMismatch; 1687 1688 return DeduceTemplateArgumentsByTypeMatch( 1689 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info, 1690 Deduced, TDF & TDF_IgnoreQualifiers); 1691 } 1692 1693 // type [i] 1694 case Type::DependentSizedArray: { 1695 const auto *AA = S.Context.getAsArrayType(A); 1696 if (!AA) 1697 return Sema::TDK_NonDeducedMismatch; 1698 1699 // Check the element type of the arrays 1700 const auto *DAP = S.Context.getAsDependentSizedArrayType(P); 1701 assert(DAP); 1702 if (auto Result = DeduceTemplateArgumentsByTypeMatch( 1703 S, TemplateParams, DAP->getElementType(), AA->getElementType(), 1704 Info, Deduced, TDF & TDF_IgnoreQualifiers)) 1705 return Result; 1706 1707 // Determine the array bound is something we can deduce. 1708 const NonTypeTemplateParmDecl *NTTP = 1709 getDeducedParameterFromExpr(Info, DAP->getSizeExpr()); 1710 if (!NTTP) 1711 return Sema::TDK_Success; 1712 1713 // We can perform template argument deduction for the given non-type 1714 // template parameter. 1715 assert(NTTP->getDepth() == Info.getDeducedDepth() && 1716 "saw non-type template parameter with wrong depth"); 1717 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) { 1718 llvm::APSInt Size(CAA->getSize()); 1719 return DeduceNonTypeTemplateArgument( 1720 S, TemplateParams, NTTP, Size, S.Context.getSizeType(), 1721 /*ArrayBound=*/true, Info, Deduced); 1722 } 1723 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA)) 1724 if (DAA->getSizeExpr()) 1725 return DeduceNonTypeTemplateArgument( 1726 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info, Deduced); 1727 1728 // Incomplete type does not match a dependently-sized array type 1729 return Sema::TDK_NonDeducedMismatch; 1730 } 1731 1732 // type(*)(T) 1733 // T(*)() 1734 // T(*)(T) 1735 case Type::FunctionProto: { 1736 const auto *FPP = P->castAs<FunctionProtoType>(), 1737 *FPA = A->getAs<FunctionProtoType>(); 1738 if (!FPA) 1739 return Sema::TDK_NonDeducedMismatch; 1740 1741 if (FPP->getMethodQuals() != FPA->getMethodQuals() || 1742 FPP->getRefQualifier() != FPA->getRefQualifier() || 1743 FPP->isVariadic() != FPA->isVariadic()) 1744 return Sema::TDK_NonDeducedMismatch; 1745 1746 // Check return types. 1747 if (auto Result = DeduceTemplateArgumentsByTypeMatch( 1748 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(), 1749 Info, Deduced, 0, 1750 /*PartialOrdering=*/false, 1751 /*DeducedFromArrayBound=*/false)) 1752 return Result; 1753 1754 // Check parameter types. 1755 if (auto Result = DeduceTemplateArguments( 1756 S, TemplateParams, FPP->param_type_begin(), FPP->getNumParams(), 1757 FPA->param_type_begin(), FPA->getNumParams(), Info, Deduced, 1758 TDF & TDF_TopLevelParameterTypeList)) 1759 return Result; 1760 1761 if (TDF & TDF_AllowCompatibleFunctionType) 1762 return Sema::TDK_Success; 1763 1764 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit 1765 // deducing through the noexcept-specifier if it's part of the canonical 1766 // type. libstdc++ relies on this. 1767 Expr *NoexceptExpr = FPP->getNoexceptExpr(); 1768 if (const NonTypeTemplateParmDecl *NTTP = 1769 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr) 1770 : nullptr) { 1771 assert(NTTP->getDepth() == Info.getDeducedDepth() && 1772 "saw non-type template parameter with wrong depth"); 1773 1774 llvm::APSInt Noexcept(1); 1775 switch (FPA->canThrow()) { 1776 case CT_Cannot: 1777 Noexcept = 1; 1778 LLVM_FALLTHROUGH; 1779 1780 case CT_Can: 1781 // We give E in noexcept(E) the "deduced from array bound" treatment. 1782 // FIXME: Should we? 1783 return DeduceNonTypeTemplateArgument( 1784 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy, 1785 /*DeducedFromArrayBound=*/true, Info, Deduced); 1786 1787 case CT_Dependent: 1788 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr()) 1789 return DeduceNonTypeTemplateArgument( 1790 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced); 1791 // Can't deduce anything from throw(T...). 1792 break; 1793 } 1794 } 1795 // FIXME: Detect non-deduced exception specification mismatches? 1796 // 1797 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow 1798 // top-level differences in noexcept-specifications. 1799 1800 return Sema::TDK_Success; 1801 } 1802 1803 case Type::InjectedClassName: 1804 // Treat a template's injected-class-name as if the template 1805 // specialization type had been used. 1806 1807 // template-name<T> (where template-name refers to a class template) 1808 // template-name<i> 1809 // TT<T> 1810 // TT<i> 1811 // TT<> 1812 case Type::TemplateSpecialization: { 1813 // When Arg cannot be a derived class, we can just try to deduce template 1814 // arguments from the template-id. 1815 if (!(TDF & TDF_DerivedClass) || !A->isRecordType()) 1816 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info, 1817 Deduced); 1818 1819 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(), 1820 Deduced.end()); 1821 1822 auto Result = 1823 DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info, Deduced); 1824 if (Result == Sema::TDK_Success) 1825 return Result; 1826 1827 // We cannot inspect base classes as part of deduction when the type 1828 // is incomplete, so either instantiate any templates necessary to 1829 // complete the type, or skip over it if it cannot be completed. 1830 if (!S.isCompleteType(Info.getLocation(), A)) 1831 return Result; 1832 1833 // Reset the incorrectly deduced argument from above. 1834 Deduced = DeducedOrig; 1835 1836 // Check bases according to C++14 [temp.deduct.call] p4b3: 1837 auto BaseResult = DeduceTemplateBases(S, getCanonicalRD(A), 1838 TemplateParams, P, Info, Deduced); 1839 return BaseResult != Sema::TDK_Invalid ? BaseResult : Result; 1840 } 1841 1842 // T type::* 1843 // T T::* 1844 // T (type::*)() 1845 // type (T::*)() 1846 // type (type::*)(T) 1847 // type (T::*)(T) 1848 // T (type::*)(T) 1849 // T (T::*)() 1850 // T (T::*)(T) 1851 case Type::MemberPointer: { 1852 const auto *MPP = P->castAs<MemberPointerType>(), 1853 *MPA = A->getAs<MemberPointerType>(); 1854 if (!MPA) 1855 return Sema::TDK_NonDeducedMismatch; 1856 1857 QualType PPT = MPP->getPointeeType(); 1858 if (PPT->isFunctionType()) 1859 S.adjustMemberFunctionCC(PPT, /*IsStatic=*/true, 1860 /*IsCtorOrDtor=*/false, Info.getLocation()); 1861 QualType APT = MPA->getPointeeType(); 1862 if (APT->isFunctionType()) 1863 S.adjustMemberFunctionCC(APT, /*IsStatic=*/true, 1864 /*IsCtorOrDtor=*/false, Info.getLocation()); 1865 1866 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 1867 if (auto Result = DeduceTemplateArgumentsByTypeMatch( 1868 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF)) 1869 return Result; 1870 return DeduceTemplateArgumentsByTypeMatch( 1871 S, TemplateParams, QualType(MPP->getClass(), 0), 1872 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF); 1873 } 1874 1875 // (clang extension) 1876 // 1877 // type(^)(T) 1878 // T(^)() 1879 // T(^)(T) 1880 case Type::BlockPointer: { 1881 const auto *BPP = P->castAs<BlockPointerType>(), 1882 *BPA = A->getAs<BlockPointerType>(); 1883 if (!BPA) 1884 return Sema::TDK_NonDeducedMismatch; 1885 return DeduceTemplateArgumentsByTypeMatch( 1886 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info, 1887 Deduced, 0); 1888 } 1889 1890 // (clang extension) 1891 // 1892 // T __attribute__(((ext_vector_type(<integral constant>)))) 1893 case Type::ExtVector: { 1894 const auto *VP = P->castAs<ExtVectorType>(); 1895 QualType ElementType; 1896 if (const auto *VA = A->getAs<ExtVectorType>()) { 1897 // Make sure that the vectors have the same number of elements. 1898 if (VP->getNumElements() != VA->getNumElements()) 1899 return Sema::TDK_NonDeducedMismatch; 1900 ElementType = VA->getElementType(); 1901 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) { 1902 // We can't check the number of elements, since the argument has a 1903 // dependent number of elements. This can only occur during partial 1904 // ordering. 1905 ElementType = VA->getElementType(); 1906 } else { 1907 return Sema::TDK_NonDeducedMismatch; 1908 } 1909 // Perform deduction on the element types. 1910 return DeduceTemplateArgumentsByTypeMatch( 1911 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced, 1912 TDF); 1913 } 1914 1915 case Type::DependentVector: { 1916 const auto *VP = P->castAs<DependentVectorType>(); 1917 1918 if (const auto *VA = A->getAs<VectorType>()) { 1919 // Perform deduction on the element types. 1920 if (auto Result = DeduceTemplateArgumentsByTypeMatch( 1921 S, TemplateParams, VP->getElementType(), VA->getElementType(), 1922 Info, Deduced, TDF)) 1923 return Result; 1924 1925 // Perform deduction on the vector size, if we can. 1926 const NonTypeTemplateParmDecl *NTTP = 1927 getDeducedParameterFromExpr(Info, VP->getSizeExpr()); 1928 if (!NTTP) 1929 return Sema::TDK_Success; 1930 1931 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); 1932 ArgSize = VA->getNumElements(); 1933 // Note that we use the "array bound" rules here; just like in that 1934 // case, we don't have any particular type for the vector size, but 1935 // we can provide one if necessary. 1936 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize, 1937 S.Context.UnsignedIntTy, true, 1938 Info, Deduced); 1939 } 1940 1941 if (const auto *VA = A->getAs<DependentVectorType>()) { 1942 // Perform deduction on the element types. 1943 if (auto Result = DeduceTemplateArgumentsByTypeMatch( 1944 S, TemplateParams, VP->getElementType(), VA->getElementType(), 1945 Info, Deduced, TDF)) 1946 return Result; 1947 1948 // Perform deduction on the vector size, if we can. 1949 const NonTypeTemplateParmDecl *NTTP = 1950 getDeducedParameterFromExpr(Info, VP->getSizeExpr()); 1951 if (!NTTP) 1952 return Sema::TDK_Success; 1953 1954 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 1955 VA->getSizeExpr(), Info, Deduced); 1956 } 1957 1958 return Sema::TDK_NonDeducedMismatch; 1959 } 1960 1961 // (clang extension) 1962 // 1963 // T __attribute__(((ext_vector_type(N)))) 1964 case Type::DependentSizedExtVector: { 1965 const auto *VP = P->castAs<DependentSizedExtVectorType>(); 1966 1967 if (const auto *VA = A->getAs<ExtVectorType>()) { 1968 // Perform deduction on the element types. 1969 if (auto Result = DeduceTemplateArgumentsByTypeMatch( 1970 S, TemplateParams, VP->getElementType(), VA->getElementType(), 1971 Info, Deduced, TDF)) 1972 return Result; 1973 1974 // Perform deduction on the vector size, if we can. 1975 const NonTypeTemplateParmDecl *NTTP = 1976 getDeducedParameterFromExpr(Info, VP->getSizeExpr()); 1977 if (!NTTP) 1978 return Sema::TDK_Success; 1979 1980 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); 1981 ArgSize = VA->getNumElements(); 1982 // Note that we use the "array bound" rules here; just like in that 1983 // case, we don't have any particular type for the vector size, but 1984 // we can provide one if necessary. 1985 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize, 1986 S.Context.IntTy, true, Info, 1987 Deduced); 1988 } 1989 1990 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) { 1991 // Perform deduction on the element types. 1992 if (auto Result = DeduceTemplateArgumentsByTypeMatch( 1993 S, TemplateParams, VP->getElementType(), VA->getElementType(), 1994 Info, Deduced, TDF)) 1995 return Result; 1996 1997 // Perform deduction on the vector size, if we can. 1998 const NonTypeTemplateParmDecl *NTTP = 1999 getDeducedParameterFromExpr(Info, VP->getSizeExpr()); 2000 if (!NTTP) 2001 return Sema::TDK_Success; 2002 2003 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 2004 VA->getSizeExpr(), Info, Deduced); 2005 } 2006 2007 return Sema::TDK_NonDeducedMismatch; 2008 } 2009 2010 // (clang extension) 2011 // 2012 // T __attribute__((matrix_type(<integral constant>, 2013 // <integral constant>))) 2014 case Type::ConstantMatrix: { 2015 const auto *MP = P->castAs<ConstantMatrixType>(), 2016 *MA = A->getAs<ConstantMatrixType>(); 2017 if (!MA) 2018 return Sema::TDK_NonDeducedMismatch; 2019 2020 // Check that the dimensions are the same 2021 if (MP->getNumRows() != MA->getNumRows() || 2022 MP->getNumColumns() != MA->getNumColumns()) { 2023 return Sema::TDK_NonDeducedMismatch; 2024 } 2025 // Perform deduction on element types. 2026 return DeduceTemplateArgumentsByTypeMatch( 2027 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info, 2028 Deduced, TDF); 2029 } 2030 2031 case Type::DependentSizedMatrix: { 2032 const auto *MP = P->castAs<DependentSizedMatrixType>(); 2033 const auto *MA = A->getAs<MatrixType>(); 2034 if (!MA) 2035 return Sema::TDK_NonDeducedMismatch; 2036 2037 // Check the element type of the matrixes. 2038 if (auto Result = DeduceTemplateArgumentsByTypeMatch( 2039 S, TemplateParams, MP->getElementType(), MA->getElementType(), 2040 Info, Deduced, TDF)) 2041 return Result; 2042 2043 // Try to deduce a matrix dimension. 2044 auto DeduceMatrixArg = 2045 [&S, &Info, &Deduced, &TemplateParams]( 2046 Expr *ParamExpr, const MatrixType *A, 2047 unsigned (ConstantMatrixType::*GetArgDimension)() const, 2048 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) { 2049 const auto *ACM = dyn_cast<ConstantMatrixType>(A); 2050 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A); 2051 if (!ParamExpr->isValueDependent()) { 2052 Optional<llvm::APSInt> ParamConst = 2053 ParamExpr->getIntegerConstantExpr(S.Context); 2054 if (!ParamConst) 2055 return Sema::TDK_NonDeducedMismatch; 2056 2057 if (ACM) { 2058 if ((ACM->*GetArgDimension)() == *ParamConst) 2059 return Sema::TDK_Success; 2060 return Sema::TDK_NonDeducedMismatch; 2061 } 2062 2063 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)(); 2064 if (Optional<llvm::APSInt> ArgConst = 2065 ArgExpr->getIntegerConstantExpr(S.Context)) 2066 if (*ArgConst == *ParamConst) 2067 return Sema::TDK_Success; 2068 return Sema::TDK_NonDeducedMismatch; 2069 } 2070 2071 const NonTypeTemplateParmDecl *NTTP = 2072 getDeducedParameterFromExpr(Info, ParamExpr); 2073 if (!NTTP) 2074 return Sema::TDK_Success; 2075 2076 if (ACM) { 2077 llvm::APSInt ArgConst( 2078 S.Context.getTypeSize(S.Context.getSizeType())); 2079 ArgConst = (ACM->*GetArgDimension)(); 2080 return DeduceNonTypeTemplateArgument( 2081 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(), 2082 /*ArrayBound=*/true, Info, Deduced); 2083 } 2084 2085 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 2086 (ADM->*GetArgDimensionExpr)(), 2087 Info, Deduced); 2088 }; 2089 2090 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA, 2091 &ConstantMatrixType::getNumRows, 2092 &DependentSizedMatrixType::getRowExpr)) 2093 return Result; 2094 2095 return DeduceMatrixArg(MP->getColumnExpr(), MA, 2096 &ConstantMatrixType::getNumColumns, 2097 &DependentSizedMatrixType::getColumnExpr); 2098 } 2099 2100 // (clang extension) 2101 // 2102 // T __attribute__(((address_space(N)))) 2103 case Type::DependentAddressSpace: { 2104 const auto *ASP = P->castAs<DependentAddressSpaceType>(); 2105 2106 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) { 2107 // Perform deduction on the pointer type. 2108 if (auto Result = DeduceTemplateArgumentsByTypeMatch( 2109 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(), 2110 Info, Deduced, TDF)) 2111 return Result; 2112 2113 // Perform deduction on the address space, if we can. 2114 const NonTypeTemplateParmDecl *NTTP = 2115 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr()); 2116 if (!NTTP) 2117 return Sema::TDK_Success; 2118 2119 return DeduceNonTypeTemplateArgument( 2120 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, Deduced); 2121 } 2122 2123 if (isTargetAddressSpace(A.getAddressSpace())) { 2124 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy), 2125 false); 2126 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace()); 2127 2128 // Perform deduction on the pointer types. 2129 if (auto Result = DeduceTemplateArgumentsByTypeMatch( 2130 S, TemplateParams, ASP->getPointeeType(), 2131 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF)) 2132 return Result; 2133 2134 // Perform deduction on the address space, if we can. 2135 const NonTypeTemplateParmDecl *NTTP = 2136 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr()); 2137 if (!NTTP) 2138 return Sema::TDK_Success; 2139 2140 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 2141 ArgAddressSpace, S.Context.IntTy, 2142 true, Info, Deduced); 2143 } 2144 2145 return Sema::TDK_NonDeducedMismatch; 2146 } 2147 case Type::DependentBitInt: { 2148 const auto *IP = P->castAs<DependentBitIntType>(); 2149 2150 if (const auto *IA = A->getAs<BitIntType>()) { 2151 if (IP->isUnsigned() != IA->isUnsigned()) 2152 return Sema::TDK_NonDeducedMismatch; 2153 2154 const NonTypeTemplateParmDecl *NTTP = 2155 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr()); 2156 if (!NTTP) 2157 return Sema::TDK_Success; 2158 2159 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); 2160 ArgSize = IA->getNumBits(); 2161 2162 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize, 2163 S.Context.IntTy, true, Info, 2164 Deduced); 2165 } 2166 2167 if (const auto *IA = A->getAs<DependentBitIntType>()) { 2168 if (IP->isUnsigned() != IA->isUnsigned()) 2169 return Sema::TDK_NonDeducedMismatch; 2170 return Sema::TDK_Success; 2171 } 2172 2173 return Sema::TDK_NonDeducedMismatch; 2174 } 2175 2176 case Type::TypeOfExpr: 2177 case Type::TypeOf: 2178 case Type::DependentName: 2179 case Type::UnresolvedUsing: 2180 case Type::Decltype: 2181 case Type::UnaryTransform: 2182 case Type::DeducedTemplateSpecialization: 2183 case Type::DependentTemplateSpecialization: 2184 case Type::PackExpansion: 2185 case Type::Pipe: 2186 // No template argument deduction for these types 2187 return Sema::TDK_Success; 2188 } 2189 2190 llvm_unreachable("Invalid Type Class!"); 2191 } 2192 2193 static Sema::TemplateDeductionResult 2194 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, 2195 const TemplateArgument &P, TemplateArgument A, 2196 TemplateDeductionInfo &Info, 2197 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 2198 // If the template argument is a pack expansion, perform template argument 2199 // deduction against the pattern of that expansion. This only occurs during 2200 // partial ordering. 2201 if (A.isPackExpansion()) 2202 A = A.getPackExpansionPattern(); 2203 2204 switch (P.getKind()) { 2205 case TemplateArgument::Null: 2206 llvm_unreachable("Null template argument in parameter list"); 2207 2208 case TemplateArgument::Type: 2209 if (A.getKind() == TemplateArgument::Type) 2210 return DeduceTemplateArgumentsByTypeMatch( 2211 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0); 2212 Info.FirstArg = P; 2213 Info.SecondArg = A; 2214 return Sema::TDK_NonDeducedMismatch; 2215 2216 case TemplateArgument::Template: 2217 if (A.getKind() == TemplateArgument::Template) 2218 return DeduceTemplateArguments(S, TemplateParams, P.getAsTemplate(), 2219 A.getAsTemplate(), Info, Deduced); 2220 Info.FirstArg = P; 2221 Info.SecondArg = A; 2222 return Sema::TDK_NonDeducedMismatch; 2223 2224 case TemplateArgument::TemplateExpansion: 2225 llvm_unreachable("caller should handle pack expansions"); 2226 2227 case TemplateArgument::Declaration: 2228 if (A.getKind() == TemplateArgument::Declaration && 2229 isSameDeclaration(P.getAsDecl(), A.getAsDecl())) 2230 return Sema::TDK_Success; 2231 2232 Info.FirstArg = P; 2233 Info.SecondArg = A; 2234 return Sema::TDK_NonDeducedMismatch; 2235 2236 case TemplateArgument::NullPtr: 2237 if (A.getKind() == TemplateArgument::NullPtr && 2238 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType())) 2239 return Sema::TDK_Success; 2240 2241 Info.FirstArg = P; 2242 Info.SecondArg = A; 2243 return Sema::TDK_NonDeducedMismatch; 2244 2245 case TemplateArgument::Integral: 2246 if (A.getKind() == TemplateArgument::Integral) { 2247 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral())) 2248 return Sema::TDK_Success; 2249 } 2250 Info.FirstArg = P; 2251 Info.SecondArg = A; 2252 return Sema::TDK_NonDeducedMismatch; 2253 2254 case TemplateArgument::Expression: 2255 if (const NonTypeTemplateParmDecl *NTTP = 2256 getDeducedParameterFromExpr(Info, P.getAsExpr())) { 2257 if (A.getKind() == TemplateArgument::Integral) 2258 return DeduceNonTypeTemplateArgument( 2259 S, TemplateParams, NTTP, A.getAsIntegral(), A.getIntegralType(), 2260 /*ArrayBound=*/false, Info, Deduced); 2261 if (A.getKind() == TemplateArgument::NullPtr) 2262 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP, 2263 A.getNullPtrType(), Info, Deduced); 2264 if (A.getKind() == TemplateArgument::Expression) 2265 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 2266 A.getAsExpr(), Info, Deduced); 2267 if (A.getKind() == TemplateArgument::Declaration) 2268 return DeduceNonTypeTemplateArgument( 2269 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(), 2270 Info, Deduced); 2271 2272 Info.FirstArg = P; 2273 Info.SecondArg = A; 2274 return Sema::TDK_NonDeducedMismatch; 2275 } 2276 2277 // Can't deduce anything, but that's okay. 2278 return Sema::TDK_Success; 2279 case TemplateArgument::Pack: 2280 llvm_unreachable("Argument packs should be expanded by the caller!"); 2281 } 2282 2283 llvm_unreachable("Invalid TemplateArgument Kind!"); 2284 } 2285 2286 /// Determine whether there is a template argument to be used for 2287 /// deduction. 2288 /// 2289 /// This routine "expands" argument packs in-place, overriding its input 2290 /// parameters so that \c Args[ArgIdx] will be the available template argument. 2291 /// 2292 /// \returns true if there is another template argument (which will be at 2293 /// \c Args[ArgIdx]), false otherwise. 2294 static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args, 2295 unsigned &ArgIdx) { 2296 if (ArgIdx == Args.size()) 2297 return false; 2298 2299 const TemplateArgument &Arg = Args[ArgIdx]; 2300 if (Arg.getKind() != TemplateArgument::Pack) 2301 return true; 2302 2303 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?"); 2304 Args = Arg.pack_elements(); 2305 ArgIdx = 0; 2306 return ArgIdx < Args.size(); 2307 } 2308 2309 /// Determine whether the given set of template arguments has a pack 2310 /// expansion that is not the last template argument. 2311 static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) { 2312 bool FoundPackExpansion = false; 2313 for (const auto &A : Args) { 2314 if (FoundPackExpansion) 2315 return true; 2316 2317 if (A.getKind() == TemplateArgument::Pack) 2318 return hasPackExpansionBeforeEnd(A.pack_elements()); 2319 2320 // FIXME: If this is a fixed-arity pack expansion from an outer level of 2321 // templates, it should not be treated as a pack expansion. 2322 if (A.isPackExpansion()) 2323 FoundPackExpansion = true; 2324 } 2325 2326 return false; 2327 } 2328 2329 static Sema::TemplateDeductionResult 2330 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, 2331 ArrayRef<TemplateArgument> Ps, 2332 ArrayRef<TemplateArgument> As, 2333 TemplateDeductionInfo &Info, 2334 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2335 bool NumberOfArgumentsMustMatch) { 2336 // C++0x [temp.deduct.type]p9: 2337 // If the template argument list of P contains a pack expansion that is not 2338 // the last template argument, the entire template argument list is a 2339 // non-deduced context. 2340 if (hasPackExpansionBeforeEnd(Ps)) 2341 return Sema::TDK_Success; 2342 2343 // C++0x [temp.deduct.type]p9: 2344 // If P has a form that contains <T> or <i>, then each argument Pi of the 2345 // respective template argument list P is compared with the corresponding 2346 // argument Ai of the corresponding template argument list of A. 2347 unsigned ArgIdx = 0, ParamIdx = 0; 2348 for (; hasTemplateArgumentForDeduction(Ps, ParamIdx); ++ParamIdx) { 2349 const TemplateArgument &P = Ps[ParamIdx]; 2350 if (!P.isPackExpansion()) { 2351 // The simple case: deduce template arguments by matching Pi and Ai. 2352 2353 // Check whether we have enough arguments. 2354 if (!hasTemplateArgumentForDeduction(As, ArgIdx)) 2355 return NumberOfArgumentsMustMatch 2356 ? Sema::TDK_MiscellaneousDeductionFailure 2357 : Sema::TDK_Success; 2358 2359 // C++1z [temp.deduct.type]p9: 2360 // During partial ordering, if Ai was originally a pack expansion [and] 2361 // Pi is not a pack expansion, template argument deduction fails. 2362 if (As[ArgIdx].isPackExpansion()) 2363 return Sema::TDK_MiscellaneousDeductionFailure; 2364 2365 // Perform deduction for this Pi/Ai pair. 2366 if (auto Result = DeduceTemplateArguments(S, TemplateParams, P, 2367 As[ArgIdx], Info, Deduced)) 2368 return Result; 2369 2370 // Move to the next argument. 2371 ++ArgIdx; 2372 continue; 2373 } 2374 2375 // The parameter is a pack expansion. 2376 2377 // C++0x [temp.deduct.type]p9: 2378 // If Pi is a pack expansion, then the pattern of Pi is compared with 2379 // each remaining argument in the template argument list of A. Each 2380 // comparison deduces template arguments for subsequent positions in the 2381 // template parameter packs expanded by Pi. 2382 TemplateArgument Pattern = P.getPackExpansionPattern(); 2383 2384 // Prepare to deduce the packs within the pattern. 2385 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern); 2386 2387 // Keep track of the deduced template arguments for each parameter pack 2388 // expanded by this pack expansion (the outer index) and for each 2389 // template argument (the inner SmallVectors). 2390 for (; hasTemplateArgumentForDeduction(As, ArgIdx) && 2391 PackScope.hasNextElement(); 2392 ++ArgIdx) { 2393 // Deduce template arguments from the pattern. 2394 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pattern, 2395 As[ArgIdx], Info, Deduced)) 2396 return Result; 2397 2398 PackScope.nextPackElement(); 2399 } 2400 2401 // Build argument packs for each of the parameter packs expanded by this 2402 // pack expansion. 2403 if (auto Result = PackScope.finish()) 2404 return Result; 2405 } 2406 2407 return Sema::TDK_Success; 2408 } 2409 2410 static Sema::TemplateDeductionResult 2411 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, 2412 const TemplateArgumentList &ParamList, 2413 const TemplateArgumentList &ArgList, 2414 TemplateDeductionInfo &Info, 2415 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 2416 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(), 2417 ArgList.asArray(), Info, Deduced, 2418 /*NumberOfArgumentsMustMatch=*/false); 2419 } 2420 2421 /// Determine whether two template arguments are the same. 2422 static bool isSameTemplateArg(ASTContext &Context, 2423 TemplateArgument X, 2424 const TemplateArgument &Y, 2425 bool PackExpansionMatchesPack = false) { 2426 // If we're checking deduced arguments (X) against original arguments (Y), 2427 // we will have flattened packs to non-expansions in X. 2428 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion()) 2429 X = X.getPackExpansionPattern(); 2430 2431 if (X.getKind() != Y.getKind()) 2432 return false; 2433 2434 switch (X.getKind()) { 2435 case TemplateArgument::Null: 2436 llvm_unreachable("Comparing NULL template argument"); 2437 2438 case TemplateArgument::Type: 2439 return Context.getCanonicalType(X.getAsType()) == 2440 Context.getCanonicalType(Y.getAsType()); 2441 2442 case TemplateArgument::Declaration: 2443 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl()); 2444 2445 case TemplateArgument::NullPtr: 2446 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()); 2447 2448 case TemplateArgument::Template: 2449 case TemplateArgument::TemplateExpansion: 2450 return Context.getCanonicalTemplateName( 2451 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() == 2452 Context.getCanonicalTemplateName( 2453 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer(); 2454 2455 case TemplateArgument::Integral: 2456 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral()); 2457 2458 case TemplateArgument::Expression: { 2459 llvm::FoldingSetNodeID XID, YID; 2460 X.getAsExpr()->Profile(XID, Context, true); 2461 Y.getAsExpr()->Profile(YID, Context, true); 2462 return XID == YID; 2463 } 2464 2465 case TemplateArgument::Pack: 2466 if (X.pack_size() != Y.pack_size()) 2467 return false; 2468 2469 for (TemplateArgument::pack_iterator XP = X.pack_begin(), 2470 XPEnd = X.pack_end(), 2471 YP = Y.pack_begin(); 2472 XP != XPEnd; ++XP, ++YP) 2473 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack)) 2474 return false; 2475 2476 return true; 2477 } 2478 2479 llvm_unreachable("Invalid TemplateArgument Kind!"); 2480 } 2481 2482 /// Allocate a TemplateArgumentLoc where all locations have 2483 /// been initialized to the given location. 2484 /// 2485 /// \param Arg The template argument we are producing template argument 2486 /// location information for. 2487 /// 2488 /// \param NTTPType For a declaration template argument, the type of 2489 /// the non-type template parameter that corresponds to this template 2490 /// argument. Can be null if no type sugar is available to add to the 2491 /// type from the template argument. 2492 /// 2493 /// \param Loc The source location to use for the resulting template 2494 /// argument. 2495 TemplateArgumentLoc 2496 Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, 2497 QualType NTTPType, SourceLocation Loc) { 2498 switch (Arg.getKind()) { 2499 case TemplateArgument::Null: 2500 llvm_unreachable("Can't get a NULL template argument here"); 2501 2502 case TemplateArgument::Type: 2503 return TemplateArgumentLoc( 2504 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc)); 2505 2506 case TemplateArgument::Declaration: { 2507 if (NTTPType.isNull()) 2508 NTTPType = Arg.getParamTypeForDecl(); 2509 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) 2510 .getAs<Expr>(); 2511 return TemplateArgumentLoc(TemplateArgument(E), E); 2512 } 2513 2514 case TemplateArgument::NullPtr: { 2515 if (NTTPType.isNull()) 2516 NTTPType = Arg.getNullPtrType(); 2517 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) 2518 .getAs<Expr>(); 2519 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true), 2520 E); 2521 } 2522 2523 case TemplateArgument::Integral: { 2524 Expr *E = 2525 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>(); 2526 return TemplateArgumentLoc(TemplateArgument(E), E); 2527 } 2528 2529 case TemplateArgument::Template: 2530 case TemplateArgument::TemplateExpansion: { 2531 NestedNameSpecifierLocBuilder Builder; 2532 TemplateName Template = Arg.getAsTemplateOrTemplatePattern(); 2533 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) 2534 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc); 2535 else if (QualifiedTemplateName *QTN = 2536 Template.getAsQualifiedTemplateName()) 2537 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc); 2538 2539 if (Arg.getKind() == TemplateArgument::Template) 2540 return TemplateArgumentLoc(Context, Arg, 2541 Builder.getWithLocInContext(Context), Loc); 2542 2543 return TemplateArgumentLoc( 2544 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc); 2545 } 2546 2547 case TemplateArgument::Expression: 2548 return TemplateArgumentLoc(Arg, Arg.getAsExpr()); 2549 2550 case TemplateArgument::Pack: 2551 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo()); 2552 } 2553 2554 llvm_unreachable("Invalid TemplateArgument Kind!"); 2555 } 2556 2557 TemplateArgumentLoc 2558 Sema::getIdentityTemplateArgumentLoc(NamedDecl *TemplateParm, 2559 SourceLocation Location) { 2560 return getTrivialTemplateArgumentLoc( 2561 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location); 2562 } 2563 2564 /// Convert the given deduced template argument and add it to the set of 2565 /// fully-converted template arguments. 2566 static bool 2567 ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, 2568 DeducedTemplateArgument Arg, 2569 NamedDecl *Template, 2570 TemplateDeductionInfo &Info, 2571 bool IsDeduced, 2572 SmallVectorImpl<TemplateArgument> &Output) { 2573 auto ConvertArg = [&](DeducedTemplateArgument Arg, 2574 unsigned ArgumentPackIndex) { 2575 // Convert the deduced template argument into a template 2576 // argument that we can check, almost as if the user had written 2577 // the template argument explicitly. 2578 TemplateArgumentLoc ArgLoc = 2579 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation()); 2580 2581 // Check the template argument, converting it as necessary. 2582 return S.CheckTemplateArgument( 2583 Param, ArgLoc, Template, Template->getLocation(), 2584 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output, 2585 IsDeduced 2586 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound 2587 : Sema::CTAK_Deduced) 2588 : Sema::CTAK_Specified); 2589 }; 2590 2591 if (Arg.getKind() == TemplateArgument::Pack) { 2592 // This is a template argument pack, so check each of its arguments against 2593 // the template parameter. 2594 SmallVector<TemplateArgument, 2> PackedArgsBuilder; 2595 for (const auto &P : Arg.pack_elements()) { 2596 // When converting the deduced template argument, append it to the 2597 // general output list. We need to do this so that the template argument 2598 // checking logic has all of the prior template arguments available. 2599 DeducedTemplateArgument InnerArg(P); 2600 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound()); 2601 assert(InnerArg.getKind() != TemplateArgument::Pack && 2602 "deduced nested pack"); 2603 if (P.isNull()) { 2604 // We deduced arguments for some elements of this pack, but not for 2605 // all of them. This happens if we get a conditionally-non-deduced 2606 // context in a pack expansion (such as an overload set in one of the 2607 // arguments). 2608 S.Diag(Param->getLocation(), 2609 diag::err_template_arg_deduced_incomplete_pack) 2610 << Arg << Param; 2611 return true; 2612 } 2613 if (ConvertArg(InnerArg, PackedArgsBuilder.size())) 2614 return true; 2615 2616 // Move the converted template argument into our argument pack. 2617 PackedArgsBuilder.push_back(Output.pop_back_val()); 2618 } 2619 2620 // If the pack is empty, we still need to substitute into the parameter 2621 // itself, in case that substitution fails. 2622 if (PackedArgsBuilder.empty()) { 2623 LocalInstantiationScope Scope(S); 2624 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output); 2625 MultiLevelTemplateArgumentList Args(TemplateArgs); 2626 2627 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2628 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template, 2629 NTTP, Output, 2630 Template->getSourceRange()); 2631 if (Inst.isInvalid() || 2632 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(), 2633 NTTP->getDeclName()).isNull()) 2634 return true; 2635 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) { 2636 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template, 2637 TTP, Output, 2638 Template->getSourceRange()); 2639 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args)) 2640 return true; 2641 } 2642 // For type parameters, no substitution is ever required. 2643 } 2644 2645 // Create the resulting argument pack. 2646 Output.push_back( 2647 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder)); 2648 return false; 2649 } 2650 2651 return ConvertArg(Arg, 0); 2652 } 2653 2654 // FIXME: This should not be a template, but 2655 // ClassTemplatePartialSpecializationDecl sadly does not derive from 2656 // TemplateDecl. 2657 template<typename TemplateDeclT> 2658 static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments( 2659 Sema &S, TemplateDeclT *Template, bool IsDeduced, 2660 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2661 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder, 2662 LocalInstantiationScope *CurrentInstantiationScope = nullptr, 2663 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) { 2664 TemplateParameterList *TemplateParams = Template->getTemplateParameters(); 2665 2666 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 2667 NamedDecl *Param = TemplateParams->getParam(I); 2668 2669 // C++0x [temp.arg.explicit]p3: 2670 // A trailing template parameter pack (14.5.3) not otherwise deduced will 2671 // be deduced to an empty sequence of template arguments. 2672 // FIXME: Where did the word "trailing" come from? 2673 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) { 2674 if (auto Result = 2675 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish()) 2676 return Result; 2677 } 2678 2679 if (!Deduced[I].isNull()) { 2680 if (I < NumAlreadyConverted) { 2681 // We may have had explicitly-specified template arguments for a 2682 // template parameter pack (that may or may not have been extended 2683 // via additional deduced arguments). 2684 if (Param->isParameterPack() && CurrentInstantiationScope && 2685 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) { 2686 // Forget the partially-substituted pack; its substitution is now 2687 // complete. 2688 CurrentInstantiationScope->ResetPartiallySubstitutedPack(); 2689 // We still need to check the argument in case it was extended by 2690 // deduction. 2691 } else { 2692 // We have already fully type-checked and converted this 2693 // argument, because it was explicitly-specified. Just record the 2694 // presence of this argument. 2695 Builder.push_back(Deduced[I]); 2696 continue; 2697 } 2698 } 2699 2700 // We may have deduced this argument, so it still needs to be 2701 // checked and converted. 2702 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info, 2703 IsDeduced, Builder)) { 2704 Info.Param = makeTemplateParameter(Param); 2705 // FIXME: These template arguments are temporary. Free them! 2706 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder)); 2707 return Sema::TDK_SubstitutionFailure; 2708 } 2709 2710 continue; 2711 } 2712 2713 // Substitute into the default template argument, if available. 2714 bool HasDefaultArg = false; 2715 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template); 2716 if (!TD) { 2717 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) || 2718 isa<VarTemplatePartialSpecializationDecl>(Template)); 2719 return Sema::TDK_Incomplete; 2720 } 2721 2722 TemplateArgumentLoc DefArg; 2723 { 2724 Qualifiers ThisTypeQuals; 2725 CXXRecordDecl *ThisContext = nullptr; 2726 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext())) 2727 if (Rec->isLambda()) 2728 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) { 2729 ThisContext = Method->getParent(); 2730 ThisTypeQuals = Method->getMethodQualifiers(); 2731 } 2732 2733 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals, 2734 S.getLangOpts().CPlusPlus17); 2735 2736 DefArg = S.SubstDefaultTemplateArgumentIfAvailable( 2737 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder, 2738 HasDefaultArg); 2739 } 2740 2741 // If there was no default argument, deduction is incomplete. 2742 if (DefArg.getArgument().isNull()) { 2743 Info.Param = makeTemplateParameter( 2744 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 2745 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder)); 2746 if (PartialOverloading) break; 2747 2748 return HasDefaultArg ? Sema::TDK_SubstitutionFailure 2749 : Sema::TDK_Incomplete; 2750 } 2751 2752 // Check whether we can actually use the default argument. 2753 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(), 2754 TD->getSourceRange().getEnd(), 0, Builder, 2755 Sema::CTAK_Specified)) { 2756 Info.Param = makeTemplateParameter( 2757 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 2758 // FIXME: These template arguments are temporary. Free them! 2759 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder)); 2760 return Sema::TDK_SubstitutionFailure; 2761 } 2762 2763 // If we get here, we successfully used the default template argument. 2764 } 2765 2766 return Sema::TDK_Success; 2767 } 2768 2769 static DeclContext *getAsDeclContextOrEnclosing(Decl *D) { 2770 if (auto *DC = dyn_cast<DeclContext>(D)) 2771 return DC; 2772 return D->getDeclContext(); 2773 } 2774 2775 template<typename T> struct IsPartialSpecialization { 2776 static constexpr bool value = false; 2777 }; 2778 template<> 2779 struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> { 2780 static constexpr bool value = true; 2781 }; 2782 template<> 2783 struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> { 2784 static constexpr bool value = true; 2785 }; 2786 template <typename TemplateDeclT> 2787 static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) { 2788 return false; 2789 } 2790 template <> 2791 bool DeducedArgsNeedReplacement<VarTemplatePartialSpecializationDecl>( 2792 VarTemplatePartialSpecializationDecl *Spec) { 2793 return !Spec->isClassScopeExplicitSpecialization(); 2794 } 2795 template <> 2796 bool DeducedArgsNeedReplacement<ClassTemplatePartialSpecializationDecl>( 2797 ClassTemplatePartialSpecializationDecl *Spec) { 2798 return !Spec->isClassScopeExplicitSpecialization(); 2799 } 2800 2801 template<typename TemplateDeclT> 2802 static Sema::TemplateDeductionResult 2803 CheckDeducedArgumentConstraints(Sema& S, TemplateDeclT *Template, 2804 ArrayRef<TemplateArgument> DeducedArgs, 2805 TemplateDeductionInfo& Info) { 2806 llvm::SmallVector<const Expr *, 3> AssociatedConstraints; 2807 Template->getAssociatedConstraints(AssociatedConstraints); 2808 MultiLevelTemplateArgumentList MLTAL; 2809 2810 bool NeedsReplacement = DeducedArgsNeedReplacement(Template); 2811 TemplateArgumentList DeducedTAL{TemplateArgumentList::OnStack, DeducedArgs}; 2812 2813 MLTAL = S.getTemplateInstantiationArgs( 2814 Template, /*InnerMost*/ NeedsReplacement ? nullptr : &DeducedTAL, 2815 /*RelativeToPrimary*/ true, /*Pattern*/ 2816 nullptr, /*LookBeyondLambda*/ true); 2817 2818 // getTemplateInstantiationArgs picks up the non-deduced version of the 2819 // template args when this is a variable template partial specialization and 2820 // not class-scope explicit specialization, so replace with Deduced Args 2821 // instead of adding to inner-most. 2822 if (NeedsReplacement) 2823 MLTAL.replaceInnermostTemplateArguments(DeducedArgs); 2824 2825 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL, 2826 Info.getLocation(), 2827 Info.AssociatedConstraintsSatisfaction) || 2828 !Info.AssociatedConstraintsSatisfaction.IsSatisfied) { 2829 Info.reset(TemplateArgumentList::CreateCopy(S.Context, DeducedArgs)); 2830 return Sema::TDK_ConstraintsNotSatisfied; 2831 } 2832 return Sema::TDK_Success; 2833 } 2834 2835 /// Complete template argument deduction for a partial specialization. 2836 template <typename T> 2837 static std::enable_if_t<IsPartialSpecialization<T>::value, 2838 Sema::TemplateDeductionResult> 2839 FinishTemplateArgumentDeduction( 2840 Sema &S, T *Partial, bool IsPartialOrdering, 2841 const TemplateArgumentList &TemplateArgs, 2842 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2843 TemplateDeductionInfo &Info) { 2844 // Unevaluated SFINAE context. 2845 EnterExpressionEvaluationContext Unevaluated( 2846 S, Sema::ExpressionEvaluationContext::Unevaluated); 2847 Sema::SFINAETrap Trap(S); 2848 2849 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial)); 2850 2851 // C++ [temp.deduct.type]p2: 2852 // [...] or if any template argument remains neither deduced nor 2853 // explicitly specified, template argument deduction fails. 2854 SmallVector<TemplateArgument, 4> Builder; 2855 if (auto Result = ConvertDeducedTemplateArguments( 2856 S, Partial, IsPartialOrdering, Deduced, Info, Builder)) 2857 return Result; 2858 2859 // Form the template argument list from the deduced template arguments. 2860 TemplateArgumentList *DeducedArgumentList 2861 = TemplateArgumentList::CreateCopy(S.Context, Builder); 2862 2863 Info.reset(DeducedArgumentList); 2864 2865 // Substitute the deduced template arguments into the template 2866 // arguments of the class template partial specialization, and 2867 // verify that the instantiated template arguments are both valid 2868 // and are equivalent to the template arguments originally provided 2869 // to the class template. 2870 LocalInstantiationScope InstScope(S); 2871 auto *Template = Partial->getSpecializedTemplate(); 2872 const ASTTemplateArgumentListInfo *PartialTemplArgInfo = 2873 Partial->getTemplateArgsAsWritten(); 2874 2875 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc, 2876 PartialTemplArgInfo->RAngleLoc); 2877 2878 if (S.SubstTemplateArguments( 2879 PartialTemplArgInfo->arguments(), 2880 MultiLevelTemplateArgumentList(*DeducedArgumentList), InstArgs)) { 2881 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx; 2882 if (ParamIdx >= Partial->getTemplateParameters()->size()) 2883 ParamIdx = Partial->getTemplateParameters()->size() - 1; 2884 2885 Decl *Param = const_cast<NamedDecl *>( 2886 Partial->getTemplateParameters()->getParam(ParamIdx)); 2887 Info.Param = makeTemplateParameter(Param); 2888 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument(); 2889 return Sema::TDK_SubstitutionFailure; 2890 } 2891 2892 bool ConstraintsNotSatisfied; 2893 SmallVector<TemplateArgument, 4> ConvertedInstArgs; 2894 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs, 2895 false, ConvertedInstArgs, 2896 /*UpdateArgsWithConversions=*/true, 2897 &ConstraintsNotSatisfied)) 2898 return ConstraintsNotSatisfied ? Sema::TDK_ConstraintsNotSatisfied : 2899 Sema::TDK_SubstitutionFailure; 2900 2901 TemplateParameterList *TemplateParams = Template->getTemplateParameters(); 2902 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { 2903 TemplateArgument InstArg = ConvertedInstArgs.data()[I]; 2904 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) { 2905 Info.Param = makeTemplateParameter(TemplateParams->getParam(I)); 2906 Info.FirstArg = TemplateArgs[I]; 2907 Info.SecondArg = InstArg; 2908 return Sema::TDK_NonDeducedMismatch; 2909 } 2910 } 2911 2912 if (Trap.hasErrorOccurred()) 2913 return Sema::TDK_SubstitutionFailure; 2914 2915 if (auto Result = CheckDeducedArgumentConstraints(S, Partial, Builder, Info)) 2916 return Result; 2917 2918 return Sema::TDK_Success; 2919 } 2920 2921 /// Complete template argument deduction for a class or variable template, 2922 /// when partial ordering against a partial specialization. 2923 // FIXME: Factor out duplication with partial specialization version above. 2924 static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction( 2925 Sema &S, TemplateDecl *Template, bool PartialOrdering, 2926 const TemplateArgumentList &TemplateArgs, 2927 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2928 TemplateDeductionInfo &Info) { 2929 // Unevaluated SFINAE context. 2930 EnterExpressionEvaluationContext Unevaluated( 2931 S, Sema::ExpressionEvaluationContext::Unevaluated); 2932 Sema::SFINAETrap Trap(S); 2933 2934 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template)); 2935 2936 // C++ [temp.deduct.type]p2: 2937 // [...] or if any template argument remains neither deduced nor 2938 // explicitly specified, template argument deduction fails. 2939 SmallVector<TemplateArgument, 4> Builder; 2940 if (auto Result = ConvertDeducedTemplateArguments( 2941 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder)) 2942 return Result; 2943 2944 // Check that we produced the correct argument list. 2945 TemplateParameterList *TemplateParams = Template->getTemplateParameters(); 2946 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { 2947 TemplateArgument InstArg = Builder[I]; 2948 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, 2949 /*PackExpansionMatchesPack*/true)) { 2950 Info.Param = makeTemplateParameter(TemplateParams->getParam(I)); 2951 Info.FirstArg = TemplateArgs[I]; 2952 Info.SecondArg = InstArg; 2953 return Sema::TDK_NonDeducedMismatch; 2954 } 2955 } 2956 2957 if (Trap.hasErrorOccurred()) 2958 return Sema::TDK_SubstitutionFailure; 2959 2960 if (auto Result = CheckDeducedArgumentConstraints(S, Template, Builder, 2961 Info)) 2962 return Result; 2963 2964 return Sema::TDK_Success; 2965 } 2966 2967 /// Perform template argument deduction to determine whether 2968 /// the given template arguments match the given class template 2969 /// partial specialization per C++ [temp.class.spec.match]. 2970 Sema::TemplateDeductionResult 2971 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 2972 const TemplateArgumentList &TemplateArgs, 2973 TemplateDeductionInfo &Info) { 2974 if (Partial->isInvalidDecl()) 2975 return TDK_Invalid; 2976 2977 // C++ [temp.class.spec.match]p2: 2978 // A partial specialization matches a given actual template 2979 // argument list if the template arguments of the partial 2980 // specialization can be deduced from the actual template argument 2981 // list (14.8.2). 2982 2983 // Unevaluated SFINAE context. 2984 EnterExpressionEvaluationContext Unevaluated( 2985 *this, Sema::ExpressionEvaluationContext::Unevaluated); 2986 SFINAETrap Trap(*this); 2987 2988 // This deduction has no relation to any outer instantiation we might be 2989 // performing. 2990 LocalInstantiationScope InstantiationScope(*this); 2991 2992 SmallVector<DeducedTemplateArgument, 4> Deduced; 2993 Deduced.resize(Partial->getTemplateParameters()->size()); 2994 if (TemplateDeductionResult Result 2995 = ::DeduceTemplateArguments(*this, 2996 Partial->getTemplateParameters(), 2997 Partial->getTemplateArgs(), 2998 TemplateArgs, Info, Deduced)) 2999 return Result; 3000 3001 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 3002 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs, 3003 Info); 3004 if (Inst.isInvalid()) 3005 return TDK_InstantiationDepth; 3006 3007 if (Trap.hasErrorOccurred()) 3008 return Sema::TDK_SubstitutionFailure; 3009 3010 TemplateDeductionResult Result; 3011 runWithSufficientStackSpace(Info.getLocation(), [&] { 3012 Result = ::FinishTemplateArgumentDeduction(*this, Partial, 3013 /*IsPartialOrdering=*/false, 3014 TemplateArgs, Deduced, Info); 3015 }); 3016 return Result; 3017 } 3018 3019 /// Perform template argument deduction to determine whether 3020 /// the given template arguments match the given variable template 3021 /// partial specialization per C++ [temp.class.spec.match]. 3022 Sema::TemplateDeductionResult 3023 Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 3024 const TemplateArgumentList &TemplateArgs, 3025 TemplateDeductionInfo &Info) { 3026 if (Partial->isInvalidDecl()) 3027 return TDK_Invalid; 3028 3029 // C++ [temp.class.spec.match]p2: 3030 // A partial specialization matches a given actual template 3031 // argument list if the template arguments of the partial 3032 // specialization can be deduced from the actual template argument 3033 // list (14.8.2). 3034 3035 // Unevaluated SFINAE context. 3036 EnterExpressionEvaluationContext Unevaluated( 3037 *this, Sema::ExpressionEvaluationContext::Unevaluated); 3038 SFINAETrap Trap(*this); 3039 3040 // This deduction has no relation to any outer instantiation we might be 3041 // performing. 3042 LocalInstantiationScope InstantiationScope(*this); 3043 3044 SmallVector<DeducedTemplateArgument, 4> Deduced; 3045 Deduced.resize(Partial->getTemplateParameters()->size()); 3046 if (TemplateDeductionResult Result = ::DeduceTemplateArguments( 3047 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(), 3048 TemplateArgs, Info, Deduced)) 3049 return Result; 3050 3051 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 3052 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs, 3053 Info); 3054 if (Inst.isInvalid()) 3055 return TDK_InstantiationDepth; 3056 3057 if (Trap.hasErrorOccurred()) 3058 return Sema::TDK_SubstitutionFailure; 3059 3060 TemplateDeductionResult Result; 3061 runWithSufficientStackSpace(Info.getLocation(), [&] { 3062 Result = ::FinishTemplateArgumentDeduction(*this, Partial, 3063 /*IsPartialOrdering=*/false, 3064 TemplateArgs, Deduced, Info); 3065 }); 3066 return Result; 3067 } 3068 3069 /// Determine whether the given type T is a simple-template-id type. 3070 static bool isSimpleTemplateIdType(QualType T) { 3071 if (const TemplateSpecializationType *Spec 3072 = T->getAs<TemplateSpecializationType>()) 3073 return Spec->getTemplateName().getAsTemplateDecl() != nullptr; 3074 3075 // C++17 [temp.local]p2: 3076 // the injected-class-name [...] is equivalent to the template-name followed 3077 // by the template-arguments of the class template specialization or partial 3078 // specialization enclosed in <> 3079 // ... which means it's equivalent to a simple-template-id. 3080 // 3081 // This only arises during class template argument deduction for a copy 3082 // deduction candidate, where it permits slicing. 3083 if (T->getAs<InjectedClassNameType>()) 3084 return true; 3085 3086 return false; 3087 } 3088 3089 /// Substitute the explicitly-provided template arguments into the 3090 /// given function template according to C++ [temp.arg.explicit]. 3091 /// 3092 /// \param FunctionTemplate the function template into which the explicit 3093 /// template arguments will be substituted. 3094 /// 3095 /// \param ExplicitTemplateArgs the explicitly-specified template 3096 /// arguments. 3097 /// 3098 /// \param Deduced the deduced template arguments, which will be populated 3099 /// with the converted and checked explicit template arguments. 3100 /// 3101 /// \param ParamTypes will be populated with the instantiated function 3102 /// parameters. 3103 /// 3104 /// \param FunctionType if non-NULL, the result type of the function template 3105 /// will also be instantiated and the pointed-to value will be updated with 3106 /// the instantiated function type. 3107 /// 3108 /// \param Info if substitution fails for any reason, this object will be 3109 /// populated with more information about the failure. 3110 /// 3111 /// \returns TDK_Success if substitution was successful, or some failure 3112 /// condition. 3113 Sema::TemplateDeductionResult 3114 Sema::SubstituteExplicitTemplateArguments( 3115 FunctionTemplateDecl *FunctionTemplate, 3116 TemplateArgumentListInfo &ExplicitTemplateArgs, 3117 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3118 SmallVectorImpl<QualType> &ParamTypes, 3119 QualType *FunctionType, 3120 TemplateDeductionInfo &Info) { 3121 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 3122 TemplateParameterList *TemplateParams 3123 = FunctionTemplate->getTemplateParameters(); 3124 3125 if (ExplicitTemplateArgs.size() == 0) { 3126 // No arguments to substitute; just copy over the parameter types and 3127 // fill in the function type. 3128 for (auto P : Function->parameters()) 3129 ParamTypes.push_back(P->getType()); 3130 3131 if (FunctionType) 3132 *FunctionType = Function->getType(); 3133 return TDK_Success; 3134 } 3135 3136 // Unevaluated SFINAE context. 3137 EnterExpressionEvaluationContext Unevaluated( 3138 *this, Sema::ExpressionEvaluationContext::Unevaluated); 3139 SFINAETrap Trap(*this); 3140 3141 // C++ [temp.arg.explicit]p3: 3142 // Template arguments that are present shall be specified in the 3143 // declaration order of their corresponding template-parameters. The 3144 // template argument list shall not specify more template-arguments than 3145 // there are corresponding template-parameters. 3146 SmallVector<TemplateArgument, 4> Builder; 3147 3148 // Enter a new template instantiation context where we check the 3149 // explicitly-specified template arguments against this function template, 3150 // and then substitute them into the function parameter types. 3151 SmallVector<TemplateArgument, 4> DeducedArgs; 3152 InstantiatingTemplate Inst( 3153 *this, Info.getLocation(), FunctionTemplate, DeducedArgs, 3154 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info); 3155 if (Inst.isInvalid()) 3156 return TDK_InstantiationDepth; 3157 3158 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(), 3159 ExplicitTemplateArgs, true, Builder, false) || 3160 Trap.hasErrorOccurred()) { 3161 unsigned Index = Builder.size(); 3162 if (Index >= TemplateParams->size()) 3163 return TDK_SubstitutionFailure; 3164 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index)); 3165 return TDK_InvalidExplicitArguments; 3166 } 3167 3168 // Form the template argument list from the explicitly-specified 3169 // template arguments. 3170 TemplateArgumentList *ExplicitArgumentList 3171 = TemplateArgumentList::CreateCopy(Context, Builder); 3172 Info.setExplicitArgs(ExplicitArgumentList); 3173 3174 // Template argument deduction and the final substitution should be 3175 // done in the context of the templated declaration. Explicit 3176 // argument substitution, on the other hand, needs to happen in the 3177 // calling context. 3178 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 3179 3180 // If we deduced template arguments for a template parameter pack, 3181 // note that the template argument pack is partially substituted and record 3182 // the explicit template arguments. They'll be used as part of deduction 3183 // for this template parameter pack. 3184 unsigned PartiallySubstitutedPackIndex = -1u; 3185 if (!Builder.empty()) { 3186 const TemplateArgument &Arg = Builder.back(); 3187 if (Arg.getKind() == TemplateArgument::Pack) { 3188 auto *Param = TemplateParams->getParam(Builder.size() - 1); 3189 // If this is a fully-saturated fixed-size pack, it should be 3190 // fully-substituted, not partially-substituted. 3191 Optional<unsigned> Expansions = getExpandedPackSize(Param); 3192 if (!Expansions || Arg.pack_size() < *Expansions) { 3193 PartiallySubstitutedPackIndex = Builder.size() - 1; 3194 CurrentInstantiationScope->SetPartiallySubstitutedPack( 3195 Param, Arg.pack_begin(), Arg.pack_size()); 3196 } 3197 } 3198 } 3199 3200 const FunctionProtoType *Proto 3201 = Function->getType()->getAs<FunctionProtoType>(); 3202 assert(Proto && "Function template does not have a prototype?"); 3203 3204 // Isolate our substituted parameters from our caller. 3205 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true); 3206 3207 ExtParameterInfoBuilder ExtParamInfos; 3208 3209 // Instantiate the types of each of the function parameters given the 3210 // explicitly-specified template arguments. If the function has a trailing 3211 // return type, substitute it after the arguments to ensure we substitute 3212 // in lexical order. 3213 if (Proto->hasTrailingReturn()) { 3214 if (SubstParmTypes(Function->getLocation(), Function->parameters(), 3215 Proto->getExtParameterInfosOrNull(), 3216 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 3217 ParamTypes, /*params*/ nullptr, ExtParamInfos)) 3218 return TDK_SubstitutionFailure; 3219 } 3220 3221 // Instantiate the return type. 3222 QualType ResultType; 3223 { 3224 // C++11 [expr.prim.general]p3: 3225 // If a declaration declares a member function or member function 3226 // template of a class X, the expression this is a prvalue of type 3227 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 3228 // and the end of the function-definition, member-declarator, or 3229 // declarator. 3230 Qualifiers ThisTypeQuals; 3231 CXXRecordDecl *ThisContext = nullptr; 3232 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 3233 ThisContext = Method->getParent(); 3234 ThisTypeQuals = Method->getMethodQualifiers(); 3235 } 3236 3237 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals, 3238 getLangOpts().CPlusPlus11); 3239 3240 ResultType = 3241 SubstType(Proto->getReturnType(), 3242 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 3243 Function->getTypeSpecStartLoc(), Function->getDeclName()); 3244 if (ResultType.isNull() || Trap.hasErrorOccurred()) 3245 return TDK_SubstitutionFailure; 3246 // CUDA: Kernel function must have 'void' return type. 3247 if (getLangOpts().CUDA) 3248 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) { 3249 Diag(Function->getLocation(), diag::err_kern_type_not_void_return) 3250 << Function->getType() << Function->getSourceRange(); 3251 return TDK_SubstitutionFailure; 3252 } 3253 } 3254 3255 // Instantiate the types of each of the function parameters given the 3256 // explicitly-specified template arguments if we didn't do so earlier. 3257 if (!Proto->hasTrailingReturn() && 3258 SubstParmTypes(Function->getLocation(), Function->parameters(), 3259 Proto->getExtParameterInfosOrNull(), 3260 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 3261 ParamTypes, /*params*/ nullptr, ExtParamInfos)) 3262 return TDK_SubstitutionFailure; 3263 3264 if (FunctionType) { 3265 auto EPI = Proto->getExtProtoInfo(); 3266 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size()); 3267 3268 // In C++1z onwards, exception specifications are part of the function type, 3269 // so substitution into the type must also substitute into the exception 3270 // specification. 3271 SmallVector<QualType, 4> ExceptionStorage; 3272 if (getLangOpts().CPlusPlus17 && 3273 SubstExceptionSpec( 3274 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage, 3275 MultiLevelTemplateArgumentList(*ExplicitArgumentList))) 3276 return TDK_SubstitutionFailure; 3277 3278 *FunctionType = BuildFunctionType(ResultType, ParamTypes, 3279 Function->getLocation(), 3280 Function->getDeclName(), 3281 EPI); 3282 if (FunctionType->isNull() || Trap.hasErrorOccurred()) 3283 return TDK_SubstitutionFailure; 3284 } 3285 3286 // C++ [temp.arg.explicit]p2: 3287 // Trailing template arguments that can be deduced (14.8.2) may be 3288 // omitted from the list of explicit template-arguments. If all of the 3289 // template arguments can be deduced, they may all be omitted; in this 3290 // case, the empty template argument list <> itself may also be omitted. 3291 // 3292 // Take all of the explicitly-specified arguments and put them into 3293 // the set of deduced template arguments. The partially-substituted 3294 // parameter pack, however, will be set to NULL since the deduction 3295 // mechanism handles the partially-substituted argument pack directly. 3296 Deduced.reserve(TemplateParams->size()); 3297 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) { 3298 const TemplateArgument &Arg = ExplicitArgumentList->get(I); 3299 if (I == PartiallySubstitutedPackIndex) 3300 Deduced.push_back(DeducedTemplateArgument()); 3301 else 3302 Deduced.push_back(Arg); 3303 } 3304 3305 return TDK_Success; 3306 } 3307 3308 /// Check whether the deduced argument type for a call to a function 3309 /// template matches the actual argument type per C++ [temp.deduct.call]p4. 3310 static Sema::TemplateDeductionResult 3311 CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info, 3312 Sema::OriginalCallArg OriginalArg, 3313 QualType DeducedA) { 3314 ASTContext &Context = S.Context; 3315 3316 auto Failed = [&]() -> Sema::TemplateDeductionResult { 3317 Info.FirstArg = TemplateArgument(DeducedA); 3318 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType); 3319 Info.CallArgIndex = OriginalArg.ArgIdx; 3320 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested 3321 : Sema::TDK_DeducedMismatch; 3322 }; 3323 3324 QualType A = OriginalArg.OriginalArgType; 3325 QualType OriginalParamType = OriginalArg.OriginalParamType; 3326 3327 // Check for type equality (top-level cv-qualifiers are ignored). 3328 if (Context.hasSameUnqualifiedType(A, DeducedA)) 3329 return Sema::TDK_Success; 3330 3331 // Strip off references on the argument types; they aren't needed for 3332 // the following checks. 3333 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>()) 3334 DeducedA = DeducedARef->getPointeeType(); 3335 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) 3336 A = ARef->getPointeeType(); 3337 3338 // C++ [temp.deduct.call]p4: 3339 // [...] However, there are three cases that allow a difference: 3340 // - If the original P is a reference type, the deduced A (i.e., the 3341 // type referred to by the reference) can be more cv-qualified than 3342 // the transformed A. 3343 if (const ReferenceType *OriginalParamRef 3344 = OriginalParamType->getAs<ReferenceType>()) { 3345 // We don't want to keep the reference around any more. 3346 OriginalParamType = OriginalParamRef->getPointeeType(); 3347 3348 // FIXME: Resolve core issue (no number yet): if the original P is a 3349 // reference type and the transformed A is function type "noexcept F", 3350 // the deduced A can be F. 3351 QualType Tmp; 3352 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp)) 3353 return Sema::TDK_Success; 3354 3355 Qualifiers AQuals = A.getQualifiers(); 3356 Qualifiers DeducedAQuals = DeducedA.getQualifiers(); 3357 3358 // Under Objective-C++ ARC, the deduced type may have implicitly 3359 // been given strong or (when dealing with a const reference) 3360 // unsafe_unretained lifetime. If so, update the original 3361 // qualifiers to include this lifetime. 3362 if (S.getLangOpts().ObjCAutoRefCount && 3363 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong && 3364 AQuals.getObjCLifetime() == Qualifiers::OCL_None) || 3365 (DeducedAQuals.hasConst() && 3366 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) { 3367 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime()); 3368 } 3369 3370 if (AQuals == DeducedAQuals) { 3371 // Qualifiers match; there's nothing to do. 3372 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) { 3373 return Failed(); 3374 } else { 3375 // Qualifiers are compatible, so have the argument type adopt the 3376 // deduced argument type's qualifiers as if we had performed the 3377 // qualification conversion. 3378 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals); 3379 } 3380 } 3381 3382 // - The transformed A can be another pointer or pointer to member 3383 // type that can be converted to the deduced A via a function pointer 3384 // conversion and/or a qualification conversion. 3385 // 3386 // Also allow conversions which merely strip __attribute__((noreturn)) from 3387 // function types (recursively). 3388 bool ObjCLifetimeConversion = false; 3389 QualType ResultTy; 3390 if ((A->isAnyPointerType() || A->isMemberPointerType()) && 3391 (S.IsQualificationConversion(A, DeducedA, false, 3392 ObjCLifetimeConversion) || 3393 S.IsFunctionConversion(A, DeducedA, ResultTy))) 3394 return Sema::TDK_Success; 3395 3396 // - If P is a class and P has the form simple-template-id, then the 3397 // transformed A can be a derived class of the deduced A. [...] 3398 // [...] Likewise, if P is a pointer to a class of the form 3399 // simple-template-id, the transformed A can be a pointer to a 3400 // derived class pointed to by the deduced A. 3401 if (const PointerType *OriginalParamPtr 3402 = OriginalParamType->getAs<PointerType>()) { 3403 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) { 3404 if (const PointerType *APtr = A->getAs<PointerType>()) { 3405 if (A->getPointeeType()->isRecordType()) { 3406 OriginalParamType = OriginalParamPtr->getPointeeType(); 3407 DeducedA = DeducedAPtr->getPointeeType(); 3408 A = APtr->getPointeeType(); 3409 } 3410 } 3411 } 3412 } 3413 3414 if (Context.hasSameUnqualifiedType(A, DeducedA)) 3415 return Sema::TDK_Success; 3416 3417 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) && 3418 S.IsDerivedFrom(Info.getLocation(), A, DeducedA)) 3419 return Sema::TDK_Success; 3420 3421 return Failed(); 3422 } 3423 3424 /// Find the pack index for a particular parameter index in an instantiation of 3425 /// a function template with specific arguments. 3426 /// 3427 /// \return The pack index for whichever pack produced this parameter, or -1 3428 /// if this was not produced by a parameter. Intended to be used as the 3429 /// ArgumentPackSubstitutionIndex for further substitutions. 3430 // FIXME: We should track this in OriginalCallArgs so we don't need to 3431 // reconstruct it here. 3432 static unsigned getPackIndexForParam(Sema &S, 3433 FunctionTemplateDecl *FunctionTemplate, 3434 const MultiLevelTemplateArgumentList &Args, 3435 unsigned ParamIdx) { 3436 unsigned Idx = 0; 3437 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) { 3438 if (PD->isParameterPack()) { 3439 unsigned NumExpansions = 3440 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1); 3441 if (Idx + NumExpansions > ParamIdx) 3442 return ParamIdx - Idx; 3443 Idx += NumExpansions; 3444 } else { 3445 if (Idx == ParamIdx) 3446 return -1; // Not a pack expansion 3447 ++Idx; 3448 } 3449 } 3450 3451 llvm_unreachable("parameter index would not be produced from template"); 3452 } 3453 3454 /// Finish template argument deduction for a function template, 3455 /// checking the deduced template arguments for completeness and forming 3456 /// the function template specialization. 3457 /// 3458 /// \param OriginalCallArgs If non-NULL, the original call arguments against 3459 /// which the deduced argument types should be compared. 3460 Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction( 3461 FunctionTemplateDecl *FunctionTemplate, 3462 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3463 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, 3464 TemplateDeductionInfo &Info, 3465 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs, 3466 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) { 3467 // Unevaluated SFINAE context. 3468 EnterExpressionEvaluationContext Unevaluated( 3469 *this, Sema::ExpressionEvaluationContext::Unevaluated); 3470 SFINAETrap Trap(*this); 3471 3472 // Enter a new template instantiation context while we instantiate the 3473 // actual function declaration. 3474 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 3475 InstantiatingTemplate Inst( 3476 *this, Info.getLocation(), FunctionTemplate, DeducedArgs, 3477 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info); 3478 if (Inst.isInvalid()) 3479 return TDK_InstantiationDepth; 3480 3481 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 3482 3483 // C++ [temp.deduct.type]p2: 3484 // [...] or if any template argument remains neither deduced nor 3485 // explicitly specified, template argument deduction fails. 3486 SmallVector<TemplateArgument, 4> Builder; 3487 if (auto Result = ConvertDeducedTemplateArguments( 3488 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder, 3489 CurrentInstantiationScope, NumExplicitlySpecified, 3490 PartialOverloading)) 3491 return Result; 3492 3493 // C++ [temp.deduct.call]p10: [DR1391] 3494 // If deduction succeeds for all parameters that contain 3495 // template-parameters that participate in template argument deduction, 3496 // and all template arguments are explicitly specified, deduced, or 3497 // obtained from default template arguments, remaining parameters are then 3498 // compared with the corresponding arguments. For each remaining parameter 3499 // P with a type that was non-dependent before substitution of any 3500 // explicitly-specified template arguments, if the corresponding argument 3501 // A cannot be implicitly converted to P, deduction fails. 3502 if (CheckNonDependent()) 3503 return TDK_NonDependentConversionFailure; 3504 3505 // Form the template argument list from the deduced template arguments. 3506 TemplateArgumentList *DeducedArgumentList 3507 = TemplateArgumentList::CreateCopy(Context, Builder); 3508 Info.reset(DeducedArgumentList); 3509 3510 // Substitute the deduced template arguments into the function template 3511 // declaration to produce the function template specialization. 3512 DeclContext *Owner = FunctionTemplate->getDeclContext(); 3513 if (FunctionTemplate->getFriendObjectKind()) 3514 Owner = FunctionTemplate->getLexicalDeclContext(); 3515 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList); 3516 Specialization = cast_or_null<FunctionDecl>( 3517 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs)); 3518 if (!Specialization || Specialization->isInvalidDecl()) 3519 return TDK_SubstitutionFailure; 3520 3521 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() == 3522 FunctionTemplate->getCanonicalDecl()); 3523 3524 // If the template argument list is owned by the function template 3525 // specialization, release it. 3526 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList && 3527 !Trap.hasErrorOccurred()) 3528 Info.take(); 3529 3530 // There may have been an error that did not prevent us from constructing a 3531 // declaration. Mark the declaration invalid and return with a substitution 3532 // failure. 3533 if (Trap.hasErrorOccurred()) { 3534 Specialization->setInvalidDecl(true); 3535 return TDK_SubstitutionFailure; 3536 } 3537 3538 // C++2a [temp.deduct]p5 3539 // [...] When all template arguments have been deduced [...] all uses of 3540 // template parameters [...] are replaced with the corresponding deduced 3541 // or default argument values. 3542 // [...] If the function template has associated constraints 3543 // ([temp.constr.decl]), those constraints are checked for satisfaction 3544 // ([temp.constr.constr]). If the constraints are not satisfied, type 3545 // deduction fails. 3546 if (!PartialOverloading || 3547 (Builder.size() == FunctionTemplate->getTemplateParameters()->size())) { 3548 if (CheckInstantiatedFunctionTemplateConstraints(Info.getLocation(), 3549 Specialization, Builder, Info.AssociatedConstraintsSatisfaction)) 3550 return TDK_MiscellaneousDeductionFailure; 3551 3552 if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) { 3553 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder)); 3554 return TDK_ConstraintsNotSatisfied; 3555 } 3556 } 3557 3558 if (OriginalCallArgs) { 3559 // C++ [temp.deduct.call]p4: 3560 // In general, the deduction process attempts to find template argument 3561 // values that will make the deduced A identical to A (after the type A 3562 // is transformed as described above). [...] 3563 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes; 3564 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) { 3565 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I]; 3566 3567 auto ParamIdx = OriginalArg.ArgIdx; 3568 if (ParamIdx >= Specialization->getNumParams()) 3569 // FIXME: This presumably means a pack ended up smaller than we 3570 // expected while deducing. Should this not result in deduction 3571 // failure? Can it even happen? 3572 continue; 3573 3574 QualType DeducedA; 3575 if (!OriginalArg.DecomposedParam) { 3576 // P is one of the function parameters, just look up its substituted 3577 // type. 3578 DeducedA = Specialization->getParamDecl(ParamIdx)->getType(); 3579 } else { 3580 // P is a decomposed element of a parameter corresponding to a 3581 // braced-init-list argument. Substitute back into P to find the 3582 // deduced A. 3583 QualType &CacheEntry = 3584 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}]; 3585 if (CacheEntry.isNull()) { 3586 ArgumentPackSubstitutionIndexRAII PackIndex( 3587 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs, 3588 ParamIdx)); 3589 CacheEntry = 3590 SubstType(OriginalArg.OriginalParamType, SubstArgs, 3591 Specialization->getTypeSpecStartLoc(), 3592 Specialization->getDeclName()); 3593 } 3594 DeducedA = CacheEntry; 3595 } 3596 3597 if (auto TDK = 3598 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) 3599 return TDK; 3600 } 3601 } 3602 3603 // If we suppressed any diagnostics while performing template argument 3604 // deduction, and if we haven't already instantiated this declaration, 3605 // keep track of these diagnostics. They'll be emitted if this specialization 3606 // is actually used. 3607 if (Info.diag_begin() != Info.diag_end()) { 3608 SuppressedDiagnosticsMap::iterator 3609 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl()); 3610 if (Pos == SuppressedDiagnostics.end()) 3611 SuppressedDiagnostics[Specialization->getCanonicalDecl()] 3612 .append(Info.diag_begin(), Info.diag_end()); 3613 } 3614 3615 return TDK_Success; 3616 } 3617 3618 /// Gets the type of a function for template-argument-deducton 3619 /// purposes when it's considered as part of an overload set. 3620 static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, 3621 FunctionDecl *Fn) { 3622 // We may need to deduce the return type of the function now. 3623 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() && 3624 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false)) 3625 return {}; 3626 3627 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 3628 if (Method->isInstance()) { 3629 // An instance method that's referenced in a form that doesn't 3630 // look like a member pointer is just invalid. 3631 if (!R.HasFormOfMemberPointer) 3632 return {}; 3633 3634 return S.Context.getMemberPointerType(Fn->getType(), 3635 S.Context.getTypeDeclType(Method->getParent()).getTypePtr()); 3636 } 3637 3638 if (!R.IsAddressOfOperand) return Fn->getType(); 3639 return S.Context.getPointerType(Fn->getType()); 3640 } 3641 3642 /// Apply the deduction rules for overload sets. 3643 /// 3644 /// \return the null type if this argument should be treated as an 3645 /// undeduced context 3646 static QualType 3647 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, 3648 Expr *Arg, QualType ParamType, 3649 bool ParamWasReference) { 3650 3651 OverloadExpr::FindResult R = OverloadExpr::find(Arg); 3652 3653 OverloadExpr *Ovl = R.Expression; 3654 3655 // C++0x [temp.deduct.call]p4 3656 unsigned TDF = 0; 3657 if (ParamWasReference) 3658 TDF |= TDF_ParamWithReferenceType; 3659 if (R.IsAddressOfOperand) 3660 TDF |= TDF_IgnoreQualifiers; 3661 3662 // C++0x [temp.deduct.call]p6: 3663 // When P is a function type, pointer to function type, or pointer 3664 // to member function type: 3665 3666 if (!ParamType->isFunctionType() && 3667 !ParamType->isFunctionPointerType() && 3668 !ParamType->isMemberFunctionPointerType()) { 3669 if (Ovl->hasExplicitTemplateArgs()) { 3670 // But we can still look for an explicit specialization. 3671 if (FunctionDecl *ExplicitSpec 3672 = S.ResolveSingleFunctionTemplateSpecialization(Ovl)) 3673 return GetTypeOfFunction(S, R, ExplicitSpec); 3674 } 3675 3676 DeclAccessPair DAP; 3677 if (FunctionDecl *Viable = 3678 S.resolveAddressOfSingleOverloadCandidate(Arg, DAP)) 3679 return GetTypeOfFunction(S, R, Viable); 3680 3681 return {}; 3682 } 3683 3684 // Gather the explicit template arguments, if any. 3685 TemplateArgumentListInfo ExplicitTemplateArgs; 3686 if (Ovl->hasExplicitTemplateArgs()) 3687 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 3688 QualType Match; 3689 for (UnresolvedSetIterator I = Ovl->decls_begin(), 3690 E = Ovl->decls_end(); I != E; ++I) { 3691 NamedDecl *D = (*I)->getUnderlyingDecl(); 3692 3693 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) { 3694 // - If the argument is an overload set containing one or more 3695 // function templates, the parameter is treated as a 3696 // non-deduced context. 3697 if (!Ovl->hasExplicitTemplateArgs()) 3698 return {}; 3699 3700 // Otherwise, see if we can resolve a function type 3701 FunctionDecl *Specialization = nullptr; 3702 TemplateDeductionInfo Info(Ovl->getNameLoc()); 3703 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs, 3704 Specialization, Info)) 3705 continue; 3706 3707 D = Specialization; 3708 } 3709 3710 FunctionDecl *Fn = cast<FunctionDecl>(D); 3711 QualType ArgType = GetTypeOfFunction(S, R, Fn); 3712 if (ArgType.isNull()) continue; 3713 3714 // Function-to-pointer conversion. 3715 if (!ParamWasReference && ParamType->isPointerType() && 3716 ArgType->isFunctionType()) 3717 ArgType = S.Context.getPointerType(ArgType); 3718 3719 // - If the argument is an overload set (not containing function 3720 // templates), trial argument deduction is attempted using each 3721 // of the members of the set. If deduction succeeds for only one 3722 // of the overload set members, that member is used as the 3723 // argument value for the deduction. If deduction succeeds for 3724 // more than one member of the overload set the parameter is 3725 // treated as a non-deduced context. 3726 3727 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2: 3728 // Type deduction is done independently for each P/A pair, and 3729 // the deduced template argument values are then combined. 3730 // So we do not reject deductions which were made elsewhere. 3731 SmallVector<DeducedTemplateArgument, 8> 3732 Deduced(TemplateParams->size()); 3733 TemplateDeductionInfo Info(Ovl->getNameLoc()); 3734 Sema::TemplateDeductionResult Result 3735 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 3736 ArgType, Info, Deduced, TDF); 3737 if (Result) continue; 3738 if (!Match.isNull()) 3739 return {}; 3740 Match = ArgType; 3741 } 3742 3743 return Match; 3744 } 3745 3746 /// Perform the adjustments to the parameter and argument types 3747 /// described in C++ [temp.deduct.call]. 3748 /// 3749 /// \returns true if the caller should not attempt to perform any template 3750 /// argument deduction based on this P/A pair because the argument is an 3751 /// overloaded function set that could not be resolved. 3752 static bool AdjustFunctionParmAndArgTypesForDeduction( 3753 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, 3754 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) { 3755 // C++0x [temp.deduct.call]p3: 3756 // If P is a cv-qualified type, the top level cv-qualifiers of P's type 3757 // are ignored for type deduction. 3758 if (ParamType.hasQualifiers()) 3759 ParamType = ParamType.getUnqualifiedType(); 3760 3761 // [...] If P is a reference type, the type referred to by P is 3762 // used for type deduction. 3763 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>(); 3764 if (ParamRefType) 3765 ParamType = ParamRefType->getPointeeType(); 3766 3767 // Overload sets usually make this parameter an undeduced context, 3768 // but there are sometimes special circumstances. Typically 3769 // involving a template-id-expr. 3770 if (ArgType == S.Context.OverloadTy) { 3771 ArgType = ResolveOverloadForDeduction(S, TemplateParams, 3772 Arg, ParamType, 3773 ParamRefType != nullptr); 3774 if (ArgType.isNull()) 3775 return true; 3776 } 3777 3778 if (ParamRefType) { 3779 // If the argument has incomplete array type, try to complete its type. 3780 if (ArgType->isIncompleteArrayType()) 3781 ArgType = S.getCompletedType(Arg); 3782 3783 // C++1z [temp.deduct.call]p3: 3784 // If P is a forwarding reference and the argument is an lvalue, the type 3785 // "lvalue reference to A" is used in place of A for type deduction. 3786 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) && 3787 Arg->isLValue()) { 3788 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace()) 3789 ArgType = S.Context.getAddrSpaceQualType( 3790 ArgType, S.Context.getDefaultOpenCLPointeeAddrSpace()); 3791 ArgType = S.Context.getLValueReferenceType(ArgType); 3792 } 3793 } else { 3794 // C++ [temp.deduct.call]p2: 3795 // If P is not a reference type: 3796 // - If A is an array type, the pointer type produced by the 3797 // array-to-pointer standard conversion (4.2) is used in place of 3798 // A for type deduction; otherwise, 3799 if (ArgType->isArrayType()) 3800 ArgType = S.Context.getArrayDecayedType(ArgType); 3801 // - If A is a function type, the pointer type produced by the 3802 // function-to-pointer standard conversion (4.3) is used in place 3803 // of A for type deduction; otherwise, 3804 else if (ArgType->isFunctionType()) 3805 ArgType = S.Context.getPointerType(ArgType); 3806 else { 3807 // - If A is a cv-qualified type, the top level cv-qualifiers of A's 3808 // type are ignored for type deduction. 3809 ArgType = ArgType.getUnqualifiedType(); 3810 } 3811 } 3812 3813 // C++0x [temp.deduct.call]p4: 3814 // In general, the deduction process attempts to find template argument 3815 // values that will make the deduced A identical to A (after the type A 3816 // is transformed as described above). [...] 3817 TDF = TDF_SkipNonDependent; 3818 3819 // - If the original P is a reference type, the deduced A (i.e., the 3820 // type referred to by the reference) can be more cv-qualified than 3821 // the transformed A. 3822 if (ParamRefType) 3823 TDF |= TDF_ParamWithReferenceType; 3824 // - The transformed A can be another pointer or pointer to member 3825 // type that can be converted to the deduced A via a qualification 3826 // conversion (4.4). 3827 if (ArgType->isPointerType() || ArgType->isMemberPointerType() || 3828 ArgType->isObjCObjectPointerType()) 3829 TDF |= TDF_IgnoreQualifiers; 3830 // - If P is a class and P has the form simple-template-id, then the 3831 // transformed A can be a derived class of the deduced A. Likewise, 3832 // if P is a pointer to a class of the form simple-template-id, the 3833 // transformed A can be a pointer to a derived class pointed to by 3834 // the deduced A. 3835 if (isSimpleTemplateIdType(ParamType) || 3836 (isa<PointerType>(ParamType) && 3837 isSimpleTemplateIdType( 3838 ParamType->castAs<PointerType>()->getPointeeType()))) 3839 TDF |= TDF_DerivedClass; 3840 3841 return false; 3842 } 3843 3844 static bool 3845 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate, 3846 QualType T); 3847 3848 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument( 3849 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, 3850 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info, 3851 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3852 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, 3853 bool DecomposedParam, unsigned ArgIdx, unsigned TDF); 3854 3855 /// Attempt template argument deduction from an initializer list 3856 /// deemed to be an argument in a function call. 3857 static Sema::TemplateDeductionResult DeduceFromInitializerList( 3858 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType, 3859 InitListExpr *ILE, TemplateDeductionInfo &Info, 3860 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3861 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx, 3862 unsigned TDF) { 3863 // C++ [temp.deduct.call]p1: (CWG 1591) 3864 // If removing references and cv-qualifiers from P gives 3865 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is 3866 // a non-empty initializer list, then deduction is performed instead for 3867 // each element of the initializer list, taking P0 as a function template 3868 // parameter type and the initializer element as its argument 3869 // 3870 // We've already removed references and cv-qualifiers here. 3871 if (!ILE->getNumInits()) 3872 return Sema::TDK_Success; 3873 3874 QualType ElTy; 3875 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType); 3876 if (ArrTy) 3877 ElTy = ArrTy->getElementType(); 3878 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) { 3879 // Otherwise, an initializer list argument causes the parameter to be 3880 // considered a non-deduced context 3881 return Sema::TDK_Success; 3882 } 3883 3884 // Resolving a core issue: a braced-init-list containing any designators is 3885 // a non-deduced context. 3886 for (Expr *E : ILE->inits()) 3887 if (isa<DesignatedInitExpr>(E)) 3888 return Sema::TDK_Success; 3889 3890 // Deduction only needs to be done for dependent types. 3891 if (ElTy->isDependentType()) { 3892 for (Expr *E : ILE->inits()) { 3893 if (auto Result = DeduceTemplateArgumentsFromCallArgument( 3894 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true, 3895 ArgIdx, TDF)) 3896 return Result; 3897 } 3898 } 3899 3900 // in the P0[N] case, if N is a non-type template parameter, N is deduced 3901 // from the length of the initializer list. 3902 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) { 3903 // Determine the array bound is something we can deduce. 3904 if (const NonTypeTemplateParmDecl *NTTP = 3905 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) { 3906 // We can perform template argument deduction for the given non-type 3907 // template parameter. 3908 // C++ [temp.deduct.type]p13: 3909 // The type of N in the type T[N] is std::size_t. 3910 QualType T = S.Context.getSizeType(); 3911 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits()); 3912 if (auto Result = DeduceNonTypeTemplateArgument( 3913 S, TemplateParams, NTTP, llvm::APSInt(Size), T, 3914 /*ArrayBound=*/true, Info, Deduced)) 3915 return Result; 3916 } 3917 } 3918 3919 return Sema::TDK_Success; 3920 } 3921 3922 /// Perform template argument deduction per [temp.deduct.call] for a 3923 /// single parameter / argument pair. 3924 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument( 3925 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, 3926 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info, 3927 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3928 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, 3929 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) { 3930 QualType ArgType = Arg->getType(); 3931 QualType OrigParamType = ParamType; 3932 3933 // If P is a reference type [...] 3934 // If P is a cv-qualified type [...] 3935 if (AdjustFunctionParmAndArgTypesForDeduction( 3936 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF)) 3937 return Sema::TDK_Success; 3938 3939 // If [...] the argument is a non-empty initializer list [...] 3940 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) 3941 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info, 3942 Deduced, OriginalCallArgs, ArgIdx, TDF); 3943 3944 // [...] the deduction process attempts to find template argument values 3945 // that will make the deduced A identical to A 3946 // 3947 // Keep track of the argument type and corresponding parameter index, 3948 // so we can check for compatibility between the deduced A and A. 3949 OriginalCallArgs.push_back( 3950 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType)); 3951 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 3952 ArgType, Info, Deduced, TDF); 3953 } 3954 3955 /// Perform template argument deduction from a function call 3956 /// (C++ [temp.deduct.call]). 3957 /// 3958 /// \param FunctionTemplate the function template for which we are performing 3959 /// template argument deduction. 3960 /// 3961 /// \param ExplicitTemplateArgs the explicit template arguments provided 3962 /// for this call. 3963 /// 3964 /// \param Args the function call arguments 3965 /// 3966 /// \param Specialization if template argument deduction was successful, 3967 /// this will be set to the function template specialization produced by 3968 /// template argument deduction. 3969 /// 3970 /// \param Info the argument will be updated to provide additional information 3971 /// about template argument deduction. 3972 /// 3973 /// \param CheckNonDependent A callback to invoke to check conversions for 3974 /// non-dependent parameters, between deduction and substitution, per DR1391. 3975 /// If this returns true, substitution will be skipped and we return 3976 /// TDK_NonDependentConversionFailure. The callback is passed the parameter 3977 /// types (after substituting explicit template arguments). 3978 /// 3979 /// \returns the result of template argument deduction. 3980 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments( 3981 FunctionTemplateDecl *FunctionTemplate, 3982 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 3983 FunctionDecl *&Specialization, TemplateDeductionInfo &Info, 3984 bool PartialOverloading, 3985 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) { 3986 if (FunctionTemplate->isInvalidDecl()) 3987 return TDK_Invalid; 3988 3989 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 3990 unsigned NumParams = Function->getNumParams(); 3991 3992 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate); 3993 3994 // C++ [temp.deduct.call]p1: 3995 // Template argument deduction is done by comparing each function template 3996 // parameter type (call it P) with the type of the corresponding argument 3997 // of the call (call it A) as described below. 3998 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading) 3999 return TDK_TooFewArguments; 4000 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) { 4001 const auto *Proto = Function->getType()->castAs<FunctionProtoType>(); 4002 if (Proto->isTemplateVariadic()) 4003 /* Do nothing */; 4004 else if (!Proto->isVariadic()) 4005 return TDK_TooManyArguments; 4006 } 4007 4008 // The types of the parameters from which we will perform template argument 4009 // deduction. 4010 LocalInstantiationScope InstScope(*this); 4011 TemplateParameterList *TemplateParams 4012 = FunctionTemplate->getTemplateParameters(); 4013 SmallVector<DeducedTemplateArgument, 4> Deduced; 4014 SmallVector<QualType, 8> ParamTypes; 4015 unsigned NumExplicitlySpecified = 0; 4016 if (ExplicitTemplateArgs) { 4017 TemplateDeductionResult Result; 4018 runWithSufficientStackSpace(Info.getLocation(), [&] { 4019 Result = SubstituteExplicitTemplateArguments( 4020 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr, 4021 Info); 4022 }); 4023 if (Result) 4024 return Result; 4025 4026 NumExplicitlySpecified = Deduced.size(); 4027 } else { 4028 // Just fill in the parameter types from the function declaration. 4029 for (unsigned I = 0; I != NumParams; ++I) 4030 ParamTypes.push_back(Function->getParamDecl(I)->getType()); 4031 } 4032 4033 SmallVector<OriginalCallArg, 8> OriginalCallArgs; 4034 4035 // Deduce an argument of type ParamType from an expression with index ArgIdx. 4036 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) { 4037 // C++ [demp.deduct.call]p1: (DR1391) 4038 // Template argument deduction is done by comparing each function template 4039 // parameter that contains template-parameters that participate in 4040 // template argument deduction ... 4041 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType)) 4042 return Sema::TDK_Success; 4043 4044 // ... with the type of the corresponding argument 4045 return DeduceTemplateArgumentsFromCallArgument( 4046 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced, 4047 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0); 4048 }; 4049 4050 // Deduce template arguments from the function parameters. 4051 Deduced.resize(TemplateParams->size()); 4052 SmallVector<QualType, 8> ParamTypesForArgChecking; 4053 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0; 4054 ParamIdx != NumParamTypes; ++ParamIdx) { 4055 QualType ParamType = ParamTypes[ParamIdx]; 4056 4057 const PackExpansionType *ParamExpansion = 4058 dyn_cast<PackExpansionType>(ParamType); 4059 if (!ParamExpansion) { 4060 // Simple case: matching a function parameter to a function argument. 4061 if (ArgIdx >= Args.size()) 4062 break; 4063 4064 ParamTypesForArgChecking.push_back(ParamType); 4065 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++)) 4066 return Result; 4067 4068 continue; 4069 } 4070 4071 QualType ParamPattern = ParamExpansion->getPattern(); 4072 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info, 4073 ParamPattern); 4074 4075 // C++0x [temp.deduct.call]p1: 4076 // For a function parameter pack that occurs at the end of the 4077 // parameter-declaration-list, the type A of each remaining argument of 4078 // the call is compared with the type P of the declarator-id of the 4079 // function parameter pack. Each comparison deduces template arguments 4080 // for subsequent positions in the template parameter packs expanded by 4081 // the function parameter pack. When a function parameter pack appears 4082 // in a non-deduced context [not at the end of the list], the type of 4083 // that parameter pack is never deduced. 4084 // 4085 // FIXME: The above rule allows the size of the parameter pack to change 4086 // after we skip it (in the non-deduced case). That makes no sense, so 4087 // we instead notionally deduce the pack against N arguments, where N is 4088 // the length of the explicitly-specified pack if it's expanded by the 4089 // parameter pack and 0 otherwise, and we treat each deduction as a 4090 // non-deduced context. 4091 if (ParamIdx + 1 == NumParamTypes || PackScope.hasFixedArity()) { 4092 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); 4093 PackScope.nextPackElement(), ++ArgIdx) { 4094 ParamTypesForArgChecking.push_back(ParamPattern); 4095 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx)) 4096 return Result; 4097 } 4098 } else { 4099 // If the parameter type contains an explicitly-specified pack that we 4100 // could not expand, skip the number of parameters notionally created 4101 // by the expansion. 4102 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions(); 4103 if (NumExpansions && !PackScope.isPartiallyExpanded()) { 4104 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size(); 4105 ++I, ++ArgIdx) { 4106 ParamTypesForArgChecking.push_back(ParamPattern); 4107 // FIXME: Should we add OriginalCallArgs for these? What if the 4108 // corresponding argument is a list? 4109 PackScope.nextPackElement(); 4110 } 4111 } 4112 } 4113 4114 // Build argument packs for each of the parameter packs expanded by this 4115 // pack expansion. 4116 if (auto Result = PackScope.finish()) 4117 return Result; 4118 } 4119 4120 // Capture the context in which the function call is made. This is the context 4121 // that is needed when the accessibility of template arguments is checked. 4122 DeclContext *CallingCtx = CurContext; 4123 4124 TemplateDeductionResult Result; 4125 runWithSufficientStackSpace(Info.getLocation(), [&] { 4126 Result = FinishTemplateArgumentDeduction( 4127 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info, 4128 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() { 4129 ContextRAII SavedContext(*this, CallingCtx); 4130 return CheckNonDependent(ParamTypesForArgChecking); 4131 }); 4132 }); 4133 return Result; 4134 } 4135 4136 QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType, 4137 QualType FunctionType, 4138 bool AdjustExceptionSpec) { 4139 if (ArgFunctionType.isNull()) 4140 return ArgFunctionType; 4141 4142 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>(); 4143 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>(); 4144 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo(); 4145 bool Rebuild = false; 4146 4147 CallingConv CC = FunctionTypeP->getCallConv(); 4148 if (EPI.ExtInfo.getCC() != CC) { 4149 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC); 4150 Rebuild = true; 4151 } 4152 4153 bool NoReturn = FunctionTypeP->getNoReturnAttr(); 4154 if (EPI.ExtInfo.getNoReturn() != NoReturn) { 4155 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn); 4156 Rebuild = true; 4157 } 4158 4159 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() || 4160 ArgFunctionTypeP->hasExceptionSpec())) { 4161 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec; 4162 Rebuild = true; 4163 } 4164 4165 if (!Rebuild) 4166 return ArgFunctionType; 4167 4168 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(), 4169 ArgFunctionTypeP->getParamTypes(), EPI); 4170 } 4171 4172 /// Deduce template arguments when taking the address of a function 4173 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to 4174 /// a template. 4175 /// 4176 /// \param FunctionTemplate the function template for which we are performing 4177 /// template argument deduction. 4178 /// 4179 /// \param ExplicitTemplateArgs the explicitly-specified template 4180 /// arguments. 4181 /// 4182 /// \param ArgFunctionType the function type that will be used as the 4183 /// "argument" type (A) when performing template argument deduction from the 4184 /// function template's function type. This type may be NULL, if there is no 4185 /// argument type to compare against, in C++0x [temp.arg.explicit]p3. 4186 /// 4187 /// \param Specialization if template argument deduction was successful, 4188 /// this will be set to the function template specialization produced by 4189 /// template argument deduction. 4190 /// 4191 /// \param Info the argument will be updated to provide additional information 4192 /// about template argument deduction. 4193 /// 4194 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking 4195 /// the address of a function template per [temp.deduct.funcaddr] and 4196 /// [over.over]. If \c false, we are looking up a function template 4197 /// specialization based on its signature, per [temp.deduct.decl]. 4198 /// 4199 /// \returns the result of template argument deduction. 4200 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments( 4201 FunctionTemplateDecl *FunctionTemplate, 4202 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, 4203 FunctionDecl *&Specialization, TemplateDeductionInfo &Info, 4204 bool IsAddressOfFunction) { 4205 if (FunctionTemplate->isInvalidDecl()) 4206 return TDK_Invalid; 4207 4208 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 4209 TemplateParameterList *TemplateParams 4210 = FunctionTemplate->getTemplateParameters(); 4211 QualType FunctionType = Function->getType(); 4212 4213 // Substitute any explicit template arguments. 4214 LocalInstantiationScope InstScope(*this); 4215 SmallVector<DeducedTemplateArgument, 4> Deduced; 4216 unsigned NumExplicitlySpecified = 0; 4217 SmallVector<QualType, 4> ParamTypes; 4218 if (ExplicitTemplateArgs) { 4219 TemplateDeductionResult Result; 4220 runWithSufficientStackSpace(Info.getLocation(), [&] { 4221 Result = SubstituteExplicitTemplateArguments( 4222 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, 4223 &FunctionType, Info); 4224 }); 4225 if (Result) 4226 return Result; 4227 4228 NumExplicitlySpecified = Deduced.size(); 4229 } 4230 4231 // When taking the address of a function, we require convertibility of 4232 // the resulting function type. Otherwise, we allow arbitrary mismatches 4233 // of calling convention and noreturn. 4234 if (!IsAddressOfFunction) 4235 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType, 4236 /*AdjustExceptionSpec*/false); 4237 4238 // Unevaluated SFINAE context. 4239 EnterExpressionEvaluationContext Unevaluated( 4240 *this, Sema::ExpressionEvaluationContext::Unevaluated); 4241 SFINAETrap Trap(*this); 4242 4243 Deduced.resize(TemplateParams->size()); 4244 4245 // If the function has a deduced return type, substitute it for a dependent 4246 // type so that we treat it as a non-deduced context in what follows. If we 4247 // are looking up by signature, the signature type should also have a deduced 4248 // return type, which we instead expect to exactly match. 4249 bool HasDeducedReturnType = false; 4250 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction && 4251 Function->getReturnType()->getContainedAutoType()) { 4252 FunctionType = SubstAutoTypeDependent(FunctionType); 4253 HasDeducedReturnType = true; 4254 } 4255 4256 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) { 4257 unsigned TDF = 4258 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType; 4259 // Deduce template arguments from the function type. 4260 if (TemplateDeductionResult Result 4261 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 4262 FunctionType, ArgFunctionType, 4263 Info, Deduced, TDF)) 4264 return Result; 4265 } 4266 4267 TemplateDeductionResult Result; 4268 runWithSufficientStackSpace(Info.getLocation(), [&] { 4269 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 4270 NumExplicitlySpecified, 4271 Specialization, Info); 4272 }); 4273 if (Result) 4274 return Result; 4275 4276 // If the function has a deduced return type, deduce it now, so we can check 4277 // that the deduced function type matches the requested type. 4278 if (HasDeducedReturnType && 4279 Specialization->getReturnType()->isUndeducedType() && 4280 DeduceReturnType(Specialization, Info.getLocation(), false)) 4281 return TDK_MiscellaneousDeductionFailure; 4282 4283 // If the function has a dependent exception specification, resolve it now, 4284 // so we can check that the exception specification matches. 4285 auto *SpecializationFPT = 4286 Specialization->getType()->castAs<FunctionProtoType>(); 4287 if (getLangOpts().CPlusPlus17 && 4288 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) && 4289 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT)) 4290 return TDK_MiscellaneousDeductionFailure; 4291 4292 // Adjust the exception specification of the argument to match the 4293 // substituted and resolved type we just formed. (Calling convention and 4294 // noreturn can't be dependent, so we don't actually need this for them 4295 // right now.) 4296 QualType SpecializationType = Specialization->getType(); 4297 if (!IsAddressOfFunction) 4298 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType, 4299 /*AdjustExceptionSpec*/true); 4300 4301 // If the requested function type does not match the actual type of the 4302 // specialization with respect to arguments of compatible pointer to function 4303 // types, template argument deduction fails. 4304 if (!ArgFunctionType.isNull()) { 4305 if (IsAddressOfFunction && 4306 !isSameOrCompatibleFunctionType( 4307 Context.getCanonicalType(SpecializationType), 4308 Context.getCanonicalType(ArgFunctionType))) 4309 return TDK_MiscellaneousDeductionFailure; 4310 4311 if (!IsAddressOfFunction && 4312 !Context.hasSameType(SpecializationType, ArgFunctionType)) 4313 return TDK_MiscellaneousDeductionFailure; 4314 } 4315 4316 return TDK_Success; 4317 } 4318 4319 /// Deduce template arguments for a templated conversion 4320 /// function (C++ [temp.deduct.conv]) and, if successful, produce a 4321 /// conversion function template specialization. 4322 Sema::TemplateDeductionResult 4323 Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate, 4324 QualType ToType, 4325 CXXConversionDecl *&Specialization, 4326 TemplateDeductionInfo &Info) { 4327 if (ConversionTemplate->isInvalidDecl()) 4328 return TDK_Invalid; 4329 4330 CXXConversionDecl *ConversionGeneric 4331 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl()); 4332 4333 QualType FromType = ConversionGeneric->getConversionType(); 4334 4335 // Canonicalize the types for deduction. 4336 QualType P = Context.getCanonicalType(FromType); 4337 QualType A = Context.getCanonicalType(ToType); 4338 4339 // C++0x [temp.deduct.conv]p2: 4340 // If P is a reference type, the type referred to by P is used for 4341 // type deduction. 4342 if (const ReferenceType *PRef = P->getAs<ReferenceType>()) 4343 P = PRef->getPointeeType(); 4344 4345 // C++0x [temp.deduct.conv]p4: 4346 // [...] If A is a reference type, the type referred to by A is used 4347 // for type deduction. 4348 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) { 4349 A = ARef->getPointeeType(); 4350 // We work around a defect in the standard here: cv-qualifiers are also 4351 // removed from P and A in this case, unless P was a reference type. This 4352 // seems to mostly match what other compilers are doing. 4353 if (!FromType->getAs<ReferenceType>()) { 4354 A = A.getUnqualifiedType(); 4355 P = P.getUnqualifiedType(); 4356 } 4357 4358 // C++ [temp.deduct.conv]p3: 4359 // 4360 // If A is not a reference type: 4361 } else { 4362 assert(!A->isReferenceType() && "Reference types were handled above"); 4363 4364 // - If P is an array type, the pointer type produced by the 4365 // array-to-pointer standard conversion (4.2) is used in place 4366 // of P for type deduction; otherwise, 4367 if (P->isArrayType()) 4368 P = Context.getArrayDecayedType(P); 4369 // - If P is a function type, the pointer type produced by the 4370 // function-to-pointer standard conversion (4.3) is used in 4371 // place of P for type deduction; otherwise, 4372 else if (P->isFunctionType()) 4373 P = Context.getPointerType(P); 4374 // - If P is a cv-qualified type, the top level cv-qualifiers of 4375 // P's type are ignored for type deduction. 4376 else 4377 P = P.getUnqualifiedType(); 4378 4379 // C++0x [temp.deduct.conv]p4: 4380 // If A is a cv-qualified type, the top level cv-qualifiers of A's 4381 // type are ignored for type deduction. If A is a reference type, the type 4382 // referred to by A is used for type deduction. 4383 A = A.getUnqualifiedType(); 4384 } 4385 4386 // Unevaluated SFINAE context. 4387 EnterExpressionEvaluationContext Unevaluated( 4388 *this, Sema::ExpressionEvaluationContext::Unevaluated); 4389 SFINAETrap Trap(*this); 4390 4391 // C++ [temp.deduct.conv]p1: 4392 // Template argument deduction is done by comparing the return 4393 // type of the template conversion function (call it P) with the 4394 // type that is required as the result of the conversion (call it 4395 // A) as described in 14.8.2.4. 4396 TemplateParameterList *TemplateParams 4397 = ConversionTemplate->getTemplateParameters(); 4398 SmallVector<DeducedTemplateArgument, 4> Deduced; 4399 Deduced.resize(TemplateParams->size()); 4400 4401 // C++0x [temp.deduct.conv]p4: 4402 // In general, the deduction process attempts to find template 4403 // argument values that will make the deduced A identical to 4404 // A. However, there are two cases that allow a difference: 4405 unsigned TDF = 0; 4406 // - If the original A is a reference type, A can be more 4407 // cv-qualified than the deduced A (i.e., the type referred to 4408 // by the reference) 4409 if (ToType->isReferenceType()) 4410 TDF |= TDF_ArgWithReferenceType; 4411 // - The deduced A can be another pointer or pointer to member 4412 // type that can be converted to A via a qualification 4413 // conversion. 4414 // 4415 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when 4416 // both P and A are pointers or member pointers. In this case, we 4417 // just ignore cv-qualifiers completely). 4418 if ((P->isPointerType() && A->isPointerType()) || 4419 (P->isMemberPointerType() && A->isMemberPointerType())) 4420 TDF |= TDF_IgnoreQualifiers; 4421 if (TemplateDeductionResult Result 4422 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 4423 P, A, Info, Deduced, TDF)) 4424 return Result; 4425 4426 // Create an Instantiation Scope for finalizing the operator. 4427 LocalInstantiationScope InstScope(*this); 4428 // Finish template argument deduction. 4429 FunctionDecl *ConversionSpecialized = nullptr; 4430 TemplateDeductionResult Result; 4431 runWithSufficientStackSpace(Info.getLocation(), [&] { 4432 Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0, 4433 ConversionSpecialized, Info); 4434 }); 4435 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized); 4436 return Result; 4437 } 4438 4439 /// Deduce template arguments for a function template when there is 4440 /// nothing to deduce against (C++0x [temp.arg.explicit]p3). 4441 /// 4442 /// \param FunctionTemplate the function template for which we are performing 4443 /// template argument deduction. 4444 /// 4445 /// \param ExplicitTemplateArgs the explicitly-specified template 4446 /// arguments. 4447 /// 4448 /// \param Specialization if template argument deduction was successful, 4449 /// this will be set to the function template specialization produced by 4450 /// template argument deduction. 4451 /// 4452 /// \param Info the argument will be updated to provide additional information 4453 /// about template argument deduction. 4454 /// 4455 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking 4456 /// the address of a function template in a context where we do not have a 4457 /// target type, per [over.over]. If \c false, we are looking up a function 4458 /// template specialization based on its signature, which only happens when 4459 /// deducing a function parameter type from an argument that is a template-id 4460 /// naming a function template specialization. 4461 /// 4462 /// \returns the result of template argument deduction. 4463 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments( 4464 FunctionTemplateDecl *FunctionTemplate, 4465 TemplateArgumentListInfo *ExplicitTemplateArgs, 4466 FunctionDecl *&Specialization, TemplateDeductionInfo &Info, 4467 bool IsAddressOfFunction) { 4468 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 4469 QualType(), Specialization, Info, 4470 IsAddressOfFunction); 4471 } 4472 4473 namespace { 4474 struct DependentAuto { bool IsPack; }; 4475 4476 /// Substitute the 'auto' specifier or deduced template specialization type 4477 /// specifier within a type for a given replacement type. 4478 class SubstituteDeducedTypeTransform : 4479 public TreeTransform<SubstituteDeducedTypeTransform> { 4480 QualType Replacement; 4481 bool ReplacementIsPack; 4482 bool UseTypeSugar; 4483 4484 public: 4485 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA) 4486 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef), 4487 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {} 4488 4489 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement, 4490 bool UseTypeSugar = true) 4491 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef), 4492 Replacement(Replacement), ReplacementIsPack(false), 4493 UseTypeSugar(UseTypeSugar) {} 4494 4495 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) { 4496 assert(isa<TemplateTypeParmType>(Replacement) && 4497 "unexpected unsugared replacement kind"); 4498 QualType Result = Replacement; 4499 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result); 4500 NewTL.setNameLoc(TL.getNameLoc()); 4501 return Result; 4502 } 4503 4504 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) { 4505 // If we're building the type pattern to deduce against, don't wrap the 4506 // substituted type in an AutoType. Certain template deduction rules 4507 // apply only when a template type parameter appears directly (and not if 4508 // the parameter is found through desugaring). For instance: 4509 // auto &&lref = lvalue; 4510 // must transform into "rvalue reference to T" not "rvalue reference to 4511 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply. 4512 // 4513 // FIXME: Is this still necessary? 4514 if (!UseTypeSugar) 4515 return TransformDesugared(TLB, TL); 4516 4517 QualType Result = SemaRef.Context.getAutoType( 4518 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(), 4519 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(), 4520 TL.getTypePtr()->getTypeConstraintArguments()); 4521 auto NewTL = TLB.push<AutoTypeLoc>(Result); 4522 NewTL.copy(TL); 4523 return Result; 4524 } 4525 4526 QualType TransformDeducedTemplateSpecializationType( 4527 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) { 4528 if (!UseTypeSugar) 4529 return TransformDesugared(TLB, TL); 4530 4531 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType( 4532 TL.getTypePtr()->getTemplateName(), 4533 Replacement, Replacement.isNull()); 4534 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result); 4535 NewTL.setNameLoc(TL.getNameLoc()); 4536 return Result; 4537 } 4538 4539 ExprResult TransformLambdaExpr(LambdaExpr *E) { 4540 // Lambdas never need to be transformed. 4541 return E; 4542 } 4543 4544 QualType Apply(TypeLoc TL) { 4545 // Create some scratch storage for the transformed type locations. 4546 // FIXME: We're just going to throw this information away. Don't build it. 4547 TypeLocBuilder TLB; 4548 TLB.reserve(TL.getFullDataSize()); 4549 return TransformType(TLB, TL); 4550 } 4551 }; 4552 4553 } // namespace 4554 4555 Sema::DeduceAutoResult 4556 Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result, 4557 Optional<unsigned> DependentDeductionDepth, 4558 bool IgnoreConstraints) { 4559 return DeduceAutoType(Type->getTypeLoc(), Init, Result, 4560 DependentDeductionDepth, IgnoreConstraints); 4561 } 4562 4563 /// Attempt to produce an informative diagostic explaining why auto deduction 4564 /// failed. 4565 /// \return \c true if diagnosed, \c false if not. 4566 static bool diagnoseAutoDeductionFailure(Sema &S, 4567 Sema::TemplateDeductionResult TDK, 4568 TemplateDeductionInfo &Info, 4569 ArrayRef<SourceRange> Ranges) { 4570 switch (TDK) { 4571 case Sema::TDK_Inconsistent: { 4572 // Inconsistent deduction means we were deducing from an initializer list. 4573 auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction); 4574 D << Info.FirstArg << Info.SecondArg; 4575 for (auto R : Ranges) 4576 D << R; 4577 return true; 4578 } 4579 4580 // FIXME: Are there other cases for which a custom diagnostic is more useful 4581 // than the basic "types don't match" diagnostic? 4582 4583 default: 4584 return false; 4585 } 4586 } 4587 4588 static Sema::DeduceAutoResult 4589 CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type, 4590 AutoTypeLoc TypeLoc, QualType Deduced) { 4591 ConstraintSatisfaction Satisfaction; 4592 ConceptDecl *Concept = Type.getTypeConstraintConcept(); 4593 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(), 4594 TypeLoc.getRAngleLoc()); 4595 TemplateArgs.addArgument( 4596 TemplateArgumentLoc(TemplateArgument(Deduced), 4597 S.Context.getTrivialTypeSourceInfo( 4598 Deduced, TypeLoc.getNameLoc()))); 4599 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I) 4600 TemplateArgs.addArgument(TypeLoc.getArgLoc(I)); 4601 4602 llvm::SmallVector<TemplateArgument, 4> Converted; 4603 if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs, 4604 /*PartialTemplateArgs=*/false, Converted)) 4605 return Sema::DAR_FailedAlreadyDiagnosed; 4606 4607 MultiLevelTemplateArgumentList MLTAL; 4608 MLTAL.addOuterTemplateArguments(Converted); 4609 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()}, 4610 MLTAL, TypeLoc.getLocalSourceRange(), 4611 Satisfaction)) 4612 return Sema::DAR_FailedAlreadyDiagnosed; 4613 if (!Satisfaction.IsSatisfied) { 4614 std::string Buf; 4615 llvm::raw_string_ostream OS(Buf); 4616 OS << "'" << Concept->getName(); 4617 if (TypeLoc.hasExplicitTemplateArgs()) { 4618 printTemplateArgumentList( 4619 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(), 4620 Type.getTypeConstraintConcept()->getTemplateParameters()); 4621 } 4622 OS << "'"; 4623 OS.flush(); 4624 S.Diag(TypeLoc.getConceptNameLoc(), 4625 diag::err_placeholder_constraints_not_satisfied) 4626 << Deduced << Buf << TypeLoc.getLocalSourceRange(); 4627 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 4628 return Sema::DAR_FailedAlreadyDiagnosed; 4629 } 4630 return Sema::DAR_Succeeded; 4631 } 4632 4633 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6) 4634 /// 4635 /// Note that this is done even if the initializer is dependent. (This is 4636 /// necessary to support partial ordering of templates using 'auto'.) 4637 /// A dependent type will be produced when deducing from a dependent type. 4638 /// 4639 /// \param Type the type pattern using the auto type-specifier. 4640 /// \param Init the initializer for the variable whose type is to be deduced. 4641 /// \param Result if type deduction was successful, this will be set to the 4642 /// deduced type. 4643 /// \param DependentDeductionDepth Set if we should permit deduction in 4644 /// dependent cases. This is necessary for template partial ordering with 4645 /// 'auto' template parameters. The value specified is the template 4646 /// parameter depth at which we should perform 'auto' deduction. 4647 /// \param IgnoreConstraints Set if we should not fail if the deduced type does 4648 /// not satisfy the type-constraint in the auto type. 4649 Sema::DeduceAutoResult 4650 Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result, 4651 Optional<unsigned> DependentDeductionDepth, 4652 bool IgnoreConstraints) { 4653 if (Init->containsErrors()) 4654 return DAR_FailedAlreadyDiagnosed; 4655 if (Init->getType()->isNonOverloadPlaceholderType()) { 4656 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init); 4657 if (NonPlaceholder.isInvalid()) 4658 return DAR_FailedAlreadyDiagnosed; 4659 Init = NonPlaceholder.get(); 4660 } 4661 4662 DependentAuto DependentResult = { 4663 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()}; 4664 4665 if (!DependentDeductionDepth && 4666 (Type.getType()->isDependentType() || Init->isTypeDependent() || 4667 Init->containsUnexpandedParameterPack())) { 4668 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type); 4669 assert(!Result.isNull() && "substituting DependentTy can't fail"); 4670 return DAR_Succeeded; 4671 } 4672 4673 // Find the depth of template parameter to synthesize. 4674 unsigned Depth = DependentDeductionDepth.value_or(0); 4675 4676 // If this is a 'decltype(auto)' specifier, do the decltype dance. 4677 // Since 'decltype(auto)' can only occur at the top of the type, we 4678 // don't need to go digging for it. 4679 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) { 4680 if (AT->isDecltypeAuto()) { 4681 if (isa<InitListExpr>(Init)) { 4682 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list); 4683 return DAR_FailedAlreadyDiagnosed; 4684 } 4685 4686 ExprResult ER = CheckPlaceholderExpr(Init); 4687 if (ER.isInvalid()) 4688 return DAR_FailedAlreadyDiagnosed; 4689 QualType Deduced = getDecltypeForExpr(ER.get()); 4690 assert(!Deduced.isNull()); 4691 if (AT->isConstrained() && !IgnoreConstraints) { 4692 auto ConstraintsResult = 4693 CheckDeducedPlaceholderConstraints(*this, *AT, 4694 Type.getContainedAutoTypeLoc(), 4695 Deduced); 4696 if (ConstraintsResult != DAR_Succeeded) 4697 return ConstraintsResult; 4698 } 4699 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type); 4700 if (Result.isNull()) 4701 return DAR_FailedAlreadyDiagnosed; 4702 return DAR_Succeeded; 4703 } else if (!getLangOpts().CPlusPlus) { 4704 if (isa<InitListExpr>(Init)) { 4705 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c); 4706 return DAR_FailedAlreadyDiagnosed; 4707 } 4708 } 4709 } 4710 4711 SourceLocation Loc = Init->getExprLoc(); 4712 4713 LocalInstantiationScope InstScope(*this); 4714 4715 // Build template<class TemplParam> void Func(FuncParam); 4716 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create( 4717 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false, 4718 false); 4719 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0); 4720 NamedDecl *TemplParamPtr = TemplParam; 4721 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt( 4722 Context, Loc, Loc, TemplParamPtr, Loc, nullptr); 4723 4724 QualType FuncParam = 4725 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/ true) 4726 .Apply(Type); 4727 assert(!FuncParam.isNull() && 4728 "substituting template parameter for 'auto' failed"); 4729 4730 // Deduce type of TemplParam in Func(Init) 4731 SmallVector<DeducedTemplateArgument, 1> Deduced; 4732 Deduced.resize(1); 4733 4734 TemplateDeductionInfo Info(Loc, Depth); 4735 4736 // If deduction failed, don't diagnose if the initializer is dependent; it 4737 // might acquire a matching type in the instantiation. 4738 auto DeductionFailed = [&](TemplateDeductionResult TDK, 4739 ArrayRef<SourceRange> Ranges) -> DeduceAutoResult { 4740 if (Init->isTypeDependent()) { 4741 Result = 4742 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type); 4743 assert(!Result.isNull() && "substituting DependentTy can't fail"); 4744 return DAR_Succeeded; 4745 } 4746 if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges)) 4747 return DAR_FailedAlreadyDiagnosed; 4748 return DAR_Failed; 4749 }; 4750 4751 SmallVector<OriginalCallArg, 4> OriginalCallArgs; 4752 4753 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 4754 if (InitList) { 4755 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce 4756 // against that. Such deduction only succeeds if removing cv-qualifiers and 4757 // references results in std::initializer_list<T>. 4758 if (!Type.getType().getNonReferenceType()->getAs<AutoType>()) 4759 return DAR_Failed; 4760 4761 // Resolving a core issue: a braced-init-list containing any designators is 4762 // a non-deduced context. 4763 for (Expr *E : InitList->inits()) 4764 if (isa<DesignatedInitExpr>(E)) 4765 return DAR_Failed; 4766 4767 SourceRange DeducedFromInitRange; 4768 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) { 4769 Expr *Init = InitList->getInit(i); 4770 4771 if (auto TDK = DeduceTemplateArgumentsFromCallArgument( 4772 *this, TemplateParamsSt.get(), 0, TemplArg, Init, 4773 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true, 4774 /*ArgIdx*/ 0, /*TDF*/ 0)) 4775 return DeductionFailed(TDK, {DeducedFromInitRange, 4776 Init->getSourceRange()}); 4777 4778 if (DeducedFromInitRange.isInvalid() && 4779 Deduced[0].getKind() != TemplateArgument::Null) 4780 DeducedFromInitRange = Init->getSourceRange(); 4781 } 4782 } else { 4783 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) { 4784 Diag(Loc, diag::err_auto_bitfield); 4785 return DAR_FailedAlreadyDiagnosed; 4786 } 4787 4788 if (auto TDK = DeduceTemplateArgumentsFromCallArgument( 4789 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced, 4790 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0)) 4791 return DeductionFailed(TDK, {}); 4792 } 4793 4794 // Could be null if somehow 'auto' appears in a non-deduced context. 4795 if (Deduced[0].getKind() != TemplateArgument::Type) 4796 return DeductionFailed(TDK_Incomplete, {}); 4797 4798 QualType DeducedType = Deduced[0].getAsType(); 4799 4800 if (InitList) { 4801 DeducedType = BuildStdInitializerList(DeducedType, Loc); 4802 if (DeducedType.isNull()) 4803 return DAR_FailedAlreadyDiagnosed; 4804 } 4805 4806 QualType MaybeAuto = Type.getType().getNonReferenceType(); 4807 while (MaybeAuto->isPointerType()) 4808 MaybeAuto = MaybeAuto->getPointeeType(); 4809 if (const auto *AT = MaybeAuto->getAs<AutoType>()) { 4810 if (AT->isConstrained() && !IgnoreConstraints) { 4811 auto ConstraintsResult = CheckDeducedPlaceholderConstraints( 4812 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType); 4813 if (ConstraintsResult != DAR_Succeeded) 4814 return ConstraintsResult; 4815 } 4816 } 4817 4818 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type); 4819 if (Result.isNull()) 4820 return DAR_FailedAlreadyDiagnosed; 4821 4822 // Check that the deduced argument type is compatible with the original 4823 // argument type per C++ [temp.deduct.call]p4. 4824 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result; 4825 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) { 4826 assert((bool)InitList == OriginalArg.DecomposedParam && 4827 "decomposed non-init-list in auto deduction?"); 4828 if (auto TDK = 4829 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) { 4830 Result = QualType(); 4831 return DeductionFailed(TDK, {}); 4832 } 4833 } 4834 4835 return DAR_Succeeded; 4836 } 4837 4838 QualType Sema::SubstAutoType(QualType TypeWithAuto, 4839 QualType TypeToReplaceAuto) { 4840 assert(TypeToReplaceAuto != Context.DependentTy); 4841 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto) 4842 .TransformType(TypeWithAuto); 4843 } 4844 4845 TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 4846 QualType TypeToReplaceAuto) { 4847 assert(TypeToReplaceAuto != Context.DependentTy); 4848 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto) 4849 .TransformType(TypeWithAuto); 4850 } 4851 4852 QualType Sema::SubstAutoTypeDependent(QualType TypeWithAuto) { 4853 return SubstituteDeducedTypeTransform(*this, DependentAuto{false}) 4854 .TransformType(TypeWithAuto); 4855 } 4856 4857 TypeSourceInfo * 4858 Sema::SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto) { 4859 return SubstituteDeducedTypeTransform(*this, DependentAuto{false}) 4860 .TransformType(TypeWithAuto); 4861 } 4862 4863 QualType Sema::ReplaceAutoType(QualType TypeWithAuto, 4864 QualType TypeToReplaceAuto) { 4865 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto, 4866 /*UseTypeSugar*/ false) 4867 .TransformType(TypeWithAuto); 4868 } 4869 4870 TypeSourceInfo *Sema::ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 4871 QualType TypeToReplaceAuto) { 4872 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto, 4873 /*UseTypeSugar*/ false) 4874 .TransformType(TypeWithAuto); 4875 } 4876 4877 void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) { 4878 if (isa<InitListExpr>(Init)) 4879 Diag(VDecl->getLocation(), 4880 VDecl->isInitCapture() 4881 ? diag::err_init_capture_deduction_failure_from_init_list 4882 : diag::err_auto_var_deduction_failure_from_init_list) 4883 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange(); 4884 else 4885 Diag(VDecl->getLocation(), 4886 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure 4887 : diag::err_auto_var_deduction_failure) 4888 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 4889 << Init->getSourceRange(); 4890 } 4891 4892 bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 4893 bool Diagnose) { 4894 assert(FD->getReturnType()->isUndeducedType()); 4895 4896 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)' 4897 // within the return type from the call operator's type. 4898 if (isLambdaConversionOperator(FD)) { 4899 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent(); 4900 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 4901 4902 // For a generic lambda, instantiate the call operator if needed. 4903 if (auto *Args = FD->getTemplateSpecializationArgs()) { 4904 CallOp = InstantiateFunctionDeclaration( 4905 CallOp->getDescribedFunctionTemplate(), Args, Loc); 4906 if (!CallOp || CallOp->isInvalidDecl()) 4907 return true; 4908 4909 // We might need to deduce the return type by instantiating the definition 4910 // of the operator() function. 4911 if (CallOp->getReturnType()->isUndeducedType()) { 4912 runWithSufficientStackSpace(Loc, [&] { 4913 InstantiateFunctionDefinition(Loc, CallOp); 4914 }); 4915 } 4916 } 4917 4918 if (CallOp->isInvalidDecl()) 4919 return true; 4920 assert(!CallOp->getReturnType()->isUndeducedType() && 4921 "failed to deduce lambda return type"); 4922 4923 // Build the new return type from scratch. 4924 CallingConv RetTyCC = FD->getReturnType() 4925 ->getPointeeType() 4926 ->castAs<FunctionType>() 4927 ->getCallConv(); 4928 QualType RetType = getLambdaConversionFunctionResultType( 4929 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC); 4930 if (FD->getReturnType()->getAs<PointerType>()) 4931 RetType = Context.getPointerType(RetType); 4932 else { 4933 assert(FD->getReturnType()->getAs<BlockPointerType>()); 4934 RetType = Context.getBlockPointerType(RetType); 4935 } 4936 Context.adjustDeducedFunctionResultType(FD, RetType); 4937 return false; 4938 } 4939 4940 if (FD->getTemplateInstantiationPattern()) { 4941 runWithSufficientStackSpace(Loc, [&] { 4942 InstantiateFunctionDefinition(Loc, FD); 4943 }); 4944 } 4945 4946 bool StillUndeduced = FD->getReturnType()->isUndeducedType(); 4947 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) { 4948 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD; 4949 Diag(FD->getLocation(), diag::note_callee_decl) << FD; 4950 } 4951 4952 return StillUndeduced; 4953 } 4954 4955 /// If this is a non-static member function, 4956 static void 4957 AddImplicitObjectParameterType(ASTContext &Context, 4958 CXXMethodDecl *Method, 4959 SmallVectorImpl<QualType> &ArgTypes) { 4960 // C++11 [temp.func.order]p3: 4961 // [...] The new parameter is of type "reference to cv A," where cv are 4962 // the cv-qualifiers of the function template (if any) and A is 4963 // the class of which the function template is a member. 4964 // 4965 // The standard doesn't say explicitly, but we pick the appropriate kind of 4966 // reference type based on [over.match.funcs]p4. 4967 QualType ArgTy = Context.getTypeDeclType(Method->getParent()); 4968 ArgTy = Context.getQualifiedType(ArgTy, Method->getMethodQualifiers()); 4969 if (Method->getRefQualifier() == RQ_RValue) 4970 ArgTy = Context.getRValueReferenceType(ArgTy); 4971 else 4972 ArgTy = Context.getLValueReferenceType(ArgTy); 4973 ArgTypes.push_back(ArgTy); 4974 } 4975 4976 /// Determine whether the function template \p FT1 is at least as 4977 /// specialized as \p FT2. 4978 static bool isAtLeastAsSpecializedAs(Sema &S, 4979 SourceLocation Loc, 4980 FunctionTemplateDecl *FT1, 4981 FunctionTemplateDecl *FT2, 4982 TemplatePartialOrderingContext TPOC, 4983 unsigned NumCallArguments1, 4984 bool Reversed) { 4985 assert(!Reversed || TPOC == TPOC_Call); 4986 4987 FunctionDecl *FD1 = FT1->getTemplatedDecl(); 4988 FunctionDecl *FD2 = FT2->getTemplatedDecl(); 4989 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>(); 4990 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>(); 4991 4992 assert(Proto1 && Proto2 && "Function templates must have prototypes"); 4993 TemplateParameterList *TemplateParams = FT2->getTemplateParameters(); 4994 SmallVector<DeducedTemplateArgument, 4> Deduced; 4995 Deduced.resize(TemplateParams->size()); 4996 4997 // C++0x [temp.deduct.partial]p3: 4998 // The types used to determine the ordering depend on the context in which 4999 // the partial ordering is done: 5000 TemplateDeductionInfo Info(Loc); 5001 SmallVector<QualType, 4> Args2; 5002 switch (TPOC) { 5003 case TPOC_Call: { 5004 // - In the context of a function call, the function parameter types are 5005 // used. 5006 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1); 5007 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2); 5008 5009 // C++11 [temp.func.order]p3: 5010 // [...] If only one of the function templates is a non-static 5011 // member, that function template is considered to have a new 5012 // first parameter inserted in its function parameter list. The 5013 // new parameter is of type "reference to cv A," where cv are 5014 // the cv-qualifiers of the function template (if any) and A is 5015 // the class of which the function template is a member. 5016 // 5017 // Note that we interpret this to mean "if one of the function 5018 // templates is a non-static member and the other is a non-member"; 5019 // otherwise, the ordering rules for static functions against non-static 5020 // functions don't make any sense. 5021 // 5022 // C++98/03 doesn't have this provision but we've extended DR532 to cover 5023 // it as wording was broken prior to it. 5024 SmallVector<QualType, 4> Args1; 5025 5026 unsigned NumComparedArguments = NumCallArguments1; 5027 5028 if (!Method2 && Method1 && !Method1->isStatic()) { 5029 // Compare 'this' from Method1 against first parameter from Method2. 5030 AddImplicitObjectParameterType(S.Context, Method1, Args1); 5031 ++NumComparedArguments; 5032 } else if (!Method1 && Method2 && !Method2->isStatic()) { 5033 // Compare 'this' from Method2 against first parameter from Method1. 5034 AddImplicitObjectParameterType(S.Context, Method2, Args2); 5035 } else if (Method1 && Method2 && Reversed) { 5036 // Compare 'this' from Method1 against second parameter from Method2 5037 // and 'this' from Method2 against second parameter from Method1. 5038 AddImplicitObjectParameterType(S.Context, Method1, Args1); 5039 AddImplicitObjectParameterType(S.Context, Method2, Args2); 5040 ++NumComparedArguments; 5041 } 5042 5043 Args1.insert(Args1.end(), Proto1->param_type_begin(), 5044 Proto1->param_type_end()); 5045 Args2.insert(Args2.end(), Proto2->param_type_begin(), 5046 Proto2->param_type_end()); 5047 5048 // C++ [temp.func.order]p5: 5049 // The presence of unused ellipsis and default arguments has no effect on 5050 // the partial ordering of function templates. 5051 if (Args1.size() > NumComparedArguments) 5052 Args1.resize(NumComparedArguments); 5053 if (Args2.size() > NumComparedArguments) 5054 Args2.resize(NumComparedArguments); 5055 if (Reversed) 5056 std::reverse(Args2.begin(), Args2.end()); 5057 5058 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(), 5059 Args1.data(), Args1.size(), Info, Deduced, 5060 TDF_None, /*PartialOrdering=*/true)) 5061 return false; 5062 5063 break; 5064 } 5065 5066 case TPOC_Conversion: 5067 // - In the context of a call to a conversion operator, the return types 5068 // of the conversion function templates are used. 5069 if (DeduceTemplateArgumentsByTypeMatch( 5070 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(), 5071 Info, Deduced, TDF_None, 5072 /*PartialOrdering=*/true)) 5073 return false; 5074 break; 5075 5076 case TPOC_Other: 5077 // - In other contexts (14.6.6.2) the function template's function type 5078 // is used. 5079 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 5080 FD2->getType(), FD1->getType(), 5081 Info, Deduced, TDF_None, 5082 /*PartialOrdering=*/true)) 5083 return false; 5084 break; 5085 } 5086 5087 // C++0x [temp.deduct.partial]p11: 5088 // In most cases, all template parameters must have values in order for 5089 // deduction to succeed, but for partial ordering purposes a template 5090 // parameter may remain without a value provided it is not used in the 5091 // types being used for partial ordering. [ Note: a template parameter used 5092 // in a non-deduced context is considered used. -end note] 5093 unsigned ArgIdx = 0, NumArgs = Deduced.size(); 5094 for (; ArgIdx != NumArgs; ++ArgIdx) 5095 if (Deduced[ArgIdx].isNull()) 5096 break; 5097 5098 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need 5099 // to substitute the deduced arguments back into the template and check that 5100 // we get the right type. 5101 5102 if (ArgIdx == NumArgs) { 5103 // All template arguments were deduced. FT1 is at least as specialized 5104 // as FT2. 5105 return true; 5106 } 5107 5108 // Figure out which template parameters were used. 5109 llvm::SmallBitVector UsedParameters(TemplateParams->size()); 5110 switch (TPOC) { 5111 case TPOC_Call: 5112 for (unsigned I = 0, N = Args2.size(); I != N; ++I) 5113 ::MarkUsedTemplateParameters(S.Context, Args2[I], false, 5114 TemplateParams->getDepth(), 5115 UsedParameters); 5116 break; 5117 5118 case TPOC_Conversion: 5119 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false, 5120 TemplateParams->getDepth(), UsedParameters); 5121 break; 5122 5123 case TPOC_Other: 5124 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false, 5125 TemplateParams->getDepth(), 5126 UsedParameters); 5127 break; 5128 } 5129 5130 for (; ArgIdx != NumArgs; ++ArgIdx) 5131 // If this argument had no value deduced but was used in one of the types 5132 // used for partial ordering, then deduction fails. 5133 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx]) 5134 return false; 5135 5136 return true; 5137 } 5138 5139 /// Determine whether this a function template whose parameter-type-list 5140 /// ends with a function parameter pack. 5141 static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) { 5142 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 5143 unsigned NumParams = Function->getNumParams(); 5144 if (NumParams == 0) 5145 return false; 5146 5147 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1); 5148 if (!Last->isParameterPack()) 5149 return false; 5150 5151 // Make sure that no previous parameter is a parameter pack. 5152 while (--NumParams > 0) { 5153 if (Function->getParamDecl(NumParams - 1)->isParameterPack()) 5154 return false; 5155 } 5156 5157 return true; 5158 } 5159 5160 /// Returns the more specialized function template according 5161 /// to the rules of function template partial ordering (C++ [temp.func.order]). 5162 /// 5163 /// \param FT1 the first function template 5164 /// 5165 /// \param FT2 the second function template 5166 /// 5167 /// \param TPOC the context in which we are performing partial ordering of 5168 /// function templates. 5169 /// 5170 /// \param NumCallArguments1 The number of arguments in the call to FT1, used 5171 /// only when \c TPOC is \c TPOC_Call. 5172 /// 5173 /// \param NumCallArguments2 The number of arguments in the call to FT2, used 5174 /// only when \c TPOC is \c TPOC_Call. 5175 /// 5176 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload 5177 /// candidate with a reversed parameter order. In this case, the corresponding 5178 /// P/A pairs between FT1 and FT2 are reversed. 5179 /// 5180 /// \param AllowOrderingByConstraints If \c is false, don't check whether one 5181 /// of the templates is more constrained than the other. Default is true. 5182 /// 5183 /// \returns the more specialized function template. If neither 5184 /// template is more specialized, returns NULL. 5185 FunctionTemplateDecl *Sema::getMoreSpecializedTemplate( 5186 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, 5187 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, 5188 unsigned NumCallArguments2, bool Reversed, 5189 bool AllowOrderingByConstraints) { 5190 5191 auto JudgeByConstraints = [&]() -> FunctionTemplateDecl * { 5192 if (!AllowOrderingByConstraints) 5193 return nullptr; 5194 llvm::SmallVector<const Expr *, 3> AC1, AC2; 5195 FT1->getAssociatedConstraints(AC1); 5196 FT2->getAssociatedConstraints(AC2); 5197 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 5198 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1)) 5199 return nullptr; 5200 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2)) 5201 return nullptr; 5202 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 5203 return nullptr; 5204 return AtLeastAsConstrained1 ? FT1 : FT2; 5205 }; 5206 5207 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 5208 NumCallArguments1, Reversed); 5209 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, 5210 NumCallArguments2, Reversed); 5211 5212 if (Better1 != Better2) // We have a clear winner 5213 return Better1 ? FT1 : FT2; 5214 5215 if (!Better1 && !Better2) // Neither is better than the other 5216 return JudgeByConstraints(); 5217 5218 // FIXME: This mimics what GCC implements, but doesn't match up with the 5219 // proposed resolution for core issue 692. This area needs to be sorted out, 5220 // but for now we attempt to maintain compatibility. 5221 bool Variadic1 = isVariadicFunctionTemplate(FT1); 5222 bool Variadic2 = isVariadicFunctionTemplate(FT2); 5223 if (Variadic1 != Variadic2) 5224 return Variadic1? FT2 : FT1; 5225 5226 return JudgeByConstraints(); 5227 } 5228 5229 /// Determine if the two templates are equivalent. 5230 static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) { 5231 if (T1 == T2) 5232 return true; 5233 5234 if (!T1 || !T2) 5235 return false; 5236 5237 return T1->getCanonicalDecl() == T2->getCanonicalDecl(); 5238 } 5239 5240 /// Retrieve the most specialized of the given function template 5241 /// specializations. 5242 /// 5243 /// \param SpecBegin the start iterator of the function template 5244 /// specializations that we will be comparing. 5245 /// 5246 /// \param SpecEnd the end iterator of the function template 5247 /// specializations, paired with \p SpecBegin. 5248 /// 5249 /// \param Loc the location where the ambiguity or no-specializations 5250 /// diagnostic should occur. 5251 /// 5252 /// \param NoneDiag partial diagnostic used to diagnose cases where there are 5253 /// no matching candidates. 5254 /// 5255 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one 5256 /// occurs. 5257 /// 5258 /// \param CandidateDiag partial diagnostic used for each function template 5259 /// specialization that is a candidate in the ambiguous ordering. One parameter 5260 /// in this diagnostic should be unbound, which will correspond to the string 5261 /// describing the template arguments for the function template specialization. 5262 /// 5263 /// \returns the most specialized function template specialization, if 5264 /// found. Otherwise, returns SpecEnd. 5265 UnresolvedSetIterator Sema::getMostSpecialized( 5266 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd, 5267 TemplateSpecCandidateSet &FailedCandidates, 5268 SourceLocation Loc, const PartialDiagnostic &NoneDiag, 5269 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, 5270 bool Complain, QualType TargetType) { 5271 if (SpecBegin == SpecEnd) { 5272 if (Complain) { 5273 Diag(Loc, NoneDiag); 5274 FailedCandidates.NoteCandidates(*this, Loc); 5275 } 5276 return SpecEnd; 5277 } 5278 5279 if (SpecBegin + 1 == SpecEnd) 5280 return SpecBegin; 5281 5282 // Find the function template that is better than all of the templates it 5283 // has been compared to. 5284 UnresolvedSetIterator Best = SpecBegin; 5285 FunctionTemplateDecl *BestTemplate 5286 = cast<FunctionDecl>(*Best)->getPrimaryTemplate(); 5287 assert(BestTemplate && "Not a function template specialization?"); 5288 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) { 5289 FunctionTemplateDecl *Challenger 5290 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 5291 assert(Challenger && "Not a function template specialization?"); 5292 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 5293 Loc, TPOC_Other, 0, 0), 5294 Challenger)) { 5295 Best = I; 5296 BestTemplate = Challenger; 5297 } 5298 } 5299 5300 // Make sure that the "best" function template is more specialized than all 5301 // of the others. 5302 bool Ambiguous = false; 5303 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 5304 FunctionTemplateDecl *Challenger 5305 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 5306 if (I != Best && 5307 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 5308 Loc, TPOC_Other, 0, 0), 5309 BestTemplate)) { 5310 Ambiguous = true; 5311 break; 5312 } 5313 } 5314 5315 if (!Ambiguous) { 5316 // We found an answer. Return it. 5317 return Best; 5318 } 5319 5320 // Diagnose the ambiguity. 5321 if (Complain) { 5322 Diag(Loc, AmbigDiag); 5323 5324 // FIXME: Can we order the candidates in some sane way? 5325 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 5326 PartialDiagnostic PD = CandidateDiag; 5327 const auto *FD = cast<FunctionDecl>(*I); 5328 PD << FD << getTemplateArgumentBindingsText( 5329 FD->getPrimaryTemplate()->getTemplateParameters(), 5330 *FD->getTemplateSpecializationArgs()); 5331 if (!TargetType.isNull()) 5332 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType); 5333 Diag((*I)->getLocation(), PD); 5334 } 5335 } 5336 5337 return SpecEnd; 5338 } 5339 5340 /// Determine whether one partial specialization, P1, is at least as 5341 /// specialized than another, P2. 5342 /// 5343 /// \tparam TemplateLikeDecl The kind of P2, which must be a 5344 /// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl. 5345 /// \param T1 The injected-class-name of P1 (faked for a variable template). 5346 /// \param T2 The injected-class-name of P2 (faked for a variable template). 5347 template<typename TemplateLikeDecl> 5348 static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2, 5349 TemplateLikeDecl *P2, 5350 TemplateDeductionInfo &Info) { 5351 // C++ [temp.class.order]p1: 5352 // For two class template partial specializations, the first is at least as 5353 // specialized as the second if, given the following rewrite to two 5354 // function templates, the first function template is at least as 5355 // specialized as the second according to the ordering rules for function 5356 // templates (14.6.6.2): 5357 // - the first function template has the same template parameters as the 5358 // first partial specialization and has a single function parameter 5359 // whose type is a class template specialization with the template 5360 // arguments of the first partial specialization, and 5361 // - the second function template has the same template parameters as the 5362 // second partial specialization and has a single function parameter 5363 // whose type is a class template specialization with the template 5364 // arguments of the second partial specialization. 5365 // 5366 // Rather than synthesize function templates, we merely perform the 5367 // equivalent partial ordering by performing deduction directly on 5368 // the template arguments of the class template partial 5369 // specializations. This computation is slightly simpler than the 5370 // general problem of function template partial ordering, because 5371 // class template partial specializations are more constrained. We 5372 // know that every template parameter is deducible from the class 5373 // template partial specialization's template arguments, for 5374 // example. 5375 SmallVector<DeducedTemplateArgument, 4> Deduced; 5376 5377 // Determine whether P1 is at least as specialized as P2. 5378 Deduced.resize(P2->getTemplateParameters()->size()); 5379 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(), 5380 T2, T1, Info, Deduced, TDF_None, 5381 /*PartialOrdering=*/true)) 5382 return false; 5383 5384 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), 5385 Deduced.end()); 5386 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs, 5387 Info); 5388 if (Inst.isInvalid()) 5389 return false; 5390 5391 auto *TST1 = T1->castAs<TemplateSpecializationType>(); 5392 bool AtLeastAsSpecialized; 5393 S.runWithSufficientStackSpace(Info.getLocation(), [&] { 5394 AtLeastAsSpecialized = !FinishTemplateArgumentDeduction( 5395 S, P2, /*IsPartialOrdering=*/true, 5396 TemplateArgumentList(TemplateArgumentList::OnStack, 5397 TST1->template_arguments()), 5398 Deduced, Info); 5399 }); 5400 return AtLeastAsSpecialized; 5401 } 5402 5403 /// Returns the more specialized class template partial specialization 5404 /// according to the rules of partial ordering of class template partial 5405 /// specializations (C++ [temp.class.order]). 5406 /// 5407 /// \param PS1 the first class template partial specialization 5408 /// 5409 /// \param PS2 the second class template partial specialization 5410 /// 5411 /// \returns the more specialized class template partial specialization. If 5412 /// neither partial specialization is more specialized, returns NULL. 5413 ClassTemplatePartialSpecializationDecl * 5414 Sema::getMoreSpecializedPartialSpecialization( 5415 ClassTemplatePartialSpecializationDecl *PS1, 5416 ClassTemplatePartialSpecializationDecl *PS2, 5417 SourceLocation Loc) { 5418 QualType PT1 = PS1->getInjectedSpecializationType(); 5419 QualType PT2 = PS2->getInjectedSpecializationType(); 5420 5421 TemplateDeductionInfo Info(Loc); 5422 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info); 5423 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info); 5424 5425 if (!Better1 && !Better2) 5426 return nullptr; 5427 if (Better1 && Better2) { 5428 llvm::SmallVector<const Expr *, 3> AC1, AC2; 5429 PS1->getAssociatedConstraints(AC1); 5430 PS2->getAssociatedConstraints(AC2); 5431 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 5432 if (IsAtLeastAsConstrained(PS1, AC1, PS2, AC2, AtLeastAsConstrained1)) 5433 return nullptr; 5434 if (IsAtLeastAsConstrained(PS2, AC2, PS1, AC1, AtLeastAsConstrained2)) 5435 return nullptr; 5436 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 5437 return nullptr; 5438 return AtLeastAsConstrained1 ? PS1 : PS2; 5439 } 5440 5441 return Better1 ? PS1 : PS2; 5442 } 5443 5444 bool Sema::isMoreSpecializedThanPrimary( 5445 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) { 5446 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate(); 5447 QualType PrimaryT = Primary->getInjectedClassNameSpecialization(); 5448 QualType PartialT = Spec->getInjectedSpecializationType(); 5449 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info)) 5450 return false; 5451 if (!isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) 5452 return true; 5453 Info.clearSFINAEDiagnostic(); 5454 llvm::SmallVector<const Expr *, 3> PrimaryAC, SpecAC; 5455 Primary->getAssociatedConstraints(PrimaryAC); 5456 Spec->getAssociatedConstraints(SpecAC); 5457 bool AtLeastAsConstrainedPrimary, AtLeastAsConstrainedSpec; 5458 if (IsAtLeastAsConstrained(Spec, SpecAC, Primary, PrimaryAC, 5459 AtLeastAsConstrainedSpec)) 5460 return false; 5461 if (!AtLeastAsConstrainedSpec) 5462 return false; 5463 if (IsAtLeastAsConstrained(Primary, PrimaryAC, Spec, SpecAC, 5464 AtLeastAsConstrainedPrimary)) 5465 return false; 5466 return !AtLeastAsConstrainedPrimary; 5467 } 5468 5469 VarTemplatePartialSpecializationDecl * 5470 Sema::getMoreSpecializedPartialSpecialization( 5471 VarTemplatePartialSpecializationDecl *PS1, 5472 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) { 5473 // Pretend the variable template specializations are class template 5474 // specializations and form a fake injected class name type for comparison. 5475 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && 5476 "the partial specializations being compared should specialize" 5477 " the same template."); 5478 TemplateName Name(PS1->getSpecializedTemplate()); 5479 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 5480 QualType PT1 = Context.getTemplateSpecializationType( 5481 CanonTemplate, PS1->getTemplateArgs().asArray()); 5482 QualType PT2 = Context.getTemplateSpecializationType( 5483 CanonTemplate, PS2->getTemplateArgs().asArray()); 5484 5485 TemplateDeductionInfo Info(Loc); 5486 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info); 5487 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info); 5488 5489 if (!Better1 && !Better2) 5490 return nullptr; 5491 if (Better1 && Better2) { 5492 llvm::SmallVector<const Expr *, 3> AC1, AC2; 5493 PS1->getAssociatedConstraints(AC1); 5494 PS2->getAssociatedConstraints(AC2); 5495 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 5496 if (IsAtLeastAsConstrained(PS1, AC1, PS2, AC2, AtLeastAsConstrained1)) 5497 return nullptr; 5498 if (IsAtLeastAsConstrained(PS2, AC2, PS1, AC1, AtLeastAsConstrained2)) 5499 return nullptr; 5500 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 5501 return nullptr; 5502 return AtLeastAsConstrained1 ? PS1 : PS2; 5503 } 5504 5505 return Better1 ? PS1 : PS2; 5506 } 5507 5508 bool Sema::isMoreSpecializedThanPrimary( 5509 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) { 5510 TemplateDecl *Primary = Spec->getSpecializedTemplate(); 5511 // FIXME: Cache the injected template arguments rather than recomputing 5512 // them for each partial specialization. 5513 SmallVector<TemplateArgument, 8> PrimaryArgs; 5514 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(), 5515 PrimaryArgs); 5516 5517 TemplateName CanonTemplate = 5518 Context.getCanonicalTemplateName(TemplateName(Primary)); 5519 QualType PrimaryT = Context.getTemplateSpecializationType( 5520 CanonTemplate, PrimaryArgs); 5521 QualType PartialT = Context.getTemplateSpecializationType( 5522 CanonTemplate, Spec->getTemplateArgs().asArray()); 5523 5524 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info)) 5525 return false; 5526 if (!isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) 5527 return true; 5528 Info.clearSFINAEDiagnostic(); 5529 llvm::SmallVector<const Expr *, 3> PrimaryAC, SpecAC; 5530 Primary->getAssociatedConstraints(PrimaryAC); 5531 Spec->getAssociatedConstraints(SpecAC); 5532 bool AtLeastAsConstrainedPrimary, AtLeastAsConstrainedSpec; 5533 if (IsAtLeastAsConstrained(Spec, SpecAC, Primary, PrimaryAC, 5534 AtLeastAsConstrainedSpec)) 5535 return false; 5536 if (!AtLeastAsConstrainedSpec) 5537 return false; 5538 if (IsAtLeastAsConstrained(Primary, PrimaryAC, Spec, SpecAC, 5539 AtLeastAsConstrainedPrimary)) 5540 return false; 5541 return !AtLeastAsConstrainedPrimary; 5542 } 5543 5544 bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs( 5545 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) { 5546 // C++1z [temp.arg.template]p4: (DR 150) 5547 // A template template-parameter P is at least as specialized as a 5548 // template template-argument A if, given the following rewrite to two 5549 // function templates... 5550 5551 // Rather than synthesize function templates, we merely perform the 5552 // equivalent partial ordering by performing deduction directly on 5553 // the template parameter lists of the template template parameters. 5554 // 5555 // Given an invented class template X with the template parameter list of 5556 // A (including default arguments): 5557 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg)); 5558 TemplateParameterList *A = AArg->getTemplateParameters(); 5559 5560 // - Each function template has a single function parameter whose type is 5561 // a specialization of X with template arguments corresponding to the 5562 // template parameters from the respective function template 5563 SmallVector<TemplateArgument, 8> AArgs; 5564 Context.getInjectedTemplateArgs(A, AArgs); 5565 5566 // Check P's arguments against A's parameter list. This will fill in default 5567 // template arguments as needed. AArgs are already correct by construction. 5568 // We can't just use CheckTemplateIdType because that will expand alias 5569 // templates. 5570 SmallVector<TemplateArgument, 4> PArgs; 5571 { 5572 SFINAETrap Trap(*this); 5573 5574 Context.getInjectedTemplateArgs(P, PArgs); 5575 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), 5576 P->getRAngleLoc()); 5577 for (unsigned I = 0, N = P->size(); I != N; ++I) { 5578 // Unwrap packs that getInjectedTemplateArgs wrapped around pack 5579 // expansions, to form an "as written" argument list. 5580 TemplateArgument Arg = PArgs[I]; 5581 if (Arg.getKind() == TemplateArgument::Pack) { 5582 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion()); 5583 Arg = *Arg.pack_begin(); 5584 } 5585 PArgList.addArgument(getTrivialTemplateArgumentLoc( 5586 Arg, QualType(), P->getParam(I)->getLocation())); 5587 } 5588 PArgs.clear(); 5589 5590 // C++1z [temp.arg.template]p3: 5591 // If the rewrite produces an invalid type, then P is not at least as 5592 // specialized as A. 5593 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) || 5594 Trap.hasErrorOccurred()) 5595 return false; 5596 } 5597 5598 QualType AType = Context.getTemplateSpecializationType(X, AArgs); 5599 QualType PType = Context.getTemplateSpecializationType(X, PArgs); 5600 5601 // ... the function template corresponding to P is at least as specialized 5602 // as the function template corresponding to A according to the partial 5603 // ordering rules for function templates. 5604 TemplateDeductionInfo Info(Loc, A->getDepth()); 5605 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info); 5606 } 5607 5608 namespace { 5609 struct MarkUsedTemplateParameterVisitor : 5610 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> { 5611 llvm::SmallBitVector &Used; 5612 unsigned Depth; 5613 5614 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used, 5615 unsigned Depth) 5616 : Used(Used), Depth(Depth) { } 5617 5618 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) { 5619 if (T->getDepth() == Depth) 5620 Used[T->getIndex()] = true; 5621 return true; 5622 } 5623 5624 bool TraverseTemplateName(TemplateName Template) { 5625 if (auto *TTP = 5626 dyn_cast<TemplateTemplateParmDecl>(Template.getAsTemplateDecl())) 5627 if (TTP->getDepth() == Depth) 5628 Used[TTP->getIndex()] = true; 5629 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor>:: 5630 TraverseTemplateName(Template); 5631 return true; 5632 } 5633 5634 bool VisitDeclRefExpr(DeclRefExpr *E) { 5635 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) 5636 if (NTTP->getDepth() == Depth) 5637 Used[NTTP->getIndex()] = true; 5638 return true; 5639 } 5640 }; 5641 } 5642 5643 /// Mark the template parameters that are used by the given 5644 /// expression. 5645 static void 5646 MarkUsedTemplateParameters(ASTContext &Ctx, 5647 const Expr *E, 5648 bool OnlyDeduced, 5649 unsigned Depth, 5650 llvm::SmallBitVector &Used) { 5651 if (!OnlyDeduced) { 5652 MarkUsedTemplateParameterVisitor(Used, Depth) 5653 .TraverseStmt(const_cast<Expr *>(E)); 5654 return; 5655 } 5656 5657 // We can deduce from a pack expansion. 5658 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E)) 5659 E = Expansion->getPattern(); 5660 5661 const NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(E, Depth); 5662 if (!NTTP) 5663 return; 5664 5665 if (NTTP->getDepth() == Depth) 5666 Used[NTTP->getIndex()] = true; 5667 5668 // In C++17 mode, additional arguments may be deduced from the type of a 5669 // non-type argument. 5670 if (Ctx.getLangOpts().CPlusPlus17) 5671 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used); 5672 } 5673 5674 /// Mark the template parameters that are used by the given 5675 /// nested name specifier. 5676 static void 5677 MarkUsedTemplateParameters(ASTContext &Ctx, 5678 NestedNameSpecifier *NNS, 5679 bool OnlyDeduced, 5680 unsigned Depth, 5681 llvm::SmallBitVector &Used) { 5682 if (!NNS) 5683 return; 5684 5685 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth, 5686 Used); 5687 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0), 5688 OnlyDeduced, Depth, Used); 5689 } 5690 5691 /// Mark the template parameters that are used by the given 5692 /// template name. 5693 static void 5694 MarkUsedTemplateParameters(ASTContext &Ctx, 5695 TemplateName Name, 5696 bool OnlyDeduced, 5697 unsigned Depth, 5698 llvm::SmallBitVector &Used) { 5699 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 5700 if (TemplateTemplateParmDecl *TTP 5701 = dyn_cast<TemplateTemplateParmDecl>(Template)) { 5702 if (TTP->getDepth() == Depth) 5703 Used[TTP->getIndex()] = true; 5704 } 5705 return; 5706 } 5707 5708 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) 5709 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced, 5710 Depth, Used); 5711 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) 5712 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced, 5713 Depth, Used); 5714 } 5715 5716 /// Mark the template parameters that are used by the given 5717 /// type. 5718 static void 5719 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 5720 bool OnlyDeduced, 5721 unsigned Depth, 5722 llvm::SmallBitVector &Used) { 5723 if (T.isNull()) 5724 return; 5725 5726 // Non-dependent types have nothing deducible 5727 if (!T->isDependentType()) 5728 return; 5729 5730 T = Ctx.getCanonicalType(T); 5731 switch (T->getTypeClass()) { 5732 case Type::Pointer: 5733 MarkUsedTemplateParameters(Ctx, 5734 cast<PointerType>(T)->getPointeeType(), 5735 OnlyDeduced, 5736 Depth, 5737 Used); 5738 break; 5739 5740 case Type::BlockPointer: 5741 MarkUsedTemplateParameters(Ctx, 5742 cast<BlockPointerType>(T)->getPointeeType(), 5743 OnlyDeduced, 5744 Depth, 5745 Used); 5746 break; 5747 5748 case Type::LValueReference: 5749 case Type::RValueReference: 5750 MarkUsedTemplateParameters(Ctx, 5751 cast<ReferenceType>(T)->getPointeeType(), 5752 OnlyDeduced, 5753 Depth, 5754 Used); 5755 break; 5756 5757 case Type::MemberPointer: { 5758 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr()); 5759 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced, 5760 Depth, Used); 5761 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0), 5762 OnlyDeduced, Depth, Used); 5763 break; 5764 } 5765 5766 case Type::DependentSizedArray: 5767 MarkUsedTemplateParameters(Ctx, 5768 cast<DependentSizedArrayType>(T)->getSizeExpr(), 5769 OnlyDeduced, Depth, Used); 5770 // Fall through to check the element type 5771 LLVM_FALLTHROUGH; 5772 5773 case Type::ConstantArray: 5774 case Type::IncompleteArray: 5775 MarkUsedTemplateParameters(Ctx, 5776 cast<ArrayType>(T)->getElementType(), 5777 OnlyDeduced, Depth, Used); 5778 break; 5779 5780 case Type::Vector: 5781 case Type::ExtVector: 5782 MarkUsedTemplateParameters(Ctx, 5783 cast<VectorType>(T)->getElementType(), 5784 OnlyDeduced, Depth, Used); 5785 break; 5786 5787 case Type::DependentVector: { 5788 const auto *VecType = cast<DependentVectorType>(T); 5789 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced, 5790 Depth, Used); 5791 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth, 5792 Used); 5793 break; 5794 } 5795 case Type::DependentSizedExtVector: { 5796 const DependentSizedExtVectorType *VecType 5797 = cast<DependentSizedExtVectorType>(T); 5798 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced, 5799 Depth, Used); 5800 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, 5801 Depth, Used); 5802 break; 5803 } 5804 5805 case Type::DependentAddressSpace: { 5806 const DependentAddressSpaceType *DependentASType = 5807 cast<DependentAddressSpaceType>(T); 5808 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(), 5809 OnlyDeduced, Depth, Used); 5810 MarkUsedTemplateParameters(Ctx, 5811 DependentASType->getAddrSpaceExpr(), 5812 OnlyDeduced, Depth, Used); 5813 break; 5814 } 5815 5816 case Type::ConstantMatrix: { 5817 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T); 5818 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced, 5819 Depth, Used); 5820 break; 5821 } 5822 5823 case Type::DependentSizedMatrix: { 5824 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T); 5825 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced, 5826 Depth, Used); 5827 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth, 5828 Used); 5829 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced, 5830 Depth, Used); 5831 break; 5832 } 5833 5834 case Type::FunctionProto: { 5835 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 5836 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth, 5837 Used); 5838 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) { 5839 // C++17 [temp.deduct.type]p5: 5840 // The non-deduced contexts are: [...] 5841 // -- A function parameter pack that does not occur at the end of the 5842 // parameter-declaration-list. 5843 if (!OnlyDeduced || I + 1 == N || 5844 !Proto->getParamType(I)->getAs<PackExpansionType>()) { 5845 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced, 5846 Depth, Used); 5847 } else { 5848 // FIXME: C++17 [temp.deduct.call]p1: 5849 // When a function parameter pack appears in a non-deduced context, 5850 // the type of that pack is never deduced. 5851 // 5852 // We should also track a set of "never deduced" parameters, and 5853 // subtract that from the list of deduced parameters after marking. 5854 } 5855 } 5856 if (auto *E = Proto->getNoexceptExpr()) 5857 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used); 5858 break; 5859 } 5860 5861 case Type::TemplateTypeParm: { 5862 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T); 5863 if (TTP->getDepth() == Depth) 5864 Used[TTP->getIndex()] = true; 5865 break; 5866 } 5867 5868 case Type::SubstTemplateTypeParmPack: { 5869 const SubstTemplateTypeParmPackType *Subst 5870 = cast<SubstTemplateTypeParmPackType>(T); 5871 MarkUsedTemplateParameters(Ctx, 5872 QualType(Subst->getReplacedParameter(), 0), 5873 OnlyDeduced, Depth, Used); 5874 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), 5875 OnlyDeduced, Depth, Used); 5876 break; 5877 } 5878 5879 case Type::InjectedClassName: 5880 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType(); 5881 LLVM_FALLTHROUGH; 5882 5883 case Type::TemplateSpecialization: { 5884 const TemplateSpecializationType *Spec 5885 = cast<TemplateSpecializationType>(T); 5886 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced, 5887 Depth, Used); 5888 5889 // C++0x [temp.deduct.type]p9: 5890 // If the template argument list of P contains a pack expansion that is 5891 // not the last template argument, the entire template argument list is a 5892 // non-deduced context. 5893 if (OnlyDeduced && 5894 hasPackExpansionBeforeEnd(Spec->template_arguments())) 5895 break; 5896 5897 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 5898 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 5899 Used); 5900 break; 5901 } 5902 5903 case Type::Complex: 5904 if (!OnlyDeduced) 5905 MarkUsedTemplateParameters(Ctx, 5906 cast<ComplexType>(T)->getElementType(), 5907 OnlyDeduced, Depth, Used); 5908 break; 5909 5910 case Type::Atomic: 5911 if (!OnlyDeduced) 5912 MarkUsedTemplateParameters(Ctx, 5913 cast<AtomicType>(T)->getValueType(), 5914 OnlyDeduced, Depth, Used); 5915 break; 5916 5917 case Type::DependentName: 5918 if (!OnlyDeduced) 5919 MarkUsedTemplateParameters(Ctx, 5920 cast<DependentNameType>(T)->getQualifier(), 5921 OnlyDeduced, Depth, Used); 5922 break; 5923 5924 case Type::DependentTemplateSpecialization: { 5925 // C++14 [temp.deduct.type]p5: 5926 // The non-deduced contexts are: 5927 // -- The nested-name-specifier of a type that was specified using a 5928 // qualified-id 5929 // 5930 // C++14 [temp.deduct.type]p6: 5931 // When a type name is specified in a way that includes a non-deduced 5932 // context, all of the types that comprise that type name are also 5933 // non-deduced. 5934 if (OnlyDeduced) 5935 break; 5936 5937 const DependentTemplateSpecializationType *Spec 5938 = cast<DependentTemplateSpecializationType>(T); 5939 5940 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(), 5941 OnlyDeduced, Depth, Used); 5942 5943 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 5944 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 5945 Used); 5946 break; 5947 } 5948 5949 case Type::TypeOf: 5950 if (!OnlyDeduced) 5951 MarkUsedTemplateParameters(Ctx, 5952 cast<TypeOfType>(T)->getUnderlyingType(), 5953 OnlyDeduced, Depth, Used); 5954 break; 5955 5956 case Type::TypeOfExpr: 5957 if (!OnlyDeduced) 5958 MarkUsedTemplateParameters(Ctx, 5959 cast<TypeOfExprType>(T)->getUnderlyingExpr(), 5960 OnlyDeduced, Depth, Used); 5961 break; 5962 5963 case Type::Decltype: 5964 if (!OnlyDeduced) 5965 MarkUsedTemplateParameters(Ctx, 5966 cast<DecltypeType>(T)->getUnderlyingExpr(), 5967 OnlyDeduced, Depth, Used); 5968 break; 5969 5970 case Type::UnaryTransform: 5971 if (!OnlyDeduced) 5972 MarkUsedTemplateParameters(Ctx, 5973 cast<UnaryTransformType>(T)->getUnderlyingType(), 5974 OnlyDeduced, Depth, Used); 5975 break; 5976 5977 case Type::PackExpansion: 5978 MarkUsedTemplateParameters(Ctx, 5979 cast<PackExpansionType>(T)->getPattern(), 5980 OnlyDeduced, Depth, Used); 5981 break; 5982 5983 case Type::Auto: 5984 case Type::DeducedTemplateSpecialization: 5985 MarkUsedTemplateParameters(Ctx, 5986 cast<DeducedType>(T)->getDeducedType(), 5987 OnlyDeduced, Depth, Used); 5988 break; 5989 case Type::DependentBitInt: 5990 MarkUsedTemplateParameters(Ctx, 5991 cast<DependentBitIntType>(T)->getNumBitsExpr(), 5992 OnlyDeduced, Depth, Used); 5993 break; 5994 5995 // None of these types have any template parameters in them. 5996 case Type::Builtin: 5997 case Type::VariableArray: 5998 case Type::FunctionNoProto: 5999 case Type::Record: 6000 case Type::Enum: 6001 case Type::ObjCInterface: 6002 case Type::ObjCObject: 6003 case Type::ObjCObjectPointer: 6004 case Type::UnresolvedUsing: 6005 case Type::Pipe: 6006 case Type::BitInt: 6007 #define TYPE(Class, Base) 6008 #define ABSTRACT_TYPE(Class, Base) 6009 #define DEPENDENT_TYPE(Class, Base) 6010 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 6011 #include "clang/AST/TypeNodes.inc" 6012 break; 6013 } 6014 } 6015 6016 /// Mark the template parameters that are used by this 6017 /// template argument. 6018 static void 6019 MarkUsedTemplateParameters(ASTContext &Ctx, 6020 const TemplateArgument &TemplateArg, 6021 bool OnlyDeduced, 6022 unsigned Depth, 6023 llvm::SmallBitVector &Used) { 6024 switch (TemplateArg.getKind()) { 6025 case TemplateArgument::Null: 6026 case TemplateArgument::Integral: 6027 case TemplateArgument::Declaration: 6028 break; 6029 6030 case TemplateArgument::NullPtr: 6031 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced, 6032 Depth, Used); 6033 break; 6034 6035 case TemplateArgument::Type: 6036 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced, 6037 Depth, Used); 6038 break; 6039 6040 case TemplateArgument::Template: 6041 case TemplateArgument::TemplateExpansion: 6042 MarkUsedTemplateParameters(Ctx, 6043 TemplateArg.getAsTemplateOrTemplatePattern(), 6044 OnlyDeduced, Depth, Used); 6045 break; 6046 6047 case TemplateArgument::Expression: 6048 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced, 6049 Depth, Used); 6050 break; 6051 6052 case TemplateArgument::Pack: 6053 for (const auto &P : TemplateArg.pack_elements()) 6054 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used); 6055 break; 6056 } 6057 } 6058 6059 /// Mark which template parameters are used in a given expression. 6060 /// 6061 /// \param E the expression from which template parameters will be deduced. 6062 /// 6063 /// \param Used a bit vector whose elements will be set to \c true 6064 /// to indicate when the corresponding template parameter will be 6065 /// deduced. 6066 void 6067 Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, 6068 unsigned Depth, 6069 llvm::SmallBitVector &Used) { 6070 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used); 6071 } 6072 6073 /// Mark which template parameters can be deduced from a given 6074 /// template argument list. 6075 /// 6076 /// \param TemplateArgs the template argument list from which template 6077 /// parameters will be deduced. 6078 /// 6079 /// \param Used a bit vector whose elements will be set to \c true 6080 /// to indicate when the corresponding template parameter will be 6081 /// deduced. 6082 void 6083 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 6084 bool OnlyDeduced, unsigned Depth, 6085 llvm::SmallBitVector &Used) { 6086 // C++0x [temp.deduct.type]p9: 6087 // If the template argument list of P contains a pack expansion that is not 6088 // the last template argument, the entire template argument list is a 6089 // non-deduced context. 6090 if (OnlyDeduced && 6091 hasPackExpansionBeforeEnd(TemplateArgs.asArray())) 6092 return; 6093 6094 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 6095 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced, 6096 Depth, Used); 6097 } 6098 6099 /// Marks all of the template parameters that will be deduced by a 6100 /// call to the given function template. 6101 void Sema::MarkDeducedTemplateParameters( 6102 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, 6103 llvm::SmallBitVector &Deduced) { 6104 TemplateParameterList *TemplateParams 6105 = FunctionTemplate->getTemplateParameters(); 6106 Deduced.clear(); 6107 Deduced.resize(TemplateParams->size()); 6108 6109 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 6110 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) 6111 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(), 6112 true, TemplateParams->getDepth(), Deduced); 6113 } 6114 6115 bool hasDeducibleTemplateParameters(Sema &S, 6116 FunctionTemplateDecl *FunctionTemplate, 6117 QualType T) { 6118 if (!T->isDependentType()) 6119 return false; 6120 6121 TemplateParameterList *TemplateParams 6122 = FunctionTemplate->getTemplateParameters(); 6123 llvm::SmallBitVector Deduced(TemplateParams->size()); 6124 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(), 6125 Deduced); 6126 6127 return Deduced.any(); 6128 } 6129