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