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