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