1 //===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/ 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 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 "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/DeclTemplate.h" 19 #include "clang/AST/Expr.h" 20 #include "clang/AST/ExprCXX.h" 21 #include "clang/AST/StmtVisitor.h" 22 #include "clang/Sema/DeclSpec.h" 23 #include "clang/Sema/Sema.h" 24 #include "clang/Sema/Template.h" 25 #include "llvm/ADT/SmallBitVector.h" 26 #include <algorithm> 27 28 namespace clang { 29 using namespace sema; 30 /// \brief Various flags that control template argument deduction. 31 /// 32 /// These flags can be bitwise-OR'd together. 33 enum TemplateDeductionFlags { 34 /// \brief No template argument deduction flags, which indicates the 35 /// strictest results for template argument deduction (as used for, e.g., 36 /// matching class template partial specializations). 37 TDF_None = 0, 38 /// \brief Within template argument deduction from a function call, we are 39 /// matching with a parameter type for which the original parameter was 40 /// a reference. 41 TDF_ParamWithReferenceType = 0x1, 42 /// \brief Within template argument deduction from a function call, we 43 /// are matching in a case where we ignore cv-qualifiers. 44 TDF_IgnoreQualifiers = 0x02, 45 /// \brief Within template argument deduction from a function call, 46 /// we are matching in a case where we can perform template argument 47 /// deduction from a template-id of a derived class of the argument type. 48 TDF_DerivedClass = 0x04, 49 /// \brief Allow non-dependent types to differ, e.g., when performing 50 /// template argument deduction from a function call where conversions 51 /// may apply. 52 TDF_SkipNonDependent = 0x08, 53 /// \brief Whether we are performing template argument deduction for 54 /// parameters and arguments in a top-level template argument 55 TDF_TopLevelParameterTypeList = 0x10, 56 /// \brief Within template argument deduction from overload resolution per 57 /// C++ [over.over] allow matching function types that are compatible in 58 /// terms of noreturn and default calling convention adjustments. 59 TDF_InOverloadResolution = 0x20 60 }; 61 } 62 63 using namespace clang; 64 65 /// \brief Compare two APSInts, extending and switching the sign as 66 /// necessary to compare their values regardless of underlying type. 67 static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) { 68 if (Y.getBitWidth() > X.getBitWidth()) 69 X = X.extend(Y.getBitWidth()); 70 else if (Y.getBitWidth() < X.getBitWidth()) 71 Y = Y.extend(X.getBitWidth()); 72 73 // If there is a signedness mismatch, correct it. 74 if (X.isSigned() != Y.isSigned()) { 75 // If the signed value is negative, then the values cannot be the same. 76 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative())) 77 return false; 78 79 Y.setIsSigned(true); 80 X.setIsSigned(true); 81 } 82 83 return X == Y; 84 } 85 86 static Sema::TemplateDeductionResult 87 DeduceTemplateArguments(Sema &S, 88 TemplateParameterList *TemplateParams, 89 const TemplateArgument &Param, 90 TemplateArgument Arg, 91 TemplateDeductionInfo &Info, 92 SmallVectorImpl<DeducedTemplateArgument> &Deduced); 93 94 /// \brief Whether template argument deduction for two reference parameters 95 /// resulted in the argument type, parameter type, or neither type being more 96 /// qualified than the other. 97 enum DeductionQualifierComparison { 98 NeitherMoreQualified = 0, 99 ParamMoreQualified, 100 ArgMoreQualified 101 }; 102 103 /// \brief Stores the result of comparing two reference parameters while 104 /// performing template argument deduction for partial ordering of function 105 /// templates. 106 struct RefParamPartialOrderingComparison { 107 /// \brief Whether the parameter type is an rvalue reference type. 108 bool ParamIsRvalueRef; 109 /// \brief Whether the argument type is an rvalue reference type. 110 bool ArgIsRvalueRef; 111 112 /// \brief Whether the parameter or argument (or neither) is more qualified. 113 DeductionQualifierComparison Qualifiers; 114 }; 115 116 117 118 static Sema::TemplateDeductionResult 119 DeduceTemplateArgumentsByTypeMatch(Sema &S, 120 TemplateParameterList *TemplateParams, 121 QualType Param, 122 QualType Arg, 123 TemplateDeductionInfo &Info, 124 SmallVectorImpl<DeducedTemplateArgument> & 125 Deduced, 126 unsigned TDF, 127 bool PartialOrdering = false, 128 SmallVectorImpl<RefParamPartialOrderingComparison> * 129 RefParamComparisons = nullptr); 130 131 static Sema::TemplateDeductionResult 132 DeduceTemplateArguments(Sema &S, 133 TemplateParameterList *TemplateParams, 134 const TemplateArgument *Params, unsigned NumParams, 135 const TemplateArgument *Args, unsigned NumArgs, 136 TemplateDeductionInfo &Info, 137 SmallVectorImpl<DeducedTemplateArgument> &Deduced); 138 139 /// \brief If the given expression is of a form that permits the deduction 140 /// of a non-type template parameter, return the declaration of that 141 /// non-type template parameter. 142 static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) { 143 // If we are within an alias template, the expression may have undergone 144 // any number of parameter substitutions already. 145 while (1) { 146 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E)) 147 E = IC->getSubExpr(); 148 else if (SubstNonTypeTemplateParmExpr *Subst = 149 dyn_cast<SubstNonTypeTemplateParmExpr>(E)) 150 E = Subst->getReplacement(); 151 else 152 break; 153 } 154 155 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 156 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 157 158 return nullptr; 159 } 160 161 /// \brief Determine whether two declaration pointers refer to the same 162 /// declaration. 163 static bool isSameDeclaration(Decl *X, Decl *Y) { 164 if (NamedDecl *NX = dyn_cast<NamedDecl>(X)) 165 X = NX->getUnderlyingDecl(); 166 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y)) 167 Y = NY->getUnderlyingDecl(); 168 169 return X->getCanonicalDecl() == Y->getCanonicalDecl(); 170 } 171 172 /// \brief Verify that the given, deduced template arguments are compatible. 173 /// 174 /// \returns The deduced template argument, or a NULL template argument if 175 /// the deduced template arguments were incompatible. 176 static DeducedTemplateArgument 177 checkDeducedTemplateArguments(ASTContext &Context, 178 const DeducedTemplateArgument &X, 179 const DeducedTemplateArgument &Y) { 180 // We have no deduction for one or both of the arguments; they're compatible. 181 if (X.isNull()) 182 return Y; 183 if (Y.isNull()) 184 return X; 185 186 switch (X.getKind()) { 187 case TemplateArgument::Null: 188 llvm_unreachable("Non-deduced template arguments handled above"); 189 190 case TemplateArgument::Type: 191 // If two template type arguments have the same type, they're compatible. 192 if (Y.getKind() == TemplateArgument::Type && 193 Context.hasSameType(X.getAsType(), Y.getAsType())) 194 return X; 195 196 return DeducedTemplateArgument(); 197 198 case TemplateArgument::Integral: 199 // If we deduced a constant in one case and either a dependent expression or 200 // declaration in another case, keep the integral constant. 201 // If both are integral constants with the same value, keep that value. 202 if (Y.getKind() == TemplateArgument::Expression || 203 Y.getKind() == TemplateArgument::Declaration || 204 (Y.getKind() == TemplateArgument::Integral && 205 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral()))) 206 return DeducedTemplateArgument(X, 207 X.wasDeducedFromArrayBound() && 208 Y.wasDeducedFromArrayBound()); 209 210 // All other combinations are incompatible. 211 return DeducedTemplateArgument(); 212 213 case TemplateArgument::Template: 214 if (Y.getKind() == TemplateArgument::Template && 215 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate())) 216 return X; 217 218 // All other combinations are incompatible. 219 return DeducedTemplateArgument(); 220 221 case TemplateArgument::TemplateExpansion: 222 if (Y.getKind() == TemplateArgument::TemplateExpansion && 223 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(), 224 Y.getAsTemplateOrTemplatePattern())) 225 return X; 226 227 // All other combinations are incompatible. 228 return DeducedTemplateArgument(); 229 230 case TemplateArgument::Expression: 231 // If we deduced a dependent expression in one case and either an integral 232 // constant or a declaration in another case, keep the integral constant 233 // or declaration. 234 if (Y.getKind() == TemplateArgument::Integral || 235 Y.getKind() == TemplateArgument::Declaration) 236 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() && 237 Y.wasDeducedFromArrayBound()); 238 239 if (Y.getKind() == TemplateArgument::Expression) { 240 // Compare the expressions for equality 241 llvm::FoldingSetNodeID ID1, ID2; 242 X.getAsExpr()->Profile(ID1, Context, true); 243 Y.getAsExpr()->Profile(ID2, Context, true); 244 if (ID1 == ID2) 245 return X; 246 } 247 248 // All other combinations are incompatible. 249 return DeducedTemplateArgument(); 250 251 case TemplateArgument::Declaration: 252 // If we deduced a declaration and a dependent expression, keep the 253 // declaration. 254 if (Y.getKind() == TemplateArgument::Expression) 255 return X; 256 257 // If we deduced a declaration and an integral constant, keep the 258 // integral constant. 259 if (Y.getKind() == TemplateArgument::Integral) 260 return Y; 261 262 // If we deduced two declarations, make sure they they refer to the 263 // same declaration. 264 if (Y.getKind() == TemplateArgument::Declaration && 265 isSameDeclaration(X.getAsDecl(), Y.getAsDecl())) 266 return X; 267 268 // All other combinations are incompatible. 269 return DeducedTemplateArgument(); 270 271 case TemplateArgument::NullPtr: 272 // If we deduced a null pointer and a dependent expression, keep the 273 // null pointer. 274 if (Y.getKind() == TemplateArgument::Expression) 275 return X; 276 277 // If we deduced a null pointer and an integral constant, keep the 278 // integral constant. 279 if (Y.getKind() == TemplateArgument::Integral) 280 return Y; 281 282 // If we deduced two null pointers, make sure they have the same type. 283 if (Y.getKind() == TemplateArgument::NullPtr && 284 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType())) 285 return X; 286 287 // All other combinations are incompatible. 288 return DeducedTemplateArgument(); 289 290 case TemplateArgument::Pack: 291 if (Y.getKind() != TemplateArgument::Pack || 292 X.pack_size() != Y.pack_size()) 293 return DeducedTemplateArgument(); 294 295 for (TemplateArgument::pack_iterator XA = X.pack_begin(), 296 XAEnd = X.pack_end(), 297 YA = Y.pack_begin(); 298 XA != XAEnd; ++XA, ++YA) { 299 // FIXME: Do we need to merge the results together here? 300 if (checkDeducedTemplateArguments(Context, 301 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()), 302 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound())) 303 .isNull()) 304 return DeducedTemplateArgument(); 305 } 306 307 return X; 308 } 309 310 llvm_unreachable("Invalid TemplateArgument Kind!"); 311 } 312 313 /// \brief Deduce the value of the given non-type template parameter 314 /// from the given constant. 315 static Sema::TemplateDeductionResult 316 DeduceNonTypeTemplateArgument(Sema &S, 317 NonTypeTemplateParmDecl *NTTP, 318 llvm::APSInt Value, QualType ValueType, 319 bool DeducedFromArrayBound, 320 TemplateDeductionInfo &Info, 321 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 322 assert(NTTP->getDepth() == 0 && 323 "Cannot deduce non-type template argument with depth > 0"); 324 325 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType, 326 DeducedFromArrayBound); 327 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 328 Deduced[NTTP->getIndex()], 329 NewDeduced); 330 if (Result.isNull()) { 331 Info.Param = NTTP; 332 Info.FirstArg = Deduced[NTTP->getIndex()]; 333 Info.SecondArg = NewDeduced; 334 return Sema::TDK_Inconsistent; 335 } 336 337 Deduced[NTTP->getIndex()] = Result; 338 return Sema::TDK_Success; 339 } 340 341 /// \brief Deduce the value of the given non-type template parameter 342 /// from the given type- or value-dependent expression. 343 /// 344 /// \returns true if deduction succeeded, false otherwise. 345 static Sema::TemplateDeductionResult 346 DeduceNonTypeTemplateArgument(Sema &S, 347 NonTypeTemplateParmDecl *NTTP, 348 Expr *Value, 349 TemplateDeductionInfo &Info, 350 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 351 assert(NTTP->getDepth() == 0 && 352 "Cannot deduce non-type template argument with depth > 0"); 353 assert((Value->isTypeDependent() || Value->isValueDependent()) && 354 "Expression template argument must be type- or value-dependent."); 355 356 DeducedTemplateArgument NewDeduced(Value); 357 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 358 Deduced[NTTP->getIndex()], 359 NewDeduced); 360 361 if (Result.isNull()) { 362 Info.Param = NTTP; 363 Info.FirstArg = Deduced[NTTP->getIndex()]; 364 Info.SecondArg = NewDeduced; 365 return Sema::TDK_Inconsistent; 366 } 367 368 Deduced[NTTP->getIndex()] = Result; 369 return Sema::TDK_Success; 370 } 371 372 /// \brief Deduce the value of the given non-type template parameter 373 /// from the given declaration. 374 /// 375 /// \returns true if deduction succeeded, false otherwise. 376 static Sema::TemplateDeductionResult 377 DeduceNonTypeTemplateArgument(Sema &S, 378 NonTypeTemplateParmDecl *NTTP, 379 ValueDecl *D, 380 TemplateDeductionInfo &Info, 381 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 382 assert(NTTP->getDepth() == 0 && 383 "Cannot deduce non-type template argument with depth > 0"); 384 385 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr; 386 TemplateArgument New(D, NTTP->getType()); 387 DeducedTemplateArgument NewDeduced(New); 388 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 389 Deduced[NTTP->getIndex()], 390 NewDeduced); 391 if (Result.isNull()) { 392 Info.Param = NTTP; 393 Info.FirstArg = Deduced[NTTP->getIndex()]; 394 Info.SecondArg = NewDeduced; 395 return Sema::TDK_Inconsistent; 396 } 397 398 Deduced[NTTP->getIndex()] = Result; 399 return Sema::TDK_Success; 400 } 401 402 static Sema::TemplateDeductionResult 403 DeduceTemplateArguments(Sema &S, 404 TemplateParameterList *TemplateParams, 405 TemplateName Param, 406 TemplateName Arg, 407 TemplateDeductionInfo &Info, 408 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 409 TemplateDecl *ParamDecl = Param.getAsTemplateDecl(); 410 if (!ParamDecl) { 411 // The parameter type is dependent and is not a template template parameter, 412 // so there is nothing that we can deduce. 413 return Sema::TDK_Success; 414 } 415 416 if (TemplateTemplateParmDecl *TempParam 417 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) { 418 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg)); 419 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 420 Deduced[TempParam->getIndex()], 421 NewDeduced); 422 if (Result.isNull()) { 423 Info.Param = TempParam; 424 Info.FirstArg = Deduced[TempParam->getIndex()]; 425 Info.SecondArg = NewDeduced; 426 return Sema::TDK_Inconsistent; 427 } 428 429 Deduced[TempParam->getIndex()] = Result; 430 return Sema::TDK_Success; 431 } 432 433 // Verify that the two template names are equivalent. 434 if (S.Context.hasSameTemplateName(Param, Arg)) 435 return Sema::TDK_Success; 436 437 // Mismatch of non-dependent template parameter to argument. 438 Info.FirstArg = TemplateArgument(Param); 439 Info.SecondArg = TemplateArgument(Arg); 440 return Sema::TDK_NonDeducedMismatch; 441 } 442 443 /// \brief Deduce the template arguments by comparing the template parameter 444 /// type (which is a template-id) with the template argument type. 445 /// 446 /// \param S the Sema 447 /// 448 /// \param TemplateParams the template parameters that we are deducing 449 /// 450 /// \param Param the parameter type 451 /// 452 /// \param Arg the argument type 453 /// 454 /// \param Info information about the template argument deduction itself 455 /// 456 /// \param Deduced the deduced template arguments 457 /// 458 /// \returns the result of template argument deduction so far. Note that a 459 /// "success" result means that template argument deduction has not yet failed, 460 /// but it may still fail, later, for other reasons. 461 static Sema::TemplateDeductionResult 462 DeduceTemplateArguments(Sema &S, 463 TemplateParameterList *TemplateParams, 464 const TemplateSpecializationType *Param, 465 QualType Arg, 466 TemplateDeductionInfo &Info, 467 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 468 assert(Arg.isCanonical() && "Argument type must be canonical"); 469 470 // Check whether the template argument is a dependent template-id. 471 if (const TemplateSpecializationType *SpecArg 472 = dyn_cast<TemplateSpecializationType>(Arg)) { 473 // Perform template argument deduction for the template name. 474 if (Sema::TemplateDeductionResult Result 475 = DeduceTemplateArguments(S, TemplateParams, 476 Param->getTemplateName(), 477 SpecArg->getTemplateName(), 478 Info, Deduced)) 479 return Result; 480 481 482 // Perform template argument deduction on each template 483 // argument. Ignore any missing/extra arguments, since they could be 484 // filled in by default arguments. 485 return DeduceTemplateArguments(S, TemplateParams, 486 Param->getArgs(), Param->getNumArgs(), 487 SpecArg->getArgs(), SpecArg->getNumArgs(), 488 Info, Deduced); 489 } 490 491 // If the argument type is a class template specialization, we 492 // perform template argument deduction using its template 493 // arguments. 494 const RecordType *RecordArg = dyn_cast<RecordType>(Arg); 495 if (!RecordArg) { 496 Info.FirstArg = TemplateArgument(QualType(Param, 0)); 497 Info.SecondArg = TemplateArgument(Arg); 498 return Sema::TDK_NonDeducedMismatch; 499 } 500 501 ClassTemplateSpecializationDecl *SpecArg 502 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl()); 503 if (!SpecArg) { 504 Info.FirstArg = TemplateArgument(QualType(Param, 0)); 505 Info.SecondArg = TemplateArgument(Arg); 506 return Sema::TDK_NonDeducedMismatch; 507 } 508 509 // Perform template argument deduction for the template name. 510 if (Sema::TemplateDeductionResult Result 511 = DeduceTemplateArguments(S, 512 TemplateParams, 513 Param->getTemplateName(), 514 TemplateName(SpecArg->getSpecializedTemplate()), 515 Info, Deduced)) 516 return Result; 517 518 // Perform template argument deduction for the template arguments. 519 return DeduceTemplateArguments(S, TemplateParams, 520 Param->getArgs(), Param->getNumArgs(), 521 SpecArg->getTemplateArgs().data(), 522 SpecArg->getTemplateArgs().size(), 523 Info, Deduced); 524 } 525 526 /// \brief Determines whether the given type is an opaque type that 527 /// might be more qualified when instantiated. 528 static bool IsPossiblyOpaquelyQualifiedType(QualType T) { 529 switch (T->getTypeClass()) { 530 case Type::TypeOfExpr: 531 case Type::TypeOf: 532 case Type::DependentName: 533 case Type::Decltype: 534 case Type::UnresolvedUsing: 535 case Type::TemplateTypeParm: 536 return true; 537 538 case Type::ConstantArray: 539 case Type::IncompleteArray: 540 case Type::VariableArray: 541 case Type::DependentSizedArray: 542 return IsPossiblyOpaquelyQualifiedType( 543 cast<ArrayType>(T)->getElementType()); 544 545 default: 546 return false; 547 } 548 } 549 550 /// \brief Retrieve the depth and index of a template parameter. 551 static std::pair<unsigned, unsigned> 552 getDepthAndIndex(NamedDecl *ND) { 553 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND)) 554 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 555 556 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND)) 557 return std::make_pair(NTTP->getDepth(), NTTP->getIndex()); 558 559 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND); 560 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 561 } 562 563 /// \brief Retrieve the depth and index of an unexpanded parameter pack. 564 static std::pair<unsigned, unsigned> 565 getDepthAndIndex(UnexpandedParameterPack UPP) { 566 if (const TemplateTypeParmType *TTP 567 = UPP.first.dyn_cast<const TemplateTypeParmType *>()) 568 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 569 570 return getDepthAndIndex(UPP.first.get<NamedDecl *>()); 571 } 572 573 /// \brief Helper function to build a TemplateParameter when we don't 574 /// know its type statically. 575 static TemplateParameter makeTemplateParameter(Decl *D) { 576 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D)) 577 return TemplateParameter(TTP); 578 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) 579 return TemplateParameter(NTTP); 580 581 return TemplateParameter(cast<TemplateTemplateParmDecl>(D)); 582 } 583 584 /// A pack that we're currently deducing. 585 struct clang::DeducedPack { 586 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {} 587 588 // The index of the pack. 589 unsigned Index; 590 591 // The old value of the pack before we started deducing it. 592 DeducedTemplateArgument Saved; 593 594 // A deferred value of this pack from an inner deduction, that couldn't be 595 // deduced because this deduction hadn't happened yet. 596 DeducedTemplateArgument DeferredDeduction; 597 598 // The new value of the pack. 599 SmallVector<DeducedTemplateArgument, 4> New; 600 601 // The outer deduction for this pack, if any. 602 DeducedPack *Outer; 603 }; 604 605 /// A scope in which we're performing pack deduction. 606 class PackDeductionScope { 607 public: 608 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams, 609 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 610 TemplateDeductionInfo &Info, TemplateArgument Pattern) 611 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) { 612 // Compute the set of template parameter indices that correspond to 613 // parameter packs expanded by the pack expansion. 614 { 615 llvm::SmallBitVector SawIndices(TemplateParams->size()); 616 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 617 S.collectUnexpandedParameterPacks(Pattern, Unexpanded); 618 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 619 unsigned Depth, Index; 620 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]); 621 if (Depth == 0 && !SawIndices[Index]) { 622 SawIndices[Index] = true; 623 624 // Save the deduced template argument for the parameter pack expanded 625 // by this pack expansion, then clear out the deduction. 626 DeducedPack Pack(Index); 627 Pack.Saved = Deduced[Index]; 628 Deduced[Index] = TemplateArgument(); 629 630 Packs.push_back(Pack); 631 } 632 } 633 } 634 assert(!Packs.empty() && "Pack expansion without unexpanded packs?"); 635 636 for (auto &Pack : Packs) { 637 if (Info.PendingDeducedPacks.size() > Pack.Index) 638 Pack.Outer = Info.PendingDeducedPacks[Pack.Index]; 639 else 640 Info.PendingDeducedPacks.resize(Pack.Index + 1); 641 Info.PendingDeducedPacks[Pack.Index] = &Pack; 642 643 if (S.CurrentInstantiationScope) { 644 // If the template argument pack was explicitly specified, add that to 645 // the set of deduced arguments. 646 const TemplateArgument *ExplicitArgs; 647 unsigned NumExplicitArgs; 648 NamedDecl *PartiallySubstitutedPack = 649 S.CurrentInstantiationScope->getPartiallySubstitutedPack( 650 &ExplicitArgs, &NumExplicitArgs); 651 if (PartiallySubstitutedPack && 652 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index) 653 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs); 654 } 655 } 656 } 657 658 ~PackDeductionScope() { 659 for (auto &Pack : Packs) 660 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer; 661 } 662 663 /// Move to deducing the next element in each pack that is being deduced. 664 void nextPackElement() { 665 // Capture the deduced template arguments for each parameter pack expanded 666 // by this pack expansion, add them to the list of arguments we've deduced 667 // for that pack, then clear out the deduced argument. 668 for (auto &Pack : Packs) { 669 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index]; 670 if (!DeducedArg.isNull()) { 671 Pack.New.push_back(DeducedArg); 672 DeducedArg = DeducedTemplateArgument(); 673 } 674 } 675 } 676 677 /// \brief Finish template argument deduction for a set of argument packs, 678 /// producing the argument packs and checking for consistency with prior 679 /// deductions. 680 Sema::TemplateDeductionResult finish(bool HasAnyArguments) { 681 // Build argument packs for each of the parameter packs expanded by this 682 // pack expansion. 683 for (auto &Pack : Packs) { 684 // Put back the old value for this pack. 685 Deduced[Pack.Index] = Pack.Saved; 686 687 // Build or find a new value for this pack. 688 DeducedTemplateArgument NewPack; 689 if (HasAnyArguments && Pack.New.empty()) { 690 if (Pack.DeferredDeduction.isNull()) { 691 // We were not able to deduce anything for this parameter pack 692 // (because it only appeared in non-deduced contexts), so just 693 // restore the saved argument pack. 694 continue; 695 } 696 697 NewPack = Pack.DeferredDeduction; 698 Pack.DeferredDeduction = TemplateArgument(); 699 } else if (Pack.New.empty()) { 700 // If we deduced an empty argument pack, create it now. 701 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack()); 702 } else { 703 TemplateArgument *ArgumentPack = 704 new (S.Context) TemplateArgument[Pack.New.size()]; 705 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack); 706 NewPack = DeducedTemplateArgument( 707 TemplateArgument(ArgumentPack, Pack.New.size()), 708 Pack.New[0].wasDeducedFromArrayBound()); 709 } 710 711 // Pick where we're going to put the merged pack. 712 DeducedTemplateArgument *Loc; 713 if (Pack.Outer) { 714 if (Pack.Outer->DeferredDeduction.isNull()) { 715 // Defer checking this pack until we have a complete pack to compare 716 // it against. 717 Pack.Outer->DeferredDeduction = NewPack; 718 continue; 719 } 720 Loc = &Pack.Outer->DeferredDeduction; 721 } else { 722 Loc = &Deduced[Pack.Index]; 723 } 724 725 // Check the new pack matches any previous value. 726 DeducedTemplateArgument OldPack = *Loc; 727 DeducedTemplateArgument Result = 728 checkDeducedTemplateArguments(S.Context, OldPack, NewPack); 729 730 // If we deferred a deduction of this pack, check that one now too. 731 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) { 732 OldPack = Result; 733 NewPack = Pack.DeferredDeduction; 734 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack); 735 } 736 737 if (Result.isNull()) { 738 Info.Param = 739 makeTemplateParameter(TemplateParams->getParam(Pack.Index)); 740 Info.FirstArg = OldPack; 741 Info.SecondArg = NewPack; 742 return Sema::TDK_Inconsistent; 743 } 744 745 *Loc = Result; 746 } 747 748 return Sema::TDK_Success; 749 } 750 751 private: 752 Sema &S; 753 TemplateParameterList *TemplateParams; 754 SmallVectorImpl<DeducedTemplateArgument> &Deduced; 755 TemplateDeductionInfo &Info; 756 757 SmallVector<DeducedPack, 2> Packs; 758 }; 759 760 /// \brief Deduce the template arguments by comparing the list of parameter 761 /// types to the list of argument types, as in the parameter-type-lists of 762 /// function types (C++ [temp.deduct.type]p10). 763 /// 764 /// \param S The semantic analysis object within which we are deducing 765 /// 766 /// \param TemplateParams The template parameters that we are deducing 767 /// 768 /// \param Params The list of parameter types 769 /// 770 /// \param NumParams The number of types in \c Params 771 /// 772 /// \param Args The list of argument types 773 /// 774 /// \param NumArgs The number of types in \c Args 775 /// 776 /// \param Info information about the template argument deduction itself 777 /// 778 /// \param Deduced the deduced template arguments 779 /// 780 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 781 /// how template argument deduction is performed. 782 /// 783 /// \param PartialOrdering If true, we are performing template argument 784 /// deduction for during partial ordering for a call 785 /// (C++0x [temp.deduct.partial]). 786 /// 787 /// \param RefParamComparisons If we're performing template argument deduction 788 /// in the context of partial ordering, the set of qualifier comparisons. 789 /// 790 /// \returns the result of template argument deduction so far. Note that a 791 /// "success" result means that template argument deduction has not yet failed, 792 /// but it may still fail, later, for other reasons. 793 static Sema::TemplateDeductionResult 794 DeduceTemplateArguments(Sema &S, 795 TemplateParameterList *TemplateParams, 796 const QualType *Params, unsigned NumParams, 797 const QualType *Args, unsigned NumArgs, 798 TemplateDeductionInfo &Info, 799 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 800 unsigned TDF, 801 bool PartialOrdering = false, 802 SmallVectorImpl<RefParamPartialOrderingComparison> * 803 RefParamComparisons = nullptr) { 804 // Fast-path check to see if we have too many/too few arguments. 805 if (NumParams != NumArgs && 806 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) && 807 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1]))) 808 return Sema::TDK_MiscellaneousDeductionFailure; 809 810 // C++0x [temp.deduct.type]p10: 811 // Similarly, if P has a form that contains (T), then each parameter type 812 // Pi of the respective parameter-type- list of P is compared with the 813 // corresponding parameter type Ai of the corresponding parameter-type-list 814 // of A. [...] 815 unsigned ArgIdx = 0, ParamIdx = 0; 816 for (; ParamIdx != NumParams; ++ParamIdx) { 817 // Check argument types. 818 const PackExpansionType *Expansion 819 = dyn_cast<PackExpansionType>(Params[ParamIdx]); 820 if (!Expansion) { 821 // Simple case: compare the parameter and argument types at this point. 822 823 // Make sure we have an argument. 824 if (ArgIdx >= NumArgs) 825 return Sema::TDK_MiscellaneousDeductionFailure; 826 827 if (isa<PackExpansionType>(Args[ArgIdx])) { 828 // C++0x [temp.deduct.type]p22: 829 // If the original function parameter associated with A is a function 830 // parameter pack and the function parameter associated with P is not 831 // a function parameter pack, then template argument deduction fails. 832 return Sema::TDK_MiscellaneousDeductionFailure; 833 } 834 835 if (Sema::TemplateDeductionResult Result 836 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 837 Params[ParamIdx], Args[ArgIdx], 838 Info, Deduced, TDF, 839 PartialOrdering, 840 RefParamComparisons)) 841 return Result; 842 843 ++ArgIdx; 844 continue; 845 } 846 847 // C++0x [temp.deduct.type]p5: 848 // The non-deduced contexts are: 849 // - A function parameter pack that does not occur at the end of the 850 // parameter-declaration-clause. 851 if (ParamIdx + 1 < NumParams) 852 return Sema::TDK_Success; 853 854 // C++0x [temp.deduct.type]p10: 855 // If the parameter-declaration corresponding to Pi is a function 856 // parameter pack, then the type of its declarator- id is compared with 857 // each remaining parameter type in the parameter-type-list of A. Each 858 // comparison deduces template arguments for subsequent positions in the 859 // template parameter packs expanded by the function parameter pack. 860 861 QualType Pattern = Expansion->getPattern(); 862 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern); 863 864 bool HasAnyArguments = false; 865 for (; ArgIdx < NumArgs; ++ArgIdx) { 866 HasAnyArguments = true; 867 868 // Deduce template arguments from the pattern. 869 if (Sema::TemplateDeductionResult Result 870 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern, 871 Args[ArgIdx], Info, Deduced, 872 TDF, PartialOrdering, 873 RefParamComparisons)) 874 return Result; 875 876 PackScope.nextPackElement(); 877 } 878 879 // Build argument packs for each of the parameter packs expanded by this 880 // pack expansion. 881 if (auto Result = PackScope.finish(HasAnyArguments)) 882 return Result; 883 } 884 885 // Make sure we don't have any extra arguments. 886 if (ArgIdx < NumArgs) 887 return Sema::TDK_MiscellaneousDeductionFailure; 888 889 return Sema::TDK_Success; 890 } 891 892 /// \brief Determine whether the parameter has qualifiers that are either 893 /// inconsistent with or a superset of the argument's qualifiers. 894 static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, 895 QualType ArgType) { 896 Qualifiers ParamQs = ParamType.getQualifiers(); 897 Qualifiers ArgQs = ArgType.getQualifiers(); 898 899 if (ParamQs == ArgQs) 900 return false; 901 902 // Mismatched (but not missing) Objective-C GC attributes. 903 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() && 904 ParamQs.hasObjCGCAttr()) 905 return true; 906 907 // Mismatched (but not missing) address spaces. 908 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() && 909 ParamQs.hasAddressSpace()) 910 return true; 911 912 // Mismatched (but not missing) Objective-C lifetime qualifiers. 913 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() && 914 ParamQs.hasObjCLifetime()) 915 return true; 916 917 // CVR qualifier superset. 918 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) && 919 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers()) 920 == ParamQs.getCVRQualifiers()); 921 } 922 923 /// \brief Compare types for equality with respect to possibly compatible 924 /// function types (noreturn adjustment, implicit calling conventions). If any 925 /// of parameter and argument is not a function, just perform type comparison. 926 /// 927 /// \param Param the template parameter type. 928 /// 929 /// \param Arg the argument type. 930 bool Sema::isSameOrCompatibleFunctionType(CanQualType Param, 931 CanQualType Arg) { 932 const FunctionType *ParamFunction = Param->getAs<FunctionType>(), 933 *ArgFunction = Arg->getAs<FunctionType>(); 934 935 // Just compare if not functions. 936 if (!ParamFunction || !ArgFunction) 937 return Param == Arg; 938 939 // Noreturn adjustment. 940 QualType AdjustedParam; 941 if (IsNoReturnConversion(Param, Arg, AdjustedParam)) 942 return Arg == Context.getCanonicalType(AdjustedParam); 943 944 // FIXME: Compatible calling conventions. 945 946 return Param == Arg; 947 } 948 949 /// \brief Deduce the template arguments by comparing the parameter type and 950 /// the argument type (C++ [temp.deduct.type]). 951 /// 952 /// \param S the semantic analysis object within which we are deducing 953 /// 954 /// \param TemplateParams the template parameters that we are deducing 955 /// 956 /// \param ParamIn the parameter type 957 /// 958 /// \param ArgIn the argument type 959 /// 960 /// \param Info information about the template argument deduction itself 961 /// 962 /// \param Deduced the deduced template arguments 963 /// 964 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 965 /// how template argument deduction is performed. 966 /// 967 /// \param PartialOrdering Whether we're performing template argument deduction 968 /// in the context of partial ordering (C++0x [temp.deduct.partial]). 969 /// 970 /// \param RefParamComparisons If we're performing template argument deduction 971 /// in the context of partial ordering, the set of qualifier comparisons. 972 /// 973 /// \returns the result of template argument deduction so far. Note that a 974 /// "success" result means that template argument deduction has not yet failed, 975 /// but it may still fail, later, for other reasons. 976 static Sema::TemplateDeductionResult 977 DeduceTemplateArgumentsByTypeMatch(Sema &S, 978 TemplateParameterList *TemplateParams, 979 QualType ParamIn, QualType ArgIn, 980 TemplateDeductionInfo &Info, 981 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 982 unsigned TDF, 983 bool PartialOrdering, 984 SmallVectorImpl<RefParamPartialOrderingComparison> * 985 RefParamComparisons) { 986 // We only want to look at the canonical types, since typedefs and 987 // sugar are not part of template argument deduction. 988 QualType Param = S.Context.getCanonicalType(ParamIn); 989 QualType Arg = S.Context.getCanonicalType(ArgIn); 990 991 // If the argument type is a pack expansion, look at its pattern. 992 // This isn't explicitly called out 993 if (const PackExpansionType *ArgExpansion 994 = dyn_cast<PackExpansionType>(Arg)) 995 Arg = ArgExpansion->getPattern(); 996 997 if (PartialOrdering) { 998 // C++0x [temp.deduct.partial]p5: 999 // Before the partial ordering is done, certain transformations are 1000 // performed on the types used for partial ordering: 1001 // - If P is a reference type, P is replaced by the type referred to. 1002 const ReferenceType *ParamRef = Param->getAs<ReferenceType>(); 1003 if (ParamRef) 1004 Param = ParamRef->getPointeeType(); 1005 1006 // - If A is a reference type, A is replaced by the type referred to. 1007 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>(); 1008 if (ArgRef) 1009 Arg = ArgRef->getPointeeType(); 1010 1011 if (RefParamComparisons && ParamRef && ArgRef) { 1012 // C++0x [temp.deduct.partial]p6: 1013 // If both P and A were reference types (before being replaced with the 1014 // type referred to above), determine which of the two types (if any) is 1015 // more cv-qualified than the other; otherwise the types are considered 1016 // to be equally cv-qualified for partial ordering purposes. The result 1017 // of this determination will be used below. 1018 // 1019 // We save this information for later, using it only when deduction 1020 // succeeds in both directions. 1021 RefParamPartialOrderingComparison Comparison; 1022 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>(); 1023 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>(); 1024 Comparison.Qualifiers = NeitherMoreQualified; 1025 1026 Qualifiers ParamQuals = Param.getQualifiers(); 1027 Qualifiers ArgQuals = Arg.getQualifiers(); 1028 if (ParamQuals.isStrictSupersetOf(ArgQuals)) 1029 Comparison.Qualifiers = ParamMoreQualified; 1030 else if (ArgQuals.isStrictSupersetOf(ParamQuals)) 1031 Comparison.Qualifiers = ArgMoreQualified; 1032 else if (ArgQuals.getObjCLifetime() != ParamQuals.getObjCLifetime() && 1033 ArgQuals.withoutObjCLifetime() 1034 == ParamQuals.withoutObjCLifetime()) { 1035 // Prefer binding to non-__unsafe_autoretained parameters. 1036 if (ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone && 1037 ParamQuals.getObjCLifetime()) 1038 Comparison.Qualifiers = ParamMoreQualified; 1039 else if (ParamQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone && 1040 ArgQuals.getObjCLifetime()) 1041 Comparison.Qualifiers = ArgMoreQualified; 1042 } 1043 RefParamComparisons->push_back(Comparison); 1044 } 1045 1046 // C++0x [temp.deduct.partial]p7: 1047 // Remove any top-level cv-qualifiers: 1048 // - If P is a cv-qualified type, P is replaced by the cv-unqualified 1049 // version of P. 1050 Param = Param.getUnqualifiedType(); 1051 // - If A is a cv-qualified type, A is replaced by the cv-unqualified 1052 // version of A. 1053 Arg = Arg.getUnqualifiedType(); 1054 } else { 1055 // C++0x [temp.deduct.call]p4 bullet 1: 1056 // - If the original P is a reference type, the deduced A (i.e., the type 1057 // referred to by the reference) can be more cv-qualified than the 1058 // transformed A. 1059 if (TDF & TDF_ParamWithReferenceType) { 1060 Qualifiers Quals; 1061 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals); 1062 Quals.setCVRQualifiers(Quals.getCVRQualifiers() & 1063 Arg.getCVRQualifiers()); 1064 Param = S.Context.getQualifiedType(UnqualParam, Quals); 1065 } 1066 1067 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) { 1068 // C++0x [temp.deduct.type]p10: 1069 // If P and A are function types that originated from deduction when 1070 // taking the address of a function template (14.8.2.2) or when deducing 1071 // template arguments from a function declaration (14.8.2.6) and Pi and 1072 // Ai are parameters of the top-level parameter-type-list of P and A, 1073 // respectively, Pi is adjusted if it is an rvalue reference to a 1074 // cv-unqualified template parameter and Ai is an lvalue reference, in 1075 // which case the type of Pi is changed to be the template parameter 1076 // type (i.e., T&& is changed to simply T). [ Note: As a result, when 1077 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be 1078 // deduced as X&. - end note ] 1079 TDF &= ~TDF_TopLevelParameterTypeList; 1080 1081 if (const RValueReferenceType *ParamRef 1082 = Param->getAs<RValueReferenceType>()) { 1083 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) && 1084 !ParamRef->getPointeeType().getQualifiers()) 1085 if (Arg->isLValueReferenceType()) 1086 Param = ParamRef->getPointeeType(); 1087 } 1088 } 1089 } 1090 1091 // C++ [temp.deduct.type]p9: 1092 // A template type argument T, a template template argument TT or a 1093 // template non-type argument i can be deduced if P and A have one of 1094 // the following forms: 1095 // 1096 // T 1097 // cv-list T 1098 if (const TemplateTypeParmType *TemplateTypeParm 1099 = Param->getAs<TemplateTypeParmType>()) { 1100 // Just skip any attempts to deduce from a placeholder type. 1101 if (Arg->isPlaceholderType()) 1102 return Sema::TDK_Success; 1103 1104 unsigned Index = TemplateTypeParm->getIndex(); 1105 bool RecanonicalizeArg = false; 1106 1107 // If the argument type is an array type, move the qualifiers up to the 1108 // top level, so they can be matched with the qualifiers on the parameter. 1109 if (isa<ArrayType>(Arg)) { 1110 Qualifiers Quals; 1111 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals); 1112 if (Quals) { 1113 Arg = S.Context.getQualifiedType(Arg, Quals); 1114 RecanonicalizeArg = true; 1115 } 1116 } 1117 1118 // The argument type can not be less qualified than the parameter 1119 // type. 1120 if (!(TDF & TDF_IgnoreQualifiers) && 1121 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) { 1122 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1123 Info.FirstArg = TemplateArgument(Param); 1124 Info.SecondArg = TemplateArgument(Arg); 1125 return Sema::TDK_Underqualified; 1126 } 1127 1128 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0"); 1129 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function"); 1130 QualType DeducedType = Arg; 1131 1132 // Remove any qualifiers on the parameter from the deduced type. 1133 // We checked the qualifiers for consistency above. 1134 Qualifiers DeducedQs = DeducedType.getQualifiers(); 1135 Qualifiers ParamQs = Param.getQualifiers(); 1136 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers()); 1137 if (ParamQs.hasObjCGCAttr()) 1138 DeducedQs.removeObjCGCAttr(); 1139 if (ParamQs.hasAddressSpace()) 1140 DeducedQs.removeAddressSpace(); 1141 if (ParamQs.hasObjCLifetime()) 1142 DeducedQs.removeObjCLifetime(); 1143 1144 // Objective-C ARC: 1145 // If template deduction would produce a lifetime qualifier on a type 1146 // that is not a lifetime type, template argument deduction fails. 1147 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() && 1148 !DeducedType->isDependentType()) { 1149 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1150 Info.FirstArg = TemplateArgument(Param); 1151 Info.SecondArg = TemplateArgument(Arg); 1152 return Sema::TDK_Underqualified; 1153 } 1154 1155 // Objective-C ARC: 1156 // If template deduction would produce an argument type with lifetime type 1157 // but no lifetime qualifier, the __strong lifetime qualifier is inferred. 1158 if (S.getLangOpts().ObjCAutoRefCount && 1159 DeducedType->isObjCLifetimeType() && 1160 !DeducedQs.hasObjCLifetime()) 1161 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong); 1162 1163 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), 1164 DeducedQs); 1165 1166 if (RecanonicalizeArg) 1167 DeducedType = S.Context.getCanonicalType(DeducedType); 1168 1169 DeducedTemplateArgument NewDeduced(DeducedType); 1170 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 1171 Deduced[Index], 1172 NewDeduced); 1173 if (Result.isNull()) { 1174 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1175 Info.FirstArg = Deduced[Index]; 1176 Info.SecondArg = NewDeduced; 1177 return Sema::TDK_Inconsistent; 1178 } 1179 1180 Deduced[Index] = Result; 1181 return Sema::TDK_Success; 1182 } 1183 1184 // Set up the template argument deduction information for a failure. 1185 Info.FirstArg = TemplateArgument(ParamIn); 1186 Info.SecondArg = TemplateArgument(ArgIn); 1187 1188 // If the parameter is an already-substituted template parameter 1189 // pack, do nothing: we don't know which of its arguments to look 1190 // at, so we have to wait until all of the parameter packs in this 1191 // expansion have arguments. 1192 if (isa<SubstTemplateTypeParmPackType>(Param)) 1193 return Sema::TDK_Success; 1194 1195 // Check the cv-qualifiers on the parameter and argument types. 1196 CanQualType CanParam = S.Context.getCanonicalType(Param); 1197 CanQualType CanArg = S.Context.getCanonicalType(Arg); 1198 if (!(TDF & TDF_IgnoreQualifiers)) { 1199 if (TDF & TDF_ParamWithReferenceType) { 1200 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg)) 1201 return Sema::TDK_NonDeducedMismatch; 1202 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) { 1203 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers()) 1204 return Sema::TDK_NonDeducedMismatch; 1205 } 1206 1207 // If the parameter type is not dependent, there is nothing to deduce. 1208 if (!Param->isDependentType()) { 1209 if (!(TDF & TDF_SkipNonDependent)) { 1210 bool NonDeduced = (TDF & TDF_InOverloadResolution)? 1211 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) : 1212 Param != Arg; 1213 if (NonDeduced) { 1214 return Sema::TDK_NonDeducedMismatch; 1215 } 1216 } 1217 return Sema::TDK_Success; 1218 } 1219 } else if (!Param->isDependentType()) { 1220 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(), 1221 ArgUnqualType = CanArg.getUnqualifiedType(); 1222 bool Success = (TDF & TDF_InOverloadResolution)? 1223 S.isSameOrCompatibleFunctionType(ParamUnqualType, 1224 ArgUnqualType) : 1225 ParamUnqualType == ArgUnqualType; 1226 if (Success) 1227 return Sema::TDK_Success; 1228 } 1229 1230 switch (Param->getTypeClass()) { 1231 // Non-canonical types cannot appear here. 1232 #define NON_CANONICAL_TYPE(Class, Base) \ 1233 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class); 1234 #define TYPE(Class, Base) 1235 #include "clang/AST/TypeNodes.def" 1236 1237 case Type::TemplateTypeParm: 1238 case Type::SubstTemplateTypeParmPack: 1239 llvm_unreachable("Type nodes handled above"); 1240 1241 // These types cannot be dependent, so simply check whether the types are 1242 // the same. 1243 case Type::Builtin: 1244 case Type::VariableArray: 1245 case Type::Vector: 1246 case Type::FunctionNoProto: 1247 case Type::Record: 1248 case Type::Enum: 1249 case Type::ObjCObject: 1250 case Type::ObjCInterface: 1251 case Type::ObjCObjectPointer: { 1252 if (TDF & TDF_SkipNonDependent) 1253 return Sema::TDK_Success; 1254 1255 if (TDF & TDF_IgnoreQualifiers) { 1256 Param = Param.getUnqualifiedType(); 1257 Arg = Arg.getUnqualifiedType(); 1258 } 1259 1260 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch; 1261 } 1262 1263 // _Complex T [placeholder extension] 1264 case Type::Complex: 1265 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>()) 1266 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1267 cast<ComplexType>(Param)->getElementType(), 1268 ComplexArg->getElementType(), 1269 Info, Deduced, TDF); 1270 1271 return Sema::TDK_NonDeducedMismatch; 1272 1273 // _Atomic T [extension] 1274 case Type::Atomic: 1275 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>()) 1276 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1277 cast<AtomicType>(Param)->getValueType(), 1278 AtomicArg->getValueType(), 1279 Info, Deduced, TDF); 1280 1281 return Sema::TDK_NonDeducedMismatch; 1282 1283 // T * 1284 case Type::Pointer: { 1285 QualType PointeeType; 1286 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) { 1287 PointeeType = PointerArg->getPointeeType(); 1288 } else if (const ObjCObjectPointerType *PointerArg 1289 = Arg->getAs<ObjCObjectPointerType>()) { 1290 PointeeType = PointerArg->getPointeeType(); 1291 } else { 1292 return Sema::TDK_NonDeducedMismatch; 1293 } 1294 1295 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass); 1296 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1297 cast<PointerType>(Param)->getPointeeType(), 1298 PointeeType, 1299 Info, Deduced, SubTDF); 1300 } 1301 1302 // T & 1303 case Type::LValueReference: { 1304 const LValueReferenceType *ReferenceArg = 1305 Arg->getAs<LValueReferenceType>(); 1306 if (!ReferenceArg) 1307 return Sema::TDK_NonDeducedMismatch; 1308 1309 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1310 cast<LValueReferenceType>(Param)->getPointeeType(), 1311 ReferenceArg->getPointeeType(), Info, Deduced, 0); 1312 } 1313 1314 // T && [C++0x] 1315 case Type::RValueReference: { 1316 const RValueReferenceType *ReferenceArg = 1317 Arg->getAs<RValueReferenceType>(); 1318 if (!ReferenceArg) 1319 return Sema::TDK_NonDeducedMismatch; 1320 1321 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1322 cast<RValueReferenceType>(Param)->getPointeeType(), 1323 ReferenceArg->getPointeeType(), 1324 Info, Deduced, 0); 1325 } 1326 1327 // T [] (implied, but not stated explicitly) 1328 case Type::IncompleteArray: { 1329 const IncompleteArrayType *IncompleteArrayArg = 1330 S.Context.getAsIncompleteArrayType(Arg); 1331 if (!IncompleteArrayArg) 1332 return Sema::TDK_NonDeducedMismatch; 1333 1334 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 1335 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1336 S.Context.getAsIncompleteArrayType(Param)->getElementType(), 1337 IncompleteArrayArg->getElementType(), 1338 Info, Deduced, SubTDF); 1339 } 1340 1341 // T [integer-constant] 1342 case Type::ConstantArray: { 1343 const ConstantArrayType *ConstantArrayArg = 1344 S.Context.getAsConstantArrayType(Arg); 1345 if (!ConstantArrayArg) 1346 return Sema::TDK_NonDeducedMismatch; 1347 1348 const ConstantArrayType *ConstantArrayParm = 1349 S.Context.getAsConstantArrayType(Param); 1350 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize()) 1351 return Sema::TDK_NonDeducedMismatch; 1352 1353 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 1354 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1355 ConstantArrayParm->getElementType(), 1356 ConstantArrayArg->getElementType(), 1357 Info, Deduced, SubTDF); 1358 } 1359 1360 // type [i] 1361 case Type::DependentSizedArray: { 1362 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg); 1363 if (!ArrayArg) 1364 return Sema::TDK_NonDeducedMismatch; 1365 1366 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 1367 1368 // Check the element type of the arrays 1369 const DependentSizedArrayType *DependentArrayParm 1370 = S.Context.getAsDependentSizedArrayType(Param); 1371 if (Sema::TemplateDeductionResult Result 1372 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1373 DependentArrayParm->getElementType(), 1374 ArrayArg->getElementType(), 1375 Info, Deduced, SubTDF)) 1376 return Result; 1377 1378 // Determine the array bound is something we can deduce. 1379 NonTypeTemplateParmDecl *NTTP 1380 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr()); 1381 if (!NTTP) 1382 return Sema::TDK_Success; 1383 1384 // We can perform template argument deduction for the given non-type 1385 // template parameter. 1386 assert(NTTP->getDepth() == 0 && 1387 "Cannot deduce non-type template argument at depth > 0"); 1388 if (const ConstantArrayType *ConstantArrayArg 1389 = dyn_cast<ConstantArrayType>(ArrayArg)) { 1390 llvm::APSInt Size(ConstantArrayArg->getSize()); 1391 return DeduceNonTypeTemplateArgument(S, NTTP, Size, 1392 S.Context.getSizeType(), 1393 /*ArrayBound=*/true, 1394 Info, Deduced); 1395 } 1396 if (const DependentSizedArrayType *DependentArrayArg 1397 = dyn_cast<DependentSizedArrayType>(ArrayArg)) 1398 if (DependentArrayArg->getSizeExpr()) 1399 return DeduceNonTypeTemplateArgument(S, NTTP, 1400 DependentArrayArg->getSizeExpr(), 1401 Info, Deduced); 1402 1403 // Incomplete type does not match a dependently-sized array type 1404 return Sema::TDK_NonDeducedMismatch; 1405 } 1406 1407 // type(*)(T) 1408 // T(*)() 1409 // T(*)(T) 1410 case Type::FunctionProto: { 1411 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList; 1412 const FunctionProtoType *FunctionProtoArg = 1413 dyn_cast<FunctionProtoType>(Arg); 1414 if (!FunctionProtoArg) 1415 return Sema::TDK_NonDeducedMismatch; 1416 1417 const FunctionProtoType *FunctionProtoParam = 1418 cast<FunctionProtoType>(Param); 1419 1420 if (FunctionProtoParam->getTypeQuals() 1421 != FunctionProtoArg->getTypeQuals() || 1422 FunctionProtoParam->getRefQualifier() 1423 != FunctionProtoArg->getRefQualifier() || 1424 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic()) 1425 return Sema::TDK_NonDeducedMismatch; 1426 1427 // Check return types. 1428 if (Sema::TemplateDeductionResult Result = 1429 DeduceTemplateArgumentsByTypeMatch( 1430 S, TemplateParams, FunctionProtoParam->getReturnType(), 1431 FunctionProtoArg->getReturnType(), Info, Deduced, 0)) 1432 return Result; 1433 1434 return DeduceTemplateArguments( 1435 S, TemplateParams, FunctionProtoParam->param_type_begin(), 1436 FunctionProtoParam->getNumParams(), 1437 FunctionProtoArg->param_type_begin(), 1438 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF); 1439 } 1440 1441 case Type::InjectedClassName: { 1442 // Treat a template's injected-class-name as if the template 1443 // specialization type had been used. 1444 Param = cast<InjectedClassNameType>(Param) 1445 ->getInjectedSpecializationType(); 1446 assert(isa<TemplateSpecializationType>(Param) && 1447 "injected class name is not a template specialization type"); 1448 // fall through 1449 } 1450 1451 // template-name<T> (where template-name refers to a class template) 1452 // template-name<i> 1453 // TT<T> 1454 // TT<i> 1455 // TT<> 1456 case Type::TemplateSpecialization: { 1457 const TemplateSpecializationType *SpecParam 1458 = cast<TemplateSpecializationType>(Param); 1459 1460 // Try to deduce template arguments from the template-id. 1461 Sema::TemplateDeductionResult Result 1462 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, 1463 Info, Deduced); 1464 1465 if (Result && (TDF & TDF_DerivedClass)) { 1466 // C++ [temp.deduct.call]p3b3: 1467 // If P is a class, and P has the form template-id, then A can be a 1468 // derived class of the deduced A. Likewise, if P is a pointer to a 1469 // class of the form template-id, A can be a pointer to a derived 1470 // class pointed to by the deduced A. 1471 // 1472 // More importantly: 1473 // These alternatives are considered only if type deduction would 1474 // otherwise fail. 1475 if (const RecordType *RecordT = Arg->getAs<RecordType>()) { 1476 // We cannot inspect base classes as part of deduction when the type 1477 // is incomplete, so either instantiate any templates necessary to 1478 // complete the type, or skip over it if it cannot be completed. 1479 if (S.RequireCompleteType(Info.getLocation(), Arg, 0)) 1480 return Result; 1481 1482 // Use data recursion to crawl through the list of base classes. 1483 // Visited contains the set of nodes we have already visited, while 1484 // ToVisit is our stack of records that we still need to visit. 1485 llvm::SmallPtrSet<const RecordType *, 8> Visited; 1486 SmallVector<const RecordType *, 8> ToVisit; 1487 ToVisit.push_back(RecordT); 1488 bool Successful = false; 1489 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(), 1490 Deduced.end()); 1491 while (!ToVisit.empty()) { 1492 // Retrieve the next class in the inheritance hierarchy. 1493 const RecordType *NextT = ToVisit.pop_back_val(); 1494 1495 // If we have already seen this type, skip it. 1496 if (!Visited.insert(NextT).second) 1497 continue; 1498 1499 // If this is a base class, try to perform template argument 1500 // deduction from it. 1501 if (NextT != RecordT) { 1502 TemplateDeductionInfo BaseInfo(Info.getLocation()); 1503 Sema::TemplateDeductionResult BaseResult 1504 = DeduceTemplateArguments(S, TemplateParams, SpecParam, 1505 QualType(NextT, 0), BaseInfo, 1506 Deduced); 1507 1508 // If template argument deduction for this base was successful, 1509 // note that we had some success. Otherwise, ignore any deductions 1510 // from this base class. 1511 if (BaseResult == Sema::TDK_Success) { 1512 Successful = true; 1513 DeducedOrig.clear(); 1514 DeducedOrig.append(Deduced.begin(), Deduced.end()); 1515 Info.Param = BaseInfo.Param; 1516 Info.FirstArg = BaseInfo.FirstArg; 1517 Info.SecondArg = BaseInfo.SecondArg; 1518 } 1519 else 1520 Deduced = DeducedOrig; 1521 } 1522 1523 // Visit base classes 1524 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl()); 1525 for (const auto &Base : Next->bases()) { 1526 assert(Base.getType()->isRecordType() && 1527 "Base class that isn't a record?"); 1528 ToVisit.push_back(Base.getType()->getAs<RecordType>()); 1529 } 1530 } 1531 1532 if (Successful) 1533 return Sema::TDK_Success; 1534 } 1535 1536 } 1537 1538 return Result; 1539 } 1540 1541 // T type::* 1542 // T T::* 1543 // T (type::*)() 1544 // type (T::*)() 1545 // type (type::*)(T) 1546 // type (T::*)(T) 1547 // T (type::*)(T) 1548 // T (T::*)() 1549 // T (T::*)(T) 1550 case Type::MemberPointer: { 1551 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param); 1552 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg); 1553 if (!MemPtrArg) 1554 return Sema::TDK_NonDeducedMismatch; 1555 1556 if (Sema::TemplateDeductionResult Result 1557 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1558 MemPtrParam->getPointeeType(), 1559 MemPtrArg->getPointeeType(), 1560 Info, Deduced, 1561 TDF & TDF_IgnoreQualifiers)) 1562 return Result; 1563 1564 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1565 QualType(MemPtrParam->getClass(), 0), 1566 QualType(MemPtrArg->getClass(), 0), 1567 Info, Deduced, 1568 TDF & TDF_IgnoreQualifiers); 1569 } 1570 1571 // (clang extension) 1572 // 1573 // type(^)(T) 1574 // T(^)() 1575 // T(^)(T) 1576 case Type::BlockPointer: { 1577 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param); 1578 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg); 1579 1580 if (!BlockPtrArg) 1581 return Sema::TDK_NonDeducedMismatch; 1582 1583 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1584 BlockPtrParam->getPointeeType(), 1585 BlockPtrArg->getPointeeType(), 1586 Info, Deduced, 0); 1587 } 1588 1589 // (clang extension) 1590 // 1591 // T __attribute__(((ext_vector_type(<integral constant>)))) 1592 case Type::ExtVector: { 1593 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param); 1594 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) { 1595 // Make sure that the vectors have the same number of elements. 1596 if (VectorParam->getNumElements() != VectorArg->getNumElements()) 1597 return Sema::TDK_NonDeducedMismatch; 1598 1599 // Perform deduction on the element types. 1600 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1601 VectorParam->getElementType(), 1602 VectorArg->getElementType(), 1603 Info, Deduced, TDF); 1604 } 1605 1606 if (const DependentSizedExtVectorType *VectorArg 1607 = dyn_cast<DependentSizedExtVectorType>(Arg)) { 1608 // We can't check the number of elements, since the argument has a 1609 // dependent number of elements. This can only occur during partial 1610 // ordering. 1611 1612 // Perform deduction on the element types. 1613 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1614 VectorParam->getElementType(), 1615 VectorArg->getElementType(), 1616 Info, Deduced, TDF); 1617 } 1618 1619 return Sema::TDK_NonDeducedMismatch; 1620 } 1621 1622 // (clang extension) 1623 // 1624 // T __attribute__(((ext_vector_type(N)))) 1625 case Type::DependentSizedExtVector: { 1626 const DependentSizedExtVectorType *VectorParam 1627 = cast<DependentSizedExtVectorType>(Param); 1628 1629 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) { 1630 // Perform deduction on the element types. 1631 if (Sema::TemplateDeductionResult Result 1632 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1633 VectorParam->getElementType(), 1634 VectorArg->getElementType(), 1635 Info, Deduced, TDF)) 1636 return Result; 1637 1638 // Perform deduction on the vector size, if we can. 1639 NonTypeTemplateParmDecl *NTTP 1640 = getDeducedParameterFromExpr(VectorParam->getSizeExpr()); 1641 if (!NTTP) 1642 return Sema::TDK_Success; 1643 1644 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); 1645 ArgSize = VectorArg->getNumElements(); 1646 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy, 1647 false, Info, Deduced); 1648 } 1649 1650 if (const DependentSizedExtVectorType *VectorArg 1651 = dyn_cast<DependentSizedExtVectorType>(Arg)) { 1652 // Perform deduction on the element types. 1653 if (Sema::TemplateDeductionResult Result 1654 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1655 VectorParam->getElementType(), 1656 VectorArg->getElementType(), 1657 Info, Deduced, TDF)) 1658 return Result; 1659 1660 // Perform deduction on the vector size, if we can. 1661 NonTypeTemplateParmDecl *NTTP 1662 = getDeducedParameterFromExpr(VectorParam->getSizeExpr()); 1663 if (!NTTP) 1664 return Sema::TDK_Success; 1665 1666 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(), 1667 Info, Deduced); 1668 } 1669 1670 return Sema::TDK_NonDeducedMismatch; 1671 } 1672 1673 case Type::TypeOfExpr: 1674 case Type::TypeOf: 1675 case Type::DependentName: 1676 case Type::UnresolvedUsing: 1677 case Type::Decltype: 1678 case Type::UnaryTransform: 1679 case Type::Auto: 1680 case Type::DependentTemplateSpecialization: 1681 case Type::PackExpansion: 1682 // No template argument deduction for these types 1683 return Sema::TDK_Success; 1684 } 1685 1686 llvm_unreachable("Invalid Type Class!"); 1687 } 1688 1689 static Sema::TemplateDeductionResult 1690 DeduceTemplateArguments(Sema &S, 1691 TemplateParameterList *TemplateParams, 1692 const TemplateArgument &Param, 1693 TemplateArgument Arg, 1694 TemplateDeductionInfo &Info, 1695 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 1696 // If the template argument is a pack expansion, perform template argument 1697 // deduction against the pattern of that expansion. This only occurs during 1698 // partial ordering. 1699 if (Arg.isPackExpansion()) 1700 Arg = Arg.getPackExpansionPattern(); 1701 1702 switch (Param.getKind()) { 1703 case TemplateArgument::Null: 1704 llvm_unreachable("Null template argument in parameter list"); 1705 1706 case TemplateArgument::Type: 1707 if (Arg.getKind() == TemplateArgument::Type) 1708 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1709 Param.getAsType(), 1710 Arg.getAsType(), 1711 Info, Deduced, 0); 1712 Info.FirstArg = Param; 1713 Info.SecondArg = Arg; 1714 return Sema::TDK_NonDeducedMismatch; 1715 1716 case TemplateArgument::Template: 1717 if (Arg.getKind() == TemplateArgument::Template) 1718 return DeduceTemplateArguments(S, TemplateParams, 1719 Param.getAsTemplate(), 1720 Arg.getAsTemplate(), Info, Deduced); 1721 Info.FirstArg = Param; 1722 Info.SecondArg = Arg; 1723 return Sema::TDK_NonDeducedMismatch; 1724 1725 case TemplateArgument::TemplateExpansion: 1726 llvm_unreachable("caller should handle pack expansions"); 1727 1728 case TemplateArgument::Declaration: 1729 if (Arg.getKind() == TemplateArgument::Declaration && 1730 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl())) 1731 return Sema::TDK_Success; 1732 1733 Info.FirstArg = Param; 1734 Info.SecondArg = Arg; 1735 return Sema::TDK_NonDeducedMismatch; 1736 1737 case TemplateArgument::NullPtr: 1738 if (Arg.getKind() == TemplateArgument::NullPtr && 1739 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType())) 1740 return Sema::TDK_Success; 1741 1742 Info.FirstArg = Param; 1743 Info.SecondArg = Arg; 1744 return Sema::TDK_NonDeducedMismatch; 1745 1746 case TemplateArgument::Integral: 1747 if (Arg.getKind() == TemplateArgument::Integral) { 1748 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral())) 1749 return Sema::TDK_Success; 1750 1751 Info.FirstArg = Param; 1752 Info.SecondArg = Arg; 1753 return Sema::TDK_NonDeducedMismatch; 1754 } 1755 1756 if (Arg.getKind() == TemplateArgument::Expression) { 1757 Info.FirstArg = Param; 1758 Info.SecondArg = Arg; 1759 return Sema::TDK_NonDeducedMismatch; 1760 } 1761 1762 Info.FirstArg = Param; 1763 Info.SecondArg = Arg; 1764 return Sema::TDK_NonDeducedMismatch; 1765 1766 case TemplateArgument::Expression: { 1767 if (NonTypeTemplateParmDecl *NTTP 1768 = getDeducedParameterFromExpr(Param.getAsExpr())) { 1769 if (Arg.getKind() == TemplateArgument::Integral) 1770 return DeduceNonTypeTemplateArgument(S, NTTP, 1771 Arg.getAsIntegral(), 1772 Arg.getIntegralType(), 1773 /*ArrayBound=*/false, 1774 Info, Deduced); 1775 if (Arg.getKind() == TemplateArgument::Expression) 1776 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(), 1777 Info, Deduced); 1778 if (Arg.getKind() == TemplateArgument::Declaration) 1779 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(), 1780 Info, Deduced); 1781 1782 Info.FirstArg = Param; 1783 Info.SecondArg = Arg; 1784 return Sema::TDK_NonDeducedMismatch; 1785 } 1786 1787 // Can't deduce anything, but that's okay. 1788 return Sema::TDK_Success; 1789 } 1790 case TemplateArgument::Pack: 1791 llvm_unreachable("Argument packs should be expanded by the caller!"); 1792 } 1793 1794 llvm_unreachable("Invalid TemplateArgument Kind!"); 1795 } 1796 1797 /// \brief Determine whether there is a template argument to be used for 1798 /// deduction. 1799 /// 1800 /// This routine "expands" argument packs in-place, overriding its input 1801 /// parameters so that \c Args[ArgIdx] will be the available template argument. 1802 /// 1803 /// \returns true if there is another template argument (which will be at 1804 /// \c Args[ArgIdx]), false otherwise. 1805 static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args, 1806 unsigned &ArgIdx, 1807 unsigned &NumArgs) { 1808 if (ArgIdx == NumArgs) 1809 return false; 1810 1811 const TemplateArgument &Arg = Args[ArgIdx]; 1812 if (Arg.getKind() != TemplateArgument::Pack) 1813 return true; 1814 1815 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?"); 1816 Args = Arg.pack_begin(); 1817 NumArgs = Arg.pack_size(); 1818 ArgIdx = 0; 1819 return ArgIdx < NumArgs; 1820 } 1821 1822 /// \brief Determine whether the given set of template arguments has a pack 1823 /// expansion that is not the last template argument. 1824 static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args, 1825 unsigned NumArgs) { 1826 unsigned ArgIdx = 0; 1827 while (ArgIdx < NumArgs) { 1828 const TemplateArgument &Arg = Args[ArgIdx]; 1829 1830 // Unwrap argument packs. 1831 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) { 1832 Args = Arg.pack_begin(); 1833 NumArgs = Arg.pack_size(); 1834 ArgIdx = 0; 1835 continue; 1836 } 1837 1838 ++ArgIdx; 1839 if (ArgIdx == NumArgs) 1840 return false; 1841 1842 if (Arg.isPackExpansion()) 1843 return true; 1844 } 1845 1846 return false; 1847 } 1848 1849 static Sema::TemplateDeductionResult 1850 DeduceTemplateArguments(Sema &S, 1851 TemplateParameterList *TemplateParams, 1852 const TemplateArgument *Params, unsigned NumParams, 1853 const TemplateArgument *Args, unsigned NumArgs, 1854 TemplateDeductionInfo &Info, 1855 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 1856 // C++0x [temp.deduct.type]p9: 1857 // If the template argument list of P contains a pack expansion that is not 1858 // the last template argument, the entire template argument list is a 1859 // non-deduced context. 1860 if (hasPackExpansionBeforeEnd(Params, NumParams)) 1861 return Sema::TDK_Success; 1862 1863 // C++0x [temp.deduct.type]p9: 1864 // If P has a form that contains <T> or <i>, then each argument Pi of the 1865 // respective template argument list P is compared with the corresponding 1866 // argument Ai of the corresponding template argument list of A. 1867 unsigned ArgIdx = 0, ParamIdx = 0; 1868 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams); 1869 ++ParamIdx) { 1870 if (!Params[ParamIdx].isPackExpansion()) { 1871 // The simple case: deduce template arguments by matching Pi and Ai. 1872 1873 // Check whether we have enough arguments. 1874 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) 1875 return Sema::TDK_Success; 1876 1877 if (Args[ArgIdx].isPackExpansion()) { 1878 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here, 1879 // but applied to pack expansions that are template arguments. 1880 return Sema::TDK_MiscellaneousDeductionFailure; 1881 } 1882 1883 // Perform deduction for this Pi/Ai pair. 1884 if (Sema::TemplateDeductionResult Result 1885 = DeduceTemplateArguments(S, TemplateParams, 1886 Params[ParamIdx], Args[ArgIdx], 1887 Info, Deduced)) 1888 return Result; 1889 1890 // Move to the next argument. 1891 ++ArgIdx; 1892 continue; 1893 } 1894 1895 // The parameter is a pack expansion. 1896 1897 // C++0x [temp.deduct.type]p9: 1898 // If Pi is a pack expansion, then the pattern of Pi is compared with 1899 // each remaining argument in the template argument list of A. Each 1900 // comparison deduces template arguments for subsequent positions in the 1901 // template parameter packs expanded by Pi. 1902 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern(); 1903 1904 // FIXME: If there are no remaining arguments, we can bail out early 1905 // and set any deduced parameter packs to an empty argument pack. 1906 // The latter part of this is a (minor) correctness issue. 1907 1908 // Prepare to deduce the packs within the pattern. 1909 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern); 1910 1911 // Keep track of the deduced template arguments for each parameter pack 1912 // expanded by this pack expansion (the outer index) and for each 1913 // template argument (the inner SmallVectors). 1914 bool HasAnyArguments = false; 1915 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) { 1916 HasAnyArguments = true; 1917 1918 // Deduce template arguments from the pattern. 1919 if (Sema::TemplateDeductionResult Result 1920 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx], 1921 Info, Deduced)) 1922 return Result; 1923 1924 PackScope.nextPackElement(); 1925 } 1926 1927 // Build argument packs for each of the parameter packs expanded by this 1928 // pack expansion. 1929 if (auto Result = PackScope.finish(HasAnyArguments)) 1930 return Result; 1931 } 1932 1933 return Sema::TDK_Success; 1934 } 1935 1936 static Sema::TemplateDeductionResult 1937 DeduceTemplateArguments(Sema &S, 1938 TemplateParameterList *TemplateParams, 1939 const TemplateArgumentList &ParamList, 1940 const TemplateArgumentList &ArgList, 1941 TemplateDeductionInfo &Info, 1942 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 1943 return DeduceTemplateArguments(S, TemplateParams, 1944 ParamList.data(), ParamList.size(), 1945 ArgList.data(), ArgList.size(), 1946 Info, Deduced); 1947 } 1948 1949 /// \brief Determine whether two template arguments are the same. 1950 static bool isSameTemplateArg(ASTContext &Context, 1951 const TemplateArgument &X, 1952 const TemplateArgument &Y) { 1953 if (X.getKind() != Y.getKind()) 1954 return false; 1955 1956 switch (X.getKind()) { 1957 case TemplateArgument::Null: 1958 llvm_unreachable("Comparing NULL template argument"); 1959 1960 case TemplateArgument::Type: 1961 return Context.getCanonicalType(X.getAsType()) == 1962 Context.getCanonicalType(Y.getAsType()); 1963 1964 case TemplateArgument::Declaration: 1965 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl()); 1966 1967 case TemplateArgument::NullPtr: 1968 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()); 1969 1970 case TemplateArgument::Template: 1971 case TemplateArgument::TemplateExpansion: 1972 return Context.getCanonicalTemplateName( 1973 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() == 1974 Context.getCanonicalTemplateName( 1975 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer(); 1976 1977 case TemplateArgument::Integral: 1978 return X.getAsIntegral() == Y.getAsIntegral(); 1979 1980 case TemplateArgument::Expression: { 1981 llvm::FoldingSetNodeID XID, YID; 1982 X.getAsExpr()->Profile(XID, Context, true); 1983 Y.getAsExpr()->Profile(YID, Context, true); 1984 return XID == YID; 1985 } 1986 1987 case TemplateArgument::Pack: 1988 if (X.pack_size() != Y.pack_size()) 1989 return false; 1990 1991 for (TemplateArgument::pack_iterator XP = X.pack_begin(), 1992 XPEnd = X.pack_end(), 1993 YP = Y.pack_begin(); 1994 XP != XPEnd; ++XP, ++YP) 1995 if (!isSameTemplateArg(Context, *XP, *YP)) 1996 return false; 1997 1998 return true; 1999 } 2000 2001 llvm_unreachable("Invalid TemplateArgument Kind!"); 2002 } 2003 2004 /// \brief Allocate a TemplateArgumentLoc where all locations have 2005 /// been initialized to the given location. 2006 /// 2007 /// \param S The semantic analysis object. 2008 /// 2009 /// \param Arg The template argument we are producing template argument 2010 /// location information for. 2011 /// 2012 /// \param NTTPType For a declaration template argument, the type of 2013 /// the non-type template parameter that corresponds to this template 2014 /// argument. 2015 /// 2016 /// \param Loc The source location to use for the resulting template 2017 /// argument. 2018 static TemplateArgumentLoc 2019 getTrivialTemplateArgumentLoc(Sema &S, 2020 const TemplateArgument &Arg, 2021 QualType NTTPType, 2022 SourceLocation Loc) { 2023 switch (Arg.getKind()) { 2024 case TemplateArgument::Null: 2025 llvm_unreachable("Can't get a NULL template argument here"); 2026 2027 case TemplateArgument::Type: 2028 return TemplateArgumentLoc(Arg, 2029 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc)); 2030 2031 case TemplateArgument::Declaration: { 2032 Expr *E 2033 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) 2034 .getAs<Expr>(); 2035 return TemplateArgumentLoc(TemplateArgument(E), E); 2036 } 2037 2038 case TemplateArgument::NullPtr: { 2039 Expr *E 2040 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) 2041 .getAs<Expr>(); 2042 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true), 2043 E); 2044 } 2045 2046 case TemplateArgument::Integral: { 2047 Expr *E 2048 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>(); 2049 return TemplateArgumentLoc(TemplateArgument(E), E); 2050 } 2051 2052 case TemplateArgument::Template: 2053 case TemplateArgument::TemplateExpansion: { 2054 NestedNameSpecifierLocBuilder Builder; 2055 TemplateName Template = Arg.getAsTemplate(); 2056 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) 2057 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc); 2058 else if (QualifiedTemplateName *QTN = 2059 Template.getAsQualifiedTemplateName()) 2060 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc); 2061 2062 if (Arg.getKind() == TemplateArgument::Template) 2063 return TemplateArgumentLoc(Arg, 2064 Builder.getWithLocInContext(S.Context), 2065 Loc); 2066 2067 2068 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context), 2069 Loc, Loc); 2070 } 2071 2072 case TemplateArgument::Expression: 2073 return TemplateArgumentLoc(Arg, Arg.getAsExpr()); 2074 2075 case TemplateArgument::Pack: 2076 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo()); 2077 } 2078 2079 llvm_unreachable("Invalid TemplateArgument Kind!"); 2080 } 2081 2082 2083 /// \brief Convert the given deduced template argument and add it to the set of 2084 /// fully-converted template arguments. 2085 static bool 2086 ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, 2087 DeducedTemplateArgument Arg, 2088 NamedDecl *Template, 2089 QualType NTTPType, 2090 unsigned ArgumentPackIndex, 2091 TemplateDeductionInfo &Info, 2092 bool InFunctionTemplate, 2093 SmallVectorImpl<TemplateArgument> &Output) { 2094 if (Arg.getKind() == TemplateArgument::Pack) { 2095 // This is a template argument pack, so check each of its arguments against 2096 // the template parameter. 2097 SmallVector<TemplateArgument, 2> PackedArgsBuilder; 2098 for (const auto &P : Arg.pack_elements()) { 2099 // When converting the deduced template argument, append it to the 2100 // general output list. We need to do this so that the template argument 2101 // checking logic has all of the prior template arguments available. 2102 DeducedTemplateArgument InnerArg(P); 2103 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound()); 2104 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template, 2105 NTTPType, PackedArgsBuilder.size(), 2106 Info, InFunctionTemplate, Output)) 2107 return true; 2108 2109 // Move the converted template argument into our argument pack. 2110 PackedArgsBuilder.push_back(Output.pop_back_val()); 2111 } 2112 2113 // Create the resulting argument pack. 2114 Output.push_back(TemplateArgument::CreatePackCopy(S.Context, 2115 PackedArgsBuilder.data(), 2116 PackedArgsBuilder.size())); 2117 return false; 2118 } 2119 2120 // Convert the deduced template argument into a template 2121 // argument that we can check, almost as if the user had written 2122 // the template argument explicitly. 2123 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType, 2124 Info.getLocation()); 2125 2126 // Check the template argument, converting it as necessary. 2127 return S.CheckTemplateArgument(Param, ArgLoc, 2128 Template, 2129 Template->getLocation(), 2130 Template->getSourceRange().getEnd(), 2131 ArgumentPackIndex, 2132 Output, 2133 InFunctionTemplate 2134 ? (Arg.wasDeducedFromArrayBound() 2135 ? Sema::CTAK_DeducedFromArrayBound 2136 : Sema::CTAK_Deduced) 2137 : Sema::CTAK_Specified); 2138 } 2139 2140 /// Complete template argument deduction for a class template partial 2141 /// specialization. 2142 static Sema::TemplateDeductionResult 2143 FinishTemplateArgumentDeduction(Sema &S, 2144 ClassTemplatePartialSpecializationDecl *Partial, 2145 const TemplateArgumentList &TemplateArgs, 2146 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2147 TemplateDeductionInfo &Info) { 2148 // Unevaluated SFINAE context. 2149 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 2150 Sema::SFINAETrap Trap(S); 2151 2152 Sema::ContextRAII SavedContext(S, Partial); 2153 2154 // C++ [temp.deduct.type]p2: 2155 // [...] or if any template argument remains neither deduced nor 2156 // explicitly specified, template argument deduction fails. 2157 SmallVector<TemplateArgument, 4> Builder; 2158 TemplateParameterList *PartialParams = Partial->getTemplateParameters(); 2159 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) { 2160 NamedDecl *Param = PartialParams->getParam(I); 2161 if (Deduced[I].isNull()) { 2162 Info.Param = makeTemplateParameter(Param); 2163 return Sema::TDK_Incomplete; 2164 } 2165 2166 // We have deduced this argument, so it still needs to be 2167 // checked and converted. 2168 2169 // First, for a non-type template parameter type that is 2170 // initialized by a declaration, we need the type of the 2171 // corresponding non-type template parameter. 2172 QualType NTTPType; 2173 if (NonTypeTemplateParmDecl *NTTP 2174 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2175 NTTPType = NTTP->getType(); 2176 if (NTTPType->isDependentType()) { 2177 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2178 Builder.data(), Builder.size()); 2179 NTTPType = S.SubstType(NTTPType, 2180 MultiLevelTemplateArgumentList(TemplateArgs), 2181 NTTP->getLocation(), 2182 NTTP->getDeclName()); 2183 if (NTTPType.isNull()) { 2184 Info.Param = makeTemplateParameter(Param); 2185 // FIXME: These template arguments are temporary. Free them! 2186 Info.reset(TemplateArgumentList::CreateCopy(S.Context, 2187 Builder.data(), 2188 Builder.size())); 2189 return Sema::TDK_SubstitutionFailure; 2190 } 2191 } 2192 } 2193 2194 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], 2195 Partial, NTTPType, 0, Info, false, 2196 Builder)) { 2197 Info.Param = makeTemplateParameter(Param); 2198 // FIXME: These template arguments are temporary. Free them! 2199 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 2200 Builder.size())); 2201 return Sema::TDK_SubstitutionFailure; 2202 } 2203 } 2204 2205 // Form the template argument list from the deduced template arguments. 2206 TemplateArgumentList *DeducedArgumentList 2207 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 2208 Builder.size()); 2209 2210 Info.reset(DeducedArgumentList); 2211 2212 // Substitute the deduced template arguments into the template 2213 // arguments of the class template partial specialization, and 2214 // verify that the instantiated template arguments are both valid 2215 // and are equivalent to the template arguments originally provided 2216 // to the class template. 2217 LocalInstantiationScope InstScope(S); 2218 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate(); 2219 const ASTTemplateArgumentListInfo *PartialTemplArgInfo 2220 = Partial->getTemplateArgsAsWritten(); 2221 const TemplateArgumentLoc *PartialTemplateArgs 2222 = PartialTemplArgInfo->getTemplateArgs(); 2223 2224 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc, 2225 PartialTemplArgInfo->RAngleLoc); 2226 2227 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs, 2228 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) { 2229 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx; 2230 if (ParamIdx >= Partial->getTemplateParameters()->size()) 2231 ParamIdx = Partial->getTemplateParameters()->size() - 1; 2232 2233 Decl *Param 2234 = const_cast<NamedDecl *>( 2235 Partial->getTemplateParameters()->getParam(ParamIdx)); 2236 Info.Param = makeTemplateParameter(Param); 2237 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument(); 2238 return Sema::TDK_SubstitutionFailure; 2239 } 2240 2241 SmallVector<TemplateArgument, 4> ConvertedInstArgs; 2242 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(), 2243 InstArgs, false, ConvertedInstArgs)) 2244 return Sema::TDK_SubstitutionFailure; 2245 2246 TemplateParameterList *TemplateParams 2247 = ClassTemplate->getTemplateParameters(); 2248 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { 2249 TemplateArgument InstArg = ConvertedInstArgs.data()[I]; 2250 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) { 2251 Info.Param = makeTemplateParameter(TemplateParams->getParam(I)); 2252 Info.FirstArg = TemplateArgs[I]; 2253 Info.SecondArg = InstArg; 2254 return Sema::TDK_NonDeducedMismatch; 2255 } 2256 } 2257 2258 if (Trap.hasErrorOccurred()) 2259 return Sema::TDK_SubstitutionFailure; 2260 2261 return Sema::TDK_Success; 2262 } 2263 2264 /// \brief Perform template argument deduction to determine whether 2265 /// the given template arguments match the given class template 2266 /// partial specialization per C++ [temp.class.spec.match]. 2267 Sema::TemplateDeductionResult 2268 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 2269 const TemplateArgumentList &TemplateArgs, 2270 TemplateDeductionInfo &Info) { 2271 if (Partial->isInvalidDecl()) 2272 return TDK_Invalid; 2273 2274 // C++ [temp.class.spec.match]p2: 2275 // A partial specialization matches a given actual template 2276 // argument list if the template arguments of the partial 2277 // specialization can be deduced from the actual template argument 2278 // list (14.8.2). 2279 2280 // Unevaluated SFINAE context. 2281 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 2282 SFINAETrap Trap(*this); 2283 2284 SmallVector<DeducedTemplateArgument, 4> Deduced; 2285 Deduced.resize(Partial->getTemplateParameters()->size()); 2286 if (TemplateDeductionResult Result 2287 = ::DeduceTemplateArguments(*this, 2288 Partial->getTemplateParameters(), 2289 Partial->getTemplateArgs(), 2290 TemplateArgs, Info, Deduced)) 2291 return Result; 2292 2293 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 2294 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs, 2295 Info); 2296 if (Inst.isInvalid()) 2297 return TDK_InstantiationDepth; 2298 2299 if (Trap.hasErrorOccurred()) 2300 return Sema::TDK_SubstitutionFailure; 2301 2302 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs, 2303 Deduced, Info); 2304 } 2305 2306 /// Complete template argument deduction for a variable template partial 2307 /// specialization. 2308 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version? 2309 /// May require unifying ClassTemplate(Partial)SpecializationDecl and 2310 /// VarTemplate(Partial)SpecializationDecl with a new data 2311 /// structure Template(Partial)SpecializationDecl, and 2312 /// using Template(Partial)SpecializationDecl as input type. 2313 static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction( 2314 Sema &S, VarTemplatePartialSpecializationDecl *Partial, 2315 const TemplateArgumentList &TemplateArgs, 2316 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2317 TemplateDeductionInfo &Info) { 2318 // Unevaluated SFINAE context. 2319 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 2320 Sema::SFINAETrap Trap(S); 2321 2322 // C++ [temp.deduct.type]p2: 2323 // [...] or if any template argument remains neither deduced nor 2324 // explicitly specified, template argument deduction fails. 2325 SmallVector<TemplateArgument, 4> Builder; 2326 TemplateParameterList *PartialParams = Partial->getTemplateParameters(); 2327 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) { 2328 NamedDecl *Param = PartialParams->getParam(I); 2329 if (Deduced[I].isNull()) { 2330 Info.Param = makeTemplateParameter(Param); 2331 return Sema::TDK_Incomplete; 2332 } 2333 2334 // We have deduced this argument, so it still needs to be 2335 // checked and converted. 2336 2337 // First, for a non-type template parameter type that is 2338 // initialized by a declaration, we need the type of the 2339 // corresponding non-type template parameter. 2340 QualType NTTPType; 2341 if (NonTypeTemplateParmDecl *NTTP = 2342 dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2343 NTTPType = NTTP->getType(); 2344 if (NTTPType->isDependentType()) { 2345 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2346 Builder.data(), Builder.size()); 2347 NTTPType = 2348 S.SubstType(NTTPType, MultiLevelTemplateArgumentList(TemplateArgs), 2349 NTTP->getLocation(), NTTP->getDeclName()); 2350 if (NTTPType.isNull()) { 2351 Info.Param = makeTemplateParameter(Param); 2352 // FIXME: These template arguments are temporary. Free them! 2353 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 2354 Builder.size())); 2355 return Sema::TDK_SubstitutionFailure; 2356 } 2357 } 2358 } 2359 2360 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial, NTTPType, 2361 0, Info, false, Builder)) { 2362 Info.Param = makeTemplateParameter(Param); 2363 // FIXME: These template arguments are temporary. Free them! 2364 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 2365 Builder.size())); 2366 return Sema::TDK_SubstitutionFailure; 2367 } 2368 } 2369 2370 // Form the template argument list from the deduced template arguments. 2371 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy( 2372 S.Context, Builder.data(), Builder.size()); 2373 2374 Info.reset(DeducedArgumentList); 2375 2376 // Substitute the deduced template arguments into the template 2377 // arguments of the class template partial specialization, and 2378 // verify that the instantiated template arguments are both valid 2379 // and are equivalent to the template arguments originally provided 2380 // to the class template. 2381 LocalInstantiationScope InstScope(S); 2382 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate(); 2383 const ASTTemplateArgumentListInfo *PartialTemplArgInfo 2384 = Partial->getTemplateArgsAsWritten(); 2385 const TemplateArgumentLoc *PartialTemplateArgs 2386 = PartialTemplArgInfo->getTemplateArgs(); 2387 2388 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc, 2389 PartialTemplArgInfo->RAngleLoc); 2390 2391 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs, 2392 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) { 2393 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx; 2394 if (ParamIdx >= Partial->getTemplateParameters()->size()) 2395 ParamIdx = Partial->getTemplateParameters()->size() - 1; 2396 2397 Decl *Param = const_cast<NamedDecl *>( 2398 Partial->getTemplateParameters()->getParam(ParamIdx)); 2399 Info.Param = makeTemplateParameter(Param); 2400 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument(); 2401 return Sema::TDK_SubstitutionFailure; 2402 } 2403 SmallVector<TemplateArgument, 4> ConvertedInstArgs; 2404 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs, 2405 false, ConvertedInstArgs)) 2406 return Sema::TDK_SubstitutionFailure; 2407 2408 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters(); 2409 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { 2410 TemplateArgument InstArg = ConvertedInstArgs.data()[I]; 2411 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) { 2412 Info.Param = makeTemplateParameter(TemplateParams->getParam(I)); 2413 Info.FirstArg = TemplateArgs[I]; 2414 Info.SecondArg = InstArg; 2415 return Sema::TDK_NonDeducedMismatch; 2416 } 2417 } 2418 2419 if (Trap.hasErrorOccurred()) 2420 return Sema::TDK_SubstitutionFailure; 2421 2422 return Sema::TDK_Success; 2423 } 2424 2425 /// \brief Perform template argument deduction to determine whether 2426 /// the given template arguments match the given variable template 2427 /// partial specialization per C++ [temp.class.spec.match]. 2428 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version? 2429 /// May require unifying ClassTemplate(Partial)SpecializationDecl and 2430 /// VarTemplate(Partial)SpecializationDecl with a new data 2431 /// structure Template(Partial)SpecializationDecl, and 2432 /// using Template(Partial)SpecializationDecl as input type. 2433 Sema::TemplateDeductionResult 2434 Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 2435 const TemplateArgumentList &TemplateArgs, 2436 TemplateDeductionInfo &Info) { 2437 if (Partial->isInvalidDecl()) 2438 return TDK_Invalid; 2439 2440 // C++ [temp.class.spec.match]p2: 2441 // A partial specialization matches a given actual template 2442 // argument list if the template arguments of the partial 2443 // specialization can be deduced from the actual template argument 2444 // list (14.8.2). 2445 2446 // Unevaluated SFINAE context. 2447 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 2448 SFINAETrap Trap(*this); 2449 2450 SmallVector<DeducedTemplateArgument, 4> Deduced; 2451 Deduced.resize(Partial->getTemplateParameters()->size()); 2452 if (TemplateDeductionResult Result = ::DeduceTemplateArguments( 2453 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(), 2454 TemplateArgs, Info, Deduced)) 2455 return Result; 2456 2457 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 2458 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs, 2459 Info); 2460 if (Inst.isInvalid()) 2461 return TDK_InstantiationDepth; 2462 2463 if (Trap.hasErrorOccurred()) 2464 return Sema::TDK_SubstitutionFailure; 2465 2466 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs, 2467 Deduced, Info); 2468 } 2469 2470 /// \brief Determine whether the given type T is a simple-template-id type. 2471 static bool isSimpleTemplateIdType(QualType T) { 2472 if (const TemplateSpecializationType *Spec 2473 = T->getAs<TemplateSpecializationType>()) 2474 return Spec->getTemplateName().getAsTemplateDecl() != nullptr; 2475 2476 return false; 2477 } 2478 2479 /// \brief Substitute the explicitly-provided template arguments into the 2480 /// given function template according to C++ [temp.arg.explicit]. 2481 /// 2482 /// \param FunctionTemplate the function template into which the explicit 2483 /// template arguments will be substituted. 2484 /// 2485 /// \param ExplicitTemplateArgs the explicitly-specified template 2486 /// arguments. 2487 /// 2488 /// \param Deduced the deduced template arguments, which will be populated 2489 /// with the converted and checked explicit template arguments. 2490 /// 2491 /// \param ParamTypes will be populated with the instantiated function 2492 /// parameters. 2493 /// 2494 /// \param FunctionType if non-NULL, the result type of the function template 2495 /// will also be instantiated and the pointed-to value will be updated with 2496 /// the instantiated function type. 2497 /// 2498 /// \param Info if substitution fails for any reason, this object will be 2499 /// populated with more information about the failure. 2500 /// 2501 /// \returns TDK_Success if substitution was successful, or some failure 2502 /// condition. 2503 Sema::TemplateDeductionResult 2504 Sema::SubstituteExplicitTemplateArguments( 2505 FunctionTemplateDecl *FunctionTemplate, 2506 TemplateArgumentListInfo &ExplicitTemplateArgs, 2507 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2508 SmallVectorImpl<QualType> &ParamTypes, 2509 QualType *FunctionType, 2510 TemplateDeductionInfo &Info) { 2511 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 2512 TemplateParameterList *TemplateParams 2513 = FunctionTemplate->getTemplateParameters(); 2514 2515 if (ExplicitTemplateArgs.size() == 0) { 2516 // No arguments to substitute; just copy over the parameter types and 2517 // fill in the function type. 2518 for (auto P : Function->params()) 2519 ParamTypes.push_back(P->getType()); 2520 2521 if (FunctionType) 2522 *FunctionType = Function->getType(); 2523 return TDK_Success; 2524 } 2525 2526 // Unevaluated SFINAE context. 2527 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 2528 SFINAETrap Trap(*this); 2529 2530 // C++ [temp.arg.explicit]p3: 2531 // Template arguments that are present shall be specified in the 2532 // declaration order of their corresponding template-parameters. The 2533 // template argument list shall not specify more template-arguments than 2534 // there are corresponding template-parameters. 2535 SmallVector<TemplateArgument, 4> Builder; 2536 2537 // Enter a new template instantiation context where we check the 2538 // explicitly-specified template arguments against this function template, 2539 // and then substitute them into the function parameter types. 2540 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 2541 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate, 2542 DeducedArgs, 2543 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution, 2544 Info); 2545 if (Inst.isInvalid()) 2546 return TDK_InstantiationDepth; 2547 2548 if (CheckTemplateArgumentList(FunctionTemplate, 2549 SourceLocation(), 2550 ExplicitTemplateArgs, 2551 true, 2552 Builder) || Trap.hasErrorOccurred()) { 2553 unsigned Index = Builder.size(); 2554 if (Index >= TemplateParams->size()) 2555 Index = TemplateParams->size() - 1; 2556 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index)); 2557 return TDK_InvalidExplicitArguments; 2558 } 2559 2560 // Form the template argument list from the explicitly-specified 2561 // template arguments. 2562 TemplateArgumentList *ExplicitArgumentList 2563 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size()); 2564 Info.reset(ExplicitArgumentList); 2565 2566 // Template argument deduction and the final substitution should be 2567 // done in the context of the templated declaration. Explicit 2568 // argument substitution, on the other hand, needs to happen in the 2569 // calling context. 2570 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 2571 2572 // If we deduced template arguments for a template parameter pack, 2573 // note that the template argument pack is partially substituted and record 2574 // the explicit template arguments. They'll be used as part of deduction 2575 // for this template parameter pack. 2576 for (unsigned I = 0, N = Builder.size(); I != N; ++I) { 2577 const TemplateArgument &Arg = Builder[I]; 2578 if (Arg.getKind() == TemplateArgument::Pack) { 2579 CurrentInstantiationScope->SetPartiallySubstitutedPack( 2580 TemplateParams->getParam(I), 2581 Arg.pack_begin(), 2582 Arg.pack_size()); 2583 break; 2584 } 2585 } 2586 2587 const FunctionProtoType *Proto 2588 = Function->getType()->getAs<FunctionProtoType>(); 2589 assert(Proto && "Function template does not have a prototype?"); 2590 2591 // Isolate our substituted parameters from our caller. 2592 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true); 2593 2594 // Instantiate the types of each of the function parameters given the 2595 // explicitly-specified template arguments. If the function has a trailing 2596 // return type, substitute it after the arguments to ensure we substitute 2597 // in lexical order. 2598 if (Proto->hasTrailingReturn()) { 2599 if (SubstParmTypes(Function->getLocation(), 2600 Function->param_begin(), Function->getNumParams(), 2601 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 2602 ParamTypes)) 2603 return TDK_SubstitutionFailure; 2604 } 2605 2606 // Instantiate the return type. 2607 QualType ResultType; 2608 { 2609 // C++11 [expr.prim.general]p3: 2610 // If a declaration declares a member function or member function 2611 // template of a class X, the expression this is a prvalue of type 2612 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 2613 // and the end of the function-definition, member-declarator, or 2614 // declarator. 2615 unsigned ThisTypeQuals = 0; 2616 CXXRecordDecl *ThisContext = nullptr; 2617 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 2618 ThisContext = Method->getParent(); 2619 ThisTypeQuals = Method->getTypeQualifiers(); 2620 } 2621 2622 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals, 2623 getLangOpts().CPlusPlus11); 2624 2625 ResultType = 2626 SubstType(Proto->getReturnType(), 2627 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 2628 Function->getTypeSpecStartLoc(), Function->getDeclName()); 2629 if (ResultType.isNull() || Trap.hasErrorOccurred()) 2630 return TDK_SubstitutionFailure; 2631 } 2632 2633 // Instantiate the types of each of the function parameters given the 2634 // explicitly-specified template arguments if we didn't do so earlier. 2635 if (!Proto->hasTrailingReturn() && 2636 SubstParmTypes(Function->getLocation(), 2637 Function->param_begin(), Function->getNumParams(), 2638 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 2639 ParamTypes)) 2640 return TDK_SubstitutionFailure; 2641 2642 if (FunctionType) { 2643 *FunctionType = BuildFunctionType(ResultType, ParamTypes, 2644 Function->getLocation(), 2645 Function->getDeclName(), 2646 Proto->getExtProtoInfo()); 2647 if (FunctionType->isNull() || Trap.hasErrorOccurred()) 2648 return TDK_SubstitutionFailure; 2649 } 2650 2651 // C++ [temp.arg.explicit]p2: 2652 // Trailing template arguments that can be deduced (14.8.2) may be 2653 // omitted from the list of explicit template-arguments. If all of the 2654 // template arguments can be deduced, they may all be omitted; in this 2655 // case, the empty template argument list <> itself may also be omitted. 2656 // 2657 // Take all of the explicitly-specified arguments and put them into 2658 // the set of deduced template arguments. Explicitly-specified 2659 // parameter packs, however, will be set to NULL since the deduction 2660 // mechanisms handle explicitly-specified argument packs directly. 2661 Deduced.reserve(TemplateParams->size()); 2662 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) { 2663 const TemplateArgument &Arg = ExplicitArgumentList->get(I); 2664 if (Arg.getKind() == TemplateArgument::Pack) 2665 Deduced.push_back(DeducedTemplateArgument()); 2666 else 2667 Deduced.push_back(Arg); 2668 } 2669 2670 return TDK_Success; 2671 } 2672 2673 /// \brief Check whether the deduced argument type for a call to a function 2674 /// template matches the actual argument type per C++ [temp.deduct.call]p4. 2675 static bool 2676 CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg, 2677 QualType DeducedA) { 2678 ASTContext &Context = S.Context; 2679 2680 QualType A = OriginalArg.OriginalArgType; 2681 QualType OriginalParamType = OriginalArg.OriginalParamType; 2682 2683 // Check for type equality (top-level cv-qualifiers are ignored). 2684 if (Context.hasSameUnqualifiedType(A, DeducedA)) 2685 return false; 2686 2687 // Strip off references on the argument types; they aren't needed for 2688 // the following checks. 2689 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>()) 2690 DeducedA = DeducedARef->getPointeeType(); 2691 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) 2692 A = ARef->getPointeeType(); 2693 2694 // C++ [temp.deduct.call]p4: 2695 // [...] However, there are three cases that allow a difference: 2696 // - If the original P is a reference type, the deduced A (i.e., the 2697 // type referred to by the reference) can be more cv-qualified than 2698 // the transformed A. 2699 if (const ReferenceType *OriginalParamRef 2700 = OriginalParamType->getAs<ReferenceType>()) { 2701 // We don't want to keep the reference around any more. 2702 OriginalParamType = OriginalParamRef->getPointeeType(); 2703 2704 Qualifiers AQuals = A.getQualifiers(); 2705 Qualifiers DeducedAQuals = DeducedA.getQualifiers(); 2706 2707 // Under Objective-C++ ARC, the deduced type may have implicitly 2708 // been given strong or (when dealing with a const reference) 2709 // unsafe_unretained lifetime. If so, update the original 2710 // qualifiers to include this lifetime. 2711 if (S.getLangOpts().ObjCAutoRefCount && 2712 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong && 2713 AQuals.getObjCLifetime() == Qualifiers::OCL_None) || 2714 (DeducedAQuals.hasConst() && 2715 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) { 2716 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime()); 2717 } 2718 2719 if (AQuals == DeducedAQuals) { 2720 // Qualifiers match; there's nothing to do. 2721 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) { 2722 return true; 2723 } else { 2724 // Qualifiers are compatible, so have the argument type adopt the 2725 // deduced argument type's qualifiers as if we had performed the 2726 // qualification conversion. 2727 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals); 2728 } 2729 } 2730 2731 // - The transformed A can be another pointer or pointer to member 2732 // type that can be converted to the deduced A via a qualification 2733 // conversion. 2734 // 2735 // Also allow conversions which merely strip [[noreturn]] from function types 2736 // (recursively) as an extension. 2737 // FIXME: Currently, this doesn't play nicely with qualification conversions. 2738 bool ObjCLifetimeConversion = false; 2739 QualType ResultTy; 2740 if ((A->isAnyPointerType() || A->isMemberPointerType()) && 2741 (S.IsQualificationConversion(A, DeducedA, false, 2742 ObjCLifetimeConversion) || 2743 S.IsNoReturnConversion(A, DeducedA, ResultTy))) 2744 return false; 2745 2746 2747 // - If P is a class and P has the form simple-template-id, then the 2748 // transformed A can be a derived class of the deduced A. [...] 2749 // [...] Likewise, if P is a pointer to a class of the form 2750 // simple-template-id, the transformed A can be a pointer to a 2751 // derived class pointed to by the deduced A. 2752 if (const PointerType *OriginalParamPtr 2753 = OriginalParamType->getAs<PointerType>()) { 2754 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) { 2755 if (const PointerType *APtr = A->getAs<PointerType>()) { 2756 if (A->getPointeeType()->isRecordType()) { 2757 OriginalParamType = OriginalParamPtr->getPointeeType(); 2758 DeducedA = DeducedAPtr->getPointeeType(); 2759 A = APtr->getPointeeType(); 2760 } 2761 } 2762 } 2763 } 2764 2765 if (Context.hasSameUnqualifiedType(A, DeducedA)) 2766 return false; 2767 2768 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) && 2769 S.IsDerivedFrom(A, DeducedA)) 2770 return false; 2771 2772 return true; 2773 } 2774 2775 /// \brief Finish template argument deduction for a function template, 2776 /// checking the deduced template arguments for completeness and forming 2777 /// the function template specialization. 2778 /// 2779 /// \param OriginalCallArgs If non-NULL, the original call arguments against 2780 /// which the deduced argument types should be compared. 2781 Sema::TemplateDeductionResult 2782 Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 2783 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2784 unsigned NumExplicitlySpecified, 2785 FunctionDecl *&Specialization, 2786 TemplateDeductionInfo &Info, 2787 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs, 2788 bool PartialOverloading) { 2789 TemplateParameterList *TemplateParams 2790 = FunctionTemplate->getTemplateParameters(); 2791 2792 // Unevaluated SFINAE context. 2793 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 2794 SFINAETrap Trap(*this); 2795 2796 // Enter a new template instantiation context while we instantiate the 2797 // actual function declaration. 2798 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 2799 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate, 2800 DeducedArgs, 2801 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution, 2802 Info); 2803 if (Inst.isInvalid()) 2804 return TDK_InstantiationDepth; 2805 2806 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 2807 2808 // C++ [temp.deduct.type]p2: 2809 // [...] or if any template argument remains neither deduced nor 2810 // explicitly specified, template argument deduction fails. 2811 SmallVector<TemplateArgument, 4> Builder; 2812 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 2813 NamedDecl *Param = TemplateParams->getParam(I); 2814 2815 if (!Deduced[I].isNull()) { 2816 if (I < NumExplicitlySpecified) { 2817 // We have already fully type-checked and converted this 2818 // argument, because it was explicitly-specified. Just record the 2819 // presence of this argument. 2820 Builder.push_back(Deduced[I]); 2821 // We may have had explicitly-specified template arguments for a 2822 // template parameter pack (that may or may not have been extended 2823 // via additional deduced arguments). 2824 if (Param->isParameterPack() && CurrentInstantiationScope) { 2825 if (CurrentInstantiationScope->getPartiallySubstitutedPack() == 2826 Param) { 2827 // Forget the partially-substituted pack; its substitution is now 2828 // complete. 2829 CurrentInstantiationScope->ResetPartiallySubstitutedPack(); 2830 } 2831 } 2832 continue; 2833 } 2834 // We have deduced this argument, so it still needs to be 2835 // checked and converted. 2836 2837 // First, for a non-type template parameter type that is 2838 // initialized by a declaration, we need the type of the 2839 // corresponding non-type template parameter. 2840 QualType NTTPType; 2841 if (NonTypeTemplateParmDecl *NTTP 2842 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2843 NTTPType = NTTP->getType(); 2844 if (NTTPType->isDependentType()) { 2845 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2846 Builder.data(), Builder.size()); 2847 NTTPType = SubstType(NTTPType, 2848 MultiLevelTemplateArgumentList(TemplateArgs), 2849 NTTP->getLocation(), 2850 NTTP->getDeclName()); 2851 if (NTTPType.isNull()) { 2852 Info.Param = makeTemplateParameter(Param); 2853 // FIXME: These template arguments are temporary. Free them! 2854 Info.reset(TemplateArgumentList::CreateCopy(Context, 2855 Builder.data(), 2856 Builder.size())); 2857 return TDK_SubstitutionFailure; 2858 } 2859 } 2860 } 2861 2862 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I], 2863 FunctionTemplate, NTTPType, 0, Info, 2864 true, Builder)) { 2865 Info.Param = makeTemplateParameter(Param); 2866 // FIXME: These template arguments are temporary. Free them! 2867 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(), 2868 Builder.size())); 2869 return TDK_SubstitutionFailure; 2870 } 2871 2872 continue; 2873 } 2874 2875 // C++0x [temp.arg.explicit]p3: 2876 // A trailing template parameter pack (14.5.3) not otherwise deduced will 2877 // be deduced to an empty sequence of template arguments. 2878 // FIXME: Where did the word "trailing" come from? 2879 if (Param->isTemplateParameterPack()) { 2880 // We may have had explicitly-specified template arguments for this 2881 // template parameter pack. If so, our empty deduction extends the 2882 // explicitly-specified set (C++0x [temp.arg.explicit]p9). 2883 const TemplateArgument *ExplicitArgs; 2884 unsigned NumExplicitArgs; 2885 if (CurrentInstantiationScope && 2886 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs, 2887 &NumExplicitArgs) 2888 == Param) { 2889 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs)); 2890 2891 // Forget the partially-substituted pack; it's substitution is now 2892 // complete. 2893 CurrentInstantiationScope->ResetPartiallySubstitutedPack(); 2894 } else { 2895 Builder.push_back(TemplateArgument::getEmptyPack()); 2896 } 2897 continue; 2898 } 2899 2900 // Substitute into the default template argument, if available. 2901 bool HasDefaultArg = false; 2902 TemplateArgumentLoc DefArg 2903 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate, 2904 FunctionTemplate->getLocation(), 2905 FunctionTemplate->getSourceRange().getEnd(), 2906 Param, 2907 Builder, HasDefaultArg); 2908 2909 // If there was no default argument, deduction is incomplete. 2910 if (DefArg.getArgument().isNull()) { 2911 Info.Param = makeTemplateParameter( 2912 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 2913 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(), 2914 Builder.size())); 2915 if (PartialOverloading) break; 2916 2917 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete; 2918 } 2919 2920 // Check whether we can actually use the default argument. 2921 if (CheckTemplateArgument(Param, DefArg, 2922 FunctionTemplate, 2923 FunctionTemplate->getLocation(), 2924 FunctionTemplate->getSourceRange().getEnd(), 2925 0, Builder, 2926 CTAK_Specified)) { 2927 Info.Param = makeTemplateParameter( 2928 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 2929 // FIXME: These template arguments are temporary. Free them! 2930 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(), 2931 Builder.size())); 2932 return TDK_SubstitutionFailure; 2933 } 2934 2935 // If we get here, we successfully used the default template argument. 2936 } 2937 2938 // Form the template argument list from the deduced template arguments. 2939 TemplateArgumentList *DeducedArgumentList 2940 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size()); 2941 Info.reset(DeducedArgumentList); 2942 2943 // Substitute the deduced template arguments into the function template 2944 // declaration to produce the function template specialization. 2945 DeclContext *Owner = FunctionTemplate->getDeclContext(); 2946 if (FunctionTemplate->getFriendObjectKind()) 2947 Owner = FunctionTemplate->getLexicalDeclContext(); 2948 Specialization = cast_or_null<FunctionDecl>( 2949 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, 2950 MultiLevelTemplateArgumentList(*DeducedArgumentList))); 2951 if (!Specialization || Specialization->isInvalidDecl()) 2952 return TDK_SubstitutionFailure; 2953 2954 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() == 2955 FunctionTemplate->getCanonicalDecl()); 2956 2957 // If the template argument list is owned by the function template 2958 // specialization, release it. 2959 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList && 2960 !Trap.hasErrorOccurred()) 2961 Info.take(); 2962 2963 // There may have been an error that did not prevent us from constructing a 2964 // declaration. Mark the declaration invalid and return with a substitution 2965 // failure. 2966 if (Trap.hasErrorOccurred()) { 2967 Specialization->setInvalidDecl(true); 2968 return TDK_SubstitutionFailure; 2969 } 2970 2971 if (OriginalCallArgs) { 2972 // C++ [temp.deduct.call]p4: 2973 // In general, the deduction process attempts to find template argument 2974 // values that will make the deduced A identical to A (after the type A 2975 // is transformed as described above). [...] 2976 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) { 2977 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I]; 2978 unsigned ParamIdx = OriginalArg.ArgIdx; 2979 2980 if (ParamIdx >= Specialization->getNumParams()) 2981 continue; 2982 2983 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType(); 2984 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) 2985 return Sema::TDK_SubstitutionFailure; 2986 } 2987 } 2988 2989 // If we suppressed any diagnostics while performing template argument 2990 // deduction, and if we haven't already instantiated this declaration, 2991 // keep track of these diagnostics. They'll be emitted if this specialization 2992 // is actually used. 2993 if (Info.diag_begin() != Info.diag_end()) { 2994 SuppressedDiagnosticsMap::iterator 2995 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl()); 2996 if (Pos == SuppressedDiagnostics.end()) 2997 SuppressedDiagnostics[Specialization->getCanonicalDecl()] 2998 .append(Info.diag_begin(), Info.diag_end()); 2999 } 3000 3001 return TDK_Success; 3002 } 3003 3004 /// Gets the type of a function for template-argument-deducton 3005 /// purposes when it's considered as part of an overload set. 3006 static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, 3007 FunctionDecl *Fn) { 3008 // We may need to deduce the return type of the function now. 3009 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() && 3010 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false)) 3011 return QualType(); 3012 3013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 3014 if (Method->isInstance()) { 3015 // An instance method that's referenced in a form that doesn't 3016 // look like a member pointer is just invalid. 3017 if (!R.HasFormOfMemberPointer) return QualType(); 3018 3019 return S.Context.getMemberPointerType(Fn->getType(), 3020 S.Context.getTypeDeclType(Method->getParent()).getTypePtr()); 3021 } 3022 3023 if (!R.IsAddressOfOperand) return Fn->getType(); 3024 return S.Context.getPointerType(Fn->getType()); 3025 } 3026 3027 /// Apply the deduction rules for overload sets. 3028 /// 3029 /// \return the null type if this argument should be treated as an 3030 /// undeduced context 3031 static QualType 3032 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, 3033 Expr *Arg, QualType ParamType, 3034 bool ParamWasReference) { 3035 3036 OverloadExpr::FindResult R = OverloadExpr::find(Arg); 3037 3038 OverloadExpr *Ovl = R.Expression; 3039 3040 // C++0x [temp.deduct.call]p4 3041 unsigned TDF = 0; 3042 if (ParamWasReference) 3043 TDF |= TDF_ParamWithReferenceType; 3044 if (R.IsAddressOfOperand) 3045 TDF |= TDF_IgnoreQualifiers; 3046 3047 // C++0x [temp.deduct.call]p6: 3048 // When P is a function type, pointer to function type, or pointer 3049 // to member function type: 3050 3051 if (!ParamType->isFunctionType() && 3052 !ParamType->isFunctionPointerType() && 3053 !ParamType->isMemberFunctionPointerType()) { 3054 if (Ovl->hasExplicitTemplateArgs()) { 3055 // But we can still look for an explicit specialization. 3056 if (FunctionDecl *ExplicitSpec 3057 = S.ResolveSingleFunctionTemplateSpecialization(Ovl)) 3058 return GetTypeOfFunction(S, R, ExplicitSpec); 3059 } 3060 3061 return QualType(); 3062 } 3063 3064 // Gather the explicit template arguments, if any. 3065 TemplateArgumentListInfo ExplicitTemplateArgs; 3066 if (Ovl->hasExplicitTemplateArgs()) 3067 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 3068 QualType Match; 3069 for (UnresolvedSetIterator I = Ovl->decls_begin(), 3070 E = Ovl->decls_end(); I != E; ++I) { 3071 NamedDecl *D = (*I)->getUnderlyingDecl(); 3072 3073 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) { 3074 // - If the argument is an overload set containing one or more 3075 // function templates, the parameter is treated as a 3076 // non-deduced context. 3077 if (!Ovl->hasExplicitTemplateArgs()) 3078 return QualType(); 3079 3080 // Otherwise, see if we can resolve a function type 3081 FunctionDecl *Specialization = nullptr; 3082 TemplateDeductionInfo Info(Ovl->getNameLoc()); 3083 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs, 3084 Specialization, Info)) 3085 continue; 3086 3087 D = Specialization; 3088 } 3089 3090 FunctionDecl *Fn = cast<FunctionDecl>(D); 3091 QualType ArgType = GetTypeOfFunction(S, R, Fn); 3092 if (ArgType.isNull()) continue; 3093 3094 // Function-to-pointer conversion. 3095 if (!ParamWasReference && ParamType->isPointerType() && 3096 ArgType->isFunctionType()) 3097 ArgType = S.Context.getPointerType(ArgType); 3098 3099 // - If the argument is an overload set (not containing function 3100 // templates), trial argument deduction is attempted using each 3101 // of the members of the set. If deduction succeeds for only one 3102 // of the overload set members, that member is used as the 3103 // argument value for the deduction. If deduction succeeds for 3104 // more than one member of the overload set the parameter is 3105 // treated as a non-deduced context. 3106 3107 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2: 3108 // Type deduction is done independently for each P/A pair, and 3109 // the deduced template argument values are then combined. 3110 // So we do not reject deductions which were made elsewhere. 3111 SmallVector<DeducedTemplateArgument, 8> 3112 Deduced(TemplateParams->size()); 3113 TemplateDeductionInfo Info(Ovl->getNameLoc()); 3114 Sema::TemplateDeductionResult Result 3115 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 3116 ArgType, Info, Deduced, TDF); 3117 if (Result) continue; 3118 if (!Match.isNull()) return QualType(); 3119 Match = ArgType; 3120 } 3121 3122 return Match; 3123 } 3124 3125 /// \brief Perform the adjustments to the parameter and argument types 3126 /// described in C++ [temp.deduct.call]. 3127 /// 3128 /// \returns true if the caller should not attempt to perform any template 3129 /// argument deduction based on this P/A pair because the argument is an 3130 /// overloaded function set that could not be resolved. 3131 static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S, 3132 TemplateParameterList *TemplateParams, 3133 QualType &ParamType, 3134 QualType &ArgType, 3135 Expr *Arg, 3136 unsigned &TDF) { 3137 // C++0x [temp.deduct.call]p3: 3138 // If P is a cv-qualified type, the top level cv-qualifiers of P's type 3139 // are ignored for type deduction. 3140 if (ParamType.hasQualifiers()) 3141 ParamType = ParamType.getUnqualifiedType(); 3142 3143 // [...] If P is a reference type, the type referred to by P is 3144 // used for type deduction. 3145 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>(); 3146 if (ParamRefType) 3147 ParamType = ParamRefType->getPointeeType(); 3148 3149 // Overload sets usually make this parameter an undeduced context, 3150 // but there are sometimes special circumstances. Typically 3151 // involving a template-id-expr. 3152 if (ArgType == S.Context.OverloadTy) { 3153 ArgType = ResolveOverloadForDeduction(S, TemplateParams, 3154 Arg, ParamType, 3155 ParamRefType != nullptr); 3156 if (ArgType.isNull()) 3157 return true; 3158 } 3159 3160 if (ParamRefType) { 3161 // If the argument has incomplete array type, try to complete its type. 3162 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0)) 3163 ArgType = Arg->getType(); 3164 3165 // C++0x [temp.deduct.call]p3: 3166 // If P is an rvalue reference to a cv-unqualified template 3167 // parameter and the argument is an lvalue, the type "lvalue 3168 // reference to A" is used in place of A for type deduction. 3169 if (ParamRefType->isRValueReferenceType() && 3170 !ParamType.getQualifiers() && 3171 isa<TemplateTypeParmType>(ParamType) && 3172 Arg->isLValue()) 3173 ArgType = S.Context.getLValueReferenceType(ArgType); 3174 } else { 3175 // C++ [temp.deduct.call]p2: 3176 // If P is not a reference type: 3177 // - If A is an array type, the pointer type produced by the 3178 // array-to-pointer standard conversion (4.2) is used in place of 3179 // A for type deduction; otherwise, 3180 if (ArgType->isArrayType()) 3181 ArgType = S.Context.getArrayDecayedType(ArgType); 3182 // - If A is a function type, the pointer type produced by the 3183 // function-to-pointer standard conversion (4.3) is used in place 3184 // of A for type deduction; otherwise, 3185 else if (ArgType->isFunctionType()) 3186 ArgType = S.Context.getPointerType(ArgType); 3187 else { 3188 // - If A is a cv-qualified type, the top level cv-qualifiers of A's 3189 // type are ignored for type deduction. 3190 ArgType = ArgType.getUnqualifiedType(); 3191 } 3192 } 3193 3194 // C++0x [temp.deduct.call]p4: 3195 // In general, the deduction process attempts to find template argument 3196 // values that will make the deduced A identical to A (after the type A 3197 // is transformed as described above). [...] 3198 TDF = TDF_SkipNonDependent; 3199 3200 // - If the original P is a reference type, the deduced A (i.e., the 3201 // type referred to by the reference) can be more cv-qualified than 3202 // the transformed A. 3203 if (ParamRefType) 3204 TDF |= TDF_ParamWithReferenceType; 3205 // - The transformed A can be another pointer or pointer to member 3206 // type that can be converted to the deduced A via a qualification 3207 // conversion (4.4). 3208 if (ArgType->isPointerType() || ArgType->isMemberPointerType() || 3209 ArgType->isObjCObjectPointerType()) 3210 TDF |= TDF_IgnoreQualifiers; 3211 // - If P is a class and P has the form simple-template-id, then the 3212 // transformed A can be a derived class of the deduced A. Likewise, 3213 // if P is a pointer to a class of the form simple-template-id, the 3214 // transformed A can be a pointer to a derived class pointed to by 3215 // the deduced A. 3216 if (isSimpleTemplateIdType(ParamType) || 3217 (isa<PointerType>(ParamType) && 3218 isSimpleTemplateIdType( 3219 ParamType->getAs<PointerType>()->getPointeeType()))) 3220 TDF |= TDF_DerivedClass; 3221 3222 return false; 3223 } 3224 3225 static bool 3226 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate, 3227 QualType T); 3228 3229 /// \brief Perform template argument deduction by matching a parameter type 3230 /// against a single expression, where the expression is an element of 3231 /// an initializer list that was originally matched against a parameter 3232 /// of type \c initializer_list\<ParamType\>. 3233 static Sema::TemplateDeductionResult 3234 DeduceTemplateArgumentByListElement(Sema &S, 3235 TemplateParameterList *TemplateParams, 3236 QualType ParamType, Expr *Arg, 3237 TemplateDeductionInfo &Info, 3238 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3239 unsigned TDF) { 3240 // Handle the case where an init list contains another init list as the 3241 // element. 3242 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 3243 QualType X; 3244 if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X)) 3245 return Sema::TDK_Success; // Just ignore this expression. 3246 3247 // Recurse down into the init list. 3248 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 3249 if (Sema::TemplateDeductionResult Result = 3250 DeduceTemplateArgumentByListElement(S, TemplateParams, X, 3251 ILE->getInit(i), 3252 Info, Deduced, TDF)) 3253 return Result; 3254 } 3255 return Sema::TDK_Success; 3256 } 3257 3258 // For all other cases, just match by type. 3259 QualType ArgType = Arg->getType(); 3260 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType, 3261 ArgType, Arg, TDF)) { 3262 Info.Expression = Arg; 3263 return Sema::TDK_FailedOverloadResolution; 3264 } 3265 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 3266 ArgType, Info, Deduced, TDF); 3267 } 3268 3269 /// \brief Perform template argument deduction from a function call 3270 /// (C++ [temp.deduct.call]). 3271 /// 3272 /// \param FunctionTemplate the function template for which we are performing 3273 /// template argument deduction. 3274 /// 3275 /// \param ExplicitTemplateArgs the explicit template arguments provided 3276 /// for this call. 3277 /// 3278 /// \param Args the function call arguments 3279 /// 3280 /// \param Specialization if template argument deduction was successful, 3281 /// this will be set to the function template specialization produced by 3282 /// template argument deduction. 3283 /// 3284 /// \param Info the argument will be updated to provide additional information 3285 /// about template argument deduction. 3286 /// 3287 /// \returns the result of template argument deduction. 3288 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments( 3289 FunctionTemplateDecl *FunctionTemplate, 3290 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 3291 FunctionDecl *&Specialization, TemplateDeductionInfo &Info, 3292 bool PartialOverloading) { 3293 if (FunctionTemplate->isInvalidDecl()) 3294 return TDK_Invalid; 3295 3296 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 3297 unsigned NumParams = Function->getNumParams(); 3298 3299 // C++ [temp.deduct.call]p1: 3300 // Template argument deduction is done by comparing each function template 3301 // parameter type (call it P) with the type of the corresponding argument 3302 // of the call (call it A) as described below. 3303 unsigned CheckArgs = Args.size(); 3304 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading) 3305 return TDK_TooFewArguments; 3306 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) { 3307 const FunctionProtoType *Proto 3308 = Function->getType()->getAs<FunctionProtoType>(); 3309 if (Proto->isTemplateVariadic()) 3310 /* Do nothing */; 3311 else if (Proto->isVariadic()) 3312 CheckArgs = NumParams; 3313 else 3314 return TDK_TooManyArguments; 3315 } 3316 3317 // The types of the parameters from which we will perform template argument 3318 // deduction. 3319 LocalInstantiationScope InstScope(*this); 3320 TemplateParameterList *TemplateParams 3321 = FunctionTemplate->getTemplateParameters(); 3322 SmallVector<DeducedTemplateArgument, 4> Deduced; 3323 SmallVector<QualType, 4> ParamTypes; 3324 unsigned NumExplicitlySpecified = 0; 3325 if (ExplicitTemplateArgs) { 3326 TemplateDeductionResult Result = 3327 SubstituteExplicitTemplateArguments(FunctionTemplate, 3328 *ExplicitTemplateArgs, 3329 Deduced, 3330 ParamTypes, 3331 nullptr, 3332 Info); 3333 if (Result) 3334 return Result; 3335 3336 NumExplicitlySpecified = Deduced.size(); 3337 } else { 3338 // Just fill in the parameter types from the function declaration. 3339 for (unsigned I = 0; I != NumParams; ++I) 3340 ParamTypes.push_back(Function->getParamDecl(I)->getType()); 3341 } 3342 3343 // Deduce template arguments from the function parameters. 3344 Deduced.resize(TemplateParams->size()); 3345 unsigned ArgIdx = 0; 3346 SmallVector<OriginalCallArg, 4> OriginalCallArgs; 3347 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(); 3348 ParamIdx != NumParamTypes; ++ParamIdx) { 3349 QualType OrigParamType = ParamTypes[ParamIdx]; 3350 QualType ParamType = OrigParamType; 3351 3352 const PackExpansionType *ParamExpansion 3353 = dyn_cast<PackExpansionType>(ParamType); 3354 if (!ParamExpansion) { 3355 // Simple case: matching a function parameter to a function argument. 3356 if (ArgIdx >= CheckArgs) 3357 break; 3358 3359 Expr *Arg = Args[ArgIdx++]; 3360 QualType ArgType = Arg->getType(); 3361 3362 unsigned TDF = 0; 3363 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams, 3364 ParamType, ArgType, Arg, 3365 TDF)) 3366 continue; 3367 3368 // If we have nothing to deduce, we're done. 3369 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType)) 3370 continue; 3371 3372 // If the argument is an initializer list ... 3373 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 3374 // ... then the parameter is an undeduced context, unless the parameter 3375 // type is (reference to cv) std::initializer_list<P'>, in which case 3376 // deduction is done for each element of the initializer list, and the 3377 // result is the deduced type if it's the same for all elements. 3378 QualType X; 3379 // Removing references was already done. 3380 if (!isStdInitializerList(ParamType, &X)) 3381 continue; 3382 3383 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 3384 if (TemplateDeductionResult Result = 3385 DeduceTemplateArgumentByListElement(*this, TemplateParams, X, 3386 ILE->getInit(i), 3387 Info, Deduced, TDF)) 3388 return Result; 3389 } 3390 // Don't track the argument type, since an initializer list has none. 3391 continue; 3392 } 3393 3394 // Keep track of the argument type and corresponding parameter index, 3395 // so we can check for compatibility between the deduced A and A. 3396 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1, 3397 ArgType)); 3398 3399 if (TemplateDeductionResult Result 3400 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 3401 ParamType, ArgType, 3402 Info, Deduced, TDF)) 3403 return Result; 3404 3405 continue; 3406 } 3407 3408 // C++0x [temp.deduct.call]p1: 3409 // For a function parameter pack that occurs at the end of the 3410 // parameter-declaration-list, the type A of each remaining argument of 3411 // the call is compared with the type P of the declarator-id of the 3412 // function parameter pack. Each comparison deduces template arguments 3413 // for subsequent positions in the template parameter packs expanded by 3414 // the function parameter pack. For a function parameter pack that does 3415 // not occur at the end of the parameter-declaration-list, the type of 3416 // the parameter pack is a non-deduced context. 3417 if (ParamIdx + 1 < NumParamTypes) 3418 break; 3419 3420 QualType ParamPattern = ParamExpansion->getPattern(); 3421 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info, 3422 ParamPattern); 3423 3424 bool HasAnyArguments = false; 3425 for (; ArgIdx < Args.size(); ++ArgIdx) { 3426 HasAnyArguments = true; 3427 3428 QualType OrigParamType = ParamPattern; 3429 ParamType = OrigParamType; 3430 Expr *Arg = Args[ArgIdx]; 3431 QualType ArgType = Arg->getType(); 3432 3433 unsigned TDF = 0; 3434 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams, 3435 ParamType, ArgType, Arg, 3436 TDF)) { 3437 // We can't actually perform any deduction for this argument, so stop 3438 // deduction at this point. 3439 ++ArgIdx; 3440 break; 3441 } 3442 3443 // As above, initializer lists need special handling. 3444 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 3445 QualType X; 3446 if (!isStdInitializerList(ParamType, &X)) { 3447 ++ArgIdx; 3448 break; 3449 } 3450 3451 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 3452 if (TemplateDeductionResult Result = 3453 DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, X, 3454 ILE->getInit(i)->getType(), 3455 Info, Deduced, TDF)) 3456 return Result; 3457 } 3458 } else { 3459 3460 // Keep track of the argument type and corresponding argument index, 3461 // so we can check for compatibility between the deduced A and A. 3462 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType)) 3463 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx, 3464 ArgType)); 3465 3466 if (TemplateDeductionResult Result 3467 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 3468 ParamType, ArgType, Info, 3469 Deduced, TDF)) 3470 return Result; 3471 } 3472 3473 PackScope.nextPackElement(); 3474 } 3475 3476 // Build argument packs for each of the parameter packs expanded by this 3477 // pack expansion. 3478 if (auto Result = PackScope.finish(HasAnyArguments)) 3479 return Result; 3480 3481 // After we've matching against a parameter pack, we're done. 3482 break; 3483 } 3484 3485 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 3486 NumExplicitlySpecified, Specialization, 3487 Info, &OriginalCallArgs, 3488 PartialOverloading); 3489 } 3490 3491 QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType, 3492 QualType FunctionType) { 3493 if (ArgFunctionType.isNull()) 3494 return ArgFunctionType; 3495 3496 const FunctionProtoType *FunctionTypeP = 3497 FunctionType->castAs<FunctionProtoType>(); 3498 CallingConv CC = FunctionTypeP->getCallConv(); 3499 bool NoReturn = FunctionTypeP->getNoReturnAttr(); 3500 const FunctionProtoType *ArgFunctionTypeP = 3501 ArgFunctionType->getAs<FunctionProtoType>(); 3502 if (ArgFunctionTypeP->getCallConv() == CC && 3503 ArgFunctionTypeP->getNoReturnAttr() == NoReturn) 3504 return ArgFunctionType; 3505 3506 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC); 3507 EI = EI.withNoReturn(NoReturn); 3508 ArgFunctionTypeP = 3509 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI)); 3510 return QualType(ArgFunctionTypeP, 0); 3511 } 3512 3513 /// \brief Deduce template arguments when taking the address of a function 3514 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to 3515 /// a template. 3516 /// 3517 /// \param FunctionTemplate the function template for which we are performing 3518 /// template argument deduction. 3519 /// 3520 /// \param ExplicitTemplateArgs the explicitly-specified template 3521 /// arguments. 3522 /// 3523 /// \param ArgFunctionType the function type that will be used as the 3524 /// "argument" type (A) when performing template argument deduction from the 3525 /// function template's function type. This type may be NULL, if there is no 3526 /// argument type to compare against, in C++0x [temp.arg.explicit]p3. 3527 /// 3528 /// \param Specialization if template argument deduction was successful, 3529 /// this will be set to the function template specialization produced by 3530 /// template argument deduction. 3531 /// 3532 /// \param Info the argument will be updated to provide additional information 3533 /// about template argument deduction. 3534 /// 3535 /// \returns the result of template argument deduction. 3536 Sema::TemplateDeductionResult 3537 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 3538 TemplateArgumentListInfo *ExplicitTemplateArgs, 3539 QualType ArgFunctionType, 3540 FunctionDecl *&Specialization, 3541 TemplateDeductionInfo &Info, 3542 bool InOverloadResolution) { 3543 if (FunctionTemplate->isInvalidDecl()) 3544 return TDK_Invalid; 3545 3546 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 3547 TemplateParameterList *TemplateParams 3548 = FunctionTemplate->getTemplateParameters(); 3549 QualType FunctionType = Function->getType(); 3550 if (!InOverloadResolution) 3551 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType); 3552 3553 // Substitute any explicit template arguments. 3554 LocalInstantiationScope InstScope(*this); 3555 SmallVector<DeducedTemplateArgument, 4> Deduced; 3556 unsigned NumExplicitlySpecified = 0; 3557 SmallVector<QualType, 4> ParamTypes; 3558 if (ExplicitTemplateArgs) { 3559 if (TemplateDeductionResult Result 3560 = SubstituteExplicitTemplateArguments(FunctionTemplate, 3561 *ExplicitTemplateArgs, 3562 Deduced, ParamTypes, 3563 &FunctionType, Info)) 3564 return Result; 3565 3566 NumExplicitlySpecified = Deduced.size(); 3567 } 3568 3569 // Unevaluated SFINAE context. 3570 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 3571 SFINAETrap Trap(*this); 3572 3573 Deduced.resize(TemplateParams->size()); 3574 3575 // If the function has a deduced return type, substitute it for a dependent 3576 // type so that we treat it as a non-deduced context in what follows. 3577 bool HasDeducedReturnType = false; 3578 if (getLangOpts().CPlusPlus14 && InOverloadResolution && 3579 Function->getReturnType()->getContainedAutoType()) { 3580 FunctionType = SubstAutoType(FunctionType, Context.DependentTy); 3581 HasDeducedReturnType = true; 3582 } 3583 3584 if (!ArgFunctionType.isNull()) { 3585 unsigned TDF = TDF_TopLevelParameterTypeList; 3586 if (InOverloadResolution) TDF |= TDF_InOverloadResolution; 3587 // Deduce template arguments from the function type. 3588 if (TemplateDeductionResult Result 3589 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 3590 FunctionType, ArgFunctionType, 3591 Info, Deduced, TDF)) 3592 return Result; 3593 } 3594 3595 if (TemplateDeductionResult Result 3596 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 3597 NumExplicitlySpecified, 3598 Specialization, Info)) 3599 return Result; 3600 3601 // If the function has a deduced return type, deduce it now, so we can check 3602 // that the deduced function type matches the requested type. 3603 if (HasDeducedReturnType && 3604 Specialization->getReturnType()->isUndeducedType() && 3605 DeduceReturnType(Specialization, Info.getLocation(), false)) 3606 return TDK_MiscellaneousDeductionFailure; 3607 3608 // If the requested function type does not match the actual type of the 3609 // specialization with respect to arguments of compatible pointer to function 3610 // types, template argument deduction fails. 3611 if (!ArgFunctionType.isNull()) { 3612 if (InOverloadResolution && !isSameOrCompatibleFunctionType( 3613 Context.getCanonicalType(Specialization->getType()), 3614 Context.getCanonicalType(ArgFunctionType))) 3615 return TDK_MiscellaneousDeductionFailure; 3616 else if(!InOverloadResolution && 3617 !Context.hasSameType(Specialization->getType(), ArgFunctionType)) 3618 return TDK_MiscellaneousDeductionFailure; 3619 } 3620 3621 return TDK_Success; 3622 } 3623 3624 /// \brief Given a function declaration (e.g. a generic lambda conversion 3625 /// function) that contains an 'auto' in its result type, substitute it 3626 /// with TypeToReplaceAutoWith. Be careful to pass in the type you want 3627 /// to replace 'auto' with and not the actual result type you want 3628 /// to set the function to. 3629 static inline void 3630 SubstAutoWithinFunctionReturnType(FunctionDecl *F, 3631 QualType TypeToReplaceAutoWith, Sema &S) { 3632 assert(!TypeToReplaceAutoWith->getContainedAutoType()); 3633 QualType AutoResultType = F->getReturnType(); 3634 assert(AutoResultType->getContainedAutoType()); 3635 QualType DeducedResultType = S.SubstAutoType(AutoResultType, 3636 TypeToReplaceAutoWith); 3637 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType); 3638 } 3639 3640 /// \brief Given a specialized conversion operator of a generic lambda 3641 /// create the corresponding specializations of the call operator and 3642 /// the static-invoker. If the return type of the call operator is auto, 3643 /// deduce its return type and check if that matches the 3644 /// return type of the destination function ptr. 3645 3646 static inline Sema::TemplateDeductionResult 3647 SpecializeCorrespondingLambdaCallOperatorAndInvoker( 3648 CXXConversionDecl *ConversionSpecialized, 3649 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments, 3650 QualType ReturnTypeOfDestFunctionPtr, 3651 TemplateDeductionInfo &TDInfo, 3652 Sema &S) { 3653 3654 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent(); 3655 assert(LambdaClass && LambdaClass->isGenericLambda()); 3656 3657 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator(); 3658 QualType CallOpResultType = CallOpGeneric->getReturnType(); 3659 const bool GenericLambdaCallOperatorHasDeducedReturnType = 3660 CallOpResultType->getContainedAutoType(); 3661 3662 FunctionTemplateDecl *CallOpTemplate = 3663 CallOpGeneric->getDescribedFunctionTemplate(); 3664 3665 FunctionDecl *CallOpSpecialized = nullptr; 3666 // Use the deduced arguments of the conversion function, to specialize our 3667 // generic lambda's call operator. 3668 if (Sema::TemplateDeductionResult Result 3669 = S.FinishTemplateArgumentDeduction(CallOpTemplate, 3670 DeducedArguments, 3671 0, CallOpSpecialized, TDInfo)) 3672 return Result; 3673 3674 // If we need to deduce the return type, do so (instantiates the callop). 3675 if (GenericLambdaCallOperatorHasDeducedReturnType && 3676 CallOpSpecialized->getReturnType()->isUndeducedType()) 3677 S.DeduceReturnType(CallOpSpecialized, 3678 CallOpSpecialized->getPointOfInstantiation(), 3679 /*Diagnose*/ true); 3680 3681 // Check to see if the return type of the destination ptr-to-function 3682 // matches the return type of the call operator. 3683 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(), 3684 ReturnTypeOfDestFunctionPtr)) 3685 return Sema::TDK_NonDeducedMismatch; 3686 // Since we have succeeded in matching the source and destination 3687 // ptr-to-functions (now including return type), and have successfully 3688 // specialized our corresponding call operator, we are ready to 3689 // specialize the static invoker with the deduced arguments of our 3690 // ptr-to-function. 3691 FunctionDecl *InvokerSpecialized = nullptr; 3692 FunctionTemplateDecl *InvokerTemplate = LambdaClass-> 3693 getLambdaStaticInvoker()->getDescribedFunctionTemplate(); 3694 3695 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result 3696 = S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0, 3697 InvokerSpecialized, TDInfo); 3698 assert(Result == Sema::TDK_Success && 3699 "If the call operator succeeded so should the invoker!"); 3700 // Set the result type to match the corresponding call operator 3701 // specialization's result type. 3702 if (GenericLambdaCallOperatorHasDeducedReturnType && 3703 InvokerSpecialized->getReturnType()->isUndeducedType()) { 3704 // Be sure to get the type to replace 'auto' with and not 3705 // the full result type of the call op specialization 3706 // to substitute into the 'auto' of the invoker and conversion 3707 // function. 3708 // For e.g. 3709 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; }; 3710 // We don't want to subst 'int*' into 'auto' to get int**. 3711 3712 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType() 3713 ->getContainedAutoType() 3714 ->getDeducedType(); 3715 SubstAutoWithinFunctionReturnType(InvokerSpecialized, 3716 TypeToReplaceAutoWith, S); 3717 SubstAutoWithinFunctionReturnType(ConversionSpecialized, 3718 TypeToReplaceAutoWith, S); 3719 } 3720 3721 // Ensure that static invoker doesn't have a const qualifier. 3722 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp 3723 // do not use the CallOperator's TypeSourceInfo which allows 3724 // the const qualifier to leak through. 3725 const FunctionProtoType *InvokerFPT = InvokerSpecialized-> 3726 getType().getTypePtr()->castAs<FunctionProtoType>(); 3727 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo(); 3728 EPI.TypeQuals = 0; 3729 InvokerSpecialized->setType(S.Context.getFunctionType( 3730 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI)); 3731 return Sema::TDK_Success; 3732 } 3733 /// \brief Deduce template arguments for a templated conversion 3734 /// function (C++ [temp.deduct.conv]) and, if successful, produce a 3735 /// conversion function template specialization. 3736 Sema::TemplateDeductionResult 3737 Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate, 3738 QualType ToType, 3739 CXXConversionDecl *&Specialization, 3740 TemplateDeductionInfo &Info) { 3741 if (ConversionTemplate->isInvalidDecl()) 3742 return TDK_Invalid; 3743 3744 CXXConversionDecl *ConversionGeneric 3745 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl()); 3746 3747 QualType FromType = ConversionGeneric->getConversionType(); 3748 3749 // Canonicalize the types for deduction. 3750 QualType P = Context.getCanonicalType(FromType); 3751 QualType A = Context.getCanonicalType(ToType); 3752 3753 // C++0x [temp.deduct.conv]p2: 3754 // If P is a reference type, the type referred to by P is used for 3755 // type deduction. 3756 if (const ReferenceType *PRef = P->getAs<ReferenceType>()) 3757 P = PRef->getPointeeType(); 3758 3759 // C++0x [temp.deduct.conv]p4: 3760 // [...] If A is a reference type, the type referred to by A is used 3761 // for type deduction. 3762 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) 3763 A = ARef->getPointeeType().getUnqualifiedType(); 3764 // C++ [temp.deduct.conv]p3: 3765 // 3766 // If A is not a reference type: 3767 else { 3768 assert(!A->isReferenceType() && "Reference types were handled above"); 3769 3770 // - If P is an array type, the pointer type produced by the 3771 // array-to-pointer standard conversion (4.2) is used in place 3772 // of P for type deduction; otherwise, 3773 if (P->isArrayType()) 3774 P = Context.getArrayDecayedType(P); 3775 // - If P is a function type, the pointer type produced by the 3776 // function-to-pointer standard conversion (4.3) is used in 3777 // place of P for type deduction; otherwise, 3778 else if (P->isFunctionType()) 3779 P = Context.getPointerType(P); 3780 // - If P is a cv-qualified type, the top level cv-qualifiers of 3781 // P's type are ignored for type deduction. 3782 else 3783 P = P.getUnqualifiedType(); 3784 3785 // C++0x [temp.deduct.conv]p4: 3786 // If A is a cv-qualified type, the top level cv-qualifiers of A's 3787 // type are ignored for type deduction. If A is a reference type, the type 3788 // referred to by A is used for type deduction. 3789 A = A.getUnqualifiedType(); 3790 } 3791 3792 // Unevaluated SFINAE context. 3793 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 3794 SFINAETrap Trap(*this); 3795 3796 // C++ [temp.deduct.conv]p1: 3797 // Template argument deduction is done by comparing the return 3798 // type of the template conversion function (call it P) with the 3799 // type that is required as the result of the conversion (call it 3800 // A) as described in 14.8.2.4. 3801 TemplateParameterList *TemplateParams 3802 = ConversionTemplate->getTemplateParameters(); 3803 SmallVector<DeducedTemplateArgument, 4> Deduced; 3804 Deduced.resize(TemplateParams->size()); 3805 3806 // C++0x [temp.deduct.conv]p4: 3807 // In general, the deduction process attempts to find template 3808 // argument values that will make the deduced A identical to 3809 // A. However, there are two cases that allow a difference: 3810 unsigned TDF = 0; 3811 // - If the original A is a reference type, A can be more 3812 // cv-qualified than the deduced A (i.e., the type referred to 3813 // by the reference) 3814 if (ToType->isReferenceType()) 3815 TDF |= TDF_ParamWithReferenceType; 3816 // - The deduced A can be another pointer or pointer to member 3817 // type that can be converted to A via a qualification 3818 // conversion. 3819 // 3820 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when 3821 // both P and A are pointers or member pointers. In this case, we 3822 // just ignore cv-qualifiers completely). 3823 if ((P->isPointerType() && A->isPointerType()) || 3824 (P->isMemberPointerType() && A->isMemberPointerType())) 3825 TDF |= TDF_IgnoreQualifiers; 3826 if (TemplateDeductionResult Result 3827 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 3828 P, A, Info, Deduced, TDF)) 3829 return Result; 3830 3831 // Create an Instantiation Scope for finalizing the operator. 3832 LocalInstantiationScope InstScope(*this); 3833 // Finish template argument deduction. 3834 FunctionDecl *ConversionSpecialized = nullptr; 3835 TemplateDeductionResult Result 3836 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0, 3837 ConversionSpecialized, Info); 3838 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized); 3839 3840 // If the conversion operator is being invoked on a lambda closure to convert 3841 // to a ptr-to-function, use the deduced arguments from the conversion 3842 // function to specialize the corresponding call operator. 3843 // e.g., int (*fp)(int) = [](auto a) { return a; }; 3844 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) { 3845 3846 // Get the return type of the destination ptr-to-function we are converting 3847 // to. This is necessary for matching the lambda call operator's return 3848 // type to that of the destination ptr-to-function's return type. 3849 assert(A->isPointerType() && 3850 "Can only convert from lambda to ptr-to-function"); 3851 const FunctionType *ToFunType = 3852 A->getPointeeType().getTypePtr()->getAs<FunctionType>(); 3853 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType(); 3854 3855 // Create the corresponding specializations of the call operator and 3856 // the static-invoker; and if the return type is auto, 3857 // deduce the return type and check if it matches the 3858 // DestFunctionPtrReturnType. 3859 // For instance: 3860 // auto L = [](auto a) { return f(a); }; 3861 // int (*fp)(int) = L; 3862 // char (*fp2)(int) = L; <-- Not OK. 3863 3864 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker( 3865 Specialization, Deduced, DestFunctionPtrReturnType, 3866 Info, *this); 3867 } 3868 return Result; 3869 } 3870 3871 /// \brief Deduce template arguments for a function template when there is 3872 /// nothing to deduce against (C++0x [temp.arg.explicit]p3). 3873 /// 3874 /// \param FunctionTemplate the function template for which we are performing 3875 /// template argument deduction. 3876 /// 3877 /// \param ExplicitTemplateArgs the explicitly-specified template 3878 /// arguments. 3879 /// 3880 /// \param Specialization if template argument deduction was successful, 3881 /// this will be set to the function template specialization produced by 3882 /// template argument deduction. 3883 /// 3884 /// \param Info the argument will be updated to provide additional information 3885 /// about template argument deduction. 3886 /// 3887 /// \returns the result of template argument deduction. 3888 Sema::TemplateDeductionResult 3889 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 3890 TemplateArgumentListInfo *ExplicitTemplateArgs, 3891 FunctionDecl *&Specialization, 3892 TemplateDeductionInfo &Info, 3893 bool InOverloadResolution) { 3894 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 3895 QualType(), Specialization, Info, 3896 InOverloadResolution); 3897 } 3898 3899 namespace { 3900 /// Substitute the 'auto' type specifier within a type for a given replacement 3901 /// type. 3902 class SubstituteAutoTransform : 3903 public TreeTransform<SubstituteAutoTransform> { 3904 QualType Replacement; 3905 public: 3906 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement) 3907 : TreeTransform<SubstituteAutoTransform>(SemaRef), 3908 Replacement(Replacement) {} 3909 3910 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) { 3911 // If we're building the type pattern to deduce against, don't wrap the 3912 // substituted type in an AutoType. Certain template deduction rules 3913 // apply only when a template type parameter appears directly (and not if 3914 // the parameter is found through desugaring). For instance: 3915 // auto &&lref = lvalue; 3916 // must transform into "rvalue reference to T" not "rvalue reference to 3917 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply. 3918 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) { 3919 QualType Result = Replacement; 3920 TemplateTypeParmTypeLoc NewTL = 3921 TLB.push<TemplateTypeParmTypeLoc>(Result); 3922 NewTL.setNameLoc(TL.getNameLoc()); 3923 return Result; 3924 } else { 3925 bool Dependent = 3926 !Replacement.isNull() && Replacement->isDependentType(); 3927 QualType Result = 3928 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement, 3929 TL.getTypePtr()->isDecltypeAuto(), 3930 Dependent); 3931 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result); 3932 NewTL.setNameLoc(TL.getNameLoc()); 3933 return Result; 3934 } 3935 } 3936 3937 ExprResult TransformLambdaExpr(LambdaExpr *E) { 3938 // Lambdas never need to be transformed. 3939 return E; 3940 } 3941 3942 QualType Apply(TypeLoc TL) { 3943 // Create some scratch storage for the transformed type locations. 3944 // FIXME: We're just going to throw this information away. Don't build it. 3945 TypeLocBuilder TLB; 3946 TLB.reserve(TL.getFullDataSize()); 3947 return TransformType(TLB, TL); 3948 } 3949 }; 3950 } 3951 3952 Sema::DeduceAutoResult 3953 Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) { 3954 return DeduceAutoType(Type->getTypeLoc(), Init, Result); 3955 } 3956 3957 /// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6) 3958 /// 3959 /// \param Type the type pattern using the auto type-specifier. 3960 /// \param Init the initializer for the variable whose type is to be deduced. 3961 /// \param Result if type deduction was successful, this will be set to the 3962 /// deduced type. 3963 Sema::DeduceAutoResult 3964 Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) { 3965 if (Init->getType()->isNonOverloadPlaceholderType()) { 3966 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init); 3967 if (NonPlaceholder.isInvalid()) 3968 return DAR_FailedAlreadyDiagnosed; 3969 Init = NonPlaceholder.get(); 3970 } 3971 3972 if (Init->isTypeDependent() || Type.getType()->isDependentType()) { 3973 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type); 3974 assert(!Result.isNull() && "substituting DependentTy can't fail"); 3975 return DAR_Succeeded; 3976 } 3977 3978 // If this is a 'decltype(auto)' specifier, do the decltype dance. 3979 // Since 'decltype(auto)' can only occur at the top of the type, we 3980 // don't need to go digging for it. 3981 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) { 3982 if (AT->isDecltypeAuto()) { 3983 if (isa<InitListExpr>(Init)) { 3984 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list); 3985 return DAR_FailedAlreadyDiagnosed; 3986 } 3987 3988 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false); 3989 // FIXME: Support a non-canonical deduced type for 'auto'. 3990 Deduced = Context.getCanonicalType(Deduced); 3991 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type); 3992 if (Result.isNull()) 3993 return DAR_FailedAlreadyDiagnosed; 3994 return DAR_Succeeded; 3995 } 3996 } 3997 3998 SourceLocation Loc = Init->getExprLoc(); 3999 4000 LocalInstantiationScope InstScope(*this); 4001 4002 // Build template<class TemplParam> void Func(FuncParam); 4003 TemplateTypeParmDecl *TemplParam = 4004 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0, 4005 nullptr, false, false); 4006 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0); 4007 NamedDecl *TemplParamPtr = TemplParam; 4008 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr, 4009 Loc); 4010 4011 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type); 4012 assert(!FuncParam.isNull() && 4013 "substituting template parameter for 'auto' failed"); 4014 4015 // Deduce type of TemplParam in Func(Init) 4016 SmallVector<DeducedTemplateArgument, 1> Deduced; 4017 Deduced.resize(1); 4018 QualType InitType = Init->getType(); 4019 unsigned TDF = 0; 4020 4021 TemplateDeductionInfo Info(Loc); 4022 4023 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 4024 if (InitList) { 4025 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) { 4026 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams, 4027 TemplArg, 4028 InitList->getInit(i), 4029 Info, Deduced, TDF)) 4030 return DAR_Failed; 4031 } 4032 } else { 4033 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams, 4034 FuncParam, InitType, Init, 4035 TDF)) 4036 return DAR_Failed; 4037 4038 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam, 4039 InitType, Info, Deduced, TDF)) 4040 return DAR_Failed; 4041 } 4042 4043 if (Deduced[0].getKind() != TemplateArgument::Type) 4044 return DAR_Failed; 4045 4046 QualType DeducedType = Deduced[0].getAsType(); 4047 4048 if (InitList) { 4049 DeducedType = BuildStdInitializerList(DeducedType, Loc); 4050 if (DeducedType.isNull()) 4051 return DAR_FailedAlreadyDiagnosed; 4052 } 4053 4054 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type); 4055 if (Result.isNull()) 4056 return DAR_FailedAlreadyDiagnosed; 4057 4058 // Check that the deduced argument type is compatible with the original 4059 // argument type per C++ [temp.deduct.call]p4. 4060 if (!InitList && !Result.isNull() && 4061 CheckOriginalCallArgDeduction(*this, 4062 Sema::OriginalCallArg(FuncParam,0,InitType), 4063 Result)) { 4064 Result = QualType(); 4065 return DAR_Failed; 4066 } 4067 4068 return DAR_Succeeded; 4069 } 4070 4071 QualType Sema::SubstAutoType(QualType TypeWithAuto, 4072 QualType TypeToReplaceAuto) { 4073 return SubstituteAutoTransform(*this, TypeToReplaceAuto). 4074 TransformType(TypeWithAuto); 4075 } 4076 4077 TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 4078 QualType TypeToReplaceAuto) { 4079 return SubstituteAutoTransform(*this, TypeToReplaceAuto). 4080 TransformType(TypeWithAuto); 4081 } 4082 4083 void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) { 4084 if (isa<InitListExpr>(Init)) 4085 Diag(VDecl->getLocation(), 4086 VDecl->isInitCapture() 4087 ? diag::err_init_capture_deduction_failure_from_init_list 4088 : diag::err_auto_var_deduction_failure_from_init_list) 4089 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange(); 4090 else 4091 Diag(VDecl->getLocation(), 4092 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure 4093 : diag::err_auto_var_deduction_failure) 4094 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 4095 << Init->getSourceRange(); 4096 } 4097 4098 bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 4099 bool Diagnose) { 4100 assert(FD->getReturnType()->isUndeducedType()); 4101 4102 if (FD->getTemplateInstantiationPattern()) 4103 InstantiateFunctionDefinition(Loc, FD); 4104 4105 bool StillUndeduced = FD->getReturnType()->isUndeducedType(); 4106 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) { 4107 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD; 4108 Diag(FD->getLocation(), diag::note_callee_decl) << FD; 4109 } 4110 4111 return StillUndeduced; 4112 } 4113 4114 static void 4115 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 4116 bool OnlyDeduced, 4117 unsigned Level, 4118 llvm::SmallBitVector &Deduced); 4119 4120 /// \brief If this is a non-static member function, 4121 static void 4122 AddImplicitObjectParameterType(ASTContext &Context, 4123 CXXMethodDecl *Method, 4124 SmallVectorImpl<QualType> &ArgTypes) { 4125 // C++11 [temp.func.order]p3: 4126 // [...] The new parameter is of type "reference to cv A," where cv are 4127 // the cv-qualifiers of the function template (if any) and A is 4128 // the class of which the function template is a member. 4129 // 4130 // The standard doesn't say explicitly, but we pick the appropriate kind of 4131 // reference type based on [over.match.funcs]p4. 4132 QualType ArgTy = Context.getTypeDeclType(Method->getParent()); 4133 ArgTy = Context.getQualifiedType(ArgTy, 4134 Qualifiers::fromCVRMask(Method->getTypeQualifiers())); 4135 if (Method->getRefQualifier() == RQ_RValue) 4136 ArgTy = Context.getRValueReferenceType(ArgTy); 4137 else 4138 ArgTy = Context.getLValueReferenceType(ArgTy); 4139 ArgTypes.push_back(ArgTy); 4140 } 4141 4142 /// \brief Determine whether the function template \p FT1 is at least as 4143 /// specialized as \p FT2. 4144 static bool isAtLeastAsSpecializedAs(Sema &S, 4145 SourceLocation Loc, 4146 FunctionTemplateDecl *FT1, 4147 FunctionTemplateDecl *FT2, 4148 TemplatePartialOrderingContext TPOC, 4149 unsigned NumCallArguments1, 4150 SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) { 4151 FunctionDecl *FD1 = FT1->getTemplatedDecl(); 4152 FunctionDecl *FD2 = FT2->getTemplatedDecl(); 4153 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>(); 4154 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>(); 4155 4156 assert(Proto1 && Proto2 && "Function templates must have prototypes"); 4157 TemplateParameterList *TemplateParams = FT2->getTemplateParameters(); 4158 SmallVector<DeducedTemplateArgument, 4> Deduced; 4159 Deduced.resize(TemplateParams->size()); 4160 4161 // C++0x [temp.deduct.partial]p3: 4162 // The types used to determine the ordering depend on the context in which 4163 // the partial ordering is done: 4164 TemplateDeductionInfo Info(Loc); 4165 SmallVector<QualType, 4> Args2; 4166 switch (TPOC) { 4167 case TPOC_Call: { 4168 // - In the context of a function call, the function parameter types are 4169 // used. 4170 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1); 4171 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2); 4172 4173 // C++11 [temp.func.order]p3: 4174 // [...] If only one of the function templates is a non-static 4175 // member, that function template is considered to have a new 4176 // first parameter inserted in its function parameter list. The 4177 // new parameter is of type "reference to cv A," where cv are 4178 // the cv-qualifiers of the function template (if any) and A is 4179 // the class of which the function template is a member. 4180 // 4181 // Note that we interpret this to mean "if one of the function 4182 // templates is a non-static member and the other is a non-member"; 4183 // otherwise, the ordering rules for static functions against non-static 4184 // functions don't make any sense. 4185 // 4186 // C++98/03 doesn't have this provision but we've extended DR532 to cover 4187 // it as wording was broken prior to it. 4188 SmallVector<QualType, 4> Args1; 4189 4190 unsigned NumComparedArguments = NumCallArguments1; 4191 4192 if (!Method2 && Method1 && !Method1->isStatic()) { 4193 // Compare 'this' from Method1 against first parameter from Method2. 4194 AddImplicitObjectParameterType(S.Context, Method1, Args1); 4195 ++NumComparedArguments; 4196 } else if (!Method1 && Method2 && !Method2->isStatic()) { 4197 // Compare 'this' from Method2 against first parameter from Method1. 4198 AddImplicitObjectParameterType(S.Context, Method2, Args2); 4199 } 4200 4201 Args1.insert(Args1.end(), Proto1->param_type_begin(), 4202 Proto1->param_type_end()); 4203 Args2.insert(Args2.end(), Proto2->param_type_begin(), 4204 Proto2->param_type_end()); 4205 4206 // C++ [temp.func.order]p5: 4207 // The presence of unused ellipsis and default arguments has no effect on 4208 // the partial ordering of function templates. 4209 if (Args1.size() > NumComparedArguments) 4210 Args1.resize(NumComparedArguments); 4211 if (Args2.size() > NumComparedArguments) 4212 Args2.resize(NumComparedArguments); 4213 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(), 4214 Args1.data(), Args1.size(), Info, Deduced, 4215 TDF_None, /*PartialOrdering=*/true, 4216 RefParamComparisons)) 4217 return false; 4218 4219 break; 4220 } 4221 4222 case TPOC_Conversion: 4223 // - In the context of a call to a conversion operator, the return types 4224 // of the conversion function templates are used. 4225 if (DeduceTemplateArgumentsByTypeMatch( 4226 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(), 4227 Info, Deduced, TDF_None, 4228 /*PartialOrdering=*/true, RefParamComparisons)) 4229 return false; 4230 break; 4231 4232 case TPOC_Other: 4233 // - In other contexts (14.6.6.2) the function template's function type 4234 // is used. 4235 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 4236 FD2->getType(), FD1->getType(), 4237 Info, Deduced, TDF_None, 4238 /*PartialOrdering=*/true, 4239 RefParamComparisons)) 4240 return false; 4241 break; 4242 } 4243 4244 // C++0x [temp.deduct.partial]p11: 4245 // In most cases, all template parameters must have values in order for 4246 // deduction to succeed, but for partial ordering purposes a template 4247 // parameter may remain without a value provided it is not used in the 4248 // types being used for partial ordering. [ Note: a template parameter used 4249 // in a non-deduced context is considered used. -end note] 4250 unsigned ArgIdx = 0, NumArgs = Deduced.size(); 4251 for (; ArgIdx != NumArgs; ++ArgIdx) 4252 if (Deduced[ArgIdx].isNull()) 4253 break; 4254 4255 if (ArgIdx == NumArgs) { 4256 // All template arguments were deduced. FT1 is at least as specialized 4257 // as FT2. 4258 return true; 4259 } 4260 4261 // Figure out which template parameters were used. 4262 llvm::SmallBitVector UsedParameters(TemplateParams->size()); 4263 switch (TPOC) { 4264 case TPOC_Call: 4265 for (unsigned I = 0, N = Args2.size(); I != N; ++I) 4266 ::MarkUsedTemplateParameters(S.Context, Args2[I], false, 4267 TemplateParams->getDepth(), 4268 UsedParameters); 4269 break; 4270 4271 case TPOC_Conversion: 4272 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false, 4273 TemplateParams->getDepth(), UsedParameters); 4274 break; 4275 4276 case TPOC_Other: 4277 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false, 4278 TemplateParams->getDepth(), 4279 UsedParameters); 4280 break; 4281 } 4282 4283 for (; ArgIdx != NumArgs; ++ArgIdx) 4284 // If this argument had no value deduced but was used in one of the types 4285 // used for partial ordering, then deduction fails. 4286 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx]) 4287 return false; 4288 4289 return true; 4290 } 4291 4292 /// \brief Determine whether this a function template whose parameter-type-list 4293 /// ends with a function parameter pack. 4294 static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) { 4295 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 4296 unsigned NumParams = Function->getNumParams(); 4297 if (NumParams == 0) 4298 return false; 4299 4300 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1); 4301 if (!Last->isParameterPack()) 4302 return false; 4303 4304 // Make sure that no previous parameter is a parameter pack. 4305 while (--NumParams > 0) { 4306 if (Function->getParamDecl(NumParams - 1)->isParameterPack()) 4307 return false; 4308 } 4309 4310 return true; 4311 } 4312 4313 /// \brief Returns the more specialized function template according 4314 /// to the rules of function template partial ordering (C++ [temp.func.order]). 4315 /// 4316 /// \param FT1 the first function template 4317 /// 4318 /// \param FT2 the second function template 4319 /// 4320 /// \param TPOC the context in which we are performing partial ordering of 4321 /// function templates. 4322 /// 4323 /// \param NumCallArguments1 The number of arguments in the call to FT1, used 4324 /// only when \c TPOC is \c TPOC_Call. 4325 /// 4326 /// \param NumCallArguments2 The number of arguments in the call to FT2, used 4327 /// only when \c TPOC is \c TPOC_Call. 4328 /// 4329 /// \returns the more specialized function template. If neither 4330 /// template is more specialized, returns NULL. 4331 FunctionTemplateDecl * 4332 Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 4333 FunctionTemplateDecl *FT2, 4334 SourceLocation Loc, 4335 TemplatePartialOrderingContext TPOC, 4336 unsigned NumCallArguments1, 4337 unsigned NumCallArguments2) { 4338 SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons; 4339 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 4340 NumCallArguments1, nullptr); 4341 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, 4342 NumCallArguments2, 4343 &RefParamComparisons); 4344 4345 if (Better1 != Better2) // We have a clear winner 4346 return Better1? FT1 : FT2; 4347 4348 if (!Better1 && !Better2) // Neither is better than the other 4349 return nullptr; 4350 4351 // C++0x [temp.deduct.partial]p10: 4352 // If for each type being considered a given template is at least as 4353 // specialized for all types and more specialized for some set of types and 4354 // the other template is not more specialized for any types or is not at 4355 // least as specialized for any types, then the given template is more 4356 // specialized than the other template. Otherwise, neither template is more 4357 // specialized than the other. 4358 Better1 = false; 4359 Better2 = false; 4360 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) { 4361 // C++0x [temp.deduct.partial]p9: 4362 // If, for a given type, deduction succeeds in both directions (i.e., the 4363 // types are identical after the transformations above) and both P and A 4364 // were reference types (before being replaced with the type referred to 4365 // above): 4366 4367 // -- if the type from the argument template was an lvalue reference 4368 // and the type from the parameter template was not, the argument 4369 // type is considered to be more specialized than the other; 4370 // otherwise, 4371 if (!RefParamComparisons[I].ArgIsRvalueRef && 4372 RefParamComparisons[I].ParamIsRvalueRef) { 4373 Better2 = true; 4374 if (Better1) 4375 return nullptr; 4376 continue; 4377 } else if (!RefParamComparisons[I].ParamIsRvalueRef && 4378 RefParamComparisons[I].ArgIsRvalueRef) { 4379 Better1 = true; 4380 if (Better2) 4381 return nullptr; 4382 continue; 4383 } 4384 4385 // -- if the type from the argument template is more cv-qualified than 4386 // the type from the parameter template (as described above), the 4387 // argument type is considered to be more specialized than the 4388 // other; otherwise, 4389 switch (RefParamComparisons[I].Qualifiers) { 4390 case NeitherMoreQualified: 4391 break; 4392 4393 case ParamMoreQualified: 4394 Better1 = true; 4395 if (Better2) 4396 return nullptr; 4397 continue; 4398 4399 case ArgMoreQualified: 4400 Better2 = true; 4401 if (Better1) 4402 return nullptr; 4403 continue; 4404 } 4405 4406 // -- neither type is more specialized than the other. 4407 } 4408 4409 assert(!(Better1 && Better2) && "Should have broken out in the loop above"); 4410 if (Better1) 4411 return FT1; 4412 else if (Better2) 4413 return FT2; 4414 4415 // FIXME: This mimics what GCC implements, but doesn't match up with the 4416 // proposed resolution for core issue 692. This area needs to be sorted out, 4417 // but for now we attempt to maintain compatibility. 4418 bool Variadic1 = isVariadicFunctionTemplate(FT1); 4419 bool Variadic2 = isVariadicFunctionTemplate(FT2); 4420 if (Variadic1 != Variadic2) 4421 return Variadic1? FT2 : FT1; 4422 4423 return nullptr; 4424 } 4425 4426 /// \brief Determine if the two templates are equivalent. 4427 static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) { 4428 if (T1 == T2) 4429 return true; 4430 4431 if (!T1 || !T2) 4432 return false; 4433 4434 return T1->getCanonicalDecl() == T2->getCanonicalDecl(); 4435 } 4436 4437 /// \brief Retrieve the most specialized of the given function template 4438 /// specializations. 4439 /// 4440 /// \param SpecBegin the start iterator of the function template 4441 /// specializations that we will be comparing. 4442 /// 4443 /// \param SpecEnd the end iterator of the function template 4444 /// specializations, paired with \p SpecBegin. 4445 /// 4446 /// \param Loc the location where the ambiguity or no-specializations 4447 /// diagnostic should occur. 4448 /// 4449 /// \param NoneDiag partial diagnostic used to diagnose cases where there are 4450 /// no matching candidates. 4451 /// 4452 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one 4453 /// occurs. 4454 /// 4455 /// \param CandidateDiag partial diagnostic used for each function template 4456 /// specialization that is a candidate in the ambiguous ordering. One parameter 4457 /// in this diagnostic should be unbound, which will correspond to the string 4458 /// describing the template arguments for the function template specialization. 4459 /// 4460 /// \returns the most specialized function template specialization, if 4461 /// found. Otherwise, returns SpecEnd. 4462 UnresolvedSetIterator Sema::getMostSpecialized( 4463 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd, 4464 TemplateSpecCandidateSet &FailedCandidates, 4465 SourceLocation Loc, const PartialDiagnostic &NoneDiag, 4466 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, 4467 bool Complain, QualType TargetType) { 4468 if (SpecBegin == SpecEnd) { 4469 if (Complain) { 4470 Diag(Loc, NoneDiag); 4471 FailedCandidates.NoteCandidates(*this, Loc); 4472 } 4473 return SpecEnd; 4474 } 4475 4476 if (SpecBegin + 1 == SpecEnd) 4477 return SpecBegin; 4478 4479 // Find the function template that is better than all of the templates it 4480 // has been compared to. 4481 UnresolvedSetIterator Best = SpecBegin; 4482 FunctionTemplateDecl *BestTemplate 4483 = cast<FunctionDecl>(*Best)->getPrimaryTemplate(); 4484 assert(BestTemplate && "Not a function template specialization?"); 4485 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) { 4486 FunctionTemplateDecl *Challenger 4487 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 4488 assert(Challenger && "Not a function template specialization?"); 4489 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 4490 Loc, TPOC_Other, 0, 0), 4491 Challenger)) { 4492 Best = I; 4493 BestTemplate = Challenger; 4494 } 4495 } 4496 4497 // Make sure that the "best" function template is more specialized than all 4498 // of the others. 4499 bool Ambiguous = false; 4500 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 4501 FunctionTemplateDecl *Challenger 4502 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 4503 if (I != Best && 4504 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 4505 Loc, TPOC_Other, 0, 0), 4506 BestTemplate)) { 4507 Ambiguous = true; 4508 break; 4509 } 4510 } 4511 4512 if (!Ambiguous) { 4513 // We found an answer. Return it. 4514 return Best; 4515 } 4516 4517 // Diagnose the ambiguity. 4518 if (Complain) { 4519 Diag(Loc, AmbigDiag); 4520 4521 // FIXME: Can we order the candidates in some sane way? 4522 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 4523 PartialDiagnostic PD = CandidateDiag; 4524 PD << getTemplateArgumentBindingsText( 4525 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(), 4526 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs()); 4527 if (!TargetType.isNull()) 4528 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(), 4529 TargetType); 4530 Diag((*I)->getLocation(), PD); 4531 } 4532 } 4533 4534 return SpecEnd; 4535 } 4536 4537 /// \brief Returns the more specialized class template partial specialization 4538 /// according to the rules of partial ordering of class template partial 4539 /// specializations (C++ [temp.class.order]). 4540 /// 4541 /// \param PS1 the first class template partial specialization 4542 /// 4543 /// \param PS2 the second class template partial specialization 4544 /// 4545 /// \returns the more specialized class template partial specialization. If 4546 /// neither partial specialization is more specialized, returns NULL. 4547 ClassTemplatePartialSpecializationDecl * 4548 Sema::getMoreSpecializedPartialSpecialization( 4549 ClassTemplatePartialSpecializationDecl *PS1, 4550 ClassTemplatePartialSpecializationDecl *PS2, 4551 SourceLocation Loc) { 4552 // C++ [temp.class.order]p1: 4553 // For two class template partial specializations, the first is at least as 4554 // specialized as the second if, given the following rewrite to two 4555 // function templates, the first function template is at least as 4556 // specialized as the second according to the ordering rules for function 4557 // templates (14.6.6.2): 4558 // - the first function template has the same template parameters as the 4559 // first partial specialization and has a single function parameter 4560 // whose type is a class template specialization with the template 4561 // arguments of the first partial specialization, and 4562 // - the second function template has the same template parameters as the 4563 // second partial specialization and has a single function parameter 4564 // whose type is a class template specialization with the template 4565 // arguments of the second partial specialization. 4566 // 4567 // Rather than synthesize function templates, we merely perform the 4568 // equivalent partial ordering by performing deduction directly on 4569 // the template arguments of the class template partial 4570 // specializations. This computation is slightly simpler than the 4571 // general problem of function template partial ordering, because 4572 // class template partial specializations are more constrained. We 4573 // know that every template parameter is deducible from the class 4574 // template partial specialization's template arguments, for 4575 // example. 4576 SmallVector<DeducedTemplateArgument, 4> Deduced; 4577 TemplateDeductionInfo Info(Loc); 4578 4579 QualType PT1 = PS1->getInjectedSpecializationType(); 4580 QualType PT2 = PS2->getInjectedSpecializationType(); 4581 4582 // Determine whether PS1 is at least as specialized as PS2 4583 Deduced.resize(PS2->getTemplateParameters()->size()); 4584 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this, 4585 PS2->getTemplateParameters(), 4586 PT2, PT1, Info, Deduced, TDF_None, 4587 /*PartialOrdering=*/true, 4588 /*RefParamComparisons=*/nullptr); 4589 if (Better1) { 4590 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end()); 4591 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info); 4592 Better1 = !::FinishTemplateArgumentDeduction( 4593 *this, PS2, PS1->getTemplateArgs(), Deduced, Info); 4594 } 4595 4596 // Determine whether PS2 is at least as specialized as PS1 4597 Deduced.clear(); 4598 Deduced.resize(PS1->getTemplateParameters()->size()); 4599 bool Better2 = !DeduceTemplateArgumentsByTypeMatch( 4600 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None, 4601 /*PartialOrdering=*/true, 4602 /*RefParamComparisons=*/nullptr); 4603 if (Better2) { 4604 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), 4605 Deduced.end()); 4606 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info); 4607 Better2 = !::FinishTemplateArgumentDeduction( 4608 *this, PS1, PS2->getTemplateArgs(), Deduced, Info); 4609 } 4610 4611 if (Better1 == Better2) 4612 return nullptr; 4613 4614 return Better1 ? PS1 : PS2; 4615 } 4616 4617 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version? 4618 /// May require unifying ClassTemplate(Partial)SpecializationDecl and 4619 /// VarTemplate(Partial)SpecializationDecl with a new data 4620 /// structure Template(Partial)SpecializationDecl, and 4621 /// using Template(Partial)SpecializationDecl as input type. 4622 VarTemplatePartialSpecializationDecl * 4623 Sema::getMoreSpecializedPartialSpecialization( 4624 VarTemplatePartialSpecializationDecl *PS1, 4625 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) { 4626 SmallVector<DeducedTemplateArgument, 4> Deduced; 4627 TemplateDeductionInfo Info(Loc); 4628 4629 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && 4630 "the partial specializations being compared should specialize" 4631 " the same template."); 4632 TemplateName Name(PS1->getSpecializedTemplate()); 4633 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 4634 QualType PT1 = Context.getTemplateSpecializationType( 4635 CanonTemplate, PS1->getTemplateArgs().data(), 4636 PS1->getTemplateArgs().size()); 4637 QualType PT2 = Context.getTemplateSpecializationType( 4638 CanonTemplate, PS2->getTemplateArgs().data(), 4639 PS2->getTemplateArgs().size()); 4640 4641 // Determine whether PS1 is at least as specialized as PS2 4642 Deduced.resize(PS2->getTemplateParameters()->size()); 4643 bool Better1 = !DeduceTemplateArgumentsByTypeMatch( 4644 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None, 4645 /*PartialOrdering=*/true, 4646 /*RefParamComparisons=*/nullptr); 4647 if (Better1) { 4648 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), 4649 Deduced.end()); 4650 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info); 4651 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2, 4652 PS1->getTemplateArgs(), 4653 Deduced, Info); 4654 } 4655 4656 // Determine whether PS2 is at least as specialized as PS1 4657 Deduced.clear(); 4658 Deduced.resize(PS1->getTemplateParameters()->size()); 4659 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this, 4660 PS1->getTemplateParameters(), 4661 PT1, PT2, Info, Deduced, TDF_None, 4662 /*PartialOrdering=*/true, 4663 /*RefParamComparisons=*/nullptr); 4664 if (Better2) { 4665 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end()); 4666 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info); 4667 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1, 4668 PS2->getTemplateArgs(), 4669 Deduced, Info); 4670 } 4671 4672 if (Better1 == Better2) 4673 return nullptr; 4674 4675 return Better1? PS1 : PS2; 4676 } 4677 4678 static void 4679 MarkUsedTemplateParameters(ASTContext &Ctx, 4680 const TemplateArgument &TemplateArg, 4681 bool OnlyDeduced, 4682 unsigned Depth, 4683 llvm::SmallBitVector &Used); 4684 4685 /// \brief Mark the template parameters that are used by the given 4686 /// expression. 4687 static void 4688 MarkUsedTemplateParameters(ASTContext &Ctx, 4689 const Expr *E, 4690 bool OnlyDeduced, 4691 unsigned Depth, 4692 llvm::SmallBitVector &Used) { 4693 // We can deduce from a pack expansion. 4694 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E)) 4695 E = Expansion->getPattern(); 4696 4697 // Skip through any implicit casts we added while type-checking, and any 4698 // substitutions performed by template alias expansion. 4699 while (1) { 4700 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 4701 E = ICE->getSubExpr(); 4702 else if (const SubstNonTypeTemplateParmExpr *Subst = 4703 dyn_cast<SubstNonTypeTemplateParmExpr>(E)) 4704 E = Subst->getReplacement(); 4705 else 4706 break; 4707 } 4708 4709 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to 4710 // find other occurrences of template parameters. 4711 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 4712 if (!DRE) 4713 return; 4714 4715 const NonTypeTemplateParmDecl *NTTP 4716 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 4717 if (!NTTP) 4718 return; 4719 4720 if (NTTP->getDepth() == Depth) 4721 Used[NTTP->getIndex()] = true; 4722 } 4723 4724 /// \brief Mark the template parameters that are used by the given 4725 /// nested name specifier. 4726 static void 4727 MarkUsedTemplateParameters(ASTContext &Ctx, 4728 NestedNameSpecifier *NNS, 4729 bool OnlyDeduced, 4730 unsigned Depth, 4731 llvm::SmallBitVector &Used) { 4732 if (!NNS) 4733 return; 4734 4735 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth, 4736 Used); 4737 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0), 4738 OnlyDeduced, Depth, Used); 4739 } 4740 4741 /// \brief Mark the template parameters that are used by the given 4742 /// template name. 4743 static void 4744 MarkUsedTemplateParameters(ASTContext &Ctx, 4745 TemplateName Name, 4746 bool OnlyDeduced, 4747 unsigned Depth, 4748 llvm::SmallBitVector &Used) { 4749 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 4750 if (TemplateTemplateParmDecl *TTP 4751 = dyn_cast<TemplateTemplateParmDecl>(Template)) { 4752 if (TTP->getDepth() == Depth) 4753 Used[TTP->getIndex()] = true; 4754 } 4755 return; 4756 } 4757 4758 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) 4759 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced, 4760 Depth, Used); 4761 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) 4762 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced, 4763 Depth, Used); 4764 } 4765 4766 /// \brief Mark the template parameters that are used by the given 4767 /// type. 4768 static void 4769 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 4770 bool OnlyDeduced, 4771 unsigned Depth, 4772 llvm::SmallBitVector &Used) { 4773 if (T.isNull()) 4774 return; 4775 4776 // Non-dependent types have nothing deducible 4777 if (!T->isDependentType()) 4778 return; 4779 4780 T = Ctx.getCanonicalType(T); 4781 switch (T->getTypeClass()) { 4782 case Type::Pointer: 4783 MarkUsedTemplateParameters(Ctx, 4784 cast<PointerType>(T)->getPointeeType(), 4785 OnlyDeduced, 4786 Depth, 4787 Used); 4788 break; 4789 4790 case Type::BlockPointer: 4791 MarkUsedTemplateParameters(Ctx, 4792 cast<BlockPointerType>(T)->getPointeeType(), 4793 OnlyDeduced, 4794 Depth, 4795 Used); 4796 break; 4797 4798 case Type::LValueReference: 4799 case Type::RValueReference: 4800 MarkUsedTemplateParameters(Ctx, 4801 cast<ReferenceType>(T)->getPointeeType(), 4802 OnlyDeduced, 4803 Depth, 4804 Used); 4805 break; 4806 4807 case Type::MemberPointer: { 4808 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr()); 4809 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced, 4810 Depth, Used); 4811 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0), 4812 OnlyDeduced, Depth, Used); 4813 break; 4814 } 4815 4816 case Type::DependentSizedArray: 4817 MarkUsedTemplateParameters(Ctx, 4818 cast<DependentSizedArrayType>(T)->getSizeExpr(), 4819 OnlyDeduced, Depth, Used); 4820 // Fall through to check the element type 4821 4822 case Type::ConstantArray: 4823 case Type::IncompleteArray: 4824 MarkUsedTemplateParameters(Ctx, 4825 cast<ArrayType>(T)->getElementType(), 4826 OnlyDeduced, Depth, Used); 4827 break; 4828 4829 case Type::Vector: 4830 case Type::ExtVector: 4831 MarkUsedTemplateParameters(Ctx, 4832 cast<VectorType>(T)->getElementType(), 4833 OnlyDeduced, Depth, Used); 4834 break; 4835 4836 case Type::DependentSizedExtVector: { 4837 const DependentSizedExtVectorType *VecType 4838 = cast<DependentSizedExtVectorType>(T); 4839 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced, 4840 Depth, Used); 4841 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, 4842 Depth, Used); 4843 break; 4844 } 4845 4846 case Type::FunctionProto: { 4847 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 4848 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth, 4849 Used); 4850 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) 4851 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced, 4852 Depth, Used); 4853 break; 4854 } 4855 4856 case Type::TemplateTypeParm: { 4857 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T); 4858 if (TTP->getDepth() == Depth) 4859 Used[TTP->getIndex()] = true; 4860 break; 4861 } 4862 4863 case Type::SubstTemplateTypeParmPack: { 4864 const SubstTemplateTypeParmPackType *Subst 4865 = cast<SubstTemplateTypeParmPackType>(T); 4866 MarkUsedTemplateParameters(Ctx, 4867 QualType(Subst->getReplacedParameter(), 0), 4868 OnlyDeduced, Depth, Used); 4869 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), 4870 OnlyDeduced, Depth, Used); 4871 break; 4872 } 4873 4874 case Type::InjectedClassName: 4875 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType(); 4876 // fall through 4877 4878 case Type::TemplateSpecialization: { 4879 const TemplateSpecializationType *Spec 4880 = cast<TemplateSpecializationType>(T); 4881 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced, 4882 Depth, Used); 4883 4884 // C++0x [temp.deduct.type]p9: 4885 // If the template argument list of P contains a pack expansion that is 4886 // not the last template argument, the entire template argument list is a 4887 // non-deduced context. 4888 if (OnlyDeduced && 4889 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs())) 4890 break; 4891 4892 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 4893 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 4894 Used); 4895 break; 4896 } 4897 4898 case Type::Complex: 4899 if (!OnlyDeduced) 4900 MarkUsedTemplateParameters(Ctx, 4901 cast<ComplexType>(T)->getElementType(), 4902 OnlyDeduced, Depth, Used); 4903 break; 4904 4905 case Type::Atomic: 4906 if (!OnlyDeduced) 4907 MarkUsedTemplateParameters(Ctx, 4908 cast<AtomicType>(T)->getValueType(), 4909 OnlyDeduced, Depth, Used); 4910 break; 4911 4912 case Type::DependentName: 4913 if (!OnlyDeduced) 4914 MarkUsedTemplateParameters(Ctx, 4915 cast<DependentNameType>(T)->getQualifier(), 4916 OnlyDeduced, Depth, Used); 4917 break; 4918 4919 case Type::DependentTemplateSpecialization: { 4920 const DependentTemplateSpecializationType *Spec 4921 = cast<DependentTemplateSpecializationType>(T); 4922 if (!OnlyDeduced) 4923 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(), 4924 OnlyDeduced, Depth, Used); 4925 4926 // C++0x [temp.deduct.type]p9: 4927 // If the template argument list of P contains a pack expansion that is not 4928 // the last template argument, the entire template argument list is a 4929 // non-deduced context. 4930 if (OnlyDeduced && 4931 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs())) 4932 break; 4933 4934 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 4935 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 4936 Used); 4937 break; 4938 } 4939 4940 case Type::TypeOf: 4941 if (!OnlyDeduced) 4942 MarkUsedTemplateParameters(Ctx, 4943 cast<TypeOfType>(T)->getUnderlyingType(), 4944 OnlyDeduced, Depth, Used); 4945 break; 4946 4947 case Type::TypeOfExpr: 4948 if (!OnlyDeduced) 4949 MarkUsedTemplateParameters(Ctx, 4950 cast<TypeOfExprType>(T)->getUnderlyingExpr(), 4951 OnlyDeduced, Depth, Used); 4952 break; 4953 4954 case Type::Decltype: 4955 if (!OnlyDeduced) 4956 MarkUsedTemplateParameters(Ctx, 4957 cast<DecltypeType>(T)->getUnderlyingExpr(), 4958 OnlyDeduced, Depth, Used); 4959 break; 4960 4961 case Type::UnaryTransform: 4962 if (!OnlyDeduced) 4963 MarkUsedTemplateParameters(Ctx, 4964 cast<UnaryTransformType>(T)->getUnderlyingType(), 4965 OnlyDeduced, Depth, Used); 4966 break; 4967 4968 case Type::PackExpansion: 4969 MarkUsedTemplateParameters(Ctx, 4970 cast<PackExpansionType>(T)->getPattern(), 4971 OnlyDeduced, Depth, Used); 4972 break; 4973 4974 case Type::Auto: 4975 MarkUsedTemplateParameters(Ctx, 4976 cast<AutoType>(T)->getDeducedType(), 4977 OnlyDeduced, Depth, Used); 4978 4979 // None of these types have any template parameters in them. 4980 case Type::Builtin: 4981 case Type::VariableArray: 4982 case Type::FunctionNoProto: 4983 case Type::Record: 4984 case Type::Enum: 4985 case Type::ObjCInterface: 4986 case Type::ObjCObject: 4987 case Type::ObjCObjectPointer: 4988 case Type::UnresolvedUsing: 4989 #define TYPE(Class, Base) 4990 #define ABSTRACT_TYPE(Class, Base) 4991 #define DEPENDENT_TYPE(Class, Base) 4992 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 4993 #include "clang/AST/TypeNodes.def" 4994 break; 4995 } 4996 } 4997 4998 /// \brief Mark the template parameters that are used by this 4999 /// template argument. 5000 static void 5001 MarkUsedTemplateParameters(ASTContext &Ctx, 5002 const TemplateArgument &TemplateArg, 5003 bool OnlyDeduced, 5004 unsigned Depth, 5005 llvm::SmallBitVector &Used) { 5006 switch (TemplateArg.getKind()) { 5007 case TemplateArgument::Null: 5008 case TemplateArgument::Integral: 5009 case TemplateArgument::Declaration: 5010 break; 5011 5012 case TemplateArgument::NullPtr: 5013 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced, 5014 Depth, Used); 5015 break; 5016 5017 case TemplateArgument::Type: 5018 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced, 5019 Depth, Used); 5020 break; 5021 5022 case TemplateArgument::Template: 5023 case TemplateArgument::TemplateExpansion: 5024 MarkUsedTemplateParameters(Ctx, 5025 TemplateArg.getAsTemplateOrTemplatePattern(), 5026 OnlyDeduced, Depth, Used); 5027 break; 5028 5029 case TemplateArgument::Expression: 5030 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced, 5031 Depth, Used); 5032 break; 5033 5034 case TemplateArgument::Pack: 5035 for (const auto &P : TemplateArg.pack_elements()) 5036 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used); 5037 break; 5038 } 5039 } 5040 5041 /// \brief Mark which template parameters can be deduced from a given 5042 /// template argument list. 5043 /// 5044 /// \param TemplateArgs the template argument list from which template 5045 /// parameters will be deduced. 5046 /// 5047 /// \param Used a bit vector whose elements will be set to \c true 5048 /// to indicate when the corresponding template parameter will be 5049 /// deduced. 5050 void 5051 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 5052 bool OnlyDeduced, unsigned Depth, 5053 llvm::SmallBitVector &Used) { 5054 // C++0x [temp.deduct.type]p9: 5055 // If the template argument list of P contains a pack expansion that is not 5056 // the last template argument, the entire template argument list is a 5057 // non-deduced context. 5058 if (OnlyDeduced && 5059 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size())) 5060 return; 5061 5062 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 5063 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced, 5064 Depth, Used); 5065 } 5066 5067 /// \brief Marks all of the template parameters that will be deduced by a 5068 /// call to the given function template. 5069 void Sema::MarkDeducedTemplateParameters( 5070 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, 5071 llvm::SmallBitVector &Deduced) { 5072 TemplateParameterList *TemplateParams 5073 = FunctionTemplate->getTemplateParameters(); 5074 Deduced.clear(); 5075 Deduced.resize(TemplateParams->size()); 5076 5077 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 5078 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) 5079 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(), 5080 true, TemplateParams->getDepth(), Deduced); 5081 } 5082 5083 bool hasDeducibleTemplateParameters(Sema &S, 5084 FunctionTemplateDecl *FunctionTemplate, 5085 QualType T) { 5086 if (!T->isDependentType()) 5087 return false; 5088 5089 TemplateParameterList *TemplateParams 5090 = FunctionTemplate->getTemplateParameters(); 5091 llvm::SmallBitVector Deduced(TemplateParams->size()); 5092 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(), 5093 Deduced); 5094 5095 return Deduced.any(); 5096 } 5097