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