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