1 //===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 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 "TypeLocBuilder.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclAccessPair.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NestedNameSpecifier.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TemplateBase.h" 29 #include "clang/AST/TemplateName.h" 30 #include "clang/AST/Type.h" 31 #include "clang/AST/TypeLoc.h" 32 #include "clang/AST/UnresolvedSet.h" 33 #include "clang/Basic/AddressSpaces.h" 34 #include "clang/Basic/ExceptionSpecificationType.h" 35 #include "clang/Basic/LLVM.h" 36 #include "clang/Basic/LangOptions.h" 37 #include "clang/Basic/PartialDiagnostic.h" 38 #include "clang/Basic/SourceLocation.h" 39 #include "clang/Basic/Specifiers.h" 40 #include "clang/Sema/Ownership.h" 41 #include "clang/Sema/Sema.h" 42 #include "clang/Sema/Template.h" 43 #include "llvm/ADT/APInt.h" 44 #include "llvm/ADT/APSInt.h" 45 #include "llvm/ADT/ArrayRef.h" 46 #include "llvm/ADT/DenseMap.h" 47 #include "llvm/ADT/FoldingSet.h" 48 #include "llvm/ADT/Optional.h" 49 #include "llvm/ADT/SmallBitVector.h" 50 #include "llvm/ADT/SmallPtrSet.h" 51 #include "llvm/ADT/SmallVector.h" 52 #include "llvm/Support/Casting.h" 53 #include "llvm/Support/Compiler.h" 54 #include "llvm/Support/ErrorHandling.h" 55 #include <algorithm> 56 #include <cassert> 57 #include <tuple> 58 #include <utility> 59 60 namespace clang { 61 62 /// Various flags that control template argument deduction. 63 /// 64 /// These flags can be bitwise-OR'd together. 65 enum TemplateDeductionFlags { 66 /// No template argument deduction flags, which indicates the 67 /// strictest results for template argument deduction (as used for, e.g., 68 /// matching class template partial specializations). 69 TDF_None = 0, 70 71 /// Within template argument deduction from a function call, we are 72 /// matching with a parameter type for which the original parameter was 73 /// a reference. 74 TDF_ParamWithReferenceType = 0x1, 75 76 /// Within template argument deduction from a function call, we 77 /// are matching in a case where we ignore cv-qualifiers. 78 TDF_IgnoreQualifiers = 0x02, 79 80 /// Within template argument deduction from a function call, 81 /// we are matching in a case where we can perform template argument 82 /// deduction from a template-id of a derived class of the argument type. 83 TDF_DerivedClass = 0x04, 84 85 /// Allow non-dependent types to differ, e.g., when performing 86 /// template argument deduction from a function call where conversions 87 /// may apply. 88 TDF_SkipNonDependent = 0x08, 89 90 /// Whether we are performing template argument deduction for 91 /// parameters and arguments in a top-level template argument 92 TDF_TopLevelParameterTypeList = 0x10, 93 94 /// Within template argument deduction from overload resolution per 95 /// C++ [over.over] allow matching function types that are compatible in 96 /// terms of noreturn and default calling convention adjustments, or 97 /// similarly matching a declared template specialization against a 98 /// possible template, per C++ [temp.deduct.decl]. In either case, permit 99 /// deduction where the parameter is a function type that can be converted 100 /// to the argument type. 101 TDF_AllowCompatibleFunctionType = 0x20, 102 103 /// Within template argument deduction for a conversion function, we are 104 /// matching with an argument type for which the original argument was 105 /// a reference. 106 TDF_ArgWithReferenceType = 0x40, 107 }; 108 } 109 110 using namespace clang; 111 using namespace sema; 112 113 /// Compare two APSInts, extending and switching the sign as 114 /// necessary to compare their values regardless of underlying type. 115 static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) { 116 if (Y.getBitWidth() > X.getBitWidth()) 117 X = X.extend(Y.getBitWidth()); 118 else if (Y.getBitWidth() < X.getBitWidth()) 119 Y = Y.extend(X.getBitWidth()); 120 121 // If there is a signedness mismatch, correct it. 122 if (X.isSigned() != Y.isSigned()) { 123 // If the signed value is negative, then the values cannot be the same. 124 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative())) 125 return false; 126 127 Y.setIsSigned(true); 128 X.setIsSigned(true); 129 } 130 131 return X == Y; 132 } 133 134 static Sema::TemplateDeductionResult 135 DeduceTemplateArguments(Sema &S, 136 TemplateParameterList *TemplateParams, 137 const TemplateArgument &Param, 138 TemplateArgument Arg, 139 TemplateDeductionInfo &Info, 140 SmallVectorImpl<DeducedTemplateArgument> &Deduced); 141 142 static Sema::TemplateDeductionResult 143 DeduceTemplateArgumentsByTypeMatch(Sema &S, 144 TemplateParameterList *TemplateParams, 145 QualType Param, 146 QualType Arg, 147 TemplateDeductionInfo &Info, 148 SmallVectorImpl<DeducedTemplateArgument> & 149 Deduced, 150 unsigned TDF, 151 bool PartialOrdering = false, 152 bool DeducedFromArrayBound = false); 153 154 static Sema::TemplateDeductionResult 155 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, 156 ArrayRef<TemplateArgument> Params, 157 ArrayRef<TemplateArgument> Args, 158 TemplateDeductionInfo &Info, 159 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 160 bool NumberOfArgumentsMustMatch); 161 162 static void MarkUsedTemplateParameters(ASTContext &Ctx, 163 const TemplateArgument &TemplateArg, 164 bool OnlyDeduced, unsigned Depth, 165 llvm::SmallBitVector &Used); 166 167 static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 168 bool OnlyDeduced, unsigned Level, 169 llvm::SmallBitVector &Deduced); 170 171 /// If the given expression is of a form that permits the deduction 172 /// of a non-type template parameter, return the declaration of that 173 /// non-type template parameter. 174 static const NonTypeTemplateParmDecl * 175 getDeducedParameterFromExpr(const Expr *E, unsigned Depth) { 176 // If we are within an alias template, the expression may have undergone 177 // any number of parameter substitutions already. 178 while (true) { 179 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E)) 180 E = IC->getSubExpr(); 181 else if (const auto *CE = dyn_cast<ConstantExpr>(E)) 182 E = CE->getSubExpr(); 183 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) 184 E = Subst->getReplacement(); 185 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) { 186 // Look through implicit copy construction from an lvalue of the same type. 187 if (CCE->getParenOrBraceRange().isValid()) 188 break; 189 // Note, there could be default arguments. 190 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg"); 191 E = CCE->getArg(0); 192 } else 193 break; 194 } 195 196 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 197 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) 198 if (NTTP->getDepth() == Depth) 199 return NTTP; 200 201 return nullptr; 202 } 203 204 static const NonTypeTemplateParmDecl * 205 getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) { 206 return getDeducedParameterFromExpr(E, Info.getDeducedDepth()); 207 } 208 209 /// Determine whether two declaration pointers refer to the same 210 /// declaration. 211 static bool isSameDeclaration(Decl *X, Decl *Y) { 212 if (NamedDecl *NX = dyn_cast<NamedDecl>(X)) 213 X = NX->getUnderlyingDecl(); 214 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y)) 215 Y = NY->getUnderlyingDecl(); 216 217 return X->getCanonicalDecl() == Y->getCanonicalDecl(); 218 } 219 220 /// Verify that the given, deduced template arguments are compatible. 221 /// 222 /// \returns The deduced template argument, or a NULL template argument if 223 /// the deduced template arguments were incompatible. 224 static DeducedTemplateArgument 225 checkDeducedTemplateArguments(ASTContext &Context, 226 const DeducedTemplateArgument &X, 227 const DeducedTemplateArgument &Y) { 228 // We have no deduction for one or both of the arguments; they're compatible. 229 if (X.isNull()) 230 return Y; 231 if (Y.isNull()) 232 return X; 233 234 // If we have two non-type template argument values deduced for the same 235 // parameter, they must both match the type of the parameter, and thus must 236 // match each other's type. As we're only keeping one of them, we must check 237 // for that now. The exception is that if either was deduced from an array 238 // bound, the type is permitted to differ. 239 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) { 240 QualType XType = X.getNonTypeTemplateArgumentType(); 241 if (!XType.isNull()) { 242 QualType YType = Y.getNonTypeTemplateArgumentType(); 243 if (YType.isNull() || !Context.hasSameType(XType, YType)) 244 return DeducedTemplateArgument(); 245 } 246 } 247 248 switch (X.getKind()) { 249 case TemplateArgument::Null: 250 llvm_unreachable("Non-deduced template arguments handled above"); 251 252 case TemplateArgument::Type: 253 // If two template type arguments have the same type, they're compatible. 254 if (Y.getKind() == TemplateArgument::Type && 255 Context.hasSameType(X.getAsType(), Y.getAsType())) 256 return X; 257 258 // If one of the two arguments was deduced from an array bound, the other 259 // supersedes it. 260 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound()) 261 return X.wasDeducedFromArrayBound() ? Y : X; 262 263 // The arguments are not compatible. 264 return DeducedTemplateArgument(); 265 266 case TemplateArgument::Integral: 267 // If we deduced a constant in one case and either a dependent expression or 268 // declaration in another case, keep the integral constant. 269 // If both are integral constants with the same value, keep that value. 270 if (Y.getKind() == TemplateArgument::Expression || 271 Y.getKind() == TemplateArgument::Declaration || 272 (Y.getKind() == TemplateArgument::Integral && 273 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral()))) 274 return X.wasDeducedFromArrayBound() ? Y : X; 275 276 // All other combinations are incompatible. 277 return DeducedTemplateArgument(); 278 279 case TemplateArgument::Template: 280 if (Y.getKind() == TemplateArgument::Template && 281 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate())) 282 return X; 283 284 // All other combinations are incompatible. 285 return DeducedTemplateArgument(); 286 287 case TemplateArgument::TemplateExpansion: 288 if (Y.getKind() == TemplateArgument::TemplateExpansion && 289 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(), 290 Y.getAsTemplateOrTemplatePattern())) 291 return X; 292 293 // All other combinations are incompatible. 294 return DeducedTemplateArgument(); 295 296 case TemplateArgument::Expression: { 297 if (Y.getKind() != TemplateArgument::Expression) 298 return checkDeducedTemplateArguments(Context, Y, X); 299 300 // Compare the expressions for equality 301 llvm::FoldingSetNodeID ID1, ID2; 302 X.getAsExpr()->Profile(ID1, Context, true); 303 Y.getAsExpr()->Profile(ID2, Context, true); 304 if (ID1 == ID2) 305 return X.wasDeducedFromArrayBound() ? Y : X; 306 307 // Differing dependent expressions are incompatible. 308 return DeducedTemplateArgument(); 309 } 310 311 case TemplateArgument::Declaration: 312 assert(!X.wasDeducedFromArrayBound()); 313 314 // If we deduced a declaration and a dependent expression, keep the 315 // declaration. 316 if (Y.getKind() == TemplateArgument::Expression) 317 return X; 318 319 // If we deduced a declaration and an integral constant, keep the 320 // integral constant and whichever type did not come from an array 321 // bound. 322 if (Y.getKind() == TemplateArgument::Integral) { 323 if (Y.wasDeducedFromArrayBound()) 324 return TemplateArgument(Context, Y.getAsIntegral(), 325 X.getParamTypeForDecl()); 326 return Y; 327 } 328 329 // If we deduced two declarations, make sure that they refer to the 330 // same declaration. 331 if (Y.getKind() == TemplateArgument::Declaration && 332 isSameDeclaration(X.getAsDecl(), Y.getAsDecl())) 333 return X; 334 335 // All other combinations are incompatible. 336 return DeducedTemplateArgument(); 337 338 case TemplateArgument::NullPtr: 339 // If we deduced a null pointer and a dependent expression, keep the 340 // null pointer. 341 if (Y.getKind() == TemplateArgument::Expression) 342 return X; 343 344 // If we deduced a null pointer and an integral constant, keep the 345 // integral constant. 346 if (Y.getKind() == TemplateArgument::Integral) 347 return Y; 348 349 // If we deduced two null pointers, they are the same. 350 if (Y.getKind() == TemplateArgument::NullPtr) 351 return X; 352 353 // All other combinations are incompatible. 354 return DeducedTemplateArgument(); 355 356 case TemplateArgument::Pack: { 357 if (Y.getKind() != TemplateArgument::Pack || 358 X.pack_size() != Y.pack_size()) 359 return DeducedTemplateArgument(); 360 361 llvm::SmallVector<TemplateArgument, 8> NewPack; 362 for (TemplateArgument::pack_iterator XA = X.pack_begin(), 363 XAEnd = X.pack_end(), 364 YA = Y.pack_begin(); 365 XA != XAEnd; ++XA, ++YA) { 366 TemplateArgument Merged = checkDeducedTemplateArguments( 367 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()), 368 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound())); 369 if (Merged.isNull() && !(XA->isNull() && YA->isNull())) 370 return DeducedTemplateArgument(); 371 NewPack.push_back(Merged); 372 } 373 374 return DeducedTemplateArgument( 375 TemplateArgument::CreatePackCopy(Context, NewPack), 376 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound()); 377 } 378 } 379 380 llvm_unreachable("Invalid TemplateArgument Kind!"); 381 } 382 383 /// Deduce the value of the given non-type template parameter 384 /// as the given deduced template argument. All non-type template parameter 385 /// deduction is funneled through here. 386 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument( 387 Sema &S, TemplateParameterList *TemplateParams, 388 const NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced, 389 QualType ValueType, TemplateDeductionInfo &Info, 390 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 391 assert(NTTP->getDepth() == Info.getDeducedDepth() && 392 "deducing non-type template argument with wrong depth"); 393 394 DeducedTemplateArgument Result = checkDeducedTemplateArguments( 395 S.Context, Deduced[NTTP->getIndex()], NewDeduced); 396 if (Result.isNull()) { 397 Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP); 398 Info.FirstArg = Deduced[NTTP->getIndex()]; 399 Info.SecondArg = NewDeduced; 400 return Sema::TDK_Inconsistent; 401 } 402 403 Deduced[NTTP->getIndex()] = Result; 404 if (!S.getLangOpts().CPlusPlus17) 405 return Sema::TDK_Success; 406 407 if (NTTP->isExpandedParameterPack()) 408 // FIXME: We may still need to deduce parts of the type here! But we 409 // don't have any way to find which slice of the type to use, and the 410 // type stored on the NTTP itself is nonsense. Perhaps the type of an 411 // expanded NTTP should be a pack expansion type? 412 return Sema::TDK_Success; 413 414 // Get the type of the parameter for deduction. If it's a (dependent) array 415 // or function type, we will not have decayed it yet, so do that now. 416 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType()); 417 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType)) 418 ParamType = Expansion->getPattern(); 419 420 // FIXME: It's not clear how deduction of a parameter of reference 421 // type from an argument (of non-reference type) should be performed. 422 // For now, we just remove reference types from both sides and let 423 // the final check for matching types sort out the mess. 424 ValueType = ValueType.getNonReferenceType(); 425 if (ParamType->isReferenceType()) 426 ParamType = ParamType.getNonReferenceType(); 427 else 428 // Top-level cv-qualifiers are irrelevant for a non-reference type. 429 ValueType = ValueType.getUnqualifiedType(); 430 431 return DeduceTemplateArgumentsByTypeMatch( 432 S, TemplateParams, ParamType, ValueType, Info, Deduced, 433 TDF_SkipNonDependent, /*PartialOrdering=*/false, 434 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound()); 435 } 436 437 /// Deduce the value of the given non-type template parameter 438 /// from the given integral constant. 439 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument( 440 Sema &S, TemplateParameterList *TemplateParams, 441 const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value, 442 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info, 443 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 444 return DeduceNonTypeTemplateArgument( 445 S, TemplateParams, NTTP, 446 DeducedTemplateArgument(S.Context, Value, ValueType, 447 DeducedFromArrayBound), 448 ValueType, Info, Deduced); 449 } 450 451 /// Deduce the value of the given non-type template parameter 452 /// from the given null pointer template argument type. 453 static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument( 454 Sema &S, TemplateParameterList *TemplateParams, 455 const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType, 456 TemplateDeductionInfo &Info, 457 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 458 Expr *Value = 459 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr( 460 S.Context.NullPtrTy, NTTP->getLocation()), 461 NullPtrType, CK_NullToPointer) 462 .get(); 463 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 464 DeducedTemplateArgument(Value), 465 Value->getType(), Info, Deduced); 466 } 467 468 /// Deduce the value of the given non-type template parameter 469 /// from the given type- or value-dependent expression. 470 /// 471 /// \returns true if deduction succeeded, false otherwise. 472 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument( 473 Sema &S, TemplateParameterList *TemplateParams, 474 const NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info, 475 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 476 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 477 DeducedTemplateArgument(Value), 478 Value->getType(), Info, Deduced); 479 } 480 481 /// Deduce the value of the given non-type template parameter 482 /// from the given declaration. 483 /// 484 /// \returns true if deduction succeeded, false otherwise. 485 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument( 486 Sema &S, TemplateParameterList *TemplateParams, 487 const NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T, 488 TemplateDeductionInfo &Info, 489 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 490 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr; 491 TemplateArgument New(D, T); 492 return DeduceNonTypeTemplateArgument( 493 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced); 494 } 495 496 static Sema::TemplateDeductionResult 497 DeduceTemplateArguments(Sema &S, 498 TemplateParameterList *TemplateParams, 499 TemplateName Param, 500 TemplateName Arg, 501 TemplateDeductionInfo &Info, 502 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 503 TemplateDecl *ParamDecl = Param.getAsTemplateDecl(); 504 if (!ParamDecl) { 505 // The parameter type is dependent and is not a template template parameter, 506 // so there is nothing that we can deduce. 507 return Sema::TDK_Success; 508 } 509 510 if (TemplateTemplateParmDecl *TempParam 511 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) { 512 // If we're not deducing at this depth, there's nothing to deduce. 513 if (TempParam->getDepth() != Info.getDeducedDepth()) 514 return Sema::TDK_Success; 515 516 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg)); 517 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 518 Deduced[TempParam->getIndex()], 519 NewDeduced); 520 if (Result.isNull()) { 521 Info.Param = TempParam; 522 Info.FirstArg = Deduced[TempParam->getIndex()]; 523 Info.SecondArg = NewDeduced; 524 return Sema::TDK_Inconsistent; 525 } 526 527 Deduced[TempParam->getIndex()] = Result; 528 return Sema::TDK_Success; 529 } 530 531 // Verify that the two template names are equivalent. 532 if (S.Context.hasSameTemplateName(Param, Arg)) 533 return Sema::TDK_Success; 534 535 // Mismatch of non-dependent template parameter to argument. 536 Info.FirstArg = TemplateArgument(Param); 537 Info.SecondArg = TemplateArgument(Arg); 538 return Sema::TDK_NonDeducedMismatch; 539 } 540 541 /// Deduce the template arguments by comparing the template parameter 542 /// type (which is a template-id) with the template argument type. 543 /// 544 /// \param S the Sema 545 /// 546 /// \param TemplateParams the template parameters that we are deducing 547 /// 548 /// \param Param the parameter type 549 /// 550 /// \param Arg the argument type 551 /// 552 /// \param Info information about the template argument deduction itself 553 /// 554 /// \param Deduced the deduced template arguments 555 /// 556 /// \returns the result of template argument deduction so far. Note that a 557 /// "success" result means that template argument deduction has not yet failed, 558 /// but it may still fail, later, for other reasons. 559 static Sema::TemplateDeductionResult 560 DeduceTemplateArguments(Sema &S, 561 TemplateParameterList *TemplateParams, 562 const TemplateSpecializationType *Param, 563 QualType Arg, 564 TemplateDeductionInfo &Info, 565 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 566 assert(Arg.isCanonical() && "Argument type must be canonical"); 567 568 // Treat an injected-class-name as its underlying template-id. 569 if (auto *Injected = dyn_cast<InjectedClassNameType>(Arg)) 570 Arg = Injected->getInjectedSpecializationType(); 571 572 // Check whether the template argument is a dependent template-id. 573 if (const TemplateSpecializationType *SpecArg 574 = dyn_cast<TemplateSpecializationType>(Arg)) { 575 // Perform template argument deduction for the template name. 576 if (Sema::TemplateDeductionResult Result 577 = DeduceTemplateArguments(S, TemplateParams, 578 Param->getTemplateName(), 579 SpecArg->getTemplateName(), 580 Info, Deduced)) 581 return Result; 582 583 584 // Perform template argument deduction on each template 585 // argument. Ignore any missing/extra arguments, since they could be 586 // filled in by default arguments. 587 return DeduceTemplateArguments(S, TemplateParams, 588 Param->template_arguments(), 589 SpecArg->template_arguments(), Info, Deduced, 590 /*NumberOfArgumentsMustMatch=*/false); 591 } 592 593 // If the argument type is a class template specialization, we 594 // perform template argument deduction using its template 595 // arguments. 596 const RecordType *RecordArg = dyn_cast<RecordType>(Arg); 597 if (!RecordArg) { 598 Info.FirstArg = TemplateArgument(QualType(Param, 0)); 599 Info.SecondArg = TemplateArgument(Arg); 600 return Sema::TDK_NonDeducedMismatch; 601 } 602 603 ClassTemplateSpecializationDecl *SpecArg 604 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl()); 605 if (!SpecArg) { 606 Info.FirstArg = TemplateArgument(QualType(Param, 0)); 607 Info.SecondArg = TemplateArgument(Arg); 608 return Sema::TDK_NonDeducedMismatch; 609 } 610 611 // Perform template argument deduction for the template name. 612 if (Sema::TemplateDeductionResult Result 613 = DeduceTemplateArguments(S, 614 TemplateParams, 615 Param->getTemplateName(), 616 TemplateName(SpecArg->getSpecializedTemplate()), 617 Info, Deduced)) 618 return Result; 619 620 // Perform template argument deduction for the template arguments. 621 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(), 622 SpecArg->getTemplateArgs().asArray(), Info, 623 Deduced, /*NumberOfArgumentsMustMatch=*/true); 624 } 625 626 /// Determines whether the given type is an opaque type that 627 /// might be more qualified when instantiated. 628 static bool IsPossiblyOpaquelyQualifiedType(QualType T) { 629 switch (T->getTypeClass()) { 630 case Type::TypeOfExpr: 631 case Type::TypeOf: 632 case Type::DependentName: 633 case Type::Decltype: 634 case Type::UnresolvedUsing: 635 case Type::TemplateTypeParm: 636 return true; 637 638 case Type::ConstantArray: 639 case Type::IncompleteArray: 640 case Type::VariableArray: 641 case Type::DependentSizedArray: 642 return IsPossiblyOpaquelyQualifiedType( 643 cast<ArrayType>(T)->getElementType()); 644 645 default: 646 return false; 647 } 648 } 649 650 /// Helper function to build a TemplateParameter when we don't 651 /// know its type statically. 652 static TemplateParameter makeTemplateParameter(Decl *D) { 653 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D)) 654 return TemplateParameter(TTP); 655 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) 656 return TemplateParameter(NTTP); 657 658 return TemplateParameter(cast<TemplateTemplateParmDecl>(D)); 659 } 660 661 /// If \p Param is an expanded parameter pack, get the number of expansions. 662 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) { 663 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 664 if (TTP->isExpandedParameterPack()) 665 return TTP->getNumExpansionParameters(); 666 667 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) 668 if (NTTP->isExpandedParameterPack()) 669 return NTTP->getNumExpansionTypes(); 670 671 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) 672 if (TTP->isExpandedParameterPack()) 673 return TTP->getNumExpansionTemplateParameters(); 674 675 return None; 676 } 677 678 /// A pack that we're currently deducing. 679 struct clang::DeducedPack { 680 // The index of the pack. 681 unsigned Index; 682 683 // The old value of the pack before we started deducing it. 684 DeducedTemplateArgument Saved; 685 686 // A deferred value of this pack from an inner deduction, that couldn't be 687 // deduced because this deduction hadn't happened yet. 688 DeducedTemplateArgument DeferredDeduction; 689 690 // The new value of the pack. 691 SmallVector<DeducedTemplateArgument, 4> New; 692 693 // The outer deduction for this pack, if any. 694 DeducedPack *Outer = nullptr; 695 696 DeducedPack(unsigned Index) : Index(Index) {} 697 }; 698 699 namespace { 700 701 /// A scope in which we're performing pack deduction. 702 class PackDeductionScope { 703 public: 704 /// Prepare to deduce the packs named within Pattern. 705 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams, 706 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 707 TemplateDeductionInfo &Info, TemplateArgument Pattern) 708 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) { 709 unsigned NumNamedPacks = addPacks(Pattern); 710 finishConstruction(NumNamedPacks); 711 } 712 713 /// Prepare to directly deduce arguments of the parameter with index \p Index. 714 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams, 715 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 716 TemplateDeductionInfo &Info, unsigned Index) 717 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) { 718 addPack(Index); 719 finishConstruction(1); 720 } 721 722 private: 723 void addPack(unsigned Index) { 724 // Save the deduced template argument for the parameter pack expanded 725 // by this pack expansion, then clear out the deduction. 726 DeducedPack Pack(Index); 727 Pack.Saved = Deduced[Index]; 728 Deduced[Index] = TemplateArgument(); 729 730 // FIXME: What if we encounter multiple packs with different numbers of 731 // pre-expanded expansions? (This should already have been diagnosed 732 // during substitution.) 733 if (Optional<unsigned> ExpandedPackExpansions = 734 getExpandedPackSize(TemplateParams->getParam(Index))) 735 FixedNumExpansions = ExpandedPackExpansions; 736 737 Packs.push_back(Pack); 738 } 739 740 unsigned addPacks(TemplateArgument Pattern) { 741 // Compute the set of template parameter indices that correspond to 742 // parameter packs expanded by the pack expansion. 743 llvm::SmallBitVector SawIndices(TemplateParams->size()); 744 llvm::SmallVector<TemplateArgument, 4> ExtraDeductions; 745 746 auto AddPack = [&](unsigned Index) { 747 if (SawIndices[Index]) 748 return; 749 SawIndices[Index] = true; 750 addPack(Index); 751 752 // Deducing a parameter pack that is a pack expansion also constrains the 753 // packs appearing in that parameter to have the same deduced arity. Also, 754 // in C++17 onwards, deducing a non-type template parameter deduces its 755 // type, so we need to collect the pending deduced values for those packs. 756 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>( 757 TemplateParams->getParam(Index))) { 758 if (!NTTP->isExpandedParameterPack()) 759 if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType())) 760 ExtraDeductions.push_back(Expansion->getPattern()); 761 } 762 // FIXME: Also collect the unexpanded packs in any type and template 763 // parameter packs that are pack expansions. 764 }; 765 766 auto Collect = [&](TemplateArgument Pattern) { 767 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 768 S.collectUnexpandedParameterPacks(Pattern, Unexpanded); 769 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 770 unsigned Depth, Index; 771 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]); 772 if (Depth == Info.getDeducedDepth()) 773 AddPack(Index); 774 } 775 }; 776 777 // Look for unexpanded packs in the pattern. 778 Collect(Pattern); 779 assert(!Packs.empty() && "Pack expansion without unexpanded packs?"); 780 781 unsigned NumNamedPacks = Packs.size(); 782 783 // Also look for unexpanded packs that are indirectly deduced by deducing 784 // the sizes of the packs in this pattern. 785 while (!ExtraDeductions.empty()) 786 Collect(ExtraDeductions.pop_back_val()); 787 788 return NumNamedPacks; 789 } 790 791 void finishConstruction(unsigned NumNamedPacks) { 792 // Dig out the partially-substituted pack, if there is one. 793 const TemplateArgument *PartialPackArgs = nullptr; 794 unsigned NumPartialPackArgs = 0; 795 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u); 796 if (auto *Scope = S.CurrentInstantiationScope) 797 if (auto *Partial = Scope->getPartiallySubstitutedPack( 798 &PartialPackArgs, &NumPartialPackArgs)) 799 PartialPackDepthIndex = getDepthAndIndex(Partial); 800 801 // This pack expansion will have been partially or fully expanded if 802 // it only names explicitly-specified parameter packs (including the 803 // partially-substituted one, if any). 804 bool IsExpanded = true; 805 for (unsigned I = 0; I != NumNamedPacks; ++I) { 806 if (Packs[I].Index >= Info.getNumExplicitArgs()) { 807 IsExpanded = false; 808 IsPartiallyExpanded = false; 809 break; 810 } 811 if (PartialPackDepthIndex == 812 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) { 813 IsPartiallyExpanded = true; 814 } 815 } 816 817 // Skip over the pack elements that were expanded into separate arguments. 818 // If we partially expanded, this is the number of partial arguments. 819 if (IsPartiallyExpanded) 820 PackElements += NumPartialPackArgs; 821 else if (IsExpanded) 822 PackElements += *FixedNumExpansions; 823 824 for (auto &Pack : Packs) { 825 if (Info.PendingDeducedPacks.size() > Pack.Index) 826 Pack.Outer = Info.PendingDeducedPacks[Pack.Index]; 827 else 828 Info.PendingDeducedPacks.resize(Pack.Index + 1); 829 Info.PendingDeducedPacks[Pack.Index] = &Pack; 830 831 if (PartialPackDepthIndex == 832 std::make_pair(Info.getDeducedDepth(), Pack.Index)) { 833 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs); 834 // We pre-populate the deduced value of the partially-substituted 835 // pack with the specified value. This is not entirely correct: the 836 // value is supposed to have been substituted, not deduced, but the 837 // cases where this is observable require an exact type match anyway. 838 // 839 // FIXME: If we could represent a "depth i, index j, pack elem k" 840 // parameter, we could substitute the partially-substituted pack 841 // everywhere and avoid this. 842 if (!IsPartiallyExpanded) 843 Deduced[Pack.Index] = Pack.New[PackElements]; 844 } 845 } 846 } 847 848 public: 849 ~PackDeductionScope() { 850 for (auto &Pack : Packs) 851 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer; 852 } 853 854 /// Determine whether this pack has already been partially expanded into a 855 /// sequence of (prior) function parameters / template arguments. 856 bool isPartiallyExpanded() { return IsPartiallyExpanded; } 857 858 /// Determine whether this pack expansion scope has a known, fixed arity. 859 /// This happens if it involves a pack from an outer template that has 860 /// (notionally) already been expanded. 861 bool hasFixedArity() { return FixedNumExpansions.hasValue(); } 862 863 /// Determine whether the next element of the argument is still part of this 864 /// pack. This is the case unless the pack is already expanded to a fixed 865 /// length. 866 bool hasNextElement() { 867 return !FixedNumExpansions || *FixedNumExpansions > PackElements; 868 } 869 870 /// Move to deducing the next element in each pack that is being deduced. 871 void nextPackElement() { 872 // Capture the deduced template arguments for each parameter pack expanded 873 // by this pack expansion, add them to the list of arguments we've deduced 874 // for that pack, then clear out the deduced argument. 875 for (auto &Pack : Packs) { 876 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index]; 877 if (!Pack.New.empty() || !DeducedArg.isNull()) { 878 while (Pack.New.size() < PackElements) 879 Pack.New.push_back(DeducedTemplateArgument()); 880 if (Pack.New.size() == PackElements) 881 Pack.New.push_back(DeducedArg); 882 else 883 Pack.New[PackElements] = DeducedArg; 884 DeducedArg = Pack.New.size() > PackElements + 1 885 ? Pack.New[PackElements + 1] 886 : DeducedTemplateArgument(); 887 } 888 } 889 ++PackElements; 890 } 891 892 /// Finish template argument deduction for a set of argument packs, 893 /// producing the argument packs and checking for consistency with prior 894 /// deductions. 895 Sema::TemplateDeductionResult finish() { 896 // Build argument packs for each of the parameter packs expanded by this 897 // pack expansion. 898 for (auto &Pack : Packs) { 899 // Put back the old value for this pack. 900 Deduced[Pack.Index] = Pack.Saved; 901 902 // Always make sure the size of this pack is correct, even if we didn't 903 // deduce any values for it. 904 // 905 // FIXME: This isn't required by the normative wording, but substitution 906 // and post-substitution checking will always fail if the arity of any 907 // pack is not equal to the number of elements we processed. (Either that 908 // or something else has gone *very* wrong.) We're permitted to skip any 909 // hard errors from those follow-on steps by the intent (but not the 910 // wording) of C++ [temp.inst]p8: 911 // 912 // If the function selected by overload resolution can be determined 913 // without instantiating a class template definition, it is unspecified 914 // whether that instantiation actually takes place 915 Pack.New.resize(PackElements); 916 917 // Build or find a new value for this pack. 918 DeducedTemplateArgument NewPack; 919 if (Pack.New.empty()) { 920 // If we deduced an empty argument pack, create it now. 921 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack()); 922 } else { 923 TemplateArgument *ArgumentPack = 924 new (S.Context) TemplateArgument[Pack.New.size()]; 925 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack); 926 NewPack = DeducedTemplateArgument( 927 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())), 928 // FIXME: This is wrong, it's possible that some pack elements are 929 // deduced from an array bound and others are not: 930 // template<typename ...T, T ...V> void g(const T (&...p)[V]); 931 // g({1, 2, 3}, {{}, {}}); 932 // ... should deduce T = {int, size_t (from array bound)}. 933 Pack.New[0].wasDeducedFromArrayBound()); 934 } 935 936 // Pick where we're going to put the merged pack. 937 DeducedTemplateArgument *Loc; 938 if (Pack.Outer) { 939 if (Pack.Outer->DeferredDeduction.isNull()) { 940 // Defer checking this pack until we have a complete pack to compare 941 // it against. 942 Pack.Outer->DeferredDeduction = NewPack; 943 continue; 944 } 945 Loc = &Pack.Outer->DeferredDeduction; 946 } else { 947 Loc = &Deduced[Pack.Index]; 948 } 949 950 // Check the new pack matches any previous value. 951 DeducedTemplateArgument OldPack = *Loc; 952 DeducedTemplateArgument Result = 953 checkDeducedTemplateArguments(S.Context, OldPack, NewPack); 954 955 // If we deferred a deduction of this pack, check that one now too. 956 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) { 957 OldPack = Result; 958 NewPack = Pack.DeferredDeduction; 959 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack); 960 } 961 962 NamedDecl *Param = TemplateParams->getParam(Pack.Index); 963 if (Result.isNull()) { 964 Info.Param = makeTemplateParameter(Param); 965 Info.FirstArg = OldPack; 966 Info.SecondArg = NewPack; 967 return Sema::TDK_Inconsistent; 968 } 969 970 // If we have a pre-expanded pack and we didn't deduce enough elements 971 // for it, fail deduction. 972 if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) { 973 if (*Expansions != PackElements) { 974 Info.Param = makeTemplateParameter(Param); 975 Info.FirstArg = Result; 976 return Sema::TDK_IncompletePack; 977 } 978 } 979 980 *Loc = Result; 981 } 982 983 return Sema::TDK_Success; 984 } 985 986 private: 987 Sema &S; 988 TemplateParameterList *TemplateParams; 989 SmallVectorImpl<DeducedTemplateArgument> &Deduced; 990 TemplateDeductionInfo &Info; 991 unsigned PackElements = 0; 992 bool IsPartiallyExpanded = false; 993 /// The number of expansions, if we have a fully-expanded pack in this scope. 994 Optional<unsigned> FixedNumExpansions; 995 996 SmallVector<DeducedPack, 2> Packs; 997 }; 998 999 } // namespace 1000 1001 /// Deduce the template arguments by comparing the list of parameter 1002 /// types to the list of argument types, as in the parameter-type-lists of 1003 /// function types (C++ [temp.deduct.type]p10). 1004 /// 1005 /// \param S The semantic analysis object within which we are deducing 1006 /// 1007 /// \param TemplateParams The template parameters that we are deducing 1008 /// 1009 /// \param Params The list of parameter types 1010 /// 1011 /// \param NumParams The number of types in \c Params 1012 /// 1013 /// \param Args The list of argument types 1014 /// 1015 /// \param NumArgs The number of types in \c Args 1016 /// 1017 /// \param Info information about the template argument deduction itself 1018 /// 1019 /// \param Deduced the deduced template arguments 1020 /// 1021 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 1022 /// how template argument deduction is performed. 1023 /// 1024 /// \param PartialOrdering If true, we are performing template argument 1025 /// deduction for during partial ordering for a call 1026 /// (C++0x [temp.deduct.partial]). 1027 /// 1028 /// \returns the result of template argument deduction so far. Note that a 1029 /// "success" result means that template argument deduction has not yet failed, 1030 /// but it may still fail, later, for other reasons. 1031 static Sema::TemplateDeductionResult 1032 DeduceTemplateArguments(Sema &S, 1033 TemplateParameterList *TemplateParams, 1034 const QualType *Params, unsigned NumParams, 1035 const QualType *Args, unsigned NumArgs, 1036 TemplateDeductionInfo &Info, 1037 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 1038 unsigned TDF, 1039 bool PartialOrdering = false) { 1040 // C++0x [temp.deduct.type]p10: 1041 // Similarly, if P has a form that contains (T), then each parameter type 1042 // Pi of the respective parameter-type- list of P is compared with the 1043 // corresponding parameter type Ai of the corresponding parameter-type-list 1044 // of A. [...] 1045 unsigned ArgIdx = 0, ParamIdx = 0; 1046 for (; ParamIdx != NumParams; ++ParamIdx) { 1047 // Check argument types. 1048 const PackExpansionType *Expansion 1049 = dyn_cast<PackExpansionType>(Params[ParamIdx]); 1050 if (!Expansion) { 1051 // Simple case: compare the parameter and argument types at this point. 1052 1053 // Make sure we have an argument. 1054 if (ArgIdx >= NumArgs) 1055 return Sema::TDK_MiscellaneousDeductionFailure; 1056 1057 if (isa<PackExpansionType>(Args[ArgIdx])) { 1058 // C++0x [temp.deduct.type]p22: 1059 // If the original function parameter associated with A is a function 1060 // parameter pack and the function parameter associated with P is not 1061 // a function parameter pack, then template argument deduction fails. 1062 return Sema::TDK_MiscellaneousDeductionFailure; 1063 } 1064 1065 if (Sema::TemplateDeductionResult Result 1066 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1067 Params[ParamIdx], Args[ArgIdx], 1068 Info, Deduced, TDF, 1069 PartialOrdering)) 1070 return Result; 1071 1072 ++ArgIdx; 1073 continue; 1074 } 1075 1076 // C++0x [temp.deduct.type]p10: 1077 // If the parameter-declaration corresponding to Pi is a function 1078 // parameter pack, then the type of its declarator- id is compared with 1079 // each remaining parameter type in the parameter-type-list of A. Each 1080 // comparison deduces template arguments for subsequent positions in the 1081 // template parameter packs expanded by the function parameter pack. 1082 1083 QualType Pattern = Expansion->getPattern(); 1084 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern); 1085 1086 // A pack scope with fixed arity is not really a pack any more, so is not 1087 // a non-deduced context. 1088 if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) { 1089 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) { 1090 // Deduce template arguments from the pattern. 1091 if (Sema::TemplateDeductionResult Result 1092 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern, 1093 Args[ArgIdx], Info, Deduced, 1094 TDF, PartialOrdering)) 1095 return Result; 1096 1097 PackScope.nextPackElement(); 1098 } 1099 } else { 1100 // C++0x [temp.deduct.type]p5: 1101 // The non-deduced contexts are: 1102 // - A function parameter pack that does not occur at the end of the 1103 // parameter-declaration-clause. 1104 // 1105 // FIXME: There is no wording to say what we should do in this case. We 1106 // choose to resolve this by applying the same rule that is applied for a 1107 // function call: that is, deduce all contained packs to their 1108 // explicitly-specified values (or to <> if there is no such value). 1109 // 1110 // This is seemingly-arbitrarily different from the case of a template-id 1111 // with a non-trailing pack-expansion in its arguments, which renders the 1112 // entire template-argument-list a non-deduced context. 1113 1114 // If the parameter type contains an explicitly-specified pack that we 1115 // could not expand, skip the number of parameters notionally created 1116 // by the expansion. 1117 Optional<unsigned> NumExpansions = Expansion->getNumExpansions(); 1118 if (NumExpansions && !PackScope.isPartiallyExpanded()) { 1119 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs; 1120 ++I, ++ArgIdx) 1121 PackScope.nextPackElement(); 1122 } 1123 } 1124 1125 // Build argument packs for each of the parameter packs expanded by this 1126 // pack expansion. 1127 if (auto Result = PackScope.finish()) 1128 return Result; 1129 } 1130 1131 // Make sure we don't have any extra arguments. 1132 if (ArgIdx < NumArgs) 1133 return Sema::TDK_MiscellaneousDeductionFailure; 1134 1135 return Sema::TDK_Success; 1136 } 1137 1138 /// Determine whether the parameter has qualifiers that the argument 1139 /// lacks. Put another way, determine whether there is no way to add 1140 /// a deduced set of qualifiers to the ParamType that would result in 1141 /// its qualifiers matching those of the ArgType. 1142 static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, 1143 QualType ArgType) { 1144 Qualifiers ParamQs = ParamType.getQualifiers(); 1145 Qualifiers ArgQs = ArgType.getQualifiers(); 1146 1147 if (ParamQs == ArgQs) 1148 return false; 1149 1150 // Mismatched (but not missing) Objective-C GC attributes. 1151 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() && 1152 ParamQs.hasObjCGCAttr()) 1153 return true; 1154 1155 // Mismatched (but not missing) address spaces. 1156 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() && 1157 ParamQs.hasAddressSpace()) 1158 return true; 1159 1160 // Mismatched (but not missing) Objective-C lifetime qualifiers. 1161 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() && 1162 ParamQs.hasObjCLifetime()) 1163 return true; 1164 1165 // CVR qualifiers inconsistent or a superset. 1166 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0; 1167 } 1168 1169 /// Compare types for equality with respect to possibly compatible 1170 /// function types (noreturn adjustment, implicit calling conventions). If any 1171 /// of parameter and argument is not a function, just perform type comparison. 1172 /// 1173 /// \param Param the template parameter type. 1174 /// 1175 /// \param Arg the argument type. 1176 bool Sema::isSameOrCompatibleFunctionType(CanQualType Param, 1177 CanQualType Arg) { 1178 const FunctionType *ParamFunction = Param->getAs<FunctionType>(), 1179 *ArgFunction = Arg->getAs<FunctionType>(); 1180 1181 // Just compare if not functions. 1182 if (!ParamFunction || !ArgFunction) 1183 return Param == Arg; 1184 1185 // Noreturn and noexcept adjustment. 1186 QualType AdjustedParam; 1187 if (IsFunctionConversion(Param, Arg, AdjustedParam)) 1188 return Arg == Context.getCanonicalType(AdjustedParam); 1189 1190 // FIXME: Compatible calling conventions. 1191 1192 return Param == Arg; 1193 } 1194 1195 /// Get the index of the first template parameter that was originally from the 1196 /// innermost template-parameter-list. This is 0 except when we concatenate 1197 /// the template parameter lists of a class template and a constructor template 1198 /// when forming an implicit deduction guide. 1199 static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) { 1200 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl()); 1201 if (!Guide || !Guide->isImplicit()) 1202 return 0; 1203 return Guide->getDeducedTemplate()->getTemplateParameters()->size(); 1204 } 1205 1206 /// Determine whether a type denotes a forwarding reference. 1207 static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) { 1208 // C++1z [temp.deduct.call]p3: 1209 // A forwarding reference is an rvalue reference to a cv-unqualified 1210 // template parameter that does not represent a template parameter of a 1211 // class template. 1212 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) { 1213 if (ParamRef->getPointeeType().getQualifiers()) 1214 return false; 1215 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>(); 1216 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex; 1217 } 1218 return false; 1219 } 1220 1221 /// Attempt to deduce the template arguments by checking the base types 1222 /// according to (C++20 [temp.deduct.call] p4b3. 1223 /// 1224 /// \param S the semantic analysis object within which we are deducing. 1225 /// 1226 /// \param RecordT the top level record object we are deducing against. 1227 /// 1228 /// \param TemplateParams the template parameters that we are deducing. 1229 /// 1230 /// \param SpecParam the template specialization parameter type. 1231 /// 1232 /// \param Info information about the template argument deduction itself. 1233 /// 1234 /// \param Deduced the deduced template arguments. 1235 /// 1236 /// \returns the result of template argument deduction with the bases. "invalid" 1237 /// means no matches, "success" found a single item, and the 1238 /// "MiscellaneousDeductionFailure" result happens when the match is ambiguous. 1239 static Sema::TemplateDeductionResult DeduceTemplateBases( 1240 Sema &S, const RecordType *RecordT, TemplateParameterList *TemplateParams, 1241 const TemplateSpecializationType *SpecParam, TemplateDeductionInfo &Info, 1242 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 1243 // C++14 [temp.deduct.call] p4b3: 1244 // If P is a class and P has the form simple-template-id, then the 1245 // transformed A can be a derived class of the deduced A. Likewise if 1246 // P is a pointer to a class of the form simple-template-id, the 1247 // transformed A can be a pointer to a derived class pointed to by the 1248 // deduced A. However, if there is a class C that is a (direct or 1249 // indirect) base class of D and derived (directly or indirectly) from a 1250 // class B and that would be a valid deduced A, the deduced A cannot be 1251 // B or pointer to B, respectively. 1252 // 1253 // These alternatives are considered only if type deduction would 1254 // otherwise fail. If they yield more than one possible deduced A, the 1255 // type deduction fails. 1256 1257 // Use a breadth-first search through the bases to collect the set of 1258 // successful matches. Visited contains the set of nodes we have already 1259 // visited, while ToVisit is our stack of records that we still need to 1260 // visit. Matches contains a list of matches that have yet to be 1261 // disqualified. 1262 llvm::SmallPtrSet<const RecordType *, 8> Visited; 1263 SmallVector<const RecordType *, 8> ToVisit; 1264 // We iterate over this later, so we have to use MapVector to ensure 1265 // determinism. 1266 llvm::MapVector<const RecordType *, SmallVector<DeducedTemplateArgument, 8>> 1267 Matches; 1268 1269 auto AddBases = [&Visited, &ToVisit](const RecordType *RT) { 1270 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1271 for (const auto &Base : RD->bases()) { 1272 assert(Base.getType()->isRecordType() && 1273 "Base class that isn't a record?"); 1274 const RecordType *RT = Base.getType()->getAs<RecordType>(); 1275 if (Visited.insert(RT).second) 1276 ToVisit.push_back(Base.getType()->getAs<RecordType>()); 1277 } 1278 }; 1279 1280 // Set up the loop by adding all the bases. 1281 AddBases(RecordT); 1282 1283 // Search each path of bases until we either run into a successful match 1284 // (where all bases of it are invalid), or we run out of bases. 1285 while (!ToVisit.empty()) { 1286 const RecordType *NextT = ToVisit.pop_back_val(); 1287 1288 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(), 1289 Deduced.end()); 1290 TemplateDeductionInfo BaseInfo(TemplateDeductionInfo::ForBase, Info); 1291 Sema::TemplateDeductionResult BaseResult = 1292 DeduceTemplateArguments(S, TemplateParams, SpecParam, 1293 QualType(NextT, 0), BaseInfo, DeducedCopy); 1294 1295 // If this was a successful deduction, add it to the list of matches, 1296 // otherwise we need to continue searching its bases. 1297 if (BaseResult == Sema::TDK_Success) 1298 Matches.insert({NextT, DeducedCopy}); 1299 else 1300 AddBases(NextT); 1301 } 1302 1303 // At this point, 'Matches' contains a list of seemingly valid bases, however 1304 // in the event that we have more than 1 match, it is possible that the base 1305 // of one of the matches might be disqualified for being a base of another 1306 // valid match. We can count on cyclical instantiations being invalid to 1307 // simplify the disqualifications. That is, if A & B are both matches, and B 1308 // inherits from A (disqualifying A), we know that A cannot inherit from B. 1309 if (Matches.size() > 1) { 1310 Visited.clear(); 1311 for (const auto &Match : Matches) 1312 AddBases(Match.first); 1313 1314 // We can give up once we have a single item (or have run out of things to 1315 // search) since cyclical inheritence isn't valid. 1316 while (Matches.size() > 1 && !ToVisit.empty()) { 1317 const RecordType *NextT = ToVisit.pop_back_val(); 1318 Matches.erase(NextT); 1319 1320 // Always add all bases, since the inheritence tree can contain 1321 // disqualifications for multiple matches. 1322 AddBases(NextT); 1323 } 1324 } 1325 1326 if (Matches.empty()) 1327 return Sema::TDK_Invalid; 1328 if (Matches.size() > 1) 1329 return Sema::TDK_MiscellaneousDeductionFailure; 1330 1331 std::swap(Matches.front().second, Deduced); 1332 return Sema::TDK_Success; 1333 } 1334 1335 /// Deduce the template arguments by comparing the parameter type and 1336 /// the argument type (C++ [temp.deduct.type]). 1337 /// 1338 /// \param S the semantic analysis object within which we are deducing 1339 /// 1340 /// \param TemplateParams the template parameters that we are deducing 1341 /// 1342 /// \param ParamIn the parameter type 1343 /// 1344 /// \param ArgIn the argument type 1345 /// 1346 /// \param Info information about the template argument deduction itself 1347 /// 1348 /// \param Deduced the deduced template arguments 1349 /// 1350 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 1351 /// how template argument deduction is performed. 1352 /// 1353 /// \param PartialOrdering Whether we're performing template argument deduction 1354 /// in the context of partial ordering (C++0x [temp.deduct.partial]). 1355 /// 1356 /// \returns the result of template argument deduction so far. Note that a 1357 /// "success" result means that template argument deduction has not yet failed, 1358 /// but it may still fail, later, for other reasons. 1359 static Sema::TemplateDeductionResult 1360 DeduceTemplateArgumentsByTypeMatch(Sema &S, 1361 TemplateParameterList *TemplateParams, 1362 QualType ParamIn, QualType ArgIn, 1363 TemplateDeductionInfo &Info, 1364 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 1365 unsigned TDF, 1366 bool PartialOrdering, 1367 bool DeducedFromArrayBound) { 1368 // We only want to look at the canonical types, since typedefs and 1369 // sugar are not part of template argument deduction. 1370 QualType Param = S.Context.getCanonicalType(ParamIn); 1371 QualType Arg = S.Context.getCanonicalType(ArgIn); 1372 1373 // If the argument type is a pack expansion, look at its pattern. 1374 // This isn't explicitly called out 1375 if (const PackExpansionType *ArgExpansion 1376 = dyn_cast<PackExpansionType>(Arg)) 1377 Arg = ArgExpansion->getPattern(); 1378 1379 if (PartialOrdering) { 1380 // C++11 [temp.deduct.partial]p5: 1381 // Before the partial ordering is done, certain transformations are 1382 // performed on the types used for partial ordering: 1383 // - If P is a reference type, P is replaced by the type referred to. 1384 const ReferenceType *ParamRef = Param->getAs<ReferenceType>(); 1385 if (ParamRef) 1386 Param = ParamRef->getPointeeType(); 1387 1388 // - If A is a reference type, A is replaced by the type referred to. 1389 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>(); 1390 if (ArgRef) 1391 Arg = ArgRef->getPointeeType(); 1392 1393 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) { 1394 // C++11 [temp.deduct.partial]p9: 1395 // If, for a given type, deduction succeeds in both directions (i.e., 1396 // the types are identical after the transformations above) and both 1397 // P and A were reference types [...]: 1398 // - if [one type] was an lvalue reference and [the other type] was 1399 // not, [the other type] is not considered to be at least as 1400 // specialized as [the first type] 1401 // - if [one type] is more cv-qualified than [the other type], 1402 // [the other type] is not considered to be at least as specialized 1403 // as [the first type] 1404 // Objective-C ARC adds: 1405 // - [one type] has non-trivial lifetime, [the other type] has 1406 // __unsafe_unretained lifetime, and the types are otherwise 1407 // identical 1408 // 1409 // A is "considered to be at least as specialized" as P iff deduction 1410 // succeeds, so we model this as a deduction failure. Note that 1411 // [the first type] is P and [the other type] is A here; the standard 1412 // gets this backwards. 1413 Qualifiers ParamQuals = Param.getQualifiers(); 1414 Qualifiers ArgQuals = Arg.getQualifiers(); 1415 if ((ParamRef->isLValueReferenceType() && 1416 !ArgRef->isLValueReferenceType()) || 1417 ParamQuals.isStrictSupersetOf(ArgQuals) || 1418 (ParamQuals.hasNonTrivialObjCLifetime() && 1419 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone && 1420 ParamQuals.withoutObjCLifetime() == 1421 ArgQuals.withoutObjCLifetime())) { 1422 Info.FirstArg = TemplateArgument(ParamIn); 1423 Info.SecondArg = TemplateArgument(ArgIn); 1424 return Sema::TDK_NonDeducedMismatch; 1425 } 1426 } 1427 1428 // C++11 [temp.deduct.partial]p7: 1429 // Remove any top-level cv-qualifiers: 1430 // - If P is a cv-qualified type, P is replaced by the cv-unqualified 1431 // version of P. 1432 Param = Param.getUnqualifiedType(); 1433 // - If A is a cv-qualified type, A is replaced by the cv-unqualified 1434 // version of A. 1435 Arg = Arg.getUnqualifiedType(); 1436 } else { 1437 // C++0x [temp.deduct.call]p4 bullet 1: 1438 // - If the original P is a reference type, the deduced A (i.e., the type 1439 // referred to by the reference) can be more cv-qualified than the 1440 // transformed A. 1441 if (TDF & TDF_ParamWithReferenceType) { 1442 Qualifiers Quals; 1443 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals); 1444 Quals.setCVRQualifiers(Quals.getCVRQualifiers() & 1445 Arg.getCVRQualifiers()); 1446 Param = S.Context.getQualifiedType(UnqualParam, Quals); 1447 } 1448 1449 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) { 1450 // C++0x [temp.deduct.type]p10: 1451 // If P and A are function types that originated from deduction when 1452 // taking the address of a function template (14.8.2.2) or when deducing 1453 // template arguments from a function declaration (14.8.2.6) and Pi and 1454 // Ai are parameters of the top-level parameter-type-list of P and A, 1455 // respectively, Pi is adjusted if it is a forwarding reference and Ai 1456 // is an lvalue reference, in 1457 // which case the type of Pi is changed to be the template parameter 1458 // type (i.e., T&& is changed to simply T). [ Note: As a result, when 1459 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be 1460 // deduced as X&. - end note ] 1461 TDF &= ~TDF_TopLevelParameterTypeList; 1462 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType()) 1463 Param = Param->getPointeeType(); 1464 } 1465 } 1466 1467 // C++ [temp.deduct.type]p9: 1468 // A template type argument T, a template template argument TT or a 1469 // template non-type argument i can be deduced if P and A have one of 1470 // the following forms: 1471 // 1472 // T 1473 // cv-list T 1474 if (const TemplateTypeParmType *TemplateTypeParm 1475 = Param->getAs<TemplateTypeParmType>()) { 1476 // Just skip any attempts to deduce from a placeholder type or a parameter 1477 // at a different depth. 1478 if (Arg->isPlaceholderType() || 1479 Info.getDeducedDepth() != TemplateTypeParm->getDepth()) 1480 return Sema::TDK_Success; 1481 1482 unsigned Index = TemplateTypeParm->getIndex(); 1483 bool RecanonicalizeArg = false; 1484 1485 // If the argument type is an array type, move the qualifiers up to the 1486 // top level, so they can be matched with the qualifiers on the parameter. 1487 if (isa<ArrayType>(Arg)) { 1488 Qualifiers Quals; 1489 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals); 1490 if (Quals) { 1491 Arg = S.Context.getQualifiedType(Arg, Quals); 1492 RecanonicalizeArg = true; 1493 } 1494 } 1495 1496 // The argument type can not be less qualified than the parameter 1497 // type. 1498 if (!(TDF & TDF_IgnoreQualifiers) && 1499 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) { 1500 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1501 Info.FirstArg = TemplateArgument(Param); 1502 Info.SecondArg = TemplateArgument(Arg); 1503 return Sema::TDK_Underqualified; 1504 } 1505 1506 // Do not match a function type with a cv-qualified type. 1507 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584 1508 if (Arg->isFunctionType() && Param.hasQualifiers()) { 1509 return Sema::TDK_NonDeducedMismatch; 1510 } 1511 1512 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() && 1513 "saw template type parameter with wrong depth"); 1514 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function"); 1515 QualType DeducedType = Arg; 1516 1517 // Remove any qualifiers on the parameter from the deduced type. 1518 // We checked the qualifiers for consistency above. 1519 Qualifiers DeducedQs = DeducedType.getQualifiers(); 1520 Qualifiers ParamQs = Param.getQualifiers(); 1521 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers()); 1522 if (ParamQs.hasObjCGCAttr()) 1523 DeducedQs.removeObjCGCAttr(); 1524 if (ParamQs.hasAddressSpace()) 1525 DeducedQs.removeAddressSpace(); 1526 if (ParamQs.hasObjCLifetime()) 1527 DeducedQs.removeObjCLifetime(); 1528 1529 // Objective-C ARC: 1530 // If template deduction would produce a lifetime qualifier on a type 1531 // that is not a lifetime type, template argument deduction fails. 1532 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() && 1533 !DeducedType->isDependentType()) { 1534 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1535 Info.FirstArg = TemplateArgument(Param); 1536 Info.SecondArg = TemplateArgument(Arg); 1537 return Sema::TDK_Underqualified; 1538 } 1539 1540 // Objective-C ARC: 1541 // If template deduction would produce an argument type with lifetime type 1542 // but no lifetime qualifier, the __strong lifetime qualifier is inferred. 1543 if (S.getLangOpts().ObjCAutoRefCount && 1544 DeducedType->isObjCLifetimeType() && 1545 !DeducedQs.hasObjCLifetime()) 1546 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong); 1547 1548 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), 1549 DeducedQs); 1550 1551 if (RecanonicalizeArg) 1552 DeducedType = S.Context.getCanonicalType(DeducedType); 1553 1554 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound); 1555 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 1556 Deduced[Index], 1557 NewDeduced); 1558 if (Result.isNull()) { 1559 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1560 Info.FirstArg = Deduced[Index]; 1561 Info.SecondArg = NewDeduced; 1562 return Sema::TDK_Inconsistent; 1563 } 1564 1565 Deduced[Index] = Result; 1566 return Sema::TDK_Success; 1567 } 1568 1569 // Set up the template argument deduction information for a failure. 1570 Info.FirstArg = TemplateArgument(ParamIn); 1571 Info.SecondArg = TemplateArgument(ArgIn); 1572 1573 // If the parameter is an already-substituted template parameter 1574 // pack, do nothing: we don't know which of its arguments to look 1575 // at, so we have to wait until all of the parameter packs in this 1576 // expansion have arguments. 1577 if (isa<SubstTemplateTypeParmPackType>(Param)) 1578 return Sema::TDK_Success; 1579 1580 // Check the cv-qualifiers on the parameter and argument types. 1581 CanQualType CanParam = S.Context.getCanonicalType(Param); 1582 CanQualType CanArg = S.Context.getCanonicalType(Arg); 1583 if (!(TDF & TDF_IgnoreQualifiers)) { 1584 if (TDF & TDF_ParamWithReferenceType) { 1585 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg)) 1586 return Sema::TDK_NonDeducedMismatch; 1587 } else if (TDF & TDF_ArgWithReferenceType) { 1588 // C++ [temp.deduct.conv]p4: 1589 // If the original A is a reference type, A can be more cv-qualified 1590 // than the deduced A 1591 if (!Arg.getQualifiers().compatiblyIncludes(Param.getQualifiers())) 1592 return Sema::TDK_NonDeducedMismatch; 1593 1594 // Strip out all extra qualifiers from the argument to figure out the 1595 // type we're converting to, prior to the qualification conversion. 1596 Qualifiers Quals; 1597 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals); 1598 Arg = S.Context.getQualifiedType(Arg, Param.getQualifiers()); 1599 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) { 1600 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers()) 1601 return Sema::TDK_NonDeducedMismatch; 1602 } 1603 1604 // If the parameter type is not dependent, there is nothing to deduce. 1605 if (!Param->isDependentType()) { 1606 if (!(TDF & TDF_SkipNonDependent)) { 1607 bool NonDeduced = 1608 (TDF & TDF_AllowCompatibleFunctionType) 1609 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg) 1610 : Param != Arg; 1611 if (NonDeduced) { 1612 return Sema::TDK_NonDeducedMismatch; 1613 } 1614 } 1615 return Sema::TDK_Success; 1616 } 1617 } else if (!Param->isDependentType()) { 1618 if (!(TDF & TDF_SkipNonDependent)) { 1619 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(), 1620 ArgUnqualType = CanArg.getUnqualifiedType(); 1621 bool Success = 1622 (TDF & TDF_AllowCompatibleFunctionType) 1623 ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType) 1624 : ParamUnqualType == ArgUnqualType; 1625 if (Success) 1626 return Sema::TDK_Success; 1627 } else { 1628 return Sema::TDK_Success; 1629 } 1630 } 1631 1632 switch (Param->getTypeClass()) { 1633 // Non-canonical types cannot appear here. 1634 #define NON_CANONICAL_TYPE(Class, Base) \ 1635 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class); 1636 #define TYPE(Class, Base) 1637 #include "clang/AST/TypeNodes.inc" 1638 1639 case Type::TemplateTypeParm: 1640 case Type::SubstTemplateTypeParmPack: 1641 llvm_unreachable("Type nodes handled above"); 1642 1643 // These types cannot be dependent, so simply check whether the types are 1644 // the same. 1645 case Type::Builtin: 1646 case Type::VariableArray: 1647 case Type::Vector: 1648 case Type::FunctionNoProto: 1649 case Type::Record: 1650 case Type::Enum: 1651 case Type::ObjCObject: 1652 case Type::ObjCInterface: 1653 case Type::ObjCObjectPointer: 1654 case Type::ExtInt: 1655 if (TDF & TDF_SkipNonDependent) 1656 return Sema::TDK_Success; 1657 1658 if (TDF & TDF_IgnoreQualifiers) { 1659 Param = Param.getUnqualifiedType(); 1660 Arg = Arg.getUnqualifiedType(); 1661 } 1662 1663 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch; 1664 1665 // _Complex T [placeholder extension] 1666 case Type::Complex: 1667 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>()) 1668 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1669 cast<ComplexType>(Param)->getElementType(), 1670 ComplexArg->getElementType(), 1671 Info, Deduced, TDF); 1672 1673 return Sema::TDK_NonDeducedMismatch; 1674 1675 // _Atomic T [extension] 1676 case Type::Atomic: 1677 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>()) 1678 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1679 cast<AtomicType>(Param)->getValueType(), 1680 AtomicArg->getValueType(), 1681 Info, Deduced, TDF); 1682 1683 return Sema::TDK_NonDeducedMismatch; 1684 1685 // T * 1686 case Type::Pointer: { 1687 QualType PointeeType; 1688 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) { 1689 PointeeType = PointerArg->getPointeeType(); 1690 } else if (const ObjCObjectPointerType *PointerArg 1691 = Arg->getAs<ObjCObjectPointerType>()) { 1692 PointeeType = PointerArg->getPointeeType(); 1693 } else { 1694 return Sema::TDK_NonDeducedMismatch; 1695 } 1696 1697 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass); 1698 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1699 cast<PointerType>(Param)->getPointeeType(), 1700 PointeeType, 1701 Info, Deduced, SubTDF); 1702 } 1703 1704 // T & 1705 case Type::LValueReference: { 1706 const LValueReferenceType *ReferenceArg = 1707 Arg->getAs<LValueReferenceType>(); 1708 if (!ReferenceArg) 1709 return Sema::TDK_NonDeducedMismatch; 1710 1711 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1712 cast<LValueReferenceType>(Param)->getPointeeType(), 1713 ReferenceArg->getPointeeType(), Info, Deduced, 0); 1714 } 1715 1716 // T && [C++0x] 1717 case Type::RValueReference: { 1718 const RValueReferenceType *ReferenceArg = 1719 Arg->getAs<RValueReferenceType>(); 1720 if (!ReferenceArg) 1721 return Sema::TDK_NonDeducedMismatch; 1722 1723 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1724 cast<RValueReferenceType>(Param)->getPointeeType(), 1725 ReferenceArg->getPointeeType(), 1726 Info, Deduced, 0); 1727 } 1728 1729 // T [] (implied, but not stated explicitly) 1730 case Type::IncompleteArray: { 1731 const IncompleteArrayType *IncompleteArrayArg = 1732 S.Context.getAsIncompleteArrayType(Arg); 1733 if (!IncompleteArrayArg) 1734 return Sema::TDK_NonDeducedMismatch; 1735 1736 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 1737 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1738 S.Context.getAsIncompleteArrayType(Param)->getElementType(), 1739 IncompleteArrayArg->getElementType(), 1740 Info, Deduced, SubTDF); 1741 } 1742 1743 // T [integer-constant] 1744 case Type::ConstantArray: { 1745 const ConstantArrayType *ConstantArrayArg = 1746 S.Context.getAsConstantArrayType(Arg); 1747 if (!ConstantArrayArg) 1748 return Sema::TDK_NonDeducedMismatch; 1749 1750 const ConstantArrayType *ConstantArrayParm = 1751 S.Context.getAsConstantArrayType(Param); 1752 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize()) 1753 return Sema::TDK_NonDeducedMismatch; 1754 1755 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 1756 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1757 ConstantArrayParm->getElementType(), 1758 ConstantArrayArg->getElementType(), 1759 Info, Deduced, SubTDF); 1760 } 1761 1762 // type [i] 1763 case Type::DependentSizedArray: { 1764 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg); 1765 if (!ArrayArg) 1766 return Sema::TDK_NonDeducedMismatch; 1767 1768 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 1769 1770 // Check the element type of the arrays 1771 const DependentSizedArrayType *DependentArrayParm 1772 = S.Context.getAsDependentSizedArrayType(Param); 1773 if (Sema::TemplateDeductionResult Result 1774 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1775 DependentArrayParm->getElementType(), 1776 ArrayArg->getElementType(), 1777 Info, Deduced, SubTDF)) 1778 return Result; 1779 1780 // Determine the array bound is something we can deduce. 1781 const NonTypeTemplateParmDecl *NTTP 1782 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr()); 1783 if (!NTTP) 1784 return Sema::TDK_Success; 1785 1786 // We can perform template argument deduction for the given non-type 1787 // template parameter. 1788 assert(NTTP->getDepth() == Info.getDeducedDepth() && 1789 "saw non-type template parameter with wrong depth"); 1790 if (const ConstantArrayType *ConstantArrayArg 1791 = dyn_cast<ConstantArrayType>(ArrayArg)) { 1792 llvm::APSInt Size(ConstantArrayArg->getSize()); 1793 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size, 1794 S.Context.getSizeType(), 1795 /*ArrayBound=*/true, 1796 Info, Deduced); 1797 } 1798 if (const DependentSizedArrayType *DependentArrayArg 1799 = dyn_cast<DependentSizedArrayType>(ArrayArg)) 1800 if (DependentArrayArg->getSizeExpr()) 1801 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 1802 DependentArrayArg->getSizeExpr(), 1803 Info, Deduced); 1804 1805 // Incomplete type does not match a dependently-sized array type 1806 return Sema::TDK_NonDeducedMismatch; 1807 } 1808 1809 // type(*)(T) 1810 // T(*)() 1811 // T(*)(T) 1812 case Type::FunctionProto: { 1813 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList; 1814 const FunctionProtoType *FunctionProtoArg = 1815 dyn_cast<FunctionProtoType>(Arg); 1816 if (!FunctionProtoArg) 1817 return Sema::TDK_NonDeducedMismatch; 1818 1819 const FunctionProtoType *FunctionProtoParam = 1820 cast<FunctionProtoType>(Param); 1821 1822 if (FunctionProtoParam->getMethodQuals() 1823 != FunctionProtoArg->getMethodQuals() || 1824 FunctionProtoParam->getRefQualifier() 1825 != FunctionProtoArg->getRefQualifier() || 1826 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic()) 1827 return Sema::TDK_NonDeducedMismatch; 1828 1829 // Check return types. 1830 if (auto Result = DeduceTemplateArgumentsByTypeMatch( 1831 S, TemplateParams, FunctionProtoParam->getReturnType(), 1832 FunctionProtoArg->getReturnType(), Info, Deduced, 0)) 1833 return Result; 1834 1835 // Check parameter types. 1836 if (auto Result = DeduceTemplateArguments( 1837 S, TemplateParams, FunctionProtoParam->param_type_begin(), 1838 FunctionProtoParam->getNumParams(), 1839 FunctionProtoArg->param_type_begin(), 1840 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF)) 1841 return Result; 1842 1843 if (TDF & TDF_AllowCompatibleFunctionType) 1844 return Sema::TDK_Success; 1845 1846 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit 1847 // deducing through the noexcept-specifier if it's part of the canonical 1848 // type. libstdc++ relies on this. 1849 Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr(); 1850 if (const NonTypeTemplateParmDecl *NTTP = 1851 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr) 1852 : nullptr) { 1853 assert(NTTP->getDepth() == Info.getDeducedDepth() && 1854 "saw non-type template parameter with wrong depth"); 1855 1856 llvm::APSInt Noexcept(1); 1857 switch (FunctionProtoArg->canThrow()) { 1858 case CT_Cannot: 1859 Noexcept = 1; 1860 LLVM_FALLTHROUGH; 1861 1862 case CT_Can: 1863 // We give E in noexcept(E) the "deduced from array bound" treatment. 1864 // FIXME: Should we? 1865 return DeduceNonTypeTemplateArgument( 1866 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy, 1867 /*ArrayBound*/true, Info, Deduced); 1868 1869 case CT_Dependent: 1870 if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr()) 1871 return DeduceNonTypeTemplateArgument( 1872 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced); 1873 // Can't deduce anything from throw(T...). 1874 break; 1875 } 1876 } 1877 // FIXME: Detect non-deduced exception specification mismatches? 1878 // 1879 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow 1880 // top-level differences in noexcept-specifications. 1881 1882 return Sema::TDK_Success; 1883 } 1884 1885 case Type::InjectedClassName: 1886 // Treat a template's injected-class-name as if the template 1887 // specialization type had been used. 1888 Param = cast<InjectedClassNameType>(Param) 1889 ->getInjectedSpecializationType(); 1890 assert(isa<TemplateSpecializationType>(Param) && 1891 "injected class name is not a template specialization type"); 1892 LLVM_FALLTHROUGH; 1893 1894 // template-name<T> (where template-name refers to a class template) 1895 // template-name<i> 1896 // TT<T> 1897 // TT<i> 1898 // TT<> 1899 case Type::TemplateSpecialization: { 1900 const TemplateSpecializationType *SpecParam = 1901 cast<TemplateSpecializationType>(Param); 1902 1903 // When Arg cannot be a derived class, we can just try to deduce template 1904 // arguments from the template-id. 1905 const RecordType *RecordT = Arg->getAs<RecordType>(); 1906 if (!(TDF & TDF_DerivedClass) || !RecordT) 1907 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info, 1908 Deduced); 1909 1910 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(), 1911 Deduced.end()); 1912 1913 Sema::TemplateDeductionResult Result = DeduceTemplateArguments( 1914 S, TemplateParams, SpecParam, Arg, Info, Deduced); 1915 1916 if (Result == Sema::TDK_Success) 1917 return Result; 1918 1919 // We cannot inspect base classes as part of deduction when the type 1920 // is incomplete, so either instantiate any templates necessary to 1921 // complete the type, or skip over it if it cannot be completed. 1922 if (!S.isCompleteType(Info.getLocation(), Arg)) 1923 return Result; 1924 1925 // Reset the incorrectly deduced argument from above. 1926 Deduced = DeducedOrig; 1927 1928 // Check bases according to C++14 [temp.deduct.call] p4b3: 1929 Sema::TemplateDeductionResult BaseResult = DeduceTemplateBases( 1930 S, RecordT, TemplateParams, SpecParam, Info, Deduced); 1931 1932 if (BaseResult != Sema::TDK_Invalid) 1933 return BaseResult; 1934 return Result; 1935 } 1936 1937 // T type::* 1938 // T T::* 1939 // T (type::*)() 1940 // type (T::*)() 1941 // type (type::*)(T) 1942 // type (T::*)(T) 1943 // T (type::*)(T) 1944 // T (T::*)() 1945 // T (T::*)(T) 1946 case Type::MemberPointer: { 1947 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param); 1948 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg); 1949 if (!MemPtrArg) 1950 return Sema::TDK_NonDeducedMismatch; 1951 1952 QualType ParamPointeeType = MemPtrParam->getPointeeType(); 1953 if (ParamPointeeType->isFunctionType()) 1954 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true, 1955 /*IsCtorOrDtor=*/false, Info.getLocation()); 1956 QualType ArgPointeeType = MemPtrArg->getPointeeType(); 1957 if (ArgPointeeType->isFunctionType()) 1958 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true, 1959 /*IsCtorOrDtor=*/false, Info.getLocation()); 1960 1961 if (Sema::TemplateDeductionResult Result 1962 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1963 ParamPointeeType, 1964 ArgPointeeType, 1965 Info, Deduced, 1966 TDF & TDF_IgnoreQualifiers)) 1967 return Result; 1968 1969 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1970 QualType(MemPtrParam->getClass(), 0), 1971 QualType(MemPtrArg->getClass(), 0), 1972 Info, Deduced, 1973 TDF & TDF_IgnoreQualifiers); 1974 } 1975 1976 // (clang extension) 1977 // 1978 // type(^)(T) 1979 // T(^)() 1980 // T(^)(T) 1981 case Type::BlockPointer: { 1982 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param); 1983 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg); 1984 1985 if (!BlockPtrArg) 1986 return Sema::TDK_NonDeducedMismatch; 1987 1988 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1989 BlockPtrParam->getPointeeType(), 1990 BlockPtrArg->getPointeeType(), 1991 Info, Deduced, 0); 1992 } 1993 1994 // (clang extension) 1995 // 1996 // T __attribute__(((ext_vector_type(<integral constant>)))) 1997 case Type::ExtVector: { 1998 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param); 1999 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) { 2000 // Make sure that the vectors have the same number of elements. 2001 if (VectorParam->getNumElements() != VectorArg->getNumElements()) 2002 return Sema::TDK_NonDeducedMismatch; 2003 2004 // Perform deduction on the element types. 2005 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 2006 VectorParam->getElementType(), 2007 VectorArg->getElementType(), 2008 Info, Deduced, TDF); 2009 } 2010 2011 if (const DependentSizedExtVectorType *VectorArg 2012 = dyn_cast<DependentSizedExtVectorType>(Arg)) { 2013 // We can't check the number of elements, since the argument has a 2014 // dependent number of elements. This can only occur during partial 2015 // ordering. 2016 2017 // Perform deduction on the element types. 2018 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 2019 VectorParam->getElementType(), 2020 VectorArg->getElementType(), 2021 Info, Deduced, TDF); 2022 } 2023 2024 return Sema::TDK_NonDeducedMismatch; 2025 } 2026 2027 case Type::DependentVector: { 2028 const auto *VectorParam = cast<DependentVectorType>(Param); 2029 2030 if (const auto *VectorArg = dyn_cast<VectorType>(Arg)) { 2031 // Perform deduction on the element types. 2032 if (Sema::TemplateDeductionResult Result = 2033 DeduceTemplateArgumentsByTypeMatch( 2034 S, TemplateParams, VectorParam->getElementType(), 2035 VectorArg->getElementType(), Info, Deduced, TDF)) 2036 return Result; 2037 2038 // Perform deduction on the vector size, if we can. 2039 const NonTypeTemplateParmDecl *NTTP = 2040 getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr()); 2041 if (!NTTP) 2042 return Sema::TDK_Success; 2043 2044 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); 2045 ArgSize = VectorArg->getNumElements(); 2046 // Note that we use the "array bound" rules here; just like in that 2047 // case, we don't have any particular type for the vector size, but 2048 // we can provide one if necessary. 2049 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize, 2050 S.Context.UnsignedIntTy, true, 2051 Info, Deduced); 2052 } 2053 2054 if (const auto *VectorArg = dyn_cast<DependentVectorType>(Arg)) { 2055 // Perform deduction on the element types. 2056 if (Sema::TemplateDeductionResult Result = 2057 DeduceTemplateArgumentsByTypeMatch( 2058 S, TemplateParams, VectorParam->getElementType(), 2059 VectorArg->getElementType(), Info, Deduced, TDF)) 2060 return Result; 2061 2062 // Perform deduction on the vector size, if we can. 2063 const NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr( 2064 Info, VectorParam->getSizeExpr()); 2065 if (!NTTP) 2066 return Sema::TDK_Success; 2067 2068 return DeduceNonTypeTemplateArgument( 2069 S, TemplateParams, NTTP, VectorArg->getSizeExpr(), Info, Deduced); 2070 } 2071 2072 return Sema::TDK_NonDeducedMismatch; 2073 } 2074 2075 // (clang extension) 2076 // 2077 // T __attribute__(((ext_vector_type(N)))) 2078 case Type::DependentSizedExtVector: { 2079 const DependentSizedExtVectorType *VectorParam 2080 = cast<DependentSizedExtVectorType>(Param); 2081 2082 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) { 2083 // Perform deduction on the element types. 2084 if (Sema::TemplateDeductionResult Result 2085 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 2086 VectorParam->getElementType(), 2087 VectorArg->getElementType(), 2088 Info, Deduced, TDF)) 2089 return Result; 2090 2091 // Perform deduction on the vector size, if we can. 2092 const NonTypeTemplateParmDecl *NTTP = 2093 getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr()); 2094 if (!NTTP) 2095 return Sema::TDK_Success; 2096 2097 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); 2098 ArgSize = VectorArg->getNumElements(); 2099 // Note that we use the "array bound" rules here; just like in that 2100 // case, we don't have any particular type for the vector size, but 2101 // we can provide one if necessary. 2102 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize, 2103 S.Context.IntTy, true, Info, 2104 Deduced); 2105 } 2106 2107 if (const DependentSizedExtVectorType *VectorArg 2108 = dyn_cast<DependentSizedExtVectorType>(Arg)) { 2109 // Perform deduction on the element types. 2110 if (Sema::TemplateDeductionResult Result 2111 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 2112 VectorParam->getElementType(), 2113 VectorArg->getElementType(), 2114 Info, Deduced, TDF)) 2115 return Result; 2116 2117 // Perform deduction on the vector size, if we can. 2118 const NonTypeTemplateParmDecl *NTTP = 2119 getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr()); 2120 if (!NTTP) 2121 return Sema::TDK_Success; 2122 2123 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 2124 VectorArg->getSizeExpr(), 2125 Info, Deduced); 2126 } 2127 2128 return Sema::TDK_NonDeducedMismatch; 2129 } 2130 2131 // (clang extension) 2132 // 2133 // T __attribute__((matrix_type(<integral constant>, 2134 // <integral constant>))) 2135 case Type::ConstantMatrix: { 2136 const ConstantMatrixType *MatrixArg = dyn_cast<ConstantMatrixType>(Arg); 2137 if (!MatrixArg) 2138 return Sema::TDK_NonDeducedMismatch; 2139 2140 const ConstantMatrixType *MatrixParam = cast<ConstantMatrixType>(Param); 2141 // Check that the dimensions are the same 2142 if (MatrixParam->getNumRows() != MatrixArg->getNumRows() || 2143 MatrixParam->getNumColumns() != MatrixArg->getNumColumns()) { 2144 return Sema::TDK_NonDeducedMismatch; 2145 } 2146 // Perform deduction on element types. 2147 return DeduceTemplateArgumentsByTypeMatch( 2148 S, TemplateParams, MatrixParam->getElementType(), 2149 MatrixArg->getElementType(), Info, Deduced, TDF); 2150 } 2151 2152 case Type::DependentSizedMatrix: { 2153 const MatrixType *MatrixArg = dyn_cast<MatrixType>(Arg); 2154 if (!MatrixArg) 2155 return Sema::TDK_NonDeducedMismatch; 2156 2157 // Check the element type of the matrixes. 2158 const DependentSizedMatrixType *MatrixParam = 2159 cast<DependentSizedMatrixType>(Param); 2160 if (Sema::TemplateDeductionResult Result = 2161 DeduceTemplateArgumentsByTypeMatch( 2162 S, TemplateParams, MatrixParam->getElementType(), 2163 MatrixArg->getElementType(), Info, Deduced, TDF)) 2164 return Result; 2165 2166 // Try to deduce a matrix dimension. 2167 auto DeduceMatrixArg = 2168 [&S, &Info, &Deduced, &TemplateParams]( 2169 Expr *ParamExpr, const MatrixType *Arg, 2170 unsigned (ConstantMatrixType::*GetArgDimension)() const, 2171 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) { 2172 const auto *ArgConstMatrix = dyn_cast<ConstantMatrixType>(Arg); 2173 const auto *ArgDepMatrix = dyn_cast<DependentSizedMatrixType>(Arg); 2174 if (!ParamExpr->isValueDependent()) { 2175 Optional<llvm::APSInt> ParamConst = 2176 ParamExpr->getIntegerConstantExpr(S.Context); 2177 if (!ParamConst) 2178 return Sema::TDK_NonDeducedMismatch; 2179 2180 if (ArgConstMatrix) { 2181 if ((ArgConstMatrix->*GetArgDimension)() == *ParamConst) 2182 return Sema::TDK_Success; 2183 return Sema::TDK_NonDeducedMismatch; 2184 } 2185 2186 Expr *ArgExpr = (ArgDepMatrix->*GetArgDimensionExpr)(); 2187 if (!ArgExpr->isValueDependent()) 2188 if (Optional<llvm::APSInt> ArgConst = 2189 ArgExpr->getIntegerConstantExpr(S.Context)) 2190 if (*ArgConst == *ParamConst) 2191 return Sema::TDK_Success; 2192 return Sema::TDK_NonDeducedMismatch; 2193 } 2194 2195 const NonTypeTemplateParmDecl *NTTP = 2196 getDeducedParameterFromExpr(Info, ParamExpr); 2197 if (!NTTP) 2198 return Sema::TDK_Success; 2199 2200 if (ArgConstMatrix) { 2201 llvm::APSInt ArgConst( 2202 S.Context.getTypeSize(S.Context.getSizeType())); 2203 ArgConst = (ArgConstMatrix->*GetArgDimension)(); 2204 return DeduceNonTypeTemplateArgument( 2205 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(), 2206 /*ArrayBound=*/true, Info, Deduced); 2207 } 2208 2209 return DeduceNonTypeTemplateArgument( 2210 S, TemplateParams, NTTP, (ArgDepMatrix->*GetArgDimensionExpr)(), 2211 Info, Deduced); 2212 }; 2213 2214 auto Result = DeduceMatrixArg(MatrixParam->getRowExpr(), MatrixArg, 2215 &ConstantMatrixType::getNumRows, 2216 &DependentSizedMatrixType::getRowExpr); 2217 if (Result) 2218 return Result; 2219 2220 return DeduceMatrixArg(MatrixParam->getColumnExpr(), MatrixArg, 2221 &ConstantMatrixType::getNumColumns, 2222 &DependentSizedMatrixType::getColumnExpr); 2223 } 2224 2225 // (clang extension) 2226 // 2227 // T __attribute__(((address_space(N)))) 2228 case Type::DependentAddressSpace: { 2229 const DependentAddressSpaceType *AddressSpaceParam = 2230 cast<DependentAddressSpaceType>(Param); 2231 2232 if (const DependentAddressSpaceType *AddressSpaceArg = 2233 dyn_cast<DependentAddressSpaceType>(Arg)) { 2234 // Perform deduction on the pointer type. 2235 if (Sema::TemplateDeductionResult Result = 2236 DeduceTemplateArgumentsByTypeMatch( 2237 S, TemplateParams, AddressSpaceParam->getPointeeType(), 2238 AddressSpaceArg->getPointeeType(), Info, Deduced, TDF)) 2239 return Result; 2240 2241 // Perform deduction on the address space, if we can. 2242 const NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr( 2243 Info, AddressSpaceParam->getAddrSpaceExpr()); 2244 if (!NTTP) 2245 return Sema::TDK_Success; 2246 2247 return DeduceNonTypeTemplateArgument( 2248 S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info, 2249 Deduced); 2250 } 2251 2252 if (isTargetAddressSpace(Arg.getAddressSpace())) { 2253 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy), 2254 false); 2255 ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace()); 2256 2257 // Perform deduction on the pointer types. 2258 if (Sema::TemplateDeductionResult Result = 2259 DeduceTemplateArgumentsByTypeMatch( 2260 S, TemplateParams, AddressSpaceParam->getPointeeType(), 2261 S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF)) 2262 return Result; 2263 2264 // Perform deduction on the address space, if we can. 2265 const NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr( 2266 Info, AddressSpaceParam->getAddrSpaceExpr()); 2267 if (!NTTP) 2268 return Sema::TDK_Success; 2269 2270 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 2271 ArgAddressSpace, S.Context.IntTy, 2272 true, Info, Deduced); 2273 } 2274 2275 return Sema::TDK_NonDeducedMismatch; 2276 } 2277 case Type::DependentExtInt: { 2278 const auto *IntParam = cast<DependentExtIntType>(Param); 2279 2280 if (const auto *IntArg = dyn_cast<ExtIntType>(Arg)){ 2281 if (IntParam->isUnsigned() != IntArg->isUnsigned()) 2282 return Sema::TDK_NonDeducedMismatch; 2283 2284 const NonTypeTemplateParmDecl *NTTP = 2285 getDeducedParameterFromExpr(Info, IntParam->getNumBitsExpr()); 2286 if (!NTTP) 2287 return Sema::TDK_Success; 2288 2289 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); 2290 ArgSize = IntArg->getNumBits(); 2291 2292 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize, 2293 S.Context.IntTy, true, Info, 2294 Deduced); 2295 } 2296 2297 if (const auto *IntArg = dyn_cast<DependentExtIntType>(Arg)) { 2298 if (IntParam->isUnsigned() != IntArg->isUnsigned()) 2299 return Sema::TDK_NonDeducedMismatch; 2300 return Sema::TDK_Success; 2301 } 2302 return Sema::TDK_NonDeducedMismatch; 2303 } 2304 2305 case Type::TypeOfExpr: 2306 case Type::TypeOf: 2307 case Type::DependentName: 2308 case Type::UnresolvedUsing: 2309 case Type::Decltype: 2310 case Type::UnaryTransform: 2311 case Type::Auto: 2312 case Type::DeducedTemplateSpecialization: 2313 case Type::DependentTemplateSpecialization: 2314 case Type::PackExpansion: 2315 case Type::Pipe: 2316 // No template argument deduction for these types 2317 return Sema::TDK_Success; 2318 } 2319 2320 llvm_unreachable("Invalid Type Class!"); 2321 } 2322 2323 static Sema::TemplateDeductionResult 2324 DeduceTemplateArguments(Sema &S, 2325 TemplateParameterList *TemplateParams, 2326 const TemplateArgument &Param, 2327 TemplateArgument Arg, 2328 TemplateDeductionInfo &Info, 2329 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 2330 // If the template argument is a pack expansion, perform template argument 2331 // deduction against the pattern of that expansion. This only occurs during 2332 // partial ordering. 2333 if (Arg.isPackExpansion()) 2334 Arg = Arg.getPackExpansionPattern(); 2335 2336 switch (Param.getKind()) { 2337 case TemplateArgument::Null: 2338 llvm_unreachable("Null template argument in parameter list"); 2339 2340 case TemplateArgument::Type: 2341 if (Arg.getKind() == TemplateArgument::Type) 2342 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 2343 Param.getAsType(), 2344 Arg.getAsType(), 2345 Info, Deduced, 0); 2346 Info.FirstArg = Param; 2347 Info.SecondArg = Arg; 2348 return Sema::TDK_NonDeducedMismatch; 2349 2350 case TemplateArgument::Template: 2351 if (Arg.getKind() == TemplateArgument::Template) 2352 return DeduceTemplateArguments(S, TemplateParams, 2353 Param.getAsTemplate(), 2354 Arg.getAsTemplate(), Info, Deduced); 2355 Info.FirstArg = Param; 2356 Info.SecondArg = Arg; 2357 return Sema::TDK_NonDeducedMismatch; 2358 2359 case TemplateArgument::TemplateExpansion: 2360 llvm_unreachable("caller should handle pack expansions"); 2361 2362 case TemplateArgument::Declaration: 2363 if (Arg.getKind() == TemplateArgument::Declaration && 2364 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl())) 2365 return Sema::TDK_Success; 2366 2367 Info.FirstArg = Param; 2368 Info.SecondArg = Arg; 2369 return Sema::TDK_NonDeducedMismatch; 2370 2371 case TemplateArgument::NullPtr: 2372 if (Arg.getKind() == TemplateArgument::NullPtr && 2373 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType())) 2374 return Sema::TDK_Success; 2375 2376 Info.FirstArg = Param; 2377 Info.SecondArg = Arg; 2378 return Sema::TDK_NonDeducedMismatch; 2379 2380 case TemplateArgument::Integral: 2381 if (Arg.getKind() == TemplateArgument::Integral) { 2382 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral())) 2383 return Sema::TDK_Success; 2384 2385 Info.FirstArg = Param; 2386 Info.SecondArg = Arg; 2387 return Sema::TDK_NonDeducedMismatch; 2388 } 2389 2390 if (Arg.getKind() == TemplateArgument::Expression) { 2391 Info.FirstArg = Param; 2392 Info.SecondArg = Arg; 2393 return Sema::TDK_NonDeducedMismatch; 2394 } 2395 2396 Info.FirstArg = Param; 2397 Info.SecondArg = Arg; 2398 return Sema::TDK_NonDeducedMismatch; 2399 2400 case TemplateArgument::Expression: 2401 if (const NonTypeTemplateParmDecl *NTTP = 2402 getDeducedParameterFromExpr(Info, Param.getAsExpr())) { 2403 if (Arg.getKind() == TemplateArgument::Integral) 2404 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 2405 Arg.getAsIntegral(), 2406 Arg.getIntegralType(), 2407 /*ArrayBound=*/false, 2408 Info, Deduced); 2409 if (Arg.getKind() == TemplateArgument::NullPtr) 2410 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP, 2411 Arg.getNullPtrType(), 2412 Info, Deduced); 2413 if (Arg.getKind() == TemplateArgument::Expression) 2414 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 2415 Arg.getAsExpr(), Info, Deduced); 2416 if (Arg.getKind() == TemplateArgument::Declaration) 2417 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, 2418 Arg.getAsDecl(), 2419 Arg.getParamTypeForDecl(), 2420 Info, Deduced); 2421 2422 Info.FirstArg = Param; 2423 Info.SecondArg = Arg; 2424 return Sema::TDK_NonDeducedMismatch; 2425 } 2426 2427 // Can't deduce anything, but that's okay. 2428 return Sema::TDK_Success; 2429 2430 case TemplateArgument::Pack: 2431 llvm_unreachable("Argument packs should be expanded by the caller!"); 2432 } 2433 2434 llvm_unreachable("Invalid TemplateArgument Kind!"); 2435 } 2436 2437 /// Determine whether there is a template argument to be used for 2438 /// deduction. 2439 /// 2440 /// This routine "expands" argument packs in-place, overriding its input 2441 /// parameters so that \c Args[ArgIdx] will be the available template argument. 2442 /// 2443 /// \returns true if there is another template argument (which will be at 2444 /// \c Args[ArgIdx]), false otherwise. 2445 static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args, 2446 unsigned &ArgIdx) { 2447 if (ArgIdx == Args.size()) 2448 return false; 2449 2450 const TemplateArgument &Arg = Args[ArgIdx]; 2451 if (Arg.getKind() != TemplateArgument::Pack) 2452 return true; 2453 2454 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?"); 2455 Args = Arg.pack_elements(); 2456 ArgIdx = 0; 2457 return ArgIdx < Args.size(); 2458 } 2459 2460 /// Determine whether the given set of template arguments has a pack 2461 /// expansion that is not the last template argument. 2462 static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) { 2463 bool FoundPackExpansion = false; 2464 for (const auto &A : Args) { 2465 if (FoundPackExpansion) 2466 return true; 2467 2468 if (A.getKind() == TemplateArgument::Pack) 2469 return hasPackExpansionBeforeEnd(A.pack_elements()); 2470 2471 // FIXME: If this is a fixed-arity pack expansion from an outer level of 2472 // templates, it should not be treated as a pack expansion. 2473 if (A.isPackExpansion()) 2474 FoundPackExpansion = true; 2475 } 2476 2477 return false; 2478 } 2479 2480 static Sema::TemplateDeductionResult 2481 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, 2482 ArrayRef<TemplateArgument> Params, 2483 ArrayRef<TemplateArgument> Args, 2484 TemplateDeductionInfo &Info, 2485 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2486 bool NumberOfArgumentsMustMatch) { 2487 // C++0x [temp.deduct.type]p9: 2488 // If the template argument list of P contains a pack expansion that is not 2489 // the last template argument, the entire template argument list is a 2490 // non-deduced context. 2491 if (hasPackExpansionBeforeEnd(Params)) 2492 return Sema::TDK_Success; 2493 2494 // C++0x [temp.deduct.type]p9: 2495 // If P has a form that contains <T> or <i>, then each argument Pi of the 2496 // respective template argument list P is compared with the corresponding 2497 // argument Ai of the corresponding template argument list of A. 2498 unsigned ArgIdx = 0, ParamIdx = 0; 2499 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) { 2500 if (!Params[ParamIdx].isPackExpansion()) { 2501 // The simple case: deduce template arguments by matching Pi and Ai. 2502 2503 // Check whether we have enough arguments. 2504 if (!hasTemplateArgumentForDeduction(Args, ArgIdx)) 2505 return NumberOfArgumentsMustMatch 2506 ? Sema::TDK_MiscellaneousDeductionFailure 2507 : Sema::TDK_Success; 2508 2509 // C++1z [temp.deduct.type]p9: 2510 // During partial ordering, if Ai was originally a pack expansion [and] 2511 // Pi is not a pack expansion, template argument deduction fails. 2512 if (Args[ArgIdx].isPackExpansion()) 2513 return Sema::TDK_MiscellaneousDeductionFailure; 2514 2515 // Perform deduction for this Pi/Ai pair. 2516 if (Sema::TemplateDeductionResult Result 2517 = DeduceTemplateArguments(S, TemplateParams, 2518 Params[ParamIdx], Args[ArgIdx], 2519 Info, Deduced)) 2520 return Result; 2521 2522 // Move to the next argument. 2523 ++ArgIdx; 2524 continue; 2525 } 2526 2527 // The parameter is a pack expansion. 2528 2529 // C++0x [temp.deduct.type]p9: 2530 // If Pi is a pack expansion, then the pattern of Pi is compared with 2531 // each remaining argument in the template argument list of A. Each 2532 // comparison deduces template arguments for subsequent positions in the 2533 // template parameter packs expanded by Pi. 2534 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern(); 2535 2536 // Prepare to deduce the packs within the pattern. 2537 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern); 2538 2539 // Keep track of the deduced template arguments for each parameter pack 2540 // expanded by this pack expansion (the outer index) and for each 2541 // template argument (the inner SmallVectors). 2542 for (; hasTemplateArgumentForDeduction(Args, ArgIdx) && 2543 PackScope.hasNextElement(); 2544 ++ArgIdx) { 2545 // Deduce template arguments from the pattern. 2546 if (Sema::TemplateDeductionResult Result 2547 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx], 2548 Info, Deduced)) 2549 return Result; 2550 2551 PackScope.nextPackElement(); 2552 } 2553 2554 // Build argument packs for each of the parameter packs expanded by this 2555 // pack expansion. 2556 if (auto Result = PackScope.finish()) 2557 return Result; 2558 } 2559 2560 return Sema::TDK_Success; 2561 } 2562 2563 static Sema::TemplateDeductionResult 2564 DeduceTemplateArguments(Sema &S, 2565 TemplateParameterList *TemplateParams, 2566 const TemplateArgumentList &ParamList, 2567 const TemplateArgumentList &ArgList, 2568 TemplateDeductionInfo &Info, 2569 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 2570 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(), 2571 ArgList.asArray(), Info, Deduced, 2572 /*NumberOfArgumentsMustMatch*/false); 2573 } 2574 2575 /// Determine whether two template arguments are the same. 2576 static bool isSameTemplateArg(ASTContext &Context, 2577 TemplateArgument X, 2578 const TemplateArgument &Y, 2579 bool PackExpansionMatchesPack = false) { 2580 // If we're checking deduced arguments (X) against original arguments (Y), 2581 // we will have flattened packs to non-expansions in X. 2582 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion()) 2583 X = X.getPackExpansionPattern(); 2584 2585 if (X.getKind() != Y.getKind()) 2586 return false; 2587 2588 switch (X.getKind()) { 2589 case TemplateArgument::Null: 2590 llvm_unreachable("Comparing NULL template argument"); 2591 2592 case TemplateArgument::Type: 2593 return Context.getCanonicalType(X.getAsType()) == 2594 Context.getCanonicalType(Y.getAsType()); 2595 2596 case TemplateArgument::Declaration: 2597 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl()); 2598 2599 case TemplateArgument::NullPtr: 2600 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()); 2601 2602 case TemplateArgument::Template: 2603 case TemplateArgument::TemplateExpansion: 2604 return Context.getCanonicalTemplateName( 2605 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() == 2606 Context.getCanonicalTemplateName( 2607 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer(); 2608 2609 case TemplateArgument::Integral: 2610 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral()); 2611 2612 case TemplateArgument::Expression: { 2613 llvm::FoldingSetNodeID XID, YID; 2614 X.getAsExpr()->Profile(XID, Context, true); 2615 Y.getAsExpr()->Profile(YID, Context, true); 2616 return XID == YID; 2617 } 2618 2619 case TemplateArgument::Pack: 2620 if (X.pack_size() != Y.pack_size()) 2621 return false; 2622 2623 for (TemplateArgument::pack_iterator XP = X.pack_begin(), 2624 XPEnd = X.pack_end(), 2625 YP = Y.pack_begin(); 2626 XP != XPEnd; ++XP, ++YP) 2627 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack)) 2628 return false; 2629 2630 return true; 2631 } 2632 2633 llvm_unreachable("Invalid TemplateArgument Kind!"); 2634 } 2635 2636 /// Allocate a TemplateArgumentLoc where all locations have 2637 /// been initialized to the given location. 2638 /// 2639 /// \param Arg The template argument we are producing template argument 2640 /// location information for. 2641 /// 2642 /// \param NTTPType For a declaration template argument, the type of 2643 /// the non-type template parameter that corresponds to this template 2644 /// argument. Can be null if no type sugar is available to add to the 2645 /// type from the template argument. 2646 /// 2647 /// \param Loc The source location to use for the resulting template 2648 /// argument. 2649 TemplateArgumentLoc 2650 Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, 2651 QualType NTTPType, SourceLocation Loc) { 2652 switch (Arg.getKind()) { 2653 case TemplateArgument::Null: 2654 llvm_unreachable("Can't get a NULL template argument here"); 2655 2656 case TemplateArgument::Type: 2657 return TemplateArgumentLoc( 2658 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc)); 2659 2660 case TemplateArgument::Declaration: { 2661 if (NTTPType.isNull()) 2662 NTTPType = Arg.getParamTypeForDecl(); 2663 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) 2664 .getAs<Expr>(); 2665 return TemplateArgumentLoc(TemplateArgument(E), E); 2666 } 2667 2668 case TemplateArgument::NullPtr: { 2669 if (NTTPType.isNull()) 2670 NTTPType = Arg.getNullPtrType(); 2671 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) 2672 .getAs<Expr>(); 2673 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true), 2674 E); 2675 } 2676 2677 case TemplateArgument::Integral: { 2678 Expr *E = 2679 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>(); 2680 return TemplateArgumentLoc(TemplateArgument(E), E); 2681 } 2682 2683 case TemplateArgument::Template: 2684 case TemplateArgument::TemplateExpansion: { 2685 NestedNameSpecifierLocBuilder Builder; 2686 TemplateName Template = Arg.getAsTemplateOrTemplatePattern(); 2687 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) 2688 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc); 2689 else if (QualifiedTemplateName *QTN = 2690 Template.getAsQualifiedTemplateName()) 2691 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc); 2692 2693 if (Arg.getKind() == TemplateArgument::Template) 2694 return TemplateArgumentLoc(Context, Arg, 2695 Builder.getWithLocInContext(Context), Loc); 2696 2697 return TemplateArgumentLoc( 2698 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc); 2699 } 2700 2701 case TemplateArgument::Expression: 2702 return TemplateArgumentLoc(Arg, Arg.getAsExpr()); 2703 2704 case TemplateArgument::Pack: 2705 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo()); 2706 } 2707 2708 llvm_unreachable("Invalid TemplateArgument Kind!"); 2709 } 2710 2711 TemplateArgumentLoc 2712 Sema::getIdentityTemplateArgumentLoc(NamedDecl *TemplateParm, 2713 SourceLocation Location) { 2714 return getTrivialTemplateArgumentLoc( 2715 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location); 2716 } 2717 2718 /// Convert the given deduced template argument and add it to the set of 2719 /// fully-converted template arguments. 2720 static bool 2721 ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, 2722 DeducedTemplateArgument Arg, 2723 NamedDecl *Template, 2724 TemplateDeductionInfo &Info, 2725 bool IsDeduced, 2726 SmallVectorImpl<TemplateArgument> &Output) { 2727 auto ConvertArg = [&](DeducedTemplateArgument Arg, 2728 unsigned ArgumentPackIndex) { 2729 // Convert the deduced template argument into a template 2730 // argument that we can check, almost as if the user had written 2731 // the template argument explicitly. 2732 TemplateArgumentLoc ArgLoc = 2733 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation()); 2734 2735 // Check the template argument, converting it as necessary. 2736 return S.CheckTemplateArgument( 2737 Param, ArgLoc, Template, Template->getLocation(), 2738 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output, 2739 IsDeduced 2740 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound 2741 : Sema::CTAK_Deduced) 2742 : Sema::CTAK_Specified); 2743 }; 2744 2745 if (Arg.getKind() == TemplateArgument::Pack) { 2746 // This is a template argument pack, so check each of its arguments against 2747 // the template parameter. 2748 SmallVector<TemplateArgument, 2> PackedArgsBuilder; 2749 for (const auto &P : Arg.pack_elements()) { 2750 // When converting the deduced template argument, append it to the 2751 // general output list. We need to do this so that the template argument 2752 // checking logic has all of the prior template arguments available. 2753 DeducedTemplateArgument InnerArg(P); 2754 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound()); 2755 assert(InnerArg.getKind() != TemplateArgument::Pack && 2756 "deduced nested pack"); 2757 if (P.isNull()) { 2758 // We deduced arguments for some elements of this pack, but not for 2759 // all of them. This happens if we get a conditionally-non-deduced 2760 // context in a pack expansion (such as an overload set in one of the 2761 // arguments). 2762 S.Diag(Param->getLocation(), 2763 diag::err_template_arg_deduced_incomplete_pack) 2764 << Arg << Param; 2765 return true; 2766 } 2767 if (ConvertArg(InnerArg, PackedArgsBuilder.size())) 2768 return true; 2769 2770 // Move the converted template argument into our argument pack. 2771 PackedArgsBuilder.push_back(Output.pop_back_val()); 2772 } 2773 2774 // If the pack is empty, we still need to substitute into the parameter 2775 // itself, in case that substitution fails. 2776 if (PackedArgsBuilder.empty()) { 2777 LocalInstantiationScope Scope(S); 2778 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output); 2779 MultiLevelTemplateArgumentList Args(TemplateArgs); 2780 2781 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2782 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template, 2783 NTTP, Output, 2784 Template->getSourceRange()); 2785 if (Inst.isInvalid() || 2786 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(), 2787 NTTP->getDeclName()).isNull()) 2788 return true; 2789 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) { 2790 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template, 2791 TTP, Output, 2792 Template->getSourceRange()); 2793 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args)) 2794 return true; 2795 } 2796 // For type parameters, no substitution is ever required. 2797 } 2798 2799 // Create the resulting argument pack. 2800 Output.push_back( 2801 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder)); 2802 return false; 2803 } 2804 2805 return ConvertArg(Arg, 0); 2806 } 2807 2808 // FIXME: This should not be a template, but 2809 // ClassTemplatePartialSpecializationDecl sadly does not derive from 2810 // TemplateDecl. 2811 template<typename TemplateDeclT> 2812 static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments( 2813 Sema &S, TemplateDeclT *Template, bool IsDeduced, 2814 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2815 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder, 2816 LocalInstantiationScope *CurrentInstantiationScope = nullptr, 2817 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) { 2818 TemplateParameterList *TemplateParams = Template->getTemplateParameters(); 2819 2820 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 2821 NamedDecl *Param = TemplateParams->getParam(I); 2822 2823 // C++0x [temp.arg.explicit]p3: 2824 // A trailing template parameter pack (14.5.3) not otherwise deduced will 2825 // be deduced to an empty sequence of template arguments. 2826 // FIXME: Where did the word "trailing" come from? 2827 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) { 2828 if (auto Result = 2829 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish()) 2830 return Result; 2831 } 2832 2833 if (!Deduced[I].isNull()) { 2834 if (I < NumAlreadyConverted) { 2835 // We may have had explicitly-specified template arguments for a 2836 // template parameter pack (that may or may not have been extended 2837 // via additional deduced arguments). 2838 if (Param->isParameterPack() && CurrentInstantiationScope && 2839 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) { 2840 // Forget the partially-substituted pack; its substitution is now 2841 // complete. 2842 CurrentInstantiationScope->ResetPartiallySubstitutedPack(); 2843 // We still need to check the argument in case it was extended by 2844 // deduction. 2845 } else { 2846 // We have already fully type-checked and converted this 2847 // argument, because it was explicitly-specified. Just record the 2848 // presence of this argument. 2849 Builder.push_back(Deduced[I]); 2850 continue; 2851 } 2852 } 2853 2854 // We may have deduced this argument, so it still needs to be 2855 // checked and converted. 2856 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info, 2857 IsDeduced, Builder)) { 2858 Info.Param = makeTemplateParameter(Param); 2859 // FIXME: These template arguments are temporary. Free them! 2860 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder)); 2861 return Sema::TDK_SubstitutionFailure; 2862 } 2863 2864 continue; 2865 } 2866 2867 // Substitute into the default template argument, if available. 2868 bool HasDefaultArg = false; 2869 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template); 2870 if (!TD) { 2871 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) || 2872 isa<VarTemplatePartialSpecializationDecl>(Template)); 2873 return Sema::TDK_Incomplete; 2874 } 2875 2876 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable( 2877 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder, 2878 HasDefaultArg); 2879 2880 // If there was no default argument, deduction is incomplete. 2881 if (DefArg.getArgument().isNull()) { 2882 Info.Param = makeTemplateParameter( 2883 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 2884 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder)); 2885 if (PartialOverloading) break; 2886 2887 return HasDefaultArg ? Sema::TDK_SubstitutionFailure 2888 : Sema::TDK_Incomplete; 2889 } 2890 2891 // Check whether we can actually use the default argument. 2892 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(), 2893 TD->getSourceRange().getEnd(), 0, Builder, 2894 Sema::CTAK_Specified)) { 2895 Info.Param = makeTemplateParameter( 2896 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 2897 // FIXME: These template arguments are temporary. Free them! 2898 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder)); 2899 return Sema::TDK_SubstitutionFailure; 2900 } 2901 2902 // If we get here, we successfully used the default template argument. 2903 } 2904 2905 return Sema::TDK_Success; 2906 } 2907 2908 static DeclContext *getAsDeclContextOrEnclosing(Decl *D) { 2909 if (auto *DC = dyn_cast<DeclContext>(D)) 2910 return DC; 2911 return D->getDeclContext(); 2912 } 2913 2914 template<typename T> struct IsPartialSpecialization { 2915 static constexpr bool value = false; 2916 }; 2917 template<> 2918 struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> { 2919 static constexpr bool value = true; 2920 }; 2921 template<> 2922 struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> { 2923 static constexpr bool value = true; 2924 }; 2925 2926 template<typename TemplateDeclT> 2927 static Sema::TemplateDeductionResult 2928 CheckDeducedArgumentConstraints(Sema& S, TemplateDeclT *Template, 2929 ArrayRef<TemplateArgument> DeducedArgs, 2930 TemplateDeductionInfo& Info) { 2931 llvm::SmallVector<const Expr *, 3> AssociatedConstraints; 2932 Template->getAssociatedConstraints(AssociatedConstraints); 2933 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, 2934 DeducedArgs, Info.getLocation(), 2935 Info.AssociatedConstraintsSatisfaction) || 2936 !Info.AssociatedConstraintsSatisfaction.IsSatisfied) { 2937 Info.reset(TemplateArgumentList::CreateCopy(S.Context, DeducedArgs)); 2938 return Sema::TDK_ConstraintsNotSatisfied; 2939 } 2940 return Sema::TDK_Success; 2941 } 2942 2943 /// Complete template argument deduction for a partial specialization. 2944 template <typename T> 2945 static std::enable_if_t<IsPartialSpecialization<T>::value, 2946 Sema::TemplateDeductionResult> 2947 FinishTemplateArgumentDeduction( 2948 Sema &S, T *Partial, bool IsPartialOrdering, 2949 const TemplateArgumentList &TemplateArgs, 2950 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2951 TemplateDeductionInfo &Info) { 2952 // Unevaluated SFINAE context. 2953 EnterExpressionEvaluationContext Unevaluated( 2954 S, Sema::ExpressionEvaluationContext::Unevaluated); 2955 Sema::SFINAETrap Trap(S); 2956 2957 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial)); 2958 2959 // C++ [temp.deduct.type]p2: 2960 // [...] or if any template argument remains neither deduced nor 2961 // explicitly specified, template argument deduction fails. 2962 SmallVector<TemplateArgument, 4> Builder; 2963 if (auto Result = ConvertDeducedTemplateArguments( 2964 S, Partial, IsPartialOrdering, Deduced, Info, Builder)) 2965 return Result; 2966 2967 // Form the template argument list from the deduced template arguments. 2968 TemplateArgumentList *DeducedArgumentList 2969 = TemplateArgumentList::CreateCopy(S.Context, Builder); 2970 2971 Info.reset(DeducedArgumentList); 2972 2973 // Substitute the deduced template arguments into the template 2974 // arguments of the class template partial specialization, and 2975 // verify that the instantiated template arguments are both valid 2976 // and are equivalent to the template arguments originally provided 2977 // to the class template. 2978 LocalInstantiationScope InstScope(S); 2979 auto *Template = Partial->getSpecializedTemplate(); 2980 const ASTTemplateArgumentListInfo *PartialTemplArgInfo = 2981 Partial->getTemplateArgsAsWritten(); 2982 const TemplateArgumentLoc *PartialTemplateArgs = 2983 PartialTemplArgInfo->getTemplateArgs(); 2984 2985 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc, 2986 PartialTemplArgInfo->RAngleLoc); 2987 2988 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs, 2989 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) { 2990 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx; 2991 if (ParamIdx >= Partial->getTemplateParameters()->size()) 2992 ParamIdx = Partial->getTemplateParameters()->size() - 1; 2993 2994 Decl *Param = const_cast<NamedDecl *>( 2995 Partial->getTemplateParameters()->getParam(ParamIdx)); 2996 Info.Param = makeTemplateParameter(Param); 2997 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument(); 2998 return Sema::TDK_SubstitutionFailure; 2999 } 3000 3001 bool ConstraintsNotSatisfied; 3002 SmallVector<TemplateArgument, 4> ConvertedInstArgs; 3003 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs, 3004 false, ConvertedInstArgs, 3005 /*UpdateArgsWithConversions=*/true, 3006 &ConstraintsNotSatisfied)) 3007 return ConstraintsNotSatisfied ? Sema::TDK_ConstraintsNotSatisfied : 3008 Sema::TDK_SubstitutionFailure; 3009 3010 TemplateParameterList *TemplateParams = Template->getTemplateParameters(); 3011 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { 3012 TemplateArgument InstArg = ConvertedInstArgs.data()[I]; 3013 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) { 3014 Info.Param = makeTemplateParameter(TemplateParams->getParam(I)); 3015 Info.FirstArg = TemplateArgs[I]; 3016 Info.SecondArg = InstArg; 3017 return Sema::TDK_NonDeducedMismatch; 3018 } 3019 } 3020 3021 if (Trap.hasErrorOccurred()) 3022 return Sema::TDK_SubstitutionFailure; 3023 3024 if (auto Result = CheckDeducedArgumentConstraints(S, Partial, Builder, Info)) 3025 return Result; 3026 3027 return Sema::TDK_Success; 3028 } 3029 3030 /// Complete template argument deduction for a class or variable template, 3031 /// when partial ordering against a partial specialization. 3032 // FIXME: Factor out duplication with partial specialization version above. 3033 static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction( 3034 Sema &S, TemplateDecl *Template, bool PartialOrdering, 3035 const TemplateArgumentList &TemplateArgs, 3036 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3037 TemplateDeductionInfo &Info) { 3038 // Unevaluated SFINAE context. 3039 EnterExpressionEvaluationContext Unevaluated( 3040 S, Sema::ExpressionEvaluationContext::Unevaluated); 3041 Sema::SFINAETrap Trap(S); 3042 3043 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template)); 3044 3045 // C++ [temp.deduct.type]p2: 3046 // [...] or if any template argument remains neither deduced nor 3047 // explicitly specified, template argument deduction fails. 3048 SmallVector<TemplateArgument, 4> Builder; 3049 if (auto Result = ConvertDeducedTemplateArguments( 3050 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder)) 3051 return Result; 3052 3053 // Check that we produced the correct argument list. 3054 TemplateParameterList *TemplateParams = Template->getTemplateParameters(); 3055 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { 3056 TemplateArgument InstArg = Builder[I]; 3057 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, 3058 /*PackExpansionMatchesPack*/true)) { 3059 Info.Param = makeTemplateParameter(TemplateParams->getParam(I)); 3060 Info.FirstArg = TemplateArgs[I]; 3061 Info.SecondArg = InstArg; 3062 return Sema::TDK_NonDeducedMismatch; 3063 } 3064 } 3065 3066 if (Trap.hasErrorOccurred()) 3067 return Sema::TDK_SubstitutionFailure; 3068 3069 if (auto Result = CheckDeducedArgumentConstraints(S, Template, Builder, 3070 Info)) 3071 return Result; 3072 3073 return Sema::TDK_Success; 3074 } 3075 3076 /// Perform template argument deduction to determine whether 3077 /// the given template arguments match the given class template 3078 /// partial specialization per C++ [temp.class.spec.match]. 3079 Sema::TemplateDeductionResult 3080 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 3081 const TemplateArgumentList &TemplateArgs, 3082 TemplateDeductionInfo &Info) { 3083 if (Partial->isInvalidDecl()) 3084 return TDK_Invalid; 3085 3086 // C++ [temp.class.spec.match]p2: 3087 // A partial specialization matches a given actual template 3088 // argument list if the template arguments of the partial 3089 // specialization can be deduced from the actual template argument 3090 // list (14.8.2). 3091 3092 // Unevaluated SFINAE context. 3093 EnterExpressionEvaluationContext Unevaluated( 3094 *this, Sema::ExpressionEvaluationContext::Unevaluated); 3095 SFINAETrap Trap(*this); 3096 3097 SmallVector<DeducedTemplateArgument, 4> Deduced; 3098 Deduced.resize(Partial->getTemplateParameters()->size()); 3099 if (TemplateDeductionResult Result 3100 = ::DeduceTemplateArguments(*this, 3101 Partial->getTemplateParameters(), 3102 Partial->getTemplateArgs(), 3103 TemplateArgs, Info, Deduced)) 3104 return Result; 3105 3106 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 3107 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs, 3108 Info); 3109 if (Inst.isInvalid()) 3110 return TDK_InstantiationDepth; 3111 3112 if (Trap.hasErrorOccurred()) 3113 return Sema::TDK_SubstitutionFailure; 3114 3115 TemplateDeductionResult Result; 3116 runWithSufficientStackSpace(Info.getLocation(), [&] { 3117 Result = ::FinishTemplateArgumentDeduction(*this, Partial, 3118 /*IsPartialOrdering=*/false, 3119 TemplateArgs, Deduced, Info); 3120 }); 3121 return Result; 3122 } 3123 3124 /// Perform template argument deduction to determine whether 3125 /// the given template arguments match the given variable template 3126 /// partial specialization per C++ [temp.class.spec.match]. 3127 Sema::TemplateDeductionResult 3128 Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 3129 const TemplateArgumentList &TemplateArgs, 3130 TemplateDeductionInfo &Info) { 3131 if (Partial->isInvalidDecl()) 3132 return TDK_Invalid; 3133 3134 // C++ [temp.class.spec.match]p2: 3135 // A partial specialization matches a given actual template 3136 // argument list if the template arguments of the partial 3137 // specialization can be deduced from the actual template argument 3138 // list (14.8.2). 3139 3140 // Unevaluated SFINAE context. 3141 EnterExpressionEvaluationContext Unevaluated( 3142 *this, Sema::ExpressionEvaluationContext::Unevaluated); 3143 SFINAETrap Trap(*this); 3144 3145 SmallVector<DeducedTemplateArgument, 4> Deduced; 3146 Deduced.resize(Partial->getTemplateParameters()->size()); 3147 if (TemplateDeductionResult Result = ::DeduceTemplateArguments( 3148 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(), 3149 TemplateArgs, Info, Deduced)) 3150 return Result; 3151 3152 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 3153 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs, 3154 Info); 3155 if (Inst.isInvalid()) 3156 return TDK_InstantiationDepth; 3157 3158 if (Trap.hasErrorOccurred()) 3159 return Sema::TDK_SubstitutionFailure; 3160 3161 TemplateDeductionResult Result; 3162 runWithSufficientStackSpace(Info.getLocation(), [&] { 3163 Result = ::FinishTemplateArgumentDeduction(*this, Partial, 3164 /*IsPartialOrdering=*/false, 3165 TemplateArgs, Deduced, Info); 3166 }); 3167 return Result; 3168 } 3169 3170 /// Determine whether the given type T is a simple-template-id type. 3171 static bool isSimpleTemplateIdType(QualType T) { 3172 if (const TemplateSpecializationType *Spec 3173 = T->getAs<TemplateSpecializationType>()) 3174 return Spec->getTemplateName().getAsTemplateDecl() != nullptr; 3175 3176 // C++17 [temp.local]p2: 3177 // the injected-class-name [...] is equivalent to the template-name followed 3178 // by the template-arguments of the class template specialization or partial 3179 // specialization enclosed in <> 3180 // ... which means it's equivalent to a simple-template-id. 3181 // 3182 // This only arises during class template argument deduction for a copy 3183 // deduction candidate, where it permits slicing. 3184 if (T->getAs<InjectedClassNameType>()) 3185 return true; 3186 3187 return false; 3188 } 3189 3190 /// Substitute the explicitly-provided template arguments into the 3191 /// given function template according to C++ [temp.arg.explicit]. 3192 /// 3193 /// \param FunctionTemplate the function template into which the explicit 3194 /// template arguments will be substituted. 3195 /// 3196 /// \param ExplicitTemplateArgs the explicitly-specified template 3197 /// arguments. 3198 /// 3199 /// \param Deduced the deduced template arguments, which will be populated 3200 /// with the converted and checked explicit template arguments. 3201 /// 3202 /// \param ParamTypes will be populated with the instantiated function 3203 /// parameters. 3204 /// 3205 /// \param FunctionType if non-NULL, the result type of the function template 3206 /// will also be instantiated and the pointed-to value will be updated with 3207 /// the instantiated function type. 3208 /// 3209 /// \param Info if substitution fails for any reason, this object will be 3210 /// populated with more information about the failure. 3211 /// 3212 /// \returns TDK_Success if substitution was successful, or some failure 3213 /// condition. 3214 Sema::TemplateDeductionResult 3215 Sema::SubstituteExplicitTemplateArguments( 3216 FunctionTemplateDecl *FunctionTemplate, 3217 TemplateArgumentListInfo &ExplicitTemplateArgs, 3218 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3219 SmallVectorImpl<QualType> &ParamTypes, 3220 QualType *FunctionType, 3221 TemplateDeductionInfo &Info) { 3222 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 3223 TemplateParameterList *TemplateParams 3224 = FunctionTemplate->getTemplateParameters(); 3225 3226 if (ExplicitTemplateArgs.size() == 0) { 3227 // No arguments to substitute; just copy over the parameter types and 3228 // fill in the function type. 3229 for (auto P : Function->parameters()) 3230 ParamTypes.push_back(P->getType()); 3231 3232 if (FunctionType) 3233 *FunctionType = Function->getType(); 3234 return TDK_Success; 3235 } 3236 3237 // Unevaluated SFINAE context. 3238 EnterExpressionEvaluationContext Unevaluated( 3239 *this, Sema::ExpressionEvaluationContext::Unevaluated); 3240 SFINAETrap Trap(*this); 3241 3242 // C++ [temp.arg.explicit]p3: 3243 // Template arguments that are present shall be specified in the 3244 // declaration order of their corresponding template-parameters. The 3245 // template argument list shall not specify more template-arguments than 3246 // there are corresponding template-parameters. 3247 SmallVector<TemplateArgument, 4> Builder; 3248 3249 // Enter a new template instantiation context where we check the 3250 // explicitly-specified template arguments against this function template, 3251 // and then substitute them into the function parameter types. 3252 SmallVector<TemplateArgument, 4> DeducedArgs; 3253 InstantiatingTemplate Inst( 3254 *this, Info.getLocation(), FunctionTemplate, DeducedArgs, 3255 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info); 3256 if (Inst.isInvalid()) 3257 return TDK_InstantiationDepth; 3258 3259 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(), 3260 ExplicitTemplateArgs, true, Builder, false) || 3261 Trap.hasErrorOccurred()) { 3262 unsigned Index = Builder.size(); 3263 if (Index >= TemplateParams->size()) 3264 return TDK_SubstitutionFailure; 3265 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index)); 3266 return TDK_InvalidExplicitArguments; 3267 } 3268 3269 // Form the template argument list from the explicitly-specified 3270 // template arguments. 3271 TemplateArgumentList *ExplicitArgumentList 3272 = TemplateArgumentList::CreateCopy(Context, Builder); 3273 Info.setExplicitArgs(ExplicitArgumentList); 3274 3275 // Template argument deduction and the final substitution should be 3276 // done in the context of the templated declaration. Explicit 3277 // argument substitution, on the other hand, needs to happen in the 3278 // calling context. 3279 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 3280 3281 // If we deduced template arguments for a template parameter pack, 3282 // note that the template argument pack is partially substituted and record 3283 // the explicit template arguments. They'll be used as part of deduction 3284 // for this template parameter pack. 3285 unsigned PartiallySubstitutedPackIndex = -1u; 3286 if (!Builder.empty()) { 3287 const TemplateArgument &Arg = Builder.back(); 3288 if (Arg.getKind() == TemplateArgument::Pack) { 3289 auto *Param = TemplateParams->getParam(Builder.size() - 1); 3290 // If this is a fully-saturated fixed-size pack, it should be 3291 // fully-substituted, not partially-substituted. 3292 Optional<unsigned> Expansions = getExpandedPackSize(Param); 3293 if (!Expansions || Arg.pack_size() < *Expansions) { 3294 PartiallySubstitutedPackIndex = Builder.size() - 1; 3295 CurrentInstantiationScope->SetPartiallySubstitutedPack( 3296 Param, Arg.pack_begin(), Arg.pack_size()); 3297 } 3298 } 3299 } 3300 3301 const FunctionProtoType *Proto 3302 = Function->getType()->getAs<FunctionProtoType>(); 3303 assert(Proto && "Function template does not have a prototype?"); 3304 3305 // Isolate our substituted parameters from our caller. 3306 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true); 3307 3308 ExtParameterInfoBuilder ExtParamInfos; 3309 3310 // Instantiate the types of each of the function parameters given the 3311 // explicitly-specified template arguments. If the function has a trailing 3312 // return type, substitute it after the arguments to ensure we substitute 3313 // in lexical order. 3314 if (Proto->hasTrailingReturn()) { 3315 if (SubstParmTypes(Function->getLocation(), Function->parameters(), 3316 Proto->getExtParameterInfosOrNull(), 3317 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 3318 ParamTypes, /*params*/ nullptr, ExtParamInfos)) 3319 return TDK_SubstitutionFailure; 3320 } 3321 3322 // Instantiate the return type. 3323 QualType ResultType; 3324 { 3325 // C++11 [expr.prim.general]p3: 3326 // If a declaration declares a member function or member function 3327 // template of a class X, the expression this is a prvalue of type 3328 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 3329 // and the end of the function-definition, member-declarator, or 3330 // declarator. 3331 Qualifiers ThisTypeQuals; 3332 CXXRecordDecl *ThisContext = nullptr; 3333 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 3334 ThisContext = Method->getParent(); 3335 ThisTypeQuals = Method->getMethodQualifiers(); 3336 } 3337 3338 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals, 3339 getLangOpts().CPlusPlus11); 3340 3341 ResultType = 3342 SubstType(Proto->getReturnType(), 3343 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 3344 Function->getTypeSpecStartLoc(), Function->getDeclName()); 3345 if (ResultType.isNull() || Trap.hasErrorOccurred()) 3346 return TDK_SubstitutionFailure; 3347 // CUDA: Kernel function must have 'void' return type. 3348 if (getLangOpts().CUDA) 3349 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) { 3350 Diag(Function->getLocation(), diag::err_kern_type_not_void_return) 3351 << Function->getType() << Function->getSourceRange(); 3352 return TDK_SubstitutionFailure; 3353 } 3354 } 3355 3356 // Instantiate the types of each of the function parameters given the 3357 // explicitly-specified template arguments if we didn't do so earlier. 3358 if (!Proto->hasTrailingReturn() && 3359 SubstParmTypes(Function->getLocation(), Function->parameters(), 3360 Proto->getExtParameterInfosOrNull(), 3361 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 3362 ParamTypes, /*params*/ nullptr, ExtParamInfos)) 3363 return TDK_SubstitutionFailure; 3364 3365 if (FunctionType) { 3366 auto EPI = Proto->getExtProtoInfo(); 3367 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size()); 3368 3369 // In C++1z onwards, exception specifications are part of the function type, 3370 // so substitution into the type must also substitute into the exception 3371 // specification. 3372 SmallVector<QualType, 4> ExceptionStorage; 3373 if (getLangOpts().CPlusPlus17 && 3374 SubstExceptionSpec( 3375 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage, 3376 MultiLevelTemplateArgumentList(*ExplicitArgumentList))) 3377 return TDK_SubstitutionFailure; 3378 3379 *FunctionType = BuildFunctionType(ResultType, ParamTypes, 3380 Function->getLocation(), 3381 Function->getDeclName(), 3382 EPI); 3383 if (FunctionType->isNull() || Trap.hasErrorOccurred()) 3384 return TDK_SubstitutionFailure; 3385 } 3386 3387 // C++ [temp.arg.explicit]p2: 3388 // Trailing template arguments that can be deduced (14.8.2) may be 3389 // omitted from the list of explicit template-arguments. If all of the 3390 // template arguments can be deduced, they may all be omitted; in this 3391 // case, the empty template argument list <> itself may also be omitted. 3392 // 3393 // Take all of the explicitly-specified arguments and put them into 3394 // the set of deduced template arguments. The partially-substituted 3395 // parameter pack, however, will be set to NULL since the deduction 3396 // mechanism handles the partially-substituted argument pack directly. 3397 Deduced.reserve(TemplateParams->size()); 3398 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) { 3399 const TemplateArgument &Arg = ExplicitArgumentList->get(I); 3400 if (I == PartiallySubstitutedPackIndex) 3401 Deduced.push_back(DeducedTemplateArgument()); 3402 else 3403 Deduced.push_back(Arg); 3404 } 3405 3406 return TDK_Success; 3407 } 3408 3409 /// Check whether the deduced argument type for a call to a function 3410 /// template matches the actual argument type per C++ [temp.deduct.call]p4. 3411 static Sema::TemplateDeductionResult 3412 CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info, 3413 Sema::OriginalCallArg OriginalArg, 3414 QualType DeducedA) { 3415 ASTContext &Context = S.Context; 3416 3417 auto Failed = [&]() -> Sema::TemplateDeductionResult { 3418 Info.FirstArg = TemplateArgument(DeducedA); 3419 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType); 3420 Info.CallArgIndex = OriginalArg.ArgIdx; 3421 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested 3422 : Sema::TDK_DeducedMismatch; 3423 }; 3424 3425 QualType A = OriginalArg.OriginalArgType; 3426 QualType OriginalParamType = OriginalArg.OriginalParamType; 3427 3428 // Check for type equality (top-level cv-qualifiers are ignored). 3429 if (Context.hasSameUnqualifiedType(A, DeducedA)) 3430 return Sema::TDK_Success; 3431 3432 // Strip off references on the argument types; they aren't needed for 3433 // the following checks. 3434 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>()) 3435 DeducedA = DeducedARef->getPointeeType(); 3436 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) 3437 A = ARef->getPointeeType(); 3438 3439 // C++ [temp.deduct.call]p4: 3440 // [...] However, there are three cases that allow a difference: 3441 // - If the original P is a reference type, the deduced A (i.e., the 3442 // type referred to by the reference) can be more cv-qualified than 3443 // the transformed A. 3444 if (const ReferenceType *OriginalParamRef 3445 = OriginalParamType->getAs<ReferenceType>()) { 3446 // We don't want to keep the reference around any more. 3447 OriginalParamType = OriginalParamRef->getPointeeType(); 3448 3449 // FIXME: Resolve core issue (no number yet): if the original P is a 3450 // reference type and the transformed A is function type "noexcept F", 3451 // the deduced A can be F. 3452 QualType Tmp; 3453 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp)) 3454 return Sema::TDK_Success; 3455 3456 Qualifiers AQuals = A.getQualifiers(); 3457 Qualifiers DeducedAQuals = DeducedA.getQualifiers(); 3458 3459 // Under Objective-C++ ARC, the deduced type may have implicitly 3460 // been given strong or (when dealing with a const reference) 3461 // unsafe_unretained lifetime. If so, update the original 3462 // qualifiers to include this lifetime. 3463 if (S.getLangOpts().ObjCAutoRefCount && 3464 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong && 3465 AQuals.getObjCLifetime() == Qualifiers::OCL_None) || 3466 (DeducedAQuals.hasConst() && 3467 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) { 3468 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime()); 3469 } 3470 3471 if (AQuals == DeducedAQuals) { 3472 // Qualifiers match; there's nothing to do. 3473 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) { 3474 return Failed(); 3475 } else { 3476 // Qualifiers are compatible, so have the argument type adopt the 3477 // deduced argument type's qualifiers as if we had performed the 3478 // qualification conversion. 3479 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals); 3480 } 3481 } 3482 3483 // - The transformed A can be another pointer or pointer to member 3484 // type that can be converted to the deduced A via a function pointer 3485 // conversion and/or a qualification conversion. 3486 // 3487 // Also allow conversions which merely strip __attribute__((noreturn)) from 3488 // function types (recursively). 3489 bool ObjCLifetimeConversion = false; 3490 QualType ResultTy; 3491 if ((A->isAnyPointerType() || A->isMemberPointerType()) && 3492 (S.IsQualificationConversion(A, DeducedA, false, 3493 ObjCLifetimeConversion) || 3494 S.IsFunctionConversion(A, DeducedA, ResultTy))) 3495 return Sema::TDK_Success; 3496 3497 // - If P is a class and P has the form simple-template-id, then the 3498 // transformed A can be a derived class of the deduced A. [...] 3499 // [...] Likewise, if P is a pointer to a class of the form 3500 // simple-template-id, the transformed A can be a pointer to a 3501 // derived class pointed to by the deduced A. 3502 if (const PointerType *OriginalParamPtr 3503 = OriginalParamType->getAs<PointerType>()) { 3504 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) { 3505 if (const PointerType *APtr = A->getAs<PointerType>()) { 3506 if (A->getPointeeType()->isRecordType()) { 3507 OriginalParamType = OriginalParamPtr->getPointeeType(); 3508 DeducedA = DeducedAPtr->getPointeeType(); 3509 A = APtr->getPointeeType(); 3510 } 3511 } 3512 } 3513 } 3514 3515 if (Context.hasSameUnqualifiedType(A, DeducedA)) 3516 return Sema::TDK_Success; 3517 3518 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) && 3519 S.IsDerivedFrom(Info.getLocation(), A, DeducedA)) 3520 return Sema::TDK_Success; 3521 3522 return Failed(); 3523 } 3524 3525 /// Find the pack index for a particular parameter index in an instantiation of 3526 /// a function template with specific arguments. 3527 /// 3528 /// \return The pack index for whichever pack produced this parameter, or -1 3529 /// if this was not produced by a parameter. Intended to be used as the 3530 /// ArgumentPackSubstitutionIndex for further substitutions. 3531 // FIXME: We should track this in OriginalCallArgs so we don't need to 3532 // reconstruct it here. 3533 static unsigned getPackIndexForParam(Sema &S, 3534 FunctionTemplateDecl *FunctionTemplate, 3535 const MultiLevelTemplateArgumentList &Args, 3536 unsigned ParamIdx) { 3537 unsigned Idx = 0; 3538 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) { 3539 if (PD->isParameterPack()) { 3540 unsigned NumExpansions = 3541 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1); 3542 if (Idx + NumExpansions > ParamIdx) 3543 return ParamIdx - Idx; 3544 Idx += NumExpansions; 3545 } else { 3546 if (Idx == ParamIdx) 3547 return -1; // Not a pack expansion 3548 ++Idx; 3549 } 3550 } 3551 3552 llvm_unreachable("parameter index would not be produced from template"); 3553 } 3554 3555 /// Finish template argument deduction for a function template, 3556 /// checking the deduced template arguments for completeness and forming 3557 /// the function template specialization. 3558 /// 3559 /// \param OriginalCallArgs If non-NULL, the original call arguments against 3560 /// which the deduced argument types should be compared. 3561 Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction( 3562 FunctionTemplateDecl *FunctionTemplate, 3563 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3564 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, 3565 TemplateDeductionInfo &Info, 3566 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs, 3567 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) { 3568 // Unevaluated SFINAE context. 3569 EnterExpressionEvaluationContext Unevaluated( 3570 *this, Sema::ExpressionEvaluationContext::Unevaluated); 3571 SFINAETrap Trap(*this); 3572 3573 // Enter a new template instantiation context while we instantiate the 3574 // actual function declaration. 3575 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 3576 InstantiatingTemplate Inst( 3577 *this, Info.getLocation(), FunctionTemplate, DeducedArgs, 3578 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info); 3579 if (Inst.isInvalid()) 3580 return TDK_InstantiationDepth; 3581 3582 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 3583 3584 // C++ [temp.deduct.type]p2: 3585 // [...] or if any template argument remains neither deduced nor 3586 // explicitly specified, template argument deduction fails. 3587 SmallVector<TemplateArgument, 4> Builder; 3588 if (auto Result = ConvertDeducedTemplateArguments( 3589 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder, 3590 CurrentInstantiationScope, NumExplicitlySpecified, 3591 PartialOverloading)) 3592 return Result; 3593 3594 // C++ [temp.deduct.call]p10: [DR1391] 3595 // If deduction succeeds for all parameters that contain 3596 // template-parameters that participate in template argument deduction, 3597 // and all template arguments are explicitly specified, deduced, or 3598 // obtained from default template arguments, remaining parameters are then 3599 // compared with the corresponding arguments. For each remaining parameter 3600 // P with a type that was non-dependent before substitution of any 3601 // explicitly-specified template arguments, if the corresponding argument 3602 // A cannot be implicitly converted to P, deduction fails. 3603 if (CheckNonDependent()) 3604 return TDK_NonDependentConversionFailure; 3605 3606 // Form the template argument list from the deduced template arguments. 3607 TemplateArgumentList *DeducedArgumentList 3608 = TemplateArgumentList::CreateCopy(Context, Builder); 3609 Info.reset(DeducedArgumentList); 3610 3611 // Substitute the deduced template arguments into the function template 3612 // declaration to produce the function template specialization. 3613 DeclContext *Owner = FunctionTemplate->getDeclContext(); 3614 if (FunctionTemplate->getFriendObjectKind()) 3615 Owner = FunctionTemplate->getLexicalDeclContext(); 3616 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList); 3617 Specialization = cast_or_null<FunctionDecl>( 3618 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs)); 3619 if (!Specialization || Specialization->isInvalidDecl()) 3620 return TDK_SubstitutionFailure; 3621 3622 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() == 3623 FunctionTemplate->getCanonicalDecl()); 3624 3625 // If the template argument list is owned by the function template 3626 // specialization, release it. 3627 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList && 3628 !Trap.hasErrorOccurred()) 3629 Info.take(); 3630 3631 // There may have been an error that did not prevent us from constructing a 3632 // declaration. Mark the declaration invalid and return with a substitution 3633 // failure. 3634 if (Trap.hasErrorOccurred()) { 3635 Specialization->setInvalidDecl(true); 3636 return TDK_SubstitutionFailure; 3637 } 3638 3639 // C++2a [temp.deduct]p5 3640 // [...] When all template arguments have been deduced [...] all uses of 3641 // template parameters [...] are replaced with the corresponding deduced 3642 // or default argument values. 3643 // [...] If the function template has associated constraints 3644 // ([temp.constr.decl]), those constraints are checked for satisfaction 3645 // ([temp.constr.constr]). If the constraints are not satisfied, type 3646 // deduction fails. 3647 if (!PartialOverloading || 3648 (Builder.size() == FunctionTemplate->getTemplateParameters()->size())) { 3649 if (CheckInstantiatedFunctionTemplateConstraints(Info.getLocation(), 3650 Specialization, Builder, Info.AssociatedConstraintsSatisfaction)) 3651 return TDK_MiscellaneousDeductionFailure; 3652 3653 if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) { 3654 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder)); 3655 return TDK_ConstraintsNotSatisfied; 3656 } 3657 } 3658 3659 if (OriginalCallArgs) { 3660 // C++ [temp.deduct.call]p4: 3661 // In general, the deduction process attempts to find template argument 3662 // values that will make the deduced A identical to A (after the type A 3663 // is transformed as described above). [...] 3664 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes; 3665 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) { 3666 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I]; 3667 3668 auto ParamIdx = OriginalArg.ArgIdx; 3669 if (ParamIdx >= Specialization->getNumParams()) 3670 // FIXME: This presumably means a pack ended up smaller than we 3671 // expected while deducing. Should this not result in deduction 3672 // failure? Can it even happen? 3673 continue; 3674 3675 QualType DeducedA; 3676 if (!OriginalArg.DecomposedParam) { 3677 // P is one of the function parameters, just look up its substituted 3678 // type. 3679 DeducedA = Specialization->getParamDecl(ParamIdx)->getType(); 3680 } else { 3681 // P is a decomposed element of a parameter corresponding to a 3682 // braced-init-list argument. Substitute back into P to find the 3683 // deduced A. 3684 QualType &CacheEntry = 3685 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}]; 3686 if (CacheEntry.isNull()) { 3687 ArgumentPackSubstitutionIndexRAII PackIndex( 3688 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs, 3689 ParamIdx)); 3690 CacheEntry = 3691 SubstType(OriginalArg.OriginalParamType, SubstArgs, 3692 Specialization->getTypeSpecStartLoc(), 3693 Specialization->getDeclName()); 3694 } 3695 DeducedA = CacheEntry; 3696 } 3697 3698 if (auto TDK = 3699 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) 3700 return TDK; 3701 } 3702 } 3703 3704 // If we suppressed any diagnostics while performing template argument 3705 // deduction, and if we haven't already instantiated this declaration, 3706 // keep track of these diagnostics. They'll be emitted if this specialization 3707 // is actually used. 3708 if (Info.diag_begin() != Info.diag_end()) { 3709 SuppressedDiagnosticsMap::iterator 3710 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl()); 3711 if (Pos == SuppressedDiagnostics.end()) 3712 SuppressedDiagnostics[Specialization->getCanonicalDecl()] 3713 .append(Info.diag_begin(), Info.diag_end()); 3714 } 3715 3716 return TDK_Success; 3717 } 3718 3719 /// Gets the type of a function for template-argument-deducton 3720 /// purposes when it's considered as part of an overload set. 3721 static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, 3722 FunctionDecl *Fn) { 3723 // We may need to deduce the return type of the function now. 3724 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() && 3725 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false)) 3726 return {}; 3727 3728 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 3729 if (Method->isInstance()) { 3730 // An instance method that's referenced in a form that doesn't 3731 // look like a member pointer is just invalid. 3732 if (!R.HasFormOfMemberPointer) 3733 return {}; 3734 3735 return S.Context.getMemberPointerType(Fn->getType(), 3736 S.Context.getTypeDeclType(Method->getParent()).getTypePtr()); 3737 } 3738 3739 if (!R.IsAddressOfOperand) return Fn->getType(); 3740 return S.Context.getPointerType(Fn->getType()); 3741 } 3742 3743 /// Apply the deduction rules for overload sets. 3744 /// 3745 /// \return the null type if this argument should be treated as an 3746 /// undeduced context 3747 static QualType 3748 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, 3749 Expr *Arg, QualType ParamType, 3750 bool ParamWasReference) { 3751 3752 OverloadExpr::FindResult R = OverloadExpr::find(Arg); 3753 3754 OverloadExpr *Ovl = R.Expression; 3755 3756 // C++0x [temp.deduct.call]p4 3757 unsigned TDF = 0; 3758 if (ParamWasReference) 3759 TDF |= TDF_ParamWithReferenceType; 3760 if (R.IsAddressOfOperand) 3761 TDF |= TDF_IgnoreQualifiers; 3762 3763 // C++0x [temp.deduct.call]p6: 3764 // When P is a function type, pointer to function type, or pointer 3765 // to member function type: 3766 3767 if (!ParamType->isFunctionType() && 3768 !ParamType->isFunctionPointerType() && 3769 !ParamType->isMemberFunctionPointerType()) { 3770 if (Ovl->hasExplicitTemplateArgs()) { 3771 // But we can still look for an explicit specialization. 3772 if (FunctionDecl *ExplicitSpec 3773 = S.ResolveSingleFunctionTemplateSpecialization(Ovl)) 3774 return GetTypeOfFunction(S, R, ExplicitSpec); 3775 } 3776 3777 DeclAccessPair DAP; 3778 if (FunctionDecl *Viable = 3779 S.resolveAddressOfSingleOverloadCandidate(Arg, DAP)) 3780 return GetTypeOfFunction(S, R, Viable); 3781 3782 return {}; 3783 } 3784 3785 // Gather the explicit template arguments, if any. 3786 TemplateArgumentListInfo ExplicitTemplateArgs; 3787 if (Ovl->hasExplicitTemplateArgs()) 3788 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 3789 QualType Match; 3790 for (UnresolvedSetIterator I = Ovl->decls_begin(), 3791 E = Ovl->decls_end(); I != E; ++I) { 3792 NamedDecl *D = (*I)->getUnderlyingDecl(); 3793 3794 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) { 3795 // - If the argument is an overload set containing one or more 3796 // function templates, the parameter is treated as a 3797 // non-deduced context. 3798 if (!Ovl->hasExplicitTemplateArgs()) 3799 return {}; 3800 3801 // Otherwise, see if we can resolve a function type 3802 FunctionDecl *Specialization = nullptr; 3803 TemplateDeductionInfo Info(Ovl->getNameLoc()); 3804 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs, 3805 Specialization, Info)) 3806 continue; 3807 3808 D = Specialization; 3809 } 3810 3811 FunctionDecl *Fn = cast<FunctionDecl>(D); 3812 QualType ArgType = GetTypeOfFunction(S, R, Fn); 3813 if (ArgType.isNull()) continue; 3814 3815 // Function-to-pointer conversion. 3816 if (!ParamWasReference && ParamType->isPointerType() && 3817 ArgType->isFunctionType()) 3818 ArgType = S.Context.getPointerType(ArgType); 3819 3820 // - If the argument is an overload set (not containing function 3821 // templates), trial argument deduction is attempted using each 3822 // of the members of the set. If deduction succeeds for only one 3823 // of the overload set members, that member is used as the 3824 // argument value for the deduction. If deduction succeeds for 3825 // more than one member of the overload set the parameter is 3826 // treated as a non-deduced context. 3827 3828 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2: 3829 // Type deduction is done independently for each P/A pair, and 3830 // the deduced template argument values are then combined. 3831 // So we do not reject deductions which were made elsewhere. 3832 SmallVector<DeducedTemplateArgument, 8> 3833 Deduced(TemplateParams->size()); 3834 TemplateDeductionInfo Info(Ovl->getNameLoc()); 3835 Sema::TemplateDeductionResult Result 3836 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 3837 ArgType, Info, Deduced, TDF); 3838 if (Result) continue; 3839 if (!Match.isNull()) 3840 return {}; 3841 Match = ArgType; 3842 } 3843 3844 return Match; 3845 } 3846 3847 /// Perform the adjustments to the parameter and argument types 3848 /// described in C++ [temp.deduct.call]. 3849 /// 3850 /// \returns true if the caller should not attempt to perform any template 3851 /// argument deduction based on this P/A pair because the argument is an 3852 /// overloaded function set that could not be resolved. 3853 static bool AdjustFunctionParmAndArgTypesForDeduction( 3854 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, 3855 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) { 3856 // C++0x [temp.deduct.call]p3: 3857 // If P is a cv-qualified type, the top level cv-qualifiers of P's type 3858 // are ignored for type deduction. 3859 if (ParamType.hasQualifiers()) 3860 ParamType = ParamType.getUnqualifiedType(); 3861 3862 // [...] If P is a reference type, the type referred to by P is 3863 // used for type deduction. 3864 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>(); 3865 if (ParamRefType) 3866 ParamType = ParamRefType->getPointeeType(); 3867 3868 // Overload sets usually make this parameter an undeduced context, 3869 // but there are sometimes special circumstances. Typically 3870 // involving a template-id-expr. 3871 if (ArgType == S.Context.OverloadTy) { 3872 ArgType = ResolveOverloadForDeduction(S, TemplateParams, 3873 Arg, ParamType, 3874 ParamRefType != nullptr); 3875 if (ArgType.isNull()) 3876 return true; 3877 } 3878 3879 if (ParamRefType) { 3880 // If the argument has incomplete array type, try to complete its type. 3881 if (ArgType->isIncompleteArrayType()) { 3882 S.completeExprArrayBound(Arg); 3883 ArgType = Arg->getType(); 3884 } 3885 3886 // C++1z [temp.deduct.call]p3: 3887 // If P is a forwarding reference and the argument is an lvalue, the type 3888 // "lvalue reference to A" is used in place of A for type deduction. 3889 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) && 3890 Arg->isLValue()) { 3891 if (S.getLangOpts().OpenCL) 3892 ArgType = S.Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 3893 ArgType = S.Context.getLValueReferenceType(ArgType); 3894 } 3895 } else { 3896 // C++ [temp.deduct.call]p2: 3897 // If P is not a reference type: 3898 // - If A is an array type, the pointer type produced by the 3899 // array-to-pointer standard conversion (4.2) is used in place of 3900 // A for type deduction; otherwise, 3901 if (ArgType->isArrayType()) 3902 ArgType = S.Context.getArrayDecayedType(ArgType); 3903 // - If A is a function type, the pointer type produced by the 3904 // function-to-pointer standard conversion (4.3) is used in place 3905 // of A for type deduction; otherwise, 3906 else if (ArgType->isFunctionType()) 3907 ArgType = S.Context.getPointerType(ArgType); 3908 else { 3909 // - If A is a cv-qualified type, the top level cv-qualifiers of A's 3910 // type are ignored for type deduction. 3911 ArgType = ArgType.getUnqualifiedType(); 3912 } 3913 } 3914 3915 // C++0x [temp.deduct.call]p4: 3916 // In general, the deduction process attempts to find template argument 3917 // values that will make the deduced A identical to A (after the type A 3918 // is transformed as described above). [...] 3919 TDF = TDF_SkipNonDependent; 3920 3921 // - If the original P is a reference type, the deduced A (i.e., the 3922 // type referred to by the reference) can be more cv-qualified than 3923 // the transformed A. 3924 if (ParamRefType) 3925 TDF |= TDF_ParamWithReferenceType; 3926 // - The transformed A can be another pointer or pointer to member 3927 // type that can be converted to the deduced A via a qualification 3928 // conversion (4.4). 3929 if (ArgType->isPointerType() || ArgType->isMemberPointerType() || 3930 ArgType->isObjCObjectPointerType()) 3931 TDF |= TDF_IgnoreQualifiers; 3932 // - If P is a class and P has the form simple-template-id, then the 3933 // transformed A can be a derived class of the deduced A. Likewise, 3934 // if P is a pointer to a class of the form simple-template-id, the 3935 // transformed A can be a pointer to a derived class pointed to by 3936 // the deduced A. 3937 if (isSimpleTemplateIdType(ParamType) || 3938 (isa<PointerType>(ParamType) && 3939 isSimpleTemplateIdType( 3940 ParamType->getAs<PointerType>()->getPointeeType()))) 3941 TDF |= TDF_DerivedClass; 3942 3943 return false; 3944 } 3945 3946 static bool 3947 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate, 3948 QualType T); 3949 3950 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument( 3951 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, 3952 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info, 3953 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3954 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, 3955 bool DecomposedParam, unsigned ArgIdx, unsigned TDF); 3956 3957 /// Attempt template argument deduction from an initializer list 3958 /// deemed to be an argument in a function call. 3959 static Sema::TemplateDeductionResult DeduceFromInitializerList( 3960 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType, 3961 InitListExpr *ILE, TemplateDeductionInfo &Info, 3962 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3963 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx, 3964 unsigned TDF) { 3965 // C++ [temp.deduct.call]p1: (CWG 1591) 3966 // If removing references and cv-qualifiers from P gives 3967 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is 3968 // a non-empty initializer list, then deduction is performed instead for 3969 // each element of the initializer list, taking P0 as a function template 3970 // parameter type and the initializer element as its argument 3971 // 3972 // We've already removed references and cv-qualifiers here. 3973 if (!ILE->getNumInits()) 3974 return Sema::TDK_Success; 3975 3976 QualType ElTy; 3977 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType); 3978 if (ArrTy) 3979 ElTy = ArrTy->getElementType(); 3980 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) { 3981 // Otherwise, an initializer list argument causes the parameter to be 3982 // considered a non-deduced context 3983 return Sema::TDK_Success; 3984 } 3985 3986 // Resolving a core issue: a braced-init-list containing any designators is 3987 // a non-deduced context. 3988 for (Expr *E : ILE->inits()) 3989 if (isa<DesignatedInitExpr>(E)) 3990 return Sema::TDK_Success; 3991 3992 // Deduction only needs to be done for dependent types. 3993 if (ElTy->isDependentType()) { 3994 for (Expr *E : ILE->inits()) { 3995 if (auto Result = DeduceTemplateArgumentsFromCallArgument( 3996 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true, 3997 ArgIdx, TDF)) 3998 return Result; 3999 } 4000 } 4001 4002 // in the P0[N] case, if N is a non-type template parameter, N is deduced 4003 // from the length of the initializer list. 4004 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) { 4005 // Determine the array bound is something we can deduce. 4006 if (const NonTypeTemplateParmDecl *NTTP = 4007 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) { 4008 // We can perform template argument deduction for the given non-type 4009 // template parameter. 4010 // C++ [temp.deduct.type]p13: 4011 // The type of N in the type T[N] is std::size_t. 4012 QualType T = S.Context.getSizeType(); 4013 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits()); 4014 if (auto Result = DeduceNonTypeTemplateArgument( 4015 S, TemplateParams, NTTP, llvm::APSInt(Size), T, 4016 /*ArrayBound=*/true, Info, Deduced)) 4017 return Result; 4018 } 4019 } 4020 4021 return Sema::TDK_Success; 4022 } 4023 4024 /// Perform template argument deduction per [temp.deduct.call] for a 4025 /// single parameter / argument pair. 4026 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument( 4027 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, 4028 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info, 4029 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 4030 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, 4031 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) { 4032 QualType ArgType = Arg->getType(); 4033 QualType OrigParamType = ParamType; 4034 4035 // If P is a reference type [...] 4036 // If P is a cv-qualified type [...] 4037 if (AdjustFunctionParmAndArgTypesForDeduction( 4038 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF)) 4039 return Sema::TDK_Success; 4040 4041 // If [...] the argument is a non-empty initializer list [...] 4042 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) 4043 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info, 4044 Deduced, OriginalCallArgs, ArgIdx, TDF); 4045 4046 // [...] the deduction process attempts to find template argument values 4047 // that will make the deduced A identical to A 4048 // 4049 // Keep track of the argument type and corresponding parameter index, 4050 // so we can check for compatibility between the deduced A and A. 4051 OriginalCallArgs.push_back( 4052 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType)); 4053 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 4054 ArgType, Info, Deduced, TDF); 4055 } 4056 4057 /// Perform template argument deduction from a function call 4058 /// (C++ [temp.deduct.call]). 4059 /// 4060 /// \param FunctionTemplate the function template for which we are performing 4061 /// template argument deduction. 4062 /// 4063 /// \param ExplicitTemplateArgs the explicit template arguments provided 4064 /// for this call. 4065 /// 4066 /// \param Args the function call arguments 4067 /// 4068 /// \param Specialization if template argument deduction was successful, 4069 /// this will be set to the function template specialization produced by 4070 /// template argument deduction. 4071 /// 4072 /// \param Info the argument will be updated to provide additional information 4073 /// about template argument deduction. 4074 /// 4075 /// \param CheckNonDependent A callback to invoke to check conversions for 4076 /// non-dependent parameters, between deduction and substitution, per DR1391. 4077 /// If this returns true, substitution will be skipped and we return 4078 /// TDK_NonDependentConversionFailure. The callback is passed the parameter 4079 /// types (after substituting explicit template arguments). 4080 /// 4081 /// \returns the result of template argument deduction. 4082 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments( 4083 FunctionTemplateDecl *FunctionTemplate, 4084 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 4085 FunctionDecl *&Specialization, TemplateDeductionInfo &Info, 4086 bool PartialOverloading, 4087 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) { 4088 if (FunctionTemplate->isInvalidDecl()) 4089 return TDK_Invalid; 4090 4091 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 4092 unsigned NumParams = Function->getNumParams(); 4093 4094 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate); 4095 4096 // C++ [temp.deduct.call]p1: 4097 // Template argument deduction is done by comparing each function template 4098 // parameter type (call it P) with the type of the corresponding argument 4099 // of the call (call it A) as described below. 4100 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading) 4101 return TDK_TooFewArguments; 4102 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) { 4103 const auto *Proto = Function->getType()->castAs<FunctionProtoType>(); 4104 if (Proto->isTemplateVariadic()) 4105 /* Do nothing */; 4106 else if (!Proto->isVariadic()) 4107 return TDK_TooManyArguments; 4108 } 4109 4110 // The types of the parameters from which we will perform template argument 4111 // deduction. 4112 LocalInstantiationScope InstScope(*this); 4113 TemplateParameterList *TemplateParams 4114 = FunctionTemplate->getTemplateParameters(); 4115 SmallVector<DeducedTemplateArgument, 4> Deduced; 4116 SmallVector<QualType, 8> ParamTypes; 4117 unsigned NumExplicitlySpecified = 0; 4118 if (ExplicitTemplateArgs) { 4119 TemplateDeductionResult Result; 4120 runWithSufficientStackSpace(Info.getLocation(), [&] { 4121 Result = SubstituteExplicitTemplateArguments( 4122 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr, 4123 Info); 4124 }); 4125 if (Result) 4126 return Result; 4127 4128 NumExplicitlySpecified = Deduced.size(); 4129 } else { 4130 // Just fill in the parameter types from the function declaration. 4131 for (unsigned I = 0; I != NumParams; ++I) 4132 ParamTypes.push_back(Function->getParamDecl(I)->getType()); 4133 } 4134 4135 SmallVector<OriginalCallArg, 8> OriginalCallArgs; 4136 4137 // Deduce an argument of type ParamType from an expression with index ArgIdx. 4138 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) { 4139 // C++ [demp.deduct.call]p1: (DR1391) 4140 // Template argument deduction is done by comparing each function template 4141 // parameter that contains template-parameters that participate in 4142 // template argument deduction ... 4143 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType)) 4144 return Sema::TDK_Success; 4145 4146 // ... with the type of the corresponding argument 4147 return DeduceTemplateArgumentsFromCallArgument( 4148 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced, 4149 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0); 4150 }; 4151 4152 // Deduce template arguments from the function parameters. 4153 Deduced.resize(TemplateParams->size()); 4154 SmallVector<QualType, 8> ParamTypesForArgChecking; 4155 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0; 4156 ParamIdx != NumParamTypes; ++ParamIdx) { 4157 QualType ParamType = ParamTypes[ParamIdx]; 4158 4159 const PackExpansionType *ParamExpansion = 4160 dyn_cast<PackExpansionType>(ParamType); 4161 if (!ParamExpansion) { 4162 // Simple case: matching a function parameter to a function argument. 4163 if (ArgIdx >= Args.size()) 4164 break; 4165 4166 ParamTypesForArgChecking.push_back(ParamType); 4167 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++)) 4168 return Result; 4169 4170 continue; 4171 } 4172 4173 QualType ParamPattern = ParamExpansion->getPattern(); 4174 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info, 4175 ParamPattern); 4176 4177 // C++0x [temp.deduct.call]p1: 4178 // For a function parameter pack that occurs at the end of the 4179 // parameter-declaration-list, the type A of each remaining argument of 4180 // the call is compared with the type P of the declarator-id of the 4181 // function parameter pack. Each comparison deduces template arguments 4182 // for subsequent positions in the template parameter packs expanded by 4183 // the function parameter pack. When a function parameter pack appears 4184 // in a non-deduced context [not at the end of the list], the type of 4185 // that parameter pack is never deduced. 4186 // 4187 // FIXME: The above rule allows the size of the parameter pack to change 4188 // after we skip it (in the non-deduced case). That makes no sense, so 4189 // we instead notionally deduce the pack against N arguments, where N is 4190 // the length of the explicitly-specified pack if it's expanded by the 4191 // parameter pack and 0 otherwise, and we treat each deduction as a 4192 // non-deduced context. 4193 if (ParamIdx + 1 == NumParamTypes || PackScope.hasFixedArity()) { 4194 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); 4195 PackScope.nextPackElement(), ++ArgIdx) { 4196 ParamTypesForArgChecking.push_back(ParamPattern); 4197 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx)) 4198 return Result; 4199 } 4200 } else { 4201 // If the parameter type contains an explicitly-specified pack that we 4202 // could not expand, skip the number of parameters notionally created 4203 // by the expansion. 4204 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions(); 4205 if (NumExpansions && !PackScope.isPartiallyExpanded()) { 4206 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size(); 4207 ++I, ++ArgIdx) { 4208 ParamTypesForArgChecking.push_back(ParamPattern); 4209 // FIXME: Should we add OriginalCallArgs for these? What if the 4210 // corresponding argument is a list? 4211 PackScope.nextPackElement(); 4212 } 4213 } 4214 } 4215 4216 // Build argument packs for each of the parameter packs expanded by this 4217 // pack expansion. 4218 if (auto Result = PackScope.finish()) 4219 return Result; 4220 } 4221 4222 // Capture the context in which the function call is made. This is the context 4223 // that is needed when the accessibility of template arguments is checked. 4224 DeclContext *CallingCtx = CurContext; 4225 4226 TemplateDeductionResult Result; 4227 runWithSufficientStackSpace(Info.getLocation(), [&] { 4228 Result = FinishTemplateArgumentDeduction( 4229 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info, 4230 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() { 4231 ContextRAII SavedContext(*this, CallingCtx); 4232 return CheckNonDependent(ParamTypesForArgChecking); 4233 }); 4234 }); 4235 return Result; 4236 } 4237 4238 QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType, 4239 QualType FunctionType, 4240 bool AdjustExceptionSpec) { 4241 if (ArgFunctionType.isNull()) 4242 return ArgFunctionType; 4243 4244 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>(); 4245 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>(); 4246 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo(); 4247 bool Rebuild = false; 4248 4249 CallingConv CC = FunctionTypeP->getCallConv(); 4250 if (EPI.ExtInfo.getCC() != CC) { 4251 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC); 4252 Rebuild = true; 4253 } 4254 4255 bool NoReturn = FunctionTypeP->getNoReturnAttr(); 4256 if (EPI.ExtInfo.getNoReturn() != NoReturn) { 4257 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn); 4258 Rebuild = true; 4259 } 4260 4261 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() || 4262 ArgFunctionTypeP->hasExceptionSpec())) { 4263 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec; 4264 Rebuild = true; 4265 } 4266 4267 if (!Rebuild) 4268 return ArgFunctionType; 4269 4270 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(), 4271 ArgFunctionTypeP->getParamTypes(), EPI); 4272 } 4273 4274 /// Deduce template arguments when taking the address of a function 4275 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to 4276 /// a template. 4277 /// 4278 /// \param FunctionTemplate the function template for which we are performing 4279 /// template argument deduction. 4280 /// 4281 /// \param ExplicitTemplateArgs the explicitly-specified template 4282 /// arguments. 4283 /// 4284 /// \param ArgFunctionType the function type that will be used as the 4285 /// "argument" type (A) when performing template argument deduction from the 4286 /// function template's function type. This type may be NULL, if there is no 4287 /// argument type to compare against, in C++0x [temp.arg.explicit]p3. 4288 /// 4289 /// \param Specialization if template argument deduction was successful, 4290 /// this will be set to the function template specialization produced by 4291 /// template argument deduction. 4292 /// 4293 /// \param Info the argument will be updated to provide additional information 4294 /// about template argument deduction. 4295 /// 4296 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking 4297 /// the address of a function template per [temp.deduct.funcaddr] and 4298 /// [over.over]. If \c false, we are looking up a function template 4299 /// specialization based on its signature, per [temp.deduct.decl]. 4300 /// 4301 /// \returns the result of template argument deduction. 4302 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments( 4303 FunctionTemplateDecl *FunctionTemplate, 4304 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, 4305 FunctionDecl *&Specialization, TemplateDeductionInfo &Info, 4306 bool IsAddressOfFunction) { 4307 if (FunctionTemplate->isInvalidDecl()) 4308 return TDK_Invalid; 4309 4310 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 4311 TemplateParameterList *TemplateParams 4312 = FunctionTemplate->getTemplateParameters(); 4313 QualType FunctionType = Function->getType(); 4314 4315 // Substitute any explicit template arguments. 4316 LocalInstantiationScope InstScope(*this); 4317 SmallVector<DeducedTemplateArgument, 4> Deduced; 4318 unsigned NumExplicitlySpecified = 0; 4319 SmallVector<QualType, 4> ParamTypes; 4320 if (ExplicitTemplateArgs) { 4321 TemplateDeductionResult Result; 4322 runWithSufficientStackSpace(Info.getLocation(), [&] { 4323 Result = SubstituteExplicitTemplateArguments( 4324 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, 4325 &FunctionType, Info); 4326 }); 4327 if (Result) 4328 return Result; 4329 4330 NumExplicitlySpecified = Deduced.size(); 4331 } 4332 4333 // When taking the address of a function, we require convertibility of 4334 // the resulting function type. Otherwise, we allow arbitrary mismatches 4335 // of calling convention and noreturn. 4336 if (!IsAddressOfFunction) 4337 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType, 4338 /*AdjustExceptionSpec*/false); 4339 4340 // Unevaluated SFINAE context. 4341 EnterExpressionEvaluationContext Unevaluated( 4342 *this, Sema::ExpressionEvaluationContext::Unevaluated); 4343 SFINAETrap Trap(*this); 4344 4345 Deduced.resize(TemplateParams->size()); 4346 4347 // If the function has a deduced return type, substitute it for a dependent 4348 // type so that we treat it as a non-deduced context in what follows. If we 4349 // are looking up by signature, the signature type should also have a deduced 4350 // return type, which we instead expect to exactly match. 4351 bool HasDeducedReturnType = false; 4352 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction && 4353 Function->getReturnType()->getContainedAutoType()) { 4354 FunctionType = SubstAutoType(FunctionType, Context.DependentTy); 4355 HasDeducedReturnType = true; 4356 } 4357 4358 if (!ArgFunctionType.isNull()) { 4359 unsigned TDF = 4360 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType; 4361 // Deduce template arguments from the function type. 4362 if (TemplateDeductionResult Result 4363 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 4364 FunctionType, ArgFunctionType, 4365 Info, Deduced, TDF)) 4366 return Result; 4367 } 4368 4369 TemplateDeductionResult Result; 4370 runWithSufficientStackSpace(Info.getLocation(), [&] { 4371 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 4372 NumExplicitlySpecified, 4373 Specialization, Info); 4374 }); 4375 if (Result) 4376 return Result; 4377 4378 // If the function has a deduced return type, deduce it now, so we can check 4379 // that the deduced function type matches the requested type. 4380 if (HasDeducedReturnType && 4381 Specialization->getReturnType()->isUndeducedType() && 4382 DeduceReturnType(Specialization, Info.getLocation(), false)) 4383 return TDK_MiscellaneousDeductionFailure; 4384 4385 // If the function has a dependent exception specification, resolve it now, 4386 // so we can check that the exception specification matches. 4387 auto *SpecializationFPT = 4388 Specialization->getType()->castAs<FunctionProtoType>(); 4389 if (getLangOpts().CPlusPlus17 && 4390 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) && 4391 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT)) 4392 return TDK_MiscellaneousDeductionFailure; 4393 4394 // Adjust the exception specification of the argument to match the 4395 // substituted and resolved type we just formed. (Calling convention and 4396 // noreturn can't be dependent, so we don't actually need this for them 4397 // right now.) 4398 QualType SpecializationType = Specialization->getType(); 4399 if (!IsAddressOfFunction) 4400 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType, 4401 /*AdjustExceptionSpec*/true); 4402 4403 // If the requested function type does not match the actual type of the 4404 // specialization with respect to arguments of compatible pointer to function 4405 // types, template argument deduction fails. 4406 if (!ArgFunctionType.isNull()) { 4407 if (IsAddressOfFunction && 4408 !isSameOrCompatibleFunctionType( 4409 Context.getCanonicalType(SpecializationType), 4410 Context.getCanonicalType(ArgFunctionType))) 4411 return TDK_MiscellaneousDeductionFailure; 4412 4413 if (!IsAddressOfFunction && 4414 !Context.hasSameType(SpecializationType, ArgFunctionType)) 4415 return TDK_MiscellaneousDeductionFailure; 4416 } 4417 4418 return TDK_Success; 4419 } 4420 4421 /// Deduce template arguments for a templated conversion 4422 /// function (C++ [temp.deduct.conv]) and, if successful, produce a 4423 /// conversion function template specialization. 4424 Sema::TemplateDeductionResult 4425 Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate, 4426 QualType ToType, 4427 CXXConversionDecl *&Specialization, 4428 TemplateDeductionInfo &Info) { 4429 if (ConversionTemplate->isInvalidDecl()) 4430 return TDK_Invalid; 4431 4432 CXXConversionDecl *ConversionGeneric 4433 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl()); 4434 4435 QualType FromType = ConversionGeneric->getConversionType(); 4436 4437 // Canonicalize the types for deduction. 4438 QualType P = Context.getCanonicalType(FromType); 4439 QualType A = Context.getCanonicalType(ToType); 4440 4441 // C++0x [temp.deduct.conv]p2: 4442 // If P is a reference type, the type referred to by P is used for 4443 // type deduction. 4444 if (const ReferenceType *PRef = P->getAs<ReferenceType>()) 4445 P = PRef->getPointeeType(); 4446 4447 // C++0x [temp.deduct.conv]p4: 4448 // [...] If A is a reference type, the type referred to by A is used 4449 // for type deduction. 4450 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) { 4451 A = ARef->getPointeeType(); 4452 // We work around a defect in the standard here: cv-qualifiers are also 4453 // removed from P and A in this case, unless P was a reference type. This 4454 // seems to mostly match what other compilers are doing. 4455 if (!FromType->getAs<ReferenceType>()) { 4456 A = A.getUnqualifiedType(); 4457 P = P.getUnqualifiedType(); 4458 } 4459 4460 // C++ [temp.deduct.conv]p3: 4461 // 4462 // If A is not a reference type: 4463 } else { 4464 assert(!A->isReferenceType() && "Reference types were handled above"); 4465 4466 // - If P is an array type, the pointer type produced by the 4467 // array-to-pointer standard conversion (4.2) is used in place 4468 // of P for type deduction; otherwise, 4469 if (P->isArrayType()) 4470 P = Context.getArrayDecayedType(P); 4471 // - If P is a function type, the pointer type produced by the 4472 // function-to-pointer standard conversion (4.3) is used in 4473 // place of P for type deduction; otherwise, 4474 else if (P->isFunctionType()) 4475 P = Context.getPointerType(P); 4476 // - If P is a cv-qualified type, the top level cv-qualifiers of 4477 // P's type are ignored for type deduction. 4478 else 4479 P = P.getUnqualifiedType(); 4480 4481 // C++0x [temp.deduct.conv]p4: 4482 // If A is a cv-qualified type, the top level cv-qualifiers of A's 4483 // type are ignored for type deduction. If A is a reference type, the type 4484 // referred to by A is used for type deduction. 4485 A = A.getUnqualifiedType(); 4486 } 4487 4488 // Unevaluated SFINAE context. 4489 EnterExpressionEvaluationContext Unevaluated( 4490 *this, Sema::ExpressionEvaluationContext::Unevaluated); 4491 SFINAETrap Trap(*this); 4492 4493 // C++ [temp.deduct.conv]p1: 4494 // Template argument deduction is done by comparing the return 4495 // type of the template conversion function (call it P) with the 4496 // type that is required as the result of the conversion (call it 4497 // A) as described in 14.8.2.4. 4498 TemplateParameterList *TemplateParams 4499 = ConversionTemplate->getTemplateParameters(); 4500 SmallVector<DeducedTemplateArgument, 4> Deduced; 4501 Deduced.resize(TemplateParams->size()); 4502 4503 // C++0x [temp.deduct.conv]p4: 4504 // In general, the deduction process attempts to find template 4505 // argument values that will make the deduced A identical to 4506 // A. However, there are two cases that allow a difference: 4507 unsigned TDF = 0; 4508 // - If the original A is a reference type, A can be more 4509 // cv-qualified than the deduced A (i.e., the type referred to 4510 // by the reference) 4511 if (ToType->isReferenceType()) 4512 TDF |= TDF_ArgWithReferenceType; 4513 // - The deduced A can be another pointer or pointer to member 4514 // type that can be converted to A via a qualification 4515 // conversion. 4516 // 4517 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when 4518 // both P and A are pointers or member pointers. In this case, we 4519 // just ignore cv-qualifiers completely). 4520 if ((P->isPointerType() && A->isPointerType()) || 4521 (P->isMemberPointerType() && A->isMemberPointerType())) 4522 TDF |= TDF_IgnoreQualifiers; 4523 if (TemplateDeductionResult Result 4524 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 4525 P, A, Info, Deduced, TDF)) 4526 return Result; 4527 4528 // Create an Instantiation Scope for finalizing the operator. 4529 LocalInstantiationScope InstScope(*this); 4530 // Finish template argument deduction. 4531 FunctionDecl *ConversionSpecialized = nullptr; 4532 TemplateDeductionResult Result; 4533 runWithSufficientStackSpace(Info.getLocation(), [&] { 4534 Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0, 4535 ConversionSpecialized, Info); 4536 }); 4537 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized); 4538 return Result; 4539 } 4540 4541 /// Deduce template arguments for a function template when there is 4542 /// nothing to deduce against (C++0x [temp.arg.explicit]p3). 4543 /// 4544 /// \param FunctionTemplate the function template for which we are performing 4545 /// template argument deduction. 4546 /// 4547 /// \param ExplicitTemplateArgs the explicitly-specified template 4548 /// arguments. 4549 /// 4550 /// \param Specialization if template argument deduction was successful, 4551 /// this will be set to the function template specialization produced by 4552 /// template argument deduction. 4553 /// 4554 /// \param Info the argument will be updated to provide additional information 4555 /// about template argument deduction. 4556 /// 4557 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking 4558 /// the address of a function template in a context where we do not have a 4559 /// target type, per [over.over]. If \c false, we are looking up a function 4560 /// template specialization based on its signature, which only happens when 4561 /// deducing a function parameter type from an argument that is a template-id 4562 /// naming a function template specialization. 4563 /// 4564 /// \returns the result of template argument deduction. 4565 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments( 4566 FunctionTemplateDecl *FunctionTemplate, 4567 TemplateArgumentListInfo *ExplicitTemplateArgs, 4568 FunctionDecl *&Specialization, TemplateDeductionInfo &Info, 4569 bool IsAddressOfFunction) { 4570 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 4571 QualType(), Specialization, Info, 4572 IsAddressOfFunction); 4573 } 4574 4575 namespace { 4576 struct DependentAuto { bool IsPack; }; 4577 4578 /// Substitute the 'auto' specifier or deduced template specialization type 4579 /// specifier within a type for a given replacement type. 4580 class SubstituteDeducedTypeTransform : 4581 public TreeTransform<SubstituteDeducedTypeTransform> { 4582 QualType Replacement; 4583 bool ReplacementIsPack; 4584 bool UseTypeSugar; 4585 4586 public: 4587 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA) 4588 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef), Replacement(), 4589 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {} 4590 4591 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement, 4592 bool UseTypeSugar = true) 4593 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef), 4594 Replacement(Replacement), ReplacementIsPack(false), 4595 UseTypeSugar(UseTypeSugar) {} 4596 4597 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) { 4598 assert(isa<TemplateTypeParmType>(Replacement) && 4599 "unexpected unsugared replacement kind"); 4600 QualType Result = Replacement; 4601 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result); 4602 NewTL.setNameLoc(TL.getNameLoc()); 4603 return Result; 4604 } 4605 4606 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) { 4607 // If we're building the type pattern to deduce against, don't wrap the 4608 // substituted type in an AutoType. Certain template deduction rules 4609 // apply only when a template type parameter appears directly (and not if 4610 // the parameter is found through desugaring). For instance: 4611 // auto &&lref = lvalue; 4612 // must transform into "rvalue reference to T" not "rvalue reference to 4613 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply. 4614 // 4615 // FIXME: Is this still necessary? 4616 if (!UseTypeSugar) 4617 return TransformDesugared(TLB, TL); 4618 4619 QualType Result = SemaRef.Context.getAutoType( 4620 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(), 4621 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(), 4622 TL.getTypePtr()->getTypeConstraintArguments()); 4623 auto NewTL = TLB.push<AutoTypeLoc>(Result); 4624 NewTL.copy(TL); 4625 return Result; 4626 } 4627 4628 QualType TransformDeducedTemplateSpecializationType( 4629 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) { 4630 if (!UseTypeSugar) 4631 return TransformDesugared(TLB, TL); 4632 4633 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType( 4634 TL.getTypePtr()->getTemplateName(), 4635 Replacement, Replacement.isNull()); 4636 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result); 4637 NewTL.setNameLoc(TL.getNameLoc()); 4638 return Result; 4639 } 4640 4641 ExprResult TransformLambdaExpr(LambdaExpr *E) { 4642 // Lambdas never need to be transformed. 4643 return E; 4644 } 4645 4646 QualType Apply(TypeLoc TL) { 4647 // Create some scratch storage for the transformed type locations. 4648 // FIXME: We're just going to throw this information away. Don't build it. 4649 TypeLocBuilder TLB; 4650 TLB.reserve(TL.getFullDataSize()); 4651 return TransformType(TLB, TL); 4652 } 4653 }; 4654 4655 } // namespace 4656 4657 Sema::DeduceAutoResult 4658 Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result, 4659 Optional<unsigned> DependentDeductionDepth, 4660 bool IgnoreConstraints) { 4661 return DeduceAutoType(Type->getTypeLoc(), Init, Result, 4662 DependentDeductionDepth, IgnoreConstraints); 4663 } 4664 4665 /// Attempt to produce an informative diagostic explaining why auto deduction 4666 /// failed. 4667 /// \return \c true if diagnosed, \c false if not. 4668 static bool diagnoseAutoDeductionFailure(Sema &S, 4669 Sema::TemplateDeductionResult TDK, 4670 TemplateDeductionInfo &Info, 4671 ArrayRef<SourceRange> Ranges) { 4672 switch (TDK) { 4673 case Sema::TDK_Inconsistent: { 4674 // Inconsistent deduction means we were deducing from an initializer list. 4675 auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction); 4676 D << Info.FirstArg << Info.SecondArg; 4677 for (auto R : Ranges) 4678 D << R; 4679 return true; 4680 } 4681 4682 // FIXME: Are there other cases for which a custom diagnostic is more useful 4683 // than the basic "types don't match" diagnostic? 4684 4685 default: 4686 return false; 4687 } 4688 } 4689 4690 static Sema::DeduceAutoResult 4691 CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type, 4692 AutoTypeLoc TypeLoc, QualType Deduced) { 4693 ConstraintSatisfaction Satisfaction; 4694 ConceptDecl *Concept = Type.getTypeConstraintConcept(); 4695 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(), 4696 TypeLoc.getRAngleLoc()); 4697 TemplateArgs.addArgument( 4698 TemplateArgumentLoc(TemplateArgument(Deduced), 4699 S.Context.getTrivialTypeSourceInfo( 4700 Deduced, TypeLoc.getNameLoc()))); 4701 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I) 4702 TemplateArgs.addArgument(TypeLoc.getArgLoc(I)); 4703 4704 llvm::SmallVector<TemplateArgument, 4> Converted; 4705 if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs, 4706 /*PartialTemplateArgs=*/false, Converted)) 4707 return Sema::DAR_FailedAlreadyDiagnosed; 4708 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()}, 4709 Converted, TypeLoc.getLocalSourceRange(), 4710 Satisfaction)) 4711 return Sema::DAR_FailedAlreadyDiagnosed; 4712 if (!Satisfaction.IsSatisfied) { 4713 std::string Buf; 4714 llvm::raw_string_ostream OS(Buf); 4715 OS << "'" << Concept->getName(); 4716 if (TypeLoc.hasExplicitTemplateArgs()) { 4717 OS << "<"; 4718 for (const auto &Arg : Type.getTypeConstraintArguments()) 4719 Arg.print(S.getPrintingPolicy(), OS); 4720 OS << ">"; 4721 } 4722 OS << "'"; 4723 OS.flush(); 4724 S.Diag(TypeLoc.getConceptNameLoc(), 4725 diag::err_placeholder_constraints_not_satisfied) 4726 << Deduced << Buf << TypeLoc.getLocalSourceRange(); 4727 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 4728 return Sema::DAR_FailedAlreadyDiagnosed; 4729 } 4730 return Sema::DAR_Succeeded; 4731 } 4732 4733 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6) 4734 /// 4735 /// Note that this is done even if the initializer is dependent. (This is 4736 /// necessary to support partial ordering of templates using 'auto'.) 4737 /// A dependent type will be produced when deducing from a dependent type. 4738 /// 4739 /// \param Type the type pattern using the auto type-specifier. 4740 /// \param Init the initializer for the variable whose type is to be deduced. 4741 /// \param Result if type deduction was successful, this will be set to the 4742 /// deduced type. 4743 /// \param DependentDeductionDepth Set if we should permit deduction in 4744 /// dependent cases. This is necessary for template partial ordering with 4745 /// 'auto' template parameters. The value specified is the template 4746 /// parameter depth at which we should perform 'auto' deduction. 4747 /// \param IgnoreConstraints Set if we should not fail if the deduced type does 4748 /// not satisfy the type-constraint in the auto type. 4749 Sema::DeduceAutoResult 4750 Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result, 4751 Optional<unsigned> DependentDeductionDepth, 4752 bool IgnoreConstraints) { 4753 if (Init->containsErrors()) 4754 return DAR_FailedAlreadyDiagnosed; 4755 if (Init->getType()->isNonOverloadPlaceholderType()) { 4756 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init); 4757 if (NonPlaceholder.isInvalid()) 4758 return DAR_FailedAlreadyDiagnosed; 4759 Init = NonPlaceholder.get(); 4760 } 4761 4762 DependentAuto DependentResult = { 4763 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()}; 4764 4765 if (!DependentDeductionDepth && 4766 (Type.getType()->isDependentType() || Init->isTypeDependent() || 4767 Init->containsUnexpandedParameterPack())) { 4768 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type); 4769 assert(!Result.isNull() && "substituting DependentTy can't fail"); 4770 return DAR_Succeeded; 4771 } 4772 4773 // Find the depth of template parameter to synthesize. 4774 unsigned Depth = DependentDeductionDepth.getValueOr(0); 4775 4776 // If this is a 'decltype(auto)' specifier, do the decltype dance. 4777 // Since 'decltype(auto)' can only occur at the top of the type, we 4778 // don't need to go digging for it. 4779 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) { 4780 if (AT->isDecltypeAuto()) { 4781 if (isa<InitListExpr>(Init)) { 4782 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list); 4783 return DAR_FailedAlreadyDiagnosed; 4784 } 4785 4786 ExprResult ER = CheckPlaceholderExpr(Init); 4787 if (ER.isInvalid()) 4788 return DAR_FailedAlreadyDiagnosed; 4789 Init = ER.get(); 4790 QualType Deduced = BuildDecltypeType(Init, Init->getBeginLoc(), false); 4791 if (Deduced.isNull()) 4792 return DAR_FailedAlreadyDiagnosed; 4793 // FIXME: Support a non-canonical deduced type for 'auto'. 4794 Deduced = Context.getCanonicalType(Deduced); 4795 if (AT->isConstrained() && !IgnoreConstraints) { 4796 auto ConstraintsResult = 4797 CheckDeducedPlaceholderConstraints(*this, *AT, 4798 Type.getContainedAutoTypeLoc(), 4799 Deduced); 4800 if (ConstraintsResult != DAR_Succeeded) 4801 return ConstraintsResult; 4802 } 4803 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type); 4804 if (Result.isNull()) 4805 return DAR_FailedAlreadyDiagnosed; 4806 return DAR_Succeeded; 4807 } else if (!getLangOpts().CPlusPlus) { 4808 if (isa<InitListExpr>(Init)) { 4809 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c); 4810 return DAR_FailedAlreadyDiagnosed; 4811 } 4812 } 4813 } 4814 4815 SourceLocation Loc = Init->getExprLoc(); 4816 4817 LocalInstantiationScope InstScope(*this); 4818 4819 // Build template<class TemplParam> void Func(FuncParam); 4820 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create( 4821 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false, 4822 false); 4823 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0); 4824 NamedDecl *TemplParamPtr = TemplParam; 4825 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt( 4826 Context, Loc, Loc, TemplParamPtr, Loc, nullptr); 4827 4828 QualType FuncParam = 4829 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false) 4830 .Apply(Type); 4831 assert(!FuncParam.isNull() && 4832 "substituting template parameter for 'auto' failed"); 4833 4834 // Deduce type of TemplParam in Func(Init) 4835 SmallVector<DeducedTemplateArgument, 1> Deduced; 4836 Deduced.resize(1); 4837 4838 TemplateDeductionInfo Info(Loc, Depth); 4839 4840 // If deduction failed, don't diagnose if the initializer is dependent; it 4841 // might acquire a matching type in the instantiation. 4842 auto DeductionFailed = [&](TemplateDeductionResult TDK, 4843 ArrayRef<SourceRange> Ranges) -> DeduceAutoResult { 4844 if (Init->isTypeDependent()) { 4845 Result = 4846 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type); 4847 assert(!Result.isNull() && "substituting DependentTy can't fail"); 4848 return DAR_Succeeded; 4849 } 4850 if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges)) 4851 return DAR_FailedAlreadyDiagnosed; 4852 return DAR_Failed; 4853 }; 4854 4855 SmallVector<OriginalCallArg, 4> OriginalCallArgs; 4856 4857 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 4858 if (InitList) { 4859 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce 4860 // against that. Such deduction only succeeds if removing cv-qualifiers and 4861 // references results in std::initializer_list<T>. 4862 if (!Type.getType().getNonReferenceType()->getAs<AutoType>()) 4863 return DAR_Failed; 4864 4865 // Resolving a core issue: a braced-init-list containing any designators is 4866 // a non-deduced context. 4867 for (Expr *E : InitList->inits()) 4868 if (isa<DesignatedInitExpr>(E)) 4869 return DAR_Failed; 4870 4871 SourceRange DeducedFromInitRange; 4872 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) { 4873 Expr *Init = InitList->getInit(i); 4874 4875 if (auto TDK = DeduceTemplateArgumentsFromCallArgument( 4876 *this, TemplateParamsSt.get(), 0, TemplArg, Init, 4877 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true, 4878 /*ArgIdx*/ 0, /*TDF*/ 0)) 4879 return DeductionFailed(TDK, {DeducedFromInitRange, 4880 Init->getSourceRange()}); 4881 4882 if (DeducedFromInitRange.isInvalid() && 4883 Deduced[0].getKind() != TemplateArgument::Null) 4884 DeducedFromInitRange = Init->getSourceRange(); 4885 } 4886 } else { 4887 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) { 4888 Diag(Loc, diag::err_auto_bitfield); 4889 return DAR_FailedAlreadyDiagnosed; 4890 } 4891 4892 if (auto TDK = DeduceTemplateArgumentsFromCallArgument( 4893 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced, 4894 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0)) 4895 return DeductionFailed(TDK, {}); 4896 } 4897 4898 // Could be null if somehow 'auto' appears in a non-deduced context. 4899 if (Deduced[0].getKind() != TemplateArgument::Type) 4900 return DeductionFailed(TDK_Incomplete, {}); 4901 4902 QualType DeducedType = Deduced[0].getAsType(); 4903 4904 if (InitList) { 4905 DeducedType = BuildStdInitializerList(DeducedType, Loc); 4906 if (DeducedType.isNull()) 4907 return DAR_FailedAlreadyDiagnosed; 4908 } 4909 4910 if (const auto *AT = Type.getType()->getAs<AutoType>()) { 4911 if (AT->isConstrained() && !IgnoreConstraints) { 4912 auto ConstraintsResult = 4913 CheckDeducedPlaceholderConstraints(*this, *AT, 4914 Type.getContainedAutoTypeLoc(), 4915 DeducedType); 4916 if (ConstraintsResult != DAR_Succeeded) 4917 return ConstraintsResult; 4918 } 4919 } 4920 4921 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type); 4922 if (Result.isNull()) 4923 return DAR_FailedAlreadyDiagnosed; 4924 4925 // Check that the deduced argument type is compatible with the original 4926 // argument type per C++ [temp.deduct.call]p4. 4927 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result; 4928 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) { 4929 assert((bool)InitList == OriginalArg.DecomposedParam && 4930 "decomposed non-init-list in auto deduction?"); 4931 if (auto TDK = 4932 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) { 4933 Result = QualType(); 4934 return DeductionFailed(TDK, {}); 4935 } 4936 } 4937 4938 return DAR_Succeeded; 4939 } 4940 4941 QualType Sema::SubstAutoType(QualType TypeWithAuto, 4942 QualType TypeToReplaceAuto) { 4943 if (TypeToReplaceAuto->isDependentType()) 4944 return SubstituteDeducedTypeTransform( 4945 *this, DependentAuto{ 4946 TypeToReplaceAuto->containsUnexpandedParameterPack()}) 4947 .TransformType(TypeWithAuto); 4948 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto) 4949 .TransformType(TypeWithAuto); 4950 } 4951 4952 TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 4953 QualType TypeToReplaceAuto) { 4954 if (TypeToReplaceAuto->isDependentType()) 4955 return SubstituteDeducedTypeTransform( 4956 *this, 4957 DependentAuto{ 4958 TypeToReplaceAuto->containsUnexpandedParameterPack()}) 4959 .TransformType(TypeWithAuto); 4960 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto) 4961 .TransformType(TypeWithAuto); 4962 } 4963 4964 QualType Sema::ReplaceAutoType(QualType TypeWithAuto, 4965 QualType TypeToReplaceAuto) { 4966 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto, 4967 /*UseTypeSugar*/ false) 4968 .TransformType(TypeWithAuto); 4969 } 4970 4971 TypeSourceInfo *Sema::ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 4972 QualType TypeToReplaceAuto) { 4973 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto, 4974 /*UseTypeSugar*/ false) 4975 .TransformType(TypeWithAuto); 4976 } 4977 4978 void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) { 4979 if (isa<InitListExpr>(Init)) 4980 Diag(VDecl->getLocation(), 4981 VDecl->isInitCapture() 4982 ? diag::err_init_capture_deduction_failure_from_init_list 4983 : diag::err_auto_var_deduction_failure_from_init_list) 4984 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange(); 4985 else 4986 Diag(VDecl->getLocation(), 4987 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure 4988 : diag::err_auto_var_deduction_failure) 4989 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 4990 << Init->getSourceRange(); 4991 } 4992 4993 bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 4994 bool Diagnose) { 4995 assert(FD->getReturnType()->isUndeducedType()); 4996 4997 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)' 4998 // within the return type from the call operator's type. 4999 if (isLambdaConversionOperator(FD)) { 5000 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent(); 5001 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 5002 5003 // For a generic lambda, instantiate the call operator if needed. 5004 if (auto *Args = FD->getTemplateSpecializationArgs()) { 5005 CallOp = InstantiateFunctionDeclaration( 5006 CallOp->getDescribedFunctionTemplate(), Args, Loc); 5007 if (!CallOp || CallOp->isInvalidDecl()) 5008 return true; 5009 5010 // We might need to deduce the return type by instantiating the definition 5011 // of the operator() function. 5012 if (CallOp->getReturnType()->isUndeducedType()) { 5013 runWithSufficientStackSpace(Loc, [&] { 5014 InstantiateFunctionDefinition(Loc, CallOp); 5015 }); 5016 } 5017 } 5018 5019 if (CallOp->isInvalidDecl()) 5020 return true; 5021 assert(!CallOp->getReturnType()->isUndeducedType() && 5022 "failed to deduce lambda return type"); 5023 5024 // Build the new return type from scratch. 5025 CallingConv RetTyCC = FD->getReturnType() 5026 ->getPointeeType() 5027 ->castAs<FunctionType>() 5028 ->getCallConv(); 5029 QualType RetType = getLambdaConversionFunctionResultType( 5030 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC); 5031 if (FD->getReturnType()->getAs<PointerType>()) 5032 RetType = Context.getPointerType(RetType); 5033 else { 5034 assert(FD->getReturnType()->getAs<BlockPointerType>()); 5035 RetType = Context.getBlockPointerType(RetType); 5036 } 5037 Context.adjustDeducedFunctionResultType(FD, RetType); 5038 return false; 5039 } 5040 5041 if (FD->getTemplateInstantiationPattern()) { 5042 runWithSufficientStackSpace(Loc, [&] { 5043 InstantiateFunctionDefinition(Loc, FD); 5044 }); 5045 } 5046 5047 bool StillUndeduced = FD->getReturnType()->isUndeducedType(); 5048 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) { 5049 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD; 5050 Diag(FD->getLocation(), diag::note_callee_decl) << FD; 5051 } 5052 5053 return StillUndeduced; 5054 } 5055 5056 /// If this is a non-static member function, 5057 static void 5058 AddImplicitObjectParameterType(ASTContext &Context, 5059 CXXMethodDecl *Method, 5060 SmallVectorImpl<QualType> &ArgTypes) { 5061 // C++11 [temp.func.order]p3: 5062 // [...] The new parameter is of type "reference to cv A," where cv are 5063 // the cv-qualifiers of the function template (if any) and A is 5064 // the class of which the function template is a member. 5065 // 5066 // The standard doesn't say explicitly, but we pick the appropriate kind of 5067 // reference type based on [over.match.funcs]p4. 5068 QualType ArgTy = Context.getTypeDeclType(Method->getParent()); 5069 ArgTy = Context.getQualifiedType(ArgTy, Method->getMethodQualifiers()); 5070 if (Method->getRefQualifier() == RQ_RValue) 5071 ArgTy = Context.getRValueReferenceType(ArgTy); 5072 else 5073 ArgTy = Context.getLValueReferenceType(ArgTy); 5074 ArgTypes.push_back(ArgTy); 5075 } 5076 5077 /// Determine whether the function template \p FT1 is at least as 5078 /// specialized as \p FT2. 5079 static bool isAtLeastAsSpecializedAs(Sema &S, 5080 SourceLocation Loc, 5081 FunctionTemplateDecl *FT1, 5082 FunctionTemplateDecl *FT2, 5083 TemplatePartialOrderingContext TPOC, 5084 unsigned NumCallArguments1, 5085 bool Reversed) { 5086 assert(!Reversed || TPOC == TPOC_Call); 5087 5088 FunctionDecl *FD1 = FT1->getTemplatedDecl(); 5089 FunctionDecl *FD2 = FT2->getTemplatedDecl(); 5090 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>(); 5091 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>(); 5092 5093 assert(Proto1 && Proto2 && "Function templates must have prototypes"); 5094 TemplateParameterList *TemplateParams = FT2->getTemplateParameters(); 5095 SmallVector<DeducedTemplateArgument, 4> Deduced; 5096 Deduced.resize(TemplateParams->size()); 5097 5098 // C++0x [temp.deduct.partial]p3: 5099 // The types used to determine the ordering depend on the context in which 5100 // the partial ordering is done: 5101 TemplateDeductionInfo Info(Loc); 5102 SmallVector<QualType, 4> Args2; 5103 switch (TPOC) { 5104 case TPOC_Call: { 5105 // - In the context of a function call, the function parameter types are 5106 // used. 5107 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1); 5108 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2); 5109 5110 // C++11 [temp.func.order]p3: 5111 // [...] If only one of the function templates is a non-static 5112 // member, that function template is considered to have a new 5113 // first parameter inserted in its function parameter list. The 5114 // new parameter is of type "reference to cv A," where cv are 5115 // the cv-qualifiers of the function template (if any) and A is 5116 // the class of which the function template is a member. 5117 // 5118 // Note that we interpret this to mean "if one of the function 5119 // templates is a non-static member and the other is a non-member"; 5120 // otherwise, the ordering rules for static functions against non-static 5121 // functions don't make any sense. 5122 // 5123 // C++98/03 doesn't have this provision but we've extended DR532 to cover 5124 // it as wording was broken prior to it. 5125 SmallVector<QualType, 4> Args1; 5126 5127 unsigned NumComparedArguments = NumCallArguments1; 5128 5129 if (!Method2 && Method1 && !Method1->isStatic()) { 5130 // Compare 'this' from Method1 against first parameter from Method2. 5131 AddImplicitObjectParameterType(S.Context, Method1, Args1); 5132 ++NumComparedArguments; 5133 } else if (!Method1 && Method2 && !Method2->isStatic()) { 5134 // Compare 'this' from Method2 against first parameter from Method1. 5135 AddImplicitObjectParameterType(S.Context, Method2, Args2); 5136 } else if (Method1 && Method2 && Reversed) { 5137 // Compare 'this' from Method1 against second parameter from Method2 5138 // and 'this' from Method2 against second parameter from Method1. 5139 AddImplicitObjectParameterType(S.Context, Method1, Args1); 5140 AddImplicitObjectParameterType(S.Context, Method2, Args2); 5141 ++NumComparedArguments; 5142 } 5143 5144 Args1.insert(Args1.end(), Proto1->param_type_begin(), 5145 Proto1->param_type_end()); 5146 Args2.insert(Args2.end(), Proto2->param_type_begin(), 5147 Proto2->param_type_end()); 5148 5149 // C++ [temp.func.order]p5: 5150 // The presence of unused ellipsis and default arguments has no effect on 5151 // the partial ordering of function templates. 5152 if (Args1.size() > NumComparedArguments) 5153 Args1.resize(NumComparedArguments); 5154 if (Args2.size() > NumComparedArguments) 5155 Args2.resize(NumComparedArguments); 5156 if (Reversed) 5157 std::reverse(Args2.begin(), Args2.end()); 5158 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(), 5159 Args1.data(), Args1.size(), Info, Deduced, 5160 TDF_None, /*PartialOrdering=*/true)) 5161 return false; 5162 5163 break; 5164 } 5165 5166 case TPOC_Conversion: 5167 // - In the context of a call to a conversion operator, the return types 5168 // of the conversion function templates are used. 5169 if (DeduceTemplateArgumentsByTypeMatch( 5170 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(), 5171 Info, Deduced, TDF_None, 5172 /*PartialOrdering=*/true)) 5173 return false; 5174 break; 5175 5176 case TPOC_Other: 5177 // - In other contexts (14.6.6.2) the function template's function type 5178 // is used. 5179 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 5180 FD2->getType(), FD1->getType(), 5181 Info, Deduced, TDF_None, 5182 /*PartialOrdering=*/true)) 5183 return false; 5184 break; 5185 } 5186 5187 // C++0x [temp.deduct.partial]p11: 5188 // In most cases, all template parameters must have values in order for 5189 // deduction to succeed, but for partial ordering purposes a template 5190 // parameter may remain without a value provided it is not used in the 5191 // types being used for partial ordering. [ Note: a template parameter used 5192 // in a non-deduced context is considered used. -end note] 5193 unsigned ArgIdx = 0, NumArgs = Deduced.size(); 5194 for (; ArgIdx != NumArgs; ++ArgIdx) 5195 if (Deduced[ArgIdx].isNull()) 5196 break; 5197 5198 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need 5199 // to substitute the deduced arguments back into the template and check that 5200 // we get the right type. 5201 5202 if (ArgIdx == NumArgs) { 5203 // All template arguments were deduced. FT1 is at least as specialized 5204 // as FT2. 5205 return true; 5206 } 5207 5208 // Figure out which template parameters were used. 5209 llvm::SmallBitVector UsedParameters(TemplateParams->size()); 5210 switch (TPOC) { 5211 case TPOC_Call: 5212 for (unsigned I = 0, N = Args2.size(); I != N; ++I) 5213 ::MarkUsedTemplateParameters(S.Context, Args2[I], false, 5214 TemplateParams->getDepth(), 5215 UsedParameters); 5216 break; 5217 5218 case TPOC_Conversion: 5219 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false, 5220 TemplateParams->getDepth(), UsedParameters); 5221 break; 5222 5223 case TPOC_Other: 5224 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false, 5225 TemplateParams->getDepth(), 5226 UsedParameters); 5227 break; 5228 } 5229 5230 for (; ArgIdx != NumArgs; ++ArgIdx) 5231 // If this argument had no value deduced but was used in one of the types 5232 // used for partial ordering, then deduction fails. 5233 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx]) 5234 return false; 5235 5236 return true; 5237 } 5238 5239 /// Determine whether this a function template whose parameter-type-list 5240 /// ends with a function parameter pack. 5241 static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) { 5242 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 5243 unsigned NumParams = Function->getNumParams(); 5244 if (NumParams == 0) 5245 return false; 5246 5247 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1); 5248 if (!Last->isParameterPack()) 5249 return false; 5250 5251 // Make sure that no previous parameter is a parameter pack. 5252 while (--NumParams > 0) { 5253 if (Function->getParamDecl(NumParams - 1)->isParameterPack()) 5254 return false; 5255 } 5256 5257 return true; 5258 } 5259 5260 /// Returns the more specialized function template according 5261 /// to the rules of function template partial ordering (C++ [temp.func.order]). 5262 /// 5263 /// \param FT1 the first function template 5264 /// 5265 /// \param FT2 the second function template 5266 /// 5267 /// \param TPOC the context in which we are performing partial ordering of 5268 /// function templates. 5269 /// 5270 /// \param NumCallArguments1 The number of arguments in the call to FT1, used 5271 /// only when \c TPOC is \c TPOC_Call. 5272 /// 5273 /// \param NumCallArguments2 The number of arguments in the call to FT2, used 5274 /// only when \c TPOC is \c TPOC_Call. 5275 /// 5276 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload 5277 /// candidate with a reversed parameter order. In this case, the corresponding 5278 /// P/A pairs between FT1 and FT2 are reversed. 5279 /// 5280 /// \returns the more specialized function template. If neither 5281 /// template is more specialized, returns NULL. 5282 FunctionTemplateDecl * 5283 Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 5284 FunctionTemplateDecl *FT2, 5285 SourceLocation Loc, 5286 TemplatePartialOrderingContext TPOC, 5287 unsigned NumCallArguments1, 5288 unsigned NumCallArguments2, 5289 bool Reversed) { 5290 5291 auto JudgeByConstraints = [&] () -> FunctionTemplateDecl * { 5292 llvm::SmallVector<const Expr *, 3> AC1, AC2; 5293 FT1->getAssociatedConstraints(AC1); 5294 FT2->getAssociatedConstraints(AC2); 5295 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 5296 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1)) 5297 return nullptr; 5298 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2)) 5299 return nullptr; 5300 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 5301 return nullptr; 5302 return AtLeastAsConstrained1 ? FT1 : FT2; 5303 }; 5304 5305 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 5306 NumCallArguments1, Reversed); 5307 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, 5308 NumCallArguments2, Reversed); 5309 5310 if (Better1 != Better2) // We have a clear winner 5311 return Better1 ? FT1 : FT2; 5312 5313 if (!Better1 && !Better2) // Neither is better than the other 5314 return JudgeByConstraints(); 5315 5316 // FIXME: This mimics what GCC implements, but doesn't match up with the 5317 // proposed resolution for core issue 692. This area needs to be sorted out, 5318 // but for now we attempt to maintain compatibility. 5319 bool Variadic1 = isVariadicFunctionTemplate(FT1); 5320 bool Variadic2 = isVariadicFunctionTemplate(FT2); 5321 if (Variadic1 != Variadic2) 5322 return Variadic1? FT2 : FT1; 5323 5324 return JudgeByConstraints(); 5325 } 5326 5327 /// Determine if the two templates are equivalent. 5328 static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) { 5329 if (T1 == T2) 5330 return true; 5331 5332 if (!T1 || !T2) 5333 return false; 5334 5335 return T1->getCanonicalDecl() == T2->getCanonicalDecl(); 5336 } 5337 5338 /// Retrieve the most specialized of the given function template 5339 /// specializations. 5340 /// 5341 /// \param SpecBegin the start iterator of the function template 5342 /// specializations that we will be comparing. 5343 /// 5344 /// \param SpecEnd the end iterator of the function template 5345 /// specializations, paired with \p SpecBegin. 5346 /// 5347 /// \param Loc the location where the ambiguity or no-specializations 5348 /// diagnostic should occur. 5349 /// 5350 /// \param NoneDiag partial diagnostic used to diagnose cases where there are 5351 /// no matching candidates. 5352 /// 5353 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one 5354 /// occurs. 5355 /// 5356 /// \param CandidateDiag partial diagnostic used for each function template 5357 /// specialization that is a candidate in the ambiguous ordering. One parameter 5358 /// in this diagnostic should be unbound, which will correspond to the string 5359 /// describing the template arguments for the function template specialization. 5360 /// 5361 /// \returns the most specialized function template specialization, if 5362 /// found. Otherwise, returns SpecEnd. 5363 UnresolvedSetIterator Sema::getMostSpecialized( 5364 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd, 5365 TemplateSpecCandidateSet &FailedCandidates, 5366 SourceLocation Loc, const PartialDiagnostic &NoneDiag, 5367 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, 5368 bool Complain, QualType TargetType) { 5369 if (SpecBegin == SpecEnd) { 5370 if (Complain) { 5371 Diag(Loc, NoneDiag); 5372 FailedCandidates.NoteCandidates(*this, Loc); 5373 } 5374 return SpecEnd; 5375 } 5376 5377 if (SpecBegin + 1 == SpecEnd) 5378 return SpecBegin; 5379 5380 // Find the function template that is better than all of the templates it 5381 // has been compared to. 5382 UnresolvedSetIterator Best = SpecBegin; 5383 FunctionTemplateDecl *BestTemplate 5384 = cast<FunctionDecl>(*Best)->getPrimaryTemplate(); 5385 assert(BestTemplate && "Not a function template specialization?"); 5386 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) { 5387 FunctionTemplateDecl *Challenger 5388 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 5389 assert(Challenger && "Not a function template specialization?"); 5390 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 5391 Loc, TPOC_Other, 0, 0), 5392 Challenger)) { 5393 Best = I; 5394 BestTemplate = Challenger; 5395 } 5396 } 5397 5398 // Make sure that the "best" function template is more specialized than all 5399 // of the others. 5400 bool Ambiguous = false; 5401 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 5402 FunctionTemplateDecl *Challenger 5403 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 5404 if (I != Best && 5405 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 5406 Loc, TPOC_Other, 0, 0), 5407 BestTemplate)) { 5408 Ambiguous = true; 5409 break; 5410 } 5411 } 5412 5413 if (!Ambiguous) { 5414 // We found an answer. Return it. 5415 return Best; 5416 } 5417 5418 // Diagnose the ambiguity. 5419 if (Complain) { 5420 Diag(Loc, AmbigDiag); 5421 5422 // FIXME: Can we order the candidates in some sane way? 5423 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 5424 PartialDiagnostic PD = CandidateDiag; 5425 const auto *FD = cast<FunctionDecl>(*I); 5426 PD << FD << getTemplateArgumentBindingsText( 5427 FD->getPrimaryTemplate()->getTemplateParameters(), 5428 *FD->getTemplateSpecializationArgs()); 5429 if (!TargetType.isNull()) 5430 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType); 5431 Diag((*I)->getLocation(), PD); 5432 } 5433 } 5434 5435 return SpecEnd; 5436 } 5437 5438 /// Determine whether one partial specialization, P1, is at least as 5439 /// specialized than another, P2. 5440 /// 5441 /// \tparam TemplateLikeDecl The kind of P2, which must be a 5442 /// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl. 5443 /// \param T1 The injected-class-name of P1 (faked for a variable template). 5444 /// \param T2 The injected-class-name of P2 (faked for a variable template). 5445 template<typename TemplateLikeDecl> 5446 static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2, 5447 TemplateLikeDecl *P2, 5448 TemplateDeductionInfo &Info) { 5449 // C++ [temp.class.order]p1: 5450 // For two class template partial specializations, the first is at least as 5451 // specialized as the second if, given the following rewrite to two 5452 // function templates, the first function template is at least as 5453 // specialized as the second according to the ordering rules for function 5454 // templates (14.6.6.2): 5455 // - the first function template has the same template parameters as the 5456 // first partial specialization and has a single function parameter 5457 // whose type is a class template specialization with the template 5458 // arguments of the first partial specialization, and 5459 // - the second function template has the same template parameters as the 5460 // second partial specialization and has a single function parameter 5461 // whose type is a class template specialization with the template 5462 // arguments of the second partial specialization. 5463 // 5464 // Rather than synthesize function templates, we merely perform the 5465 // equivalent partial ordering by performing deduction directly on 5466 // the template arguments of the class template partial 5467 // specializations. This computation is slightly simpler than the 5468 // general problem of function template partial ordering, because 5469 // class template partial specializations are more constrained. We 5470 // know that every template parameter is deducible from the class 5471 // template partial specialization's template arguments, for 5472 // example. 5473 SmallVector<DeducedTemplateArgument, 4> Deduced; 5474 5475 // Determine whether P1 is at least as specialized as P2. 5476 Deduced.resize(P2->getTemplateParameters()->size()); 5477 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(), 5478 T2, T1, Info, Deduced, TDF_None, 5479 /*PartialOrdering=*/true)) 5480 return false; 5481 5482 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), 5483 Deduced.end()); 5484 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs, 5485 Info); 5486 auto *TST1 = T1->castAs<TemplateSpecializationType>(); 5487 bool AtLeastAsSpecialized; 5488 S.runWithSufficientStackSpace(Info.getLocation(), [&] { 5489 AtLeastAsSpecialized = !FinishTemplateArgumentDeduction( 5490 S, P2, /*IsPartialOrdering=*/true, 5491 TemplateArgumentList(TemplateArgumentList::OnStack, 5492 TST1->template_arguments()), 5493 Deduced, Info); 5494 }); 5495 return AtLeastAsSpecialized; 5496 } 5497 5498 /// Returns the more specialized class template partial specialization 5499 /// according to the rules of partial ordering of class template partial 5500 /// specializations (C++ [temp.class.order]). 5501 /// 5502 /// \param PS1 the first class template partial specialization 5503 /// 5504 /// \param PS2 the second class template partial specialization 5505 /// 5506 /// \returns the more specialized class template partial specialization. If 5507 /// neither partial specialization is more specialized, returns NULL. 5508 ClassTemplatePartialSpecializationDecl * 5509 Sema::getMoreSpecializedPartialSpecialization( 5510 ClassTemplatePartialSpecializationDecl *PS1, 5511 ClassTemplatePartialSpecializationDecl *PS2, 5512 SourceLocation Loc) { 5513 QualType PT1 = PS1->getInjectedSpecializationType(); 5514 QualType PT2 = PS2->getInjectedSpecializationType(); 5515 5516 TemplateDeductionInfo Info(Loc); 5517 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info); 5518 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info); 5519 5520 if (!Better1 && !Better2) 5521 return nullptr; 5522 if (Better1 && Better2) { 5523 llvm::SmallVector<const Expr *, 3> AC1, AC2; 5524 PS1->getAssociatedConstraints(AC1); 5525 PS2->getAssociatedConstraints(AC2); 5526 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 5527 if (IsAtLeastAsConstrained(PS1, AC1, PS2, AC2, AtLeastAsConstrained1)) 5528 return nullptr; 5529 if (IsAtLeastAsConstrained(PS2, AC2, PS1, AC1, AtLeastAsConstrained2)) 5530 return nullptr; 5531 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 5532 return nullptr; 5533 return AtLeastAsConstrained1 ? PS1 : PS2; 5534 } 5535 5536 return Better1 ? PS1 : PS2; 5537 } 5538 5539 bool Sema::isMoreSpecializedThanPrimary( 5540 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) { 5541 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate(); 5542 QualType PrimaryT = Primary->getInjectedClassNameSpecialization(); 5543 QualType PartialT = Spec->getInjectedSpecializationType(); 5544 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info)) 5545 return false; 5546 if (!isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) 5547 return true; 5548 Info.clearSFINAEDiagnostic(); 5549 llvm::SmallVector<const Expr *, 3> PrimaryAC, SpecAC; 5550 Primary->getAssociatedConstraints(PrimaryAC); 5551 Spec->getAssociatedConstraints(SpecAC); 5552 bool AtLeastAsConstrainedPrimary, AtLeastAsConstrainedSpec; 5553 if (IsAtLeastAsConstrained(Spec, SpecAC, Primary, PrimaryAC, 5554 AtLeastAsConstrainedSpec)) 5555 return false; 5556 if (!AtLeastAsConstrainedSpec) 5557 return false; 5558 if (IsAtLeastAsConstrained(Primary, PrimaryAC, Spec, SpecAC, 5559 AtLeastAsConstrainedPrimary)) 5560 return false; 5561 return !AtLeastAsConstrainedPrimary; 5562 } 5563 5564 VarTemplatePartialSpecializationDecl * 5565 Sema::getMoreSpecializedPartialSpecialization( 5566 VarTemplatePartialSpecializationDecl *PS1, 5567 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) { 5568 // Pretend the variable template specializations are class template 5569 // specializations and form a fake injected class name type for comparison. 5570 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && 5571 "the partial specializations being compared should specialize" 5572 " the same template."); 5573 TemplateName Name(PS1->getSpecializedTemplate()); 5574 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 5575 QualType PT1 = Context.getTemplateSpecializationType( 5576 CanonTemplate, PS1->getTemplateArgs().asArray()); 5577 QualType PT2 = Context.getTemplateSpecializationType( 5578 CanonTemplate, PS2->getTemplateArgs().asArray()); 5579 5580 TemplateDeductionInfo Info(Loc); 5581 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info); 5582 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info); 5583 5584 if (!Better1 && !Better2) 5585 return nullptr; 5586 if (Better1 && Better2) { 5587 llvm::SmallVector<const Expr *, 3> AC1, AC2; 5588 PS1->getAssociatedConstraints(AC1); 5589 PS2->getAssociatedConstraints(AC2); 5590 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 5591 if (IsAtLeastAsConstrained(PS1, AC1, PS2, AC2, AtLeastAsConstrained1)) 5592 return nullptr; 5593 if (IsAtLeastAsConstrained(PS2, AC2, PS1, AC1, AtLeastAsConstrained2)) 5594 return nullptr; 5595 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 5596 return nullptr; 5597 return AtLeastAsConstrained1 ? PS1 : PS2; 5598 } 5599 5600 return Better1 ? PS1 : PS2; 5601 } 5602 5603 bool Sema::isMoreSpecializedThanPrimary( 5604 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) { 5605 TemplateDecl *Primary = Spec->getSpecializedTemplate(); 5606 // FIXME: Cache the injected template arguments rather than recomputing 5607 // them for each partial specialization. 5608 SmallVector<TemplateArgument, 8> PrimaryArgs; 5609 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(), 5610 PrimaryArgs); 5611 5612 TemplateName CanonTemplate = 5613 Context.getCanonicalTemplateName(TemplateName(Primary)); 5614 QualType PrimaryT = Context.getTemplateSpecializationType( 5615 CanonTemplate, PrimaryArgs); 5616 QualType PartialT = Context.getTemplateSpecializationType( 5617 CanonTemplate, Spec->getTemplateArgs().asArray()); 5618 5619 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info)) 5620 return false; 5621 if (!isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) 5622 return true; 5623 Info.clearSFINAEDiagnostic(); 5624 llvm::SmallVector<const Expr *, 3> PrimaryAC, SpecAC; 5625 Primary->getAssociatedConstraints(PrimaryAC); 5626 Spec->getAssociatedConstraints(SpecAC); 5627 bool AtLeastAsConstrainedPrimary, AtLeastAsConstrainedSpec; 5628 if (IsAtLeastAsConstrained(Spec, SpecAC, Primary, PrimaryAC, 5629 AtLeastAsConstrainedSpec)) 5630 return false; 5631 if (!AtLeastAsConstrainedSpec) 5632 return false; 5633 if (IsAtLeastAsConstrained(Primary, PrimaryAC, Spec, SpecAC, 5634 AtLeastAsConstrainedPrimary)) 5635 return false; 5636 return !AtLeastAsConstrainedPrimary; 5637 } 5638 5639 bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs( 5640 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) { 5641 // C++1z [temp.arg.template]p4: (DR 150) 5642 // A template template-parameter P is at least as specialized as a 5643 // template template-argument A if, given the following rewrite to two 5644 // function templates... 5645 5646 // Rather than synthesize function templates, we merely perform the 5647 // equivalent partial ordering by performing deduction directly on 5648 // the template parameter lists of the template template parameters. 5649 // 5650 // Given an invented class template X with the template parameter list of 5651 // A (including default arguments): 5652 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg)); 5653 TemplateParameterList *A = AArg->getTemplateParameters(); 5654 5655 // - Each function template has a single function parameter whose type is 5656 // a specialization of X with template arguments corresponding to the 5657 // template parameters from the respective function template 5658 SmallVector<TemplateArgument, 8> AArgs; 5659 Context.getInjectedTemplateArgs(A, AArgs); 5660 5661 // Check P's arguments against A's parameter list. This will fill in default 5662 // template arguments as needed. AArgs are already correct by construction. 5663 // We can't just use CheckTemplateIdType because that will expand alias 5664 // templates. 5665 SmallVector<TemplateArgument, 4> PArgs; 5666 { 5667 SFINAETrap Trap(*this); 5668 5669 Context.getInjectedTemplateArgs(P, PArgs); 5670 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), 5671 P->getRAngleLoc()); 5672 for (unsigned I = 0, N = P->size(); I != N; ++I) { 5673 // Unwrap packs that getInjectedTemplateArgs wrapped around pack 5674 // expansions, to form an "as written" argument list. 5675 TemplateArgument Arg = PArgs[I]; 5676 if (Arg.getKind() == TemplateArgument::Pack) { 5677 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion()); 5678 Arg = *Arg.pack_begin(); 5679 } 5680 PArgList.addArgument(getTrivialTemplateArgumentLoc( 5681 Arg, QualType(), P->getParam(I)->getLocation())); 5682 } 5683 PArgs.clear(); 5684 5685 // C++1z [temp.arg.template]p3: 5686 // If the rewrite produces an invalid type, then P is not at least as 5687 // specialized as A. 5688 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) || 5689 Trap.hasErrorOccurred()) 5690 return false; 5691 } 5692 5693 QualType AType = Context.getTemplateSpecializationType(X, AArgs); 5694 QualType PType = Context.getTemplateSpecializationType(X, PArgs); 5695 5696 // ... the function template corresponding to P is at least as specialized 5697 // as the function template corresponding to A according to the partial 5698 // ordering rules for function templates. 5699 TemplateDeductionInfo Info(Loc, A->getDepth()); 5700 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info); 5701 } 5702 5703 namespace { 5704 struct MarkUsedTemplateParameterVisitor : 5705 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> { 5706 llvm::SmallBitVector &Used; 5707 unsigned Depth; 5708 5709 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used, 5710 unsigned Depth) 5711 : Used(Used), Depth(Depth) { } 5712 5713 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) { 5714 if (T->getDepth() == Depth) 5715 Used[T->getIndex()] = true; 5716 return true; 5717 } 5718 5719 bool TraverseTemplateName(TemplateName Template) { 5720 if (auto *TTP = 5721 dyn_cast<TemplateTemplateParmDecl>(Template.getAsTemplateDecl())) 5722 if (TTP->getDepth() == Depth) 5723 Used[TTP->getIndex()] = true; 5724 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor>:: 5725 TraverseTemplateName(Template); 5726 return true; 5727 } 5728 5729 bool VisitDeclRefExpr(DeclRefExpr *E) { 5730 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) 5731 if (NTTP->getDepth() == Depth) 5732 Used[NTTP->getIndex()] = true; 5733 return true; 5734 } 5735 }; 5736 } 5737 5738 /// Mark the template parameters that are used by the given 5739 /// expression. 5740 static void 5741 MarkUsedTemplateParameters(ASTContext &Ctx, 5742 const Expr *E, 5743 bool OnlyDeduced, 5744 unsigned Depth, 5745 llvm::SmallBitVector &Used) { 5746 if (!OnlyDeduced) { 5747 MarkUsedTemplateParameterVisitor(Used, Depth) 5748 .TraverseStmt(const_cast<Expr *>(E)); 5749 return; 5750 } 5751 5752 // We can deduce from a pack expansion. 5753 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E)) 5754 E = Expansion->getPattern(); 5755 5756 const NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(E, Depth); 5757 if (!NTTP) 5758 return; 5759 5760 if (NTTP->getDepth() == Depth) 5761 Used[NTTP->getIndex()] = true; 5762 5763 // In C++17 mode, additional arguments may be deduced from the type of a 5764 // non-type argument. 5765 if (Ctx.getLangOpts().CPlusPlus17) 5766 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used); 5767 } 5768 5769 /// Mark the template parameters that are used by the given 5770 /// nested name specifier. 5771 static void 5772 MarkUsedTemplateParameters(ASTContext &Ctx, 5773 NestedNameSpecifier *NNS, 5774 bool OnlyDeduced, 5775 unsigned Depth, 5776 llvm::SmallBitVector &Used) { 5777 if (!NNS) 5778 return; 5779 5780 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth, 5781 Used); 5782 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0), 5783 OnlyDeduced, Depth, Used); 5784 } 5785 5786 /// Mark the template parameters that are used by the given 5787 /// template name. 5788 static void 5789 MarkUsedTemplateParameters(ASTContext &Ctx, 5790 TemplateName Name, 5791 bool OnlyDeduced, 5792 unsigned Depth, 5793 llvm::SmallBitVector &Used) { 5794 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 5795 if (TemplateTemplateParmDecl *TTP 5796 = dyn_cast<TemplateTemplateParmDecl>(Template)) { 5797 if (TTP->getDepth() == Depth) 5798 Used[TTP->getIndex()] = true; 5799 } 5800 return; 5801 } 5802 5803 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) 5804 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced, 5805 Depth, Used); 5806 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) 5807 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced, 5808 Depth, Used); 5809 } 5810 5811 /// Mark the template parameters that are used by the given 5812 /// type. 5813 static void 5814 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 5815 bool OnlyDeduced, 5816 unsigned Depth, 5817 llvm::SmallBitVector &Used) { 5818 if (T.isNull()) 5819 return; 5820 5821 // Non-dependent types have nothing deducible 5822 if (!T->isDependentType()) 5823 return; 5824 5825 T = Ctx.getCanonicalType(T); 5826 switch (T->getTypeClass()) { 5827 case Type::Pointer: 5828 MarkUsedTemplateParameters(Ctx, 5829 cast<PointerType>(T)->getPointeeType(), 5830 OnlyDeduced, 5831 Depth, 5832 Used); 5833 break; 5834 5835 case Type::BlockPointer: 5836 MarkUsedTemplateParameters(Ctx, 5837 cast<BlockPointerType>(T)->getPointeeType(), 5838 OnlyDeduced, 5839 Depth, 5840 Used); 5841 break; 5842 5843 case Type::LValueReference: 5844 case Type::RValueReference: 5845 MarkUsedTemplateParameters(Ctx, 5846 cast<ReferenceType>(T)->getPointeeType(), 5847 OnlyDeduced, 5848 Depth, 5849 Used); 5850 break; 5851 5852 case Type::MemberPointer: { 5853 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr()); 5854 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced, 5855 Depth, Used); 5856 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0), 5857 OnlyDeduced, Depth, Used); 5858 break; 5859 } 5860 5861 case Type::DependentSizedArray: 5862 MarkUsedTemplateParameters(Ctx, 5863 cast<DependentSizedArrayType>(T)->getSizeExpr(), 5864 OnlyDeduced, Depth, Used); 5865 // Fall through to check the element type 5866 LLVM_FALLTHROUGH; 5867 5868 case Type::ConstantArray: 5869 case Type::IncompleteArray: 5870 MarkUsedTemplateParameters(Ctx, 5871 cast<ArrayType>(T)->getElementType(), 5872 OnlyDeduced, Depth, Used); 5873 break; 5874 5875 case Type::Vector: 5876 case Type::ExtVector: 5877 MarkUsedTemplateParameters(Ctx, 5878 cast<VectorType>(T)->getElementType(), 5879 OnlyDeduced, Depth, Used); 5880 break; 5881 5882 case Type::DependentVector: { 5883 const auto *VecType = cast<DependentVectorType>(T); 5884 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced, 5885 Depth, Used); 5886 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth, 5887 Used); 5888 break; 5889 } 5890 case Type::DependentSizedExtVector: { 5891 const DependentSizedExtVectorType *VecType 5892 = cast<DependentSizedExtVectorType>(T); 5893 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced, 5894 Depth, Used); 5895 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, 5896 Depth, Used); 5897 break; 5898 } 5899 5900 case Type::DependentAddressSpace: { 5901 const DependentAddressSpaceType *DependentASType = 5902 cast<DependentAddressSpaceType>(T); 5903 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(), 5904 OnlyDeduced, Depth, Used); 5905 MarkUsedTemplateParameters(Ctx, 5906 DependentASType->getAddrSpaceExpr(), 5907 OnlyDeduced, Depth, Used); 5908 break; 5909 } 5910 5911 case Type::ConstantMatrix: { 5912 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T); 5913 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced, 5914 Depth, Used); 5915 break; 5916 } 5917 5918 case Type::DependentSizedMatrix: { 5919 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T); 5920 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced, 5921 Depth, Used); 5922 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth, 5923 Used); 5924 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced, 5925 Depth, Used); 5926 break; 5927 } 5928 5929 case Type::FunctionProto: { 5930 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 5931 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth, 5932 Used); 5933 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) { 5934 // C++17 [temp.deduct.type]p5: 5935 // The non-deduced contexts are: [...] 5936 // -- A function parameter pack that does not occur at the end of the 5937 // parameter-declaration-list. 5938 if (!OnlyDeduced || I + 1 == N || 5939 !Proto->getParamType(I)->getAs<PackExpansionType>()) { 5940 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced, 5941 Depth, Used); 5942 } else { 5943 // FIXME: C++17 [temp.deduct.call]p1: 5944 // When a function parameter pack appears in a non-deduced context, 5945 // the type of that pack is never deduced. 5946 // 5947 // We should also track a set of "never deduced" parameters, and 5948 // subtract that from the list of deduced parameters after marking. 5949 } 5950 } 5951 if (auto *E = Proto->getNoexceptExpr()) 5952 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used); 5953 break; 5954 } 5955 5956 case Type::TemplateTypeParm: { 5957 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T); 5958 if (TTP->getDepth() == Depth) 5959 Used[TTP->getIndex()] = true; 5960 break; 5961 } 5962 5963 case Type::SubstTemplateTypeParmPack: { 5964 const SubstTemplateTypeParmPackType *Subst 5965 = cast<SubstTemplateTypeParmPackType>(T); 5966 MarkUsedTemplateParameters(Ctx, 5967 QualType(Subst->getReplacedParameter(), 0), 5968 OnlyDeduced, Depth, Used); 5969 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), 5970 OnlyDeduced, Depth, Used); 5971 break; 5972 } 5973 5974 case Type::InjectedClassName: 5975 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType(); 5976 LLVM_FALLTHROUGH; 5977 5978 case Type::TemplateSpecialization: { 5979 const TemplateSpecializationType *Spec 5980 = cast<TemplateSpecializationType>(T); 5981 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced, 5982 Depth, Used); 5983 5984 // C++0x [temp.deduct.type]p9: 5985 // If the template argument list of P contains a pack expansion that is 5986 // not the last template argument, the entire template argument list is a 5987 // non-deduced context. 5988 if (OnlyDeduced && 5989 hasPackExpansionBeforeEnd(Spec->template_arguments())) 5990 break; 5991 5992 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 5993 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 5994 Used); 5995 break; 5996 } 5997 5998 case Type::Complex: 5999 if (!OnlyDeduced) 6000 MarkUsedTemplateParameters(Ctx, 6001 cast<ComplexType>(T)->getElementType(), 6002 OnlyDeduced, Depth, Used); 6003 break; 6004 6005 case Type::Atomic: 6006 if (!OnlyDeduced) 6007 MarkUsedTemplateParameters(Ctx, 6008 cast<AtomicType>(T)->getValueType(), 6009 OnlyDeduced, Depth, Used); 6010 break; 6011 6012 case Type::DependentName: 6013 if (!OnlyDeduced) 6014 MarkUsedTemplateParameters(Ctx, 6015 cast<DependentNameType>(T)->getQualifier(), 6016 OnlyDeduced, Depth, Used); 6017 break; 6018 6019 case Type::DependentTemplateSpecialization: { 6020 // C++14 [temp.deduct.type]p5: 6021 // The non-deduced contexts are: 6022 // -- The nested-name-specifier of a type that was specified using a 6023 // qualified-id 6024 // 6025 // C++14 [temp.deduct.type]p6: 6026 // When a type name is specified in a way that includes a non-deduced 6027 // context, all of the types that comprise that type name are also 6028 // non-deduced. 6029 if (OnlyDeduced) 6030 break; 6031 6032 const DependentTemplateSpecializationType *Spec 6033 = cast<DependentTemplateSpecializationType>(T); 6034 6035 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(), 6036 OnlyDeduced, Depth, Used); 6037 6038 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 6039 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 6040 Used); 6041 break; 6042 } 6043 6044 case Type::TypeOf: 6045 if (!OnlyDeduced) 6046 MarkUsedTemplateParameters(Ctx, 6047 cast<TypeOfType>(T)->getUnderlyingType(), 6048 OnlyDeduced, Depth, Used); 6049 break; 6050 6051 case Type::TypeOfExpr: 6052 if (!OnlyDeduced) 6053 MarkUsedTemplateParameters(Ctx, 6054 cast<TypeOfExprType>(T)->getUnderlyingExpr(), 6055 OnlyDeduced, Depth, Used); 6056 break; 6057 6058 case Type::Decltype: 6059 if (!OnlyDeduced) 6060 MarkUsedTemplateParameters(Ctx, 6061 cast<DecltypeType>(T)->getUnderlyingExpr(), 6062 OnlyDeduced, Depth, Used); 6063 break; 6064 6065 case Type::UnaryTransform: 6066 if (!OnlyDeduced) 6067 MarkUsedTemplateParameters(Ctx, 6068 cast<UnaryTransformType>(T)->getUnderlyingType(), 6069 OnlyDeduced, Depth, Used); 6070 break; 6071 6072 case Type::PackExpansion: 6073 MarkUsedTemplateParameters(Ctx, 6074 cast<PackExpansionType>(T)->getPattern(), 6075 OnlyDeduced, Depth, Used); 6076 break; 6077 6078 case Type::Auto: 6079 case Type::DeducedTemplateSpecialization: 6080 MarkUsedTemplateParameters(Ctx, 6081 cast<DeducedType>(T)->getDeducedType(), 6082 OnlyDeduced, Depth, Used); 6083 break; 6084 case Type::DependentExtInt: 6085 MarkUsedTemplateParameters(Ctx, 6086 cast<DependentExtIntType>(T)->getNumBitsExpr(), 6087 OnlyDeduced, Depth, Used); 6088 break; 6089 6090 // None of these types have any template parameters in them. 6091 case Type::Builtin: 6092 case Type::VariableArray: 6093 case Type::FunctionNoProto: 6094 case Type::Record: 6095 case Type::Enum: 6096 case Type::ObjCInterface: 6097 case Type::ObjCObject: 6098 case Type::ObjCObjectPointer: 6099 case Type::UnresolvedUsing: 6100 case Type::Pipe: 6101 case Type::ExtInt: 6102 #define TYPE(Class, Base) 6103 #define ABSTRACT_TYPE(Class, Base) 6104 #define DEPENDENT_TYPE(Class, Base) 6105 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 6106 #include "clang/AST/TypeNodes.inc" 6107 break; 6108 } 6109 } 6110 6111 /// Mark the template parameters that are used by this 6112 /// template argument. 6113 static void 6114 MarkUsedTemplateParameters(ASTContext &Ctx, 6115 const TemplateArgument &TemplateArg, 6116 bool OnlyDeduced, 6117 unsigned Depth, 6118 llvm::SmallBitVector &Used) { 6119 switch (TemplateArg.getKind()) { 6120 case TemplateArgument::Null: 6121 case TemplateArgument::Integral: 6122 case TemplateArgument::Declaration: 6123 break; 6124 6125 case TemplateArgument::NullPtr: 6126 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced, 6127 Depth, Used); 6128 break; 6129 6130 case TemplateArgument::Type: 6131 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced, 6132 Depth, Used); 6133 break; 6134 6135 case TemplateArgument::Template: 6136 case TemplateArgument::TemplateExpansion: 6137 MarkUsedTemplateParameters(Ctx, 6138 TemplateArg.getAsTemplateOrTemplatePattern(), 6139 OnlyDeduced, Depth, Used); 6140 break; 6141 6142 case TemplateArgument::Expression: 6143 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced, 6144 Depth, Used); 6145 break; 6146 6147 case TemplateArgument::Pack: 6148 for (const auto &P : TemplateArg.pack_elements()) 6149 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used); 6150 break; 6151 } 6152 } 6153 6154 /// Mark which template parameters are used in a given expression. 6155 /// 6156 /// \param E the expression from which template parameters will be deduced. 6157 /// 6158 /// \param Used a bit vector whose elements will be set to \c true 6159 /// to indicate when the corresponding template parameter will be 6160 /// deduced. 6161 void 6162 Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, 6163 unsigned Depth, 6164 llvm::SmallBitVector &Used) { 6165 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used); 6166 } 6167 6168 /// Mark which template parameters can be deduced from a given 6169 /// template argument list. 6170 /// 6171 /// \param TemplateArgs the template argument list from which template 6172 /// parameters will be deduced. 6173 /// 6174 /// \param Used a bit vector whose elements will be set to \c true 6175 /// to indicate when the corresponding template parameter will be 6176 /// deduced. 6177 void 6178 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 6179 bool OnlyDeduced, unsigned Depth, 6180 llvm::SmallBitVector &Used) { 6181 // C++0x [temp.deduct.type]p9: 6182 // If the template argument list of P contains a pack expansion that is not 6183 // the last template argument, the entire template argument list is a 6184 // non-deduced context. 6185 if (OnlyDeduced && 6186 hasPackExpansionBeforeEnd(TemplateArgs.asArray())) 6187 return; 6188 6189 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 6190 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced, 6191 Depth, Used); 6192 } 6193 6194 /// Marks all of the template parameters that will be deduced by a 6195 /// call to the given function template. 6196 void Sema::MarkDeducedTemplateParameters( 6197 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, 6198 llvm::SmallBitVector &Deduced) { 6199 TemplateParameterList *TemplateParams 6200 = FunctionTemplate->getTemplateParameters(); 6201 Deduced.clear(); 6202 Deduced.resize(TemplateParams->size()); 6203 6204 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 6205 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) 6206 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(), 6207 true, TemplateParams->getDepth(), Deduced); 6208 } 6209 6210 bool hasDeducibleTemplateParameters(Sema &S, 6211 FunctionTemplateDecl *FunctionTemplate, 6212 QualType T) { 6213 if (!T->isDependentType()) 6214 return false; 6215 6216 TemplateParameterList *TemplateParams 6217 = FunctionTemplate->getTemplateParameters(); 6218 llvm::SmallBitVector Deduced(TemplateParams->size()); 6219 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(), 6220 Deduced); 6221 6222 return Deduced.any(); 6223 } 6224