clang API Documentation
00001 //===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/ 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 //===----------------------------------------------------------------------===/ 00008 // 00009 // This file implements C++ template argument deduction. 00010 // 00011 //===----------------------------------------------------------------------===/ 00012 00013 #include "clang/Sema/TemplateDeduction.h" 00014 #include "TreeTransform.h" 00015 #include "clang/AST/ASTContext.h" 00016 #include "clang/AST/ASTLambda.h" 00017 #include "clang/AST/DeclObjC.h" 00018 #include "clang/AST/DeclTemplate.h" 00019 #include "clang/AST/Expr.h" 00020 #include "clang/AST/ExprCXX.h" 00021 #include "clang/AST/StmtVisitor.h" 00022 #include "clang/Sema/DeclSpec.h" 00023 #include "clang/Sema/Sema.h" 00024 #include "clang/Sema/Template.h" 00025 #include "llvm/ADT/SmallBitVector.h" 00026 #include <algorithm> 00027 00028 namespace clang { 00029 using namespace sema; 00030 /// \brief Various flags that control template argument deduction. 00031 /// 00032 /// These flags can be bitwise-OR'd together. 00033 enum TemplateDeductionFlags { 00034 /// \brief No template argument deduction flags, which indicates the 00035 /// strictest results for template argument deduction (as used for, e.g., 00036 /// matching class template partial specializations). 00037 TDF_None = 0, 00038 /// \brief Within template argument deduction from a function call, we are 00039 /// matching with a parameter type for which the original parameter was 00040 /// a reference. 00041 TDF_ParamWithReferenceType = 0x1, 00042 /// \brief Within template argument deduction from a function call, we 00043 /// are matching in a case where we ignore cv-qualifiers. 00044 TDF_IgnoreQualifiers = 0x02, 00045 /// \brief Within template argument deduction from a function call, 00046 /// we are matching in a case where we can perform template argument 00047 /// deduction from a template-id of a derived class of the argument type. 00048 TDF_DerivedClass = 0x04, 00049 /// \brief Allow non-dependent types to differ, e.g., when performing 00050 /// template argument deduction from a function call where conversions 00051 /// may apply. 00052 TDF_SkipNonDependent = 0x08, 00053 /// \brief Whether we are performing template argument deduction for 00054 /// parameters and arguments in a top-level template argument 00055 TDF_TopLevelParameterTypeList = 0x10, 00056 /// \brief Within template argument deduction from overload resolution per 00057 /// C++ [over.over] allow matching function types that are compatible in 00058 /// terms of noreturn and default calling convention adjustments. 00059 TDF_InOverloadResolution = 0x20 00060 }; 00061 } 00062 00063 using namespace clang; 00064 00065 /// \brief Compare two APSInts, extending and switching the sign as 00066 /// necessary to compare their values regardless of underlying type. 00067 static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) { 00068 if (Y.getBitWidth() > X.getBitWidth()) 00069 X = X.extend(Y.getBitWidth()); 00070 else if (Y.getBitWidth() < X.getBitWidth()) 00071 Y = Y.extend(X.getBitWidth()); 00072 00073 // If there is a signedness mismatch, correct it. 00074 if (X.isSigned() != Y.isSigned()) { 00075 // If the signed value is negative, then the values cannot be the same. 00076 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative())) 00077 return false; 00078 00079 Y.setIsSigned(true); 00080 X.setIsSigned(true); 00081 } 00082 00083 return X == Y; 00084 } 00085 00086 static Sema::TemplateDeductionResult 00087 DeduceTemplateArguments(Sema &S, 00088 TemplateParameterList *TemplateParams, 00089 const TemplateArgument &Param, 00090 TemplateArgument Arg, 00091 TemplateDeductionInfo &Info, 00092 SmallVectorImpl<DeducedTemplateArgument> &Deduced); 00093 00094 /// \brief Whether template argument deduction for two reference parameters 00095 /// resulted in the argument type, parameter type, or neither type being more 00096 /// qualified than the other. 00097 enum DeductionQualifierComparison { 00098 NeitherMoreQualified = 0, 00099 ParamMoreQualified, 00100 ArgMoreQualified 00101 }; 00102 00103 /// \brief Stores the result of comparing two reference parameters while 00104 /// performing template argument deduction for partial ordering of function 00105 /// templates. 00106 struct RefParamPartialOrderingComparison { 00107 /// \brief Whether the parameter type is an rvalue reference type. 00108 bool ParamIsRvalueRef; 00109 /// \brief Whether the argument type is an rvalue reference type. 00110 bool ArgIsRvalueRef; 00111 00112 /// \brief Whether the parameter or argument (or neither) is more qualified. 00113 DeductionQualifierComparison Qualifiers; 00114 }; 00115 00116 00117 00118 static Sema::TemplateDeductionResult 00119 DeduceTemplateArgumentsByTypeMatch(Sema &S, 00120 TemplateParameterList *TemplateParams, 00121 QualType Param, 00122 QualType Arg, 00123 TemplateDeductionInfo &Info, 00124 SmallVectorImpl<DeducedTemplateArgument> & 00125 Deduced, 00126 unsigned TDF, 00127 bool PartialOrdering = false, 00128 SmallVectorImpl<RefParamPartialOrderingComparison> * 00129 RefParamComparisons = nullptr); 00130 00131 static Sema::TemplateDeductionResult 00132 DeduceTemplateArguments(Sema &S, 00133 TemplateParameterList *TemplateParams, 00134 const TemplateArgument *Params, unsigned NumParams, 00135 const TemplateArgument *Args, unsigned NumArgs, 00136 TemplateDeductionInfo &Info, 00137 SmallVectorImpl<DeducedTemplateArgument> &Deduced); 00138 00139 /// \brief If the given expression is of a form that permits the deduction 00140 /// of a non-type template parameter, return the declaration of that 00141 /// non-type template parameter. 00142 static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) { 00143 // If we are within an alias template, the expression may have undergone 00144 // any number of parameter substitutions already. 00145 while (1) { 00146 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E)) 00147 E = IC->getSubExpr(); 00148 else if (SubstNonTypeTemplateParmExpr *Subst = 00149 dyn_cast<SubstNonTypeTemplateParmExpr>(E)) 00150 E = Subst->getReplacement(); 00151 else 00152 break; 00153 } 00154 00155 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 00156 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 00157 00158 return nullptr; 00159 } 00160 00161 /// \brief Determine whether two declaration pointers refer to the same 00162 /// declaration. 00163 static bool isSameDeclaration(Decl *X, Decl *Y) { 00164 if (NamedDecl *NX = dyn_cast<NamedDecl>(X)) 00165 X = NX->getUnderlyingDecl(); 00166 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y)) 00167 Y = NY->getUnderlyingDecl(); 00168 00169 return X->getCanonicalDecl() == Y->getCanonicalDecl(); 00170 } 00171 00172 /// \brief Verify that the given, deduced template arguments are compatible. 00173 /// 00174 /// \returns The deduced template argument, or a NULL template argument if 00175 /// the deduced template arguments were incompatible. 00176 static DeducedTemplateArgument 00177 checkDeducedTemplateArguments(ASTContext &Context, 00178 const DeducedTemplateArgument &X, 00179 const DeducedTemplateArgument &Y) { 00180 // We have no deduction for one or both of the arguments; they're compatible. 00181 if (X.isNull()) 00182 return Y; 00183 if (Y.isNull()) 00184 return X; 00185 00186 switch (X.getKind()) { 00187 case TemplateArgument::Null: 00188 llvm_unreachable("Non-deduced template arguments handled above"); 00189 00190 case TemplateArgument::Type: 00191 // If two template type arguments have the same type, they're compatible. 00192 if (Y.getKind() == TemplateArgument::Type && 00193 Context.hasSameType(X.getAsType(), Y.getAsType())) 00194 return X; 00195 00196 return DeducedTemplateArgument(); 00197 00198 case TemplateArgument::Integral: 00199 // If we deduced a constant in one case and either a dependent expression or 00200 // declaration in another case, keep the integral constant. 00201 // If both are integral constants with the same value, keep that value. 00202 if (Y.getKind() == TemplateArgument::Expression || 00203 Y.getKind() == TemplateArgument::Declaration || 00204 (Y.getKind() == TemplateArgument::Integral && 00205 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral()))) 00206 return DeducedTemplateArgument(X, 00207 X.wasDeducedFromArrayBound() && 00208 Y.wasDeducedFromArrayBound()); 00209 00210 // All other combinations are incompatible. 00211 return DeducedTemplateArgument(); 00212 00213 case TemplateArgument::Template: 00214 if (Y.getKind() == TemplateArgument::Template && 00215 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate())) 00216 return X; 00217 00218 // All other combinations are incompatible. 00219 return DeducedTemplateArgument(); 00220 00221 case TemplateArgument::TemplateExpansion: 00222 if (Y.getKind() == TemplateArgument::TemplateExpansion && 00223 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(), 00224 Y.getAsTemplateOrTemplatePattern())) 00225 return X; 00226 00227 // All other combinations are incompatible. 00228 return DeducedTemplateArgument(); 00229 00230 case TemplateArgument::Expression: 00231 // If we deduced a dependent expression in one case and either an integral 00232 // constant or a declaration in another case, keep the integral constant 00233 // or declaration. 00234 if (Y.getKind() == TemplateArgument::Integral || 00235 Y.getKind() == TemplateArgument::Declaration) 00236 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() && 00237 Y.wasDeducedFromArrayBound()); 00238 00239 if (Y.getKind() == TemplateArgument::Expression) { 00240 // Compare the expressions for equality 00241 llvm::FoldingSetNodeID ID1, ID2; 00242 X.getAsExpr()->Profile(ID1, Context, true); 00243 Y.getAsExpr()->Profile(ID2, Context, true); 00244 if (ID1 == ID2) 00245 return X; 00246 } 00247 00248 // All other combinations are incompatible. 00249 return DeducedTemplateArgument(); 00250 00251 case TemplateArgument::Declaration: 00252 // If we deduced a declaration and a dependent expression, keep the 00253 // declaration. 00254 if (Y.getKind() == TemplateArgument::Expression) 00255 return X; 00256 00257 // If we deduced a declaration and an integral constant, keep the 00258 // integral constant. 00259 if (Y.getKind() == TemplateArgument::Integral) 00260 return Y; 00261 00262 // If we deduced two declarations, make sure they they refer to the 00263 // same declaration. 00264 if (Y.getKind() == TemplateArgument::Declaration && 00265 isSameDeclaration(X.getAsDecl(), Y.getAsDecl())) 00266 return X; 00267 00268 // All other combinations are incompatible. 00269 return DeducedTemplateArgument(); 00270 00271 case TemplateArgument::NullPtr: 00272 // If we deduced a null pointer and a dependent expression, keep the 00273 // null pointer. 00274 if (Y.getKind() == TemplateArgument::Expression) 00275 return X; 00276 00277 // If we deduced a null pointer and an integral constant, keep the 00278 // integral constant. 00279 if (Y.getKind() == TemplateArgument::Integral) 00280 return Y; 00281 00282 // If we deduced two null pointers, make sure they have the same type. 00283 if (Y.getKind() == TemplateArgument::NullPtr && 00284 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType())) 00285 return X; 00286 00287 // All other combinations are incompatible. 00288 return DeducedTemplateArgument(); 00289 00290 case TemplateArgument::Pack: 00291 if (Y.getKind() != TemplateArgument::Pack || 00292 X.pack_size() != Y.pack_size()) 00293 return DeducedTemplateArgument(); 00294 00295 for (TemplateArgument::pack_iterator XA = X.pack_begin(), 00296 XAEnd = X.pack_end(), 00297 YA = Y.pack_begin(); 00298 XA != XAEnd; ++XA, ++YA) { 00299 // FIXME: Do we need to merge the results together here? 00300 if (checkDeducedTemplateArguments(Context, 00301 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()), 00302 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound())) 00303 .isNull()) 00304 return DeducedTemplateArgument(); 00305 } 00306 00307 return X; 00308 } 00309 00310 llvm_unreachable("Invalid TemplateArgument Kind!"); 00311 } 00312 00313 /// \brief Deduce the value of the given non-type template parameter 00314 /// from the given constant. 00315 static Sema::TemplateDeductionResult 00316 DeduceNonTypeTemplateArgument(Sema &S, 00317 NonTypeTemplateParmDecl *NTTP, 00318 llvm::APSInt Value, QualType ValueType, 00319 bool DeducedFromArrayBound, 00320 TemplateDeductionInfo &Info, 00321 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 00322 assert(NTTP->getDepth() == 0 && 00323 "Cannot deduce non-type template argument with depth > 0"); 00324 00325 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType, 00326 DeducedFromArrayBound); 00327 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 00328 Deduced[NTTP->getIndex()], 00329 NewDeduced); 00330 if (Result.isNull()) { 00331 Info.Param = NTTP; 00332 Info.FirstArg = Deduced[NTTP->getIndex()]; 00333 Info.SecondArg = NewDeduced; 00334 return Sema::TDK_Inconsistent; 00335 } 00336 00337 Deduced[NTTP->getIndex()] = Result; 00338 return Sema::TDK_Success; 00339 } 00340 00341 /// \brief Deduce the value of the given non-type template parameter 00342 /// from the given type- or value-dependent expression. 00343 /// 00344 /// \returns true if deduction succeeded, false otherwise. 00345 static Sema::TemplateDeductionResult 00346 DeduceNonTypeTemplateArgument(Sema &S, 00347 NonTypeTemplateParmDecl *NTTP, 00348 Expr *Value, 00349 TemplateDeductionInfo &Info, 00350 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 00351 assert(NTTP->getDepth() == 0 && 00352 "Cannot deduce non-type template argument with depth > 0"); 00353 assert((Value->isTypeDependent() || Value->isValueDependent()) && 00354 "Expression template argument must be type- or value-dependent."); 00355 00356 DeducedTemplateArgument NewDeduced(Value); 00357 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 00358 Deduced[NTTP->getIndex()], 00359 NewDeduced); 00360 00361 if (Result.isNull()) { 00362 Info.Param = NTTP; 00363 Info.FirstArg = Deduced[NTTP->getIndex()]; 00364 Info.SecondArg = NewDeduced; 00365 return Sema::TDK_Inconsistent; 00366 } 00367 00368 Deduced[NTTP->getIndex()] = Result; 00369 return Sema::TDK_Success; 00370 } 00371 00372 /// \brief Deduce the value of the given non-type template parameter 00373 /// from the given declaration. 00374 /// 00375 /// \returns true if deduction succeeded, false otherwise. 00376 static Sema::TemplateDeductionResult 00377 DeduceNonTypeTemplateArgument(Sema &S, 00378 NonTypeTemplateParmDecl *NTTP, 00379 ValueDecl *D, 00380 TemplateDeductionInfo &Info, 00381 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 00382 assert(NTTP->getDepth() == 0 && 00383 "Cannot deduce non-type template argument with depth > 0"); 00384 00385 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr; 00386 TemplateArgument New(D, NTTP->getType()); 00387 DeducedTemplateArgument NewDeduced(New); 00388 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 00389 Deduced[NTTP->getIndex()], 00390 NewDeduced); 00391 if (Result.isNull()) { 00392 Info.Param = NTTP; 00393 Info.FirstArg = Deduced[NTTP->getIndex()]; 00394 Info.SecondArg = NewDeduced; 00395 return Sema::TDK_Inconsistent; 00396 } 00397 00398 Deduced[NTTP->getIndex()] = Result; 00399 return Sema::TDK_Success; 00400 } 00401 00402 static Sema::TemplateDeductionResult 00403 DeduceTemplateArguments(Sema &S, 00404 TemplateParameterList *TemplateParams, 00405 TemplateName Param, 00406 TemplateName Arg, 00407 TemplateDeductionInfo &Info, 00408 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 00409 TemplateDecl *ParamDecl = Param.getAsTemplateDecl(); 00410 if (!ParamDecl) { 00411 // The parameter type is dependent and is not a template template parameter, 00412 // so there is nothing that we can deduce. 00413 return Sema::TDK_Success; 00414 } 00415 00416 if (TemplateTemplateParmDecl *TempParam 00417 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) { 00418 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg)); 00419 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 00420 Deduced[TempParam->getIndex()], 00421 NewDeduced); 00422 if (Result.isNull()) { 00423 Info.Param = TempParam; 00424 Info.FirstArg = Deduced[TempParam->getIndex()]; 00425 Info.SecondArg = NewDeduced; 00426 return Sema::TDK_Inconsistent; 00427 } 00428 00429 Deduced[TempParam->getIndex()] = Result; 00430 return Sema::TDK_Success; 00431 } 00432 00433 // Verify that the two template names are equivalent. 00434 if (S.Context.hasSameTemplateName(Param, Arg)) 00435 return Sema::TDK_Success; 00436 00437 // Mismatch of non-dependent template parameter to argument. 00438 Info.FirstArg = TemplateArgument(Param); 00439 Info.SecondArg = TemplateArgument(Arg); 00440 return Sema::TDK_NonDeducedMismatch; 00441 } 00442 00443 /// \brief Deduce the template arguments by comparing the template parameter 00444 /// type (which is a template-id) with the template argument type. 00445 /// 00446 /// \param S the Sema 00447 /// 00448 /// \param TemplateParams the template parameters that we are deducing 00449 /// 00450 /// \param Param the parameter type 00451 /// 00452 /// \param Arg the argument type 00453 /// 00454 /// \param Info information about the template argument deduction itself 00455 /// 00456 /// \param Deduced the deduced template arguments 00457 /// 00458 /// \returns the result of template argument deduction so far. Note that a 00459 /// "success" result means that template argument deduction has not yet failed, 00460 /// but it may still fail, later, for other reasons. 00461 static Sema::TemplateDeductionResult 00462 DeduceTemplateArguments(Sema &S, 00463 TemplateParameterList *TemplateParams, 00464 const TemplateSpecializationType *Param, 00465 QualType Arg, 00466 TemplateDeductionInfo &Info, 00467 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 00468 assert(Arg.isCanonical() && "Argument type must be canonical"); 00469 00470 // Check whether the template argument is a dependent template-id. 00471 if (const TemplateSpecializationType *SpecArg 00472 = dyn_cast<TemplateSpecializationType>(Arg)) { 00473 // Perform template argument deduction for the template name. 00474 if (Sema::TemplateDeductionResult Result 00475 = DeduceTemplateArguments(S, TemplateParams, 00476 Param->getTemplateName(), 00477 SpecArg->getTemplateName(), 00478 Info, Deduced)) 00479 return Result; 00480 00481 00482 // Perform template argument deduction on each template 00483 // argument. Ignore any missing/extra arguments, since they could be 00484 // filled in by default arguments. 00485 return DeduceTemplateArguments(S, TemplateParams, 00486 Param->getArgs(), Param->getNumArgs(), 00487 SpecArg->getArgs(), SpecArg->getNumArgs(), 00488 Info, Deduced); 00489 } 00490 00491 // If the argument type is a class template specialization, we 00492 // perform template argument deduction using its template 00493 // arguments. 00494 const RecordType *RecordArg = dyn_cast<RecordType>(Arg); 00495 if (!RecordArg) { 00496 Info.FirstArg = TemplateArgument(QualType(Param, 0)); 00497 Info.SecondArg = TemplateArgument(Arg); 00498 return Sema::TDK_NonDeducedMismatch; 00499 } 00500 00501 ClassTemplateSpecializationDecl *SpecArg 00502 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl()); 00503 if (!SpecArg) { 00504 Info.FirstArg = TemplateArgument(QualType(Param, 0)); 00505 Info.SecondArg = TemplateArgument(Arg); 00506 return Sema::TDK_NonDeducedMismatch; 00507 } 00508 00509 // Perform template argument deduction for the template name. 00510 if (Sema::TemplateDeductionResult Result 00511 = DeduceTemplateArguments(S, 00512 TemplateParams, 00513 Param->getTemplateName(), 00514 TemplateName(SpecArg->getSpecializedTemplate()), 00515 Info, Deduced)) 00516 return Result; 00517 00518 // Perform template argument deduction for the template arguments. 00519 return DeduceTemplateArguments(S, TemplateParams, 00520 Param->getArgs(), Param->getNumArgs(), 00521 SpecArg->getTemplateArgs().data(), 00522 SpecArg->getTemplateArgs().size(), 00523 Info, Deduced); 00524 } 00525 00526 /// \brief Determines whether the given type is an opaque type that 00527 /// might be more qualified when instantiated. 00528 static bool IsPossiblyOpaquelyQualifiedType(QualType T) { 00529 switch (T->getTypeClass()) { 00530 case Type::TypeOfExpr: 00531 case Type::TypeOf: 00532 case Type::DependentName: 00533 case Type::Decltype: 00534 case Type::UnresolvedUsing: 00535 case Type::TemplateTypeParm: 00536 return true; 00537 00538 case Type::ConstantArray: 00539 case Type::IncompleteArray: 00540 case Type::VariableArray: 00541 case Type::DependentSizedArray: 00542 return IsPossiblyOpaquelyQualifiedType( 00543 cast<ArrayType>(T)->getElementType()); 00544 00545 default: 00546 return false; 00547 } 00548 } 00549 00550 /// \brief Retrieve the depth and index of a template parameter. 00551 static std::pair<unsigned, unsigned> 00552 getDepthAndIndex(NamedDecl *ND) { 00553 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND)) 00554 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 00555 00556 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND)) 00557 return std::make_pair(NTTP->getDepth(), NTTP->getIndex()); 00558 00559 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND); 00560 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 00561 } 00562 00563 /// \brief Retrieve the depth and index of an unexpanded parameter pack. 00564 static std::pair<unsigned, unsigned> 00565 getDepthAndIndex(UnexpandedParameterPack UPP) { 00566 if (const TemplateTypeParmType *TTP 00567 = UPP.first.dyn_cast<const TemplateTypeParmType *>()) 00568 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 00569 00570 return getDepthAndIndex(UPP.first.get<NamedDecl *>()); 00571 } 00572 00573 /// \brief Helper function to build a TemplateParameter when we don't 00574 /// know its type statically. 00575 static TemplateParameter makeTemplateParameter(Decl *D) { 00576 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D)) 00577 return TemplateParameter(TTP); 00578 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) 00579 return TemplateParameter(NTTP); 00580 00581 return TemplateParameter(cast<TemplateTemplateParmDecl>(D)); 00582 } 00583 00584 /// A pack that we're currently deducing. 00585 struct clang::DeducedPack { 00586 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {} 00587 00588 // The index of the pack. 00589 unsigned Index; 00590 00591 // The old value of the pack before we started deducing it. 00592 DeducedTemplateArgument Saved; 00593 00594 // A deferred value of this pack from an inner deduction, that couldn't be 00595 // deduced because this deduction hadn't happened yet. 00596 DeducedTemplateArgument DeferredDeduction; 00597 00598 // The new value of the pack. 00599 SmallVector<DeducedTemplateArgument, 4> New; 00600 00601 // The outer deduction for this pack, if any. 00602 DeducedPack *Outer; 00603 }; 00604 00605 /// A scope in which we're performing pack deduction. 00606 class PackDeductionScope { 00607 public: 00608 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams, 00609 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 00610 TemplateDeductionInfo &Info, TemplateArgument Pattern) 00611 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) { 00612 // Compute the set of template parameter indices that correspond to 00613 // parameter packs expanded by the pack expansion. 00614 { 00615 llvm::SmallBitVector SawIndices(TemplateParams->size()); 00616 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 00617 S.collectUnexpandedParameterPacks(Pattern, Unexpanded); 00618 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 00619 unsigned Depth, Index; 00620 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]); 00621 if (Depth == 0 && !SawIndices[Index]) { 00622 SawIndices[Index] = true; 00623 00624 // Save the deduced template argument for the parameter pack expanded 00625 // by this pack expansion, then clear out the deduction. 00626 DeducedPack Pack(Index); 00627 Pack.Saved = Deduced[Index]; 00628 Deduced[Index] = TemplateArgument(); 00629 00630 Packs.push_back(Pack); 00631 } 00632 } 00633 } 00634 assert(!Packs.empty() && "Pack expansion without unexpanded packs?"); 00635 00636 for (auto &Pack : Packs) { 00637 if (Info.PendingDeducedPacks.size() > Pack.Index) 00638 Pack.Outer = Info.PendingDeducedPacks[Pack.Index]; 00639 else 00640 Info.PendingDeducedPacks.resize(Pack.Index + 1); 00641 Info.PendingDeducedPacks[Pack.Index] = &Pack; 00642 00643 if (S.CurrentInstantiationScope) { 00644 // If the template argument pack was explicitly specified, add that to 00645 // the set of deduced arguments. 00646 const TemplateArgument *ExplicitArgs; 00647 unsigned NumExplicitArgs; 00648 NamedDecl *PartiallySubstitutedPack = 00649 S.CurrentInstantiationScope->getPartiallySubstitutedPack( 00650 &ExplicitArgs, &NumExplicitArgs); 00651 if (PartiallySubstitutedPack && 00652 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index) 00653 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs); 00654 } 00655 } 00656 } 00657 00658 ~PackDeductionScope() { 00659 for (auto &Pack : Packs) 00660 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer; 00661 } 00662 00663 /// Move to deducing the next element in each pack that is being deduced. 00664 void nextPackElement() { 00665 // Capture the deduced template arguments for each parameter pack expanded 00666 // by this pack expansion, add them to the list of arguments we've deduced 00667 // for that pack, then clear out the deduced argument. 00668 for (auto &Pack : Packs) { 00669 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index]; 00670 if (!DeducedArg.isNull()) { 00671 Pack.New.push_back(DeducedArg); 00672 DeducedArg = DeducedTemplateArgument(); 00673 } 00674 } 00675 } 00676 00677 /// \brief Finish template argument deduction for a set of argument packs, 00678 /// producing the argument packs and checking for consistency with prior 00679 /// deductions. 00680 Sema::TemplateDeductionResult finish(bool HasAnyArguments) { 00681 // Build argument packs for each of the parameter packs expanded by this 00682 // pack expansion. 00683 for (auto &Pack : Packs) { 00684 // Put back the old value for this pack. 00685 Deduced[Pack.Index] = Pack.Saved; 00686 00687 // Build or find a new value for this pack. 00688 DeducedTemplateArgument NewPack; 00689 if (HasAnyArguments && Pack.New.empty()) { 00690 if (Pack.DeferredDeduction.isNull()) { 00691 // We were not able to deduce anything for this parameter pack 00692 // (because it only appeared in non-deduced contexts), so just 00693 // restore the saved argument pack. 00694 continue; 00695 } 00696 00697 NewPack = Pack.DeferredDeduction; 00698 Pack.DeferredDeduction = TemplateArgument(); 00699 } else if (Pack.New.empty()) { 00700 // If we deduced an empty argument pack, create it now. 00701 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack()); 00702 } else { 00703 TemplateArgument *ArgumentPack = 00704 new (S.Context) TemplateArgument[Pack.New.size()]; 00705 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack); 00706 NewPack = DeducedTemplateArgument( 00707 TemplateArgument(ArgumentPack, Pack.New.size()), 00708 Pack.New[0].wasDeducedFromArrayBound()); 00709 } 00710 00711 // Pick where we're going to put the merged pack. 00712 DeducedTemplateArgument *Loc; 00713 if (Pack.Outer) { 00714 if (Pack.Outer->DeferredDeduction.isNull()) { 00715 // Defer checking this pack until we have a complete pack to compare 00716 // it against. 00717 Pack.Outer->DeferredDeduction = NewPack; 00718 continue; 00719 } 00720 Loc = &Pack.Outer->DeferredDeduction; 00721 } else { 00722 Loc = &Deduced[Pack.Index]; 00723 } 00724 00725 // Check the new pack matches any previous value. 00726 DeducedTemplateArgument OldPack = *Loc; 00727 DeducedTemplateArgument Result = 00728 checkDeducedTemplateArguments(S.Context, OldPack, NewPack); 00729 00730 // If we deferred a deduction of this pack, check that one now too. 00731 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) { 00732 OldPack = Result; 00733 NewPack = Pack.DeferredDeduction; 00734 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack); 00735 } 00736 00737 if (Result.isNull()) { 00738 Info.Param = 00739 makeTemplateParameter(TemplateParams->getParam(Pack.Index)); 00740 Info.FirstArg = OldPack; 00741 Info.SecondArg = NewPack; 00742 return Sema::TDK_Inconsistent; 00743 } 00744 00745 *Loc = Result; 00746 } 00747 00748 return Sema::TDK_Success; 00749 } 00750 00751 private: 00752 Sema &S; 00753 TemplateParameterList *TemplateParams; 00754 SmallVectorImpl<DeducedTemplateArgument> &Deduced; 00755 TemplateDeductionInfo &Info; 00756 00757 SmallVector<DeducedPack, 2> Packs; 00758 }; 00759 00760 /// \brief Deduce the template arguments by comparing the list of parameter 00761 /// types to the list of argument types, as in the parameter-type-lists of 00762 /// function types (C++ [temp.deduct.type]p10). 00763 /// 00764 /// \param S The semantic analysis object within which we are deducing 00765 /// 00766 /// \param TemplateParams The template parameters that we are deducing 00767 /// 00768 /// \param Params The list of parameter types 00769 /// 00770 /// \param NumParams The number of types in \c Params 00771 /// 00772 /// \param Args The list of argument types 00773 /// 00774 /// \param NumArgs The number of types in \c Args 00775 /// 00776 /// \param Info information about the template argument deduction itself 00777 /// 00778 /// \param Deduced the deduced template arguments 00779 /// 00780 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 00781 /// how template argument deduction is performed. 00782 /// 00783 /// \param PartialOrdering If true, we are performing template argument 00784 /// deduction for during partial ordering for a call 00785 /// (C++0x [temp.deduct.partial]). 00786 /// 00787 /// \param RefParamComparisons If we're performing template argument deduction 00788 /// in the context of partial ordering, the set of qualifier comparisons. 00789 /// 00790 /// \returns the result of template argument deduction so far. Note that a 00791 /// "success" result means that template argument deduction has not yet failed, 00792 /// but it may still fail, later, for other reasons. 00793 static Sema::TemplateDeductionResult 00794 DeduceTemplateArguments(Sema &S, 00795 TemplateParameterList *TemplateParams, 00796 const QualType *Params, unsigned NumParams, 00797 const QualType *Args, unsigned NumArgs, 00798 TemplateDeductionInfo &Info, 00799 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 00800 unsigned TDF, 00801 bool PartialOrdering = false, 00802 SmallVectorImpl<RefParamPartialOrderingComparison> * 00803 RefParamComparisons = nullptr) { 00804 // Fast-path check to see if we have too many/too few arguments. 00805 if (NumParams != NumArgs && 00806 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) && 00807 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1]))) 00808 return Sema::TDK_MiscellaneousDeductionFailure; 00809 00810 // C++0x [temp.deduct.type]p10: 00811 // Similarly, if P has a form that contains (T), then each parameter type 00812 // Pi of the respective parameter-type- list of P is compared with the 00813 // corresponding parameter type Ai of the corresponding parameter-type-list 00814 // of A. [...] 00815 unsigned ArgIdx = 0, ParamIdx = 0; 00816 for (; ParamIdx != NumParams; ++ParamIdx) { 00817 // Check argument types. 00818 const PackExpansionType *Expansion 00819 = dyn_cast<PackExpansionType>(Params[ParamIdx]); 00820 if (!Expansion) { 00821 // Simple case: compare the parameter and argument types at this point. 00822 00823 // Make sure we have an argument. 00824 if (ArgIdx >= NumArgs) 00825 return Sema::TDK_MiscellaneousDeductionFailure; 00826 00827 if (isa<PackExpansionType>(Args[ArgIdx])) { 00828 // C++0x [temp.deduct.type]p22: 00829 // If the original function parameter associated with A is a function 00830 // parameter pack and the function parameter associated with P is not 00831 // a function parameter pack, then template argument deduction fails. 00832 return Sema::TDK_MiscellaneousDeductionFailure; 00833 } 00834 00835 if (Sema::TemplateDeductionResult Result 00836 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 00837 Params[ParamIdx], Args[ArgIdx], 00838 Info, Deduced, TDF, 00839 PartialOrdering, 00840 RefParamComparisons)) 00841 return Result; 00842 00843 ++ArgIdx; 00844 continue; 00845 } 00846 00847 // C++0x [temp.deduct.type]p5: 00848 // The non-deduced contexts are: 00849 // - A function parameter pack that does not occur at the end of the 00850 // parameter-declaration-clause. 00851 if (ParamIdx + 1 < NumParams) 00852 return Sema::TDK_Success; 00853 00854 // C++0x [temp.deduct.type]p10: 00855 // If the parameter-declaration corresponding to Pi is a function 00856 // parameter pack, then the type of its declarator- id is compared with 00857 // each remaining parameter type in the parameter-type-list of A. Each 00858 // comparison deduces template arguments for subsequent positions in the 00859 // template parameter packs expanded by the function parameter pack. 00860 00861 QualType Pattern = Expansion->getPattern(); 00862 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern); 00863 00864 bool HasAnyArguments = false; 00865 for (; ArgIdx < NumArgs; ++ArgIdx) { 00866 HasAnyArguments = true; 00867 00868 // Deduce template arguments from the pattern. 00869 if (Sema::TemplateDeductionResult Result 00870 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern, 00871 Args[ArgIdx], Info, Deduced, 00872 TDF, PartialOrdering, 00873 RefParamComparisons)) 00874 return Result; 00875 00876 PackScope.nextPackElement(); 00877 } 00878 00879 // Build argument packs for each of the parameter packs expanded by this 00880 // pack expansion. 00881 if (auto Result = PackScope.finish(HasAnyArguments)) 00882 return Result; 00883 } 00884 00885 // Make sure we don't have any extra arguments. 00886 if (ArgIdx < NumArgs) 00887 return Sema::TDK_MiscellaneousDeductionFailure; 00888 00889 return Sema::TDK_Success; 00890 } 00891 00892 /// \brief Determine whether the parameter has qualifiers that are either 00893 /// inconsistent with or a superset of the argument's qualifiers. 00894 static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, 00895 QualType ArgType) { 00896 Qualifiers ParamQs = ParamType.getQualifiers(); 00897 Qualifiers ArgQs = ArgType.getQualifiers(); 00898 00899 if (ParamQs == ArgQs) 00900 return false; 00901 00902 // Mismatched (but not missing) Objective-C GC attributes. 00903 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() && 00904 ParamQs.hasObjCGCAttr()) 00905 return true; 00906 00907 // Mismatched (but not missing) address spaces. 00908 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() && 00909 ParamQs.hasAddressSpace()) 00910 return true; 00911 00912 // Mismatched (but not missing) Objective-C lifetime qualifiers. 00913 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() && 00914 ParamQs.hasObjCLifetime()) 00915 return true; 00916 00917 // CVR qualifier superset. 00918 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) && 00919 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers()) 00920 == ParamQs.getCVRQualifiers()); 00921 } 00922 00923 /// \brief Compare types for equality with respect to possibly compatible 00924 /// function types (noreturn adjustment, implicit calling conventions). If any 00925 /// of parameter and argument is not a function, just perform type comparison. 00926 /// 00927 /// \param Param the template parameter type. 00928 /// 00929 /// \param Arg the argument type. 00930 bool Sema::isSameOrCompatibleFunctionType(CanQualType Param, 00931 CanQualType Arg) { 00932 const FunctionType *ParamFunction = Param->getAs<FunctionType>(), 00933 *ArgFunction = Arg->getAs<FunctionType>(); 00934 00935 // Just compare if not functions. 00936 if (!ParamFunction || !ArgFunction) 00937 return Param == Arg; 00938 00939 // Noreturn adjustment. 00940 QualType AdjustedParam; 00941 if (IsNoReturnConversion(Param, Arg, AdjustedParam)) 00942 return Arg == Context.getCanonicalType(AdjustedParam); 00943 00944 // FIXME: Compatible calling conventions. 00945 00946 return Param == Arg; 00947 } 00948 00949 /// \brief Deduce the template arguments by comparing the parameter type and 00950 /// the argument type (C++ [temp.deduct.type]). 00951 /// 00952 /// \param S the semantic analysis object within which we are deducing 00953 /// 00954 /// \param TemplateParams the template parameters that we are deducing 00955 /// 00956 /// \param ParamIn the parameter type 00957 /// 00958 /// \param ArgIn the argument type 00959 /// 00960 /// \param Info information about the template argument deduction itself 00961 /// 00962 /// \param Deduced the deduced template arguments 00963 /// 00964 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 00965 /// how template argument deduction is performed. 00966 /// 00967 /// \param PartialOrdering Whether we're performing template argument deduction 00968 /// in the context of partial ordering (C++0x [temp.deduct.partial]). 00969 /// 00970 /// \param RefParamComparisons If we're performing template argument deduction 00971 /// in the context of partial ordering, the set of qualifier comparisons. 00972 /// 00973 /// \returns the result of template argument deduction so far. Note that a 00974 /// "success" result means that template argument deduction has not yet failed, 00975 /// but it may still fail, later, for other reasons. 00976 static Sema::TemplateDeductionResult 00977 DeduceTemplateArgumentsByTypeMatch(Sema &S, 00978 TemplateParameterList *TemplateParams, 00979 QualType ParamIn, QualType ArgIn, 00980 TemplateDeductionInfo &Info, 00981 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 00982 unsigned TDF, 00983 bool PartialOrdering, 00984 SmallVectorImpl<RefParamPartialOrderingComparison> * 00985 RefParamComparisons) { 00986 // We only want to look at the canonical types, since typedefs and 00987 // sugar are not part of template argument deduction. 00988 QualType Param = S.Context.getCanonicalType(ParamIn); 00989 QualType Arg = S.Context.getCanonicalType(ArgIn); 00990 00991 // If the argument type is a pack expansion, look at its pattern. 00992 // This isn't explicitly called out 00993 if (const PackExpansionType *ArgExpansion 00994 = dyn_cast<PackExpansionType>(Arg)) 00995 Arg = ArgExpansion->getPattern(); 00996 00997 if (PartialOrdering) { 00998 // C++0x [temp.deduct.partial]p5: 00999 // Before the partial ordering is done, certain transformations are 01000 // performed on the types used for partial ordering: 01001 // - If P is a reference type, P is replaced by the type referred to. 01002 const ReferenceType *ParamRef = Param->getAs<ReferenceType>(); 01003 if (ParamRef) 01004 Param = ParamRef->getPointeeType(); 01005 01006 // - If A is a reference type, A is replaced by the type referred to. 01007 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>(); 01008 if (ArgRef) 01009 Arg = ArgRef->getPointeeType(); 01010 01011 if (RefParamComparisons && ParamRef && ArgRef) { 01012 // C++0x [temp.deduct.partial]p6: 01013 // If both P and A were reference types (before being replaced with the 01014 // type referred to above), determine which of the two types (if any) is 01015 // more cv-qualified than the other; otherwise the types are considered 01016 // to be equally cv-qualified for partial ordering purposes. The result 01017 // of this determination will be used below. 01018 // 01019 // We save this information for later, using it only when deduction 01020 // succeeds in both directions. 01021 RefParamPartialOrderingComparison Comparison; 01022 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>(); 01023 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>(); 01024 Comparison.Qualifiers = NeitherMoreQualified; 01025 01026 Qualifiers ParamQuals = Param.getQualifiers(); 01027 Qualifiers ArgQuals = Arg.getQualifiers(); 01028 if (ParamQuals.isStrictSupersetOf(ArgQuals)) 01029 Comparison.Qualifiers = ParamMoreQualified; 01030 else if (ArgQuals.isStrictSupersetOf(ParamQuals)) 01031 Comparison.Qualifiers = ArgMoreQualified; 01032 else if (ArgQuals.getObjCLifetime() != ParamQuals.getObjCLifetime() && 01033 ArgQuals.withoutObjCLifetime() 01034 == ParamQuals.withoutObjCLifetime()) { 01035 // Prefer binding to non-__unsafe_autoretained parameters. 01036 if (ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone && 01037 ParamQuals.getObjCLifetime()) 01038 Comparison.Qualifiers = ParamMoreQualified; 01039 else if (ParamQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone && 01040 ArgQuals.getObjCLifetime()) 01041 Comparison.Qualifiers = ArgMoreQualified; 01042 } 01043 RefParamComparisons->push_back(Comparison); 01044 } 01045 01046 // C++0x [temp.deduct.partial]p7: 01047 // Remove any top-level cv-qualifiers: 01048 // - If P is a cv-qualified type, P is replaced by the cv-unqualified 01049 // version of P. 01050 Param = Param.getUnqualifiedType(); 01051 // - If A is a cv-qualified type, A is replaced by the cv-unqualified 01052 // version of A. 01053 Arg = Arg.getUnqualifiedType(); 01054 } else { 01055 // C++0x [temp.deduct.call]p4 bullet 1: 01056 // - If the original P is a reference type, the deduced A (i.e., the type 01057 // referred to by the reference) can be more cv-qualified than the 01058 // transformed A. 01059 if (TDF & TDF_ParamWithReferenceType) { 01060 Qualifiers Quals; 01061 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals); 01062 Quals.setCVRQualifiers(Quals.getCVRQualifiers() & 01063 Arg.getCVRQualifiers()); 01064 Param = S.Context.getQualifiedType(UnqualParam, Quals); 01065 } 01066 01067 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) { 01068 // C++0x [temp.deduct.type]p10: 01069 // If P and A are function types that originated from deduction when 01070 // taking the address of a function template (14.8.2.2) or when deducing 01071 // template arguments from a function declaration (14.8.2.6) and Pi and 01072 // Ai are parameters of the top-level parameter-type-list of P and A, 01073 // respectively, Pi is adjusted if it is an rvalue reference to a 01074 // cv-unqualified template parameter and Ai is an lvalue reference, in 01075 // which case the type of Pi is changed to be the template parameter 01076 // type (i.e., T&& is changed to simply T). [ Note: As a result, when 01077 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be 01078 // deduced as X&. - end note ] 01079 TDF &= ~TDF_TopLevelParameterTypeList; 01080 01081 if (const RValueReferenceType *ParamRef 01082 = Param->getAs<RValueReferenceType>()) { 01083 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) && 01084 !ParamRef->getPointeeType().getQualifiers()) 01085 if (Arg->isLValueReferenceType()) 01086 Param = ParamRef->getPointeeType(); 01087 } 01088 } 01089 } 01090 01091 // C++ [temp.deduct.type]p9: 01092 // A template type argument T, a template template argument TT or a 01093 // template non-type argument i can be deduced if P and A have one of 01094 // the following forms: 01095 // 01096 // T 01097 // cv-list T 01098 if (const TemplateTypeParmType *TemplateTypeParm 01099 = Param->getAs<TemplateTypeParmType>()) { 01100 // Just skip any attempts to deduce from a placeholder type. 01101 if (Arg->isPlaceholderType()) 01102 return Sema::TDK_Success; 01103 01104 unsigned Index = TemplateTypeParm->getIndex(); 01105 bool RecanonicalizeArg = false; 01106 01107 // If the argument type is an array type, move the qualifiers up to the 01108 // top level, so they can be matched with the qualifiers on the parameter. 01109 if (isa<ArrayType>(Arg)) { 01110 Qualifiers Quals; 01111 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals); 01112 if (Quals) { 01113 Arg = S.Context.getQualifiedType(Arg, Quals); 01114 RecanonicalizeArg = true; 01115 } 01116 } 01117 01118 // The argument type can not be less qualified than the parameter 01119 // type. 01120 if (!(TDF & TDF_IgnoreQualifiers) && 01121 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) { 01122 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 01123 Info.FirstArg = TemplateArgument(Param); 01124 Info.SecondArg = TemplateArgument(Arg); 01125 return Sema::TDK_Underqualified; 01126 } 01127 01128 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0"); 01129 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function"); 01130 QualType DeducedType = Arg; 01131 01132 // Remove any qualifiers on the parameter from the deduced type. 01133 // We checked the qualifiers for consistency above. 01134 Qualifiers DeducedQs = DeducedType.getQualifiers(); 01135 Qualifiers ParamQs = Param.getQualifiers(); 01136 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers()); 01137 if (ParamQs.hasObjCGCAttr()) 01138 DeducedQs.removeObjCGCAttr(); 01139 if (ParamQs.hasAddressSpace()) 01140 DeducedQs.removeAddressSpace(); 01141 if (ParamQs.hasObjCLifetime()) 01142 DeducedQs.removeObjCLifetime(); 01143 01144 // Objective-C ARC: 01145 // If template deduction would produce a lifetime qualifier on a type 01146 // that is not a lifetime type, template argument deduction fails. 01147 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() && 01148 !DeducedType->isDependentType()) { 01149 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 01150 Info.FirstArg = TemplateArgument(Param); 01151 Info.SecondArg = TemplateArgument(Arg); 01152 return Sema::TDK_Underqualified; 01153 } 01154 01155 // Objective-C ARC: 01156 // If template deduction would produce an argument type with lifetime type 01157 // but no lifetime qualifier, the __strong lifetime qualifier is inferred. 01158 if (S.getLangOpts().ObjCAutoRefCount && 01159 DeducedType->isObjCLifetimeType() && 01160 !DeducedQs.hasObjCLifetime()) 01161 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong); 01162 01163 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), 01164 DeducedQs); 01165 01166 if (RecanonicalizeArg) 01167 DeducedType = S.Context.getCanonicalType(DeducedType); 01168 01169 DeducedTemplateArgument NewDeduced(DeducedType); 01170 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 01171 Deduced[Index], 01172 NewDeduced); 01173 if (Result.isNull()) { 01174 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 01175 Info.FirstArg = Deduced[Index]; 01176 Info.SecondArg = NewDeduced; 01177 return Sema::TDK_Inconsistent; 01178 } 01179 01180 Deduced[Index] = Result; 01181 return Sema::TDK_Success; 01182 } 01183 01184 // Set up the template argument deduction information for a failure. 01185 Info.FirstArg = TemplateArgument(ParamIn); 01186 Info.SecondArg = TemplateArgument(ArgIn); 01187 01188 // If the parameter is an already-substituted template parameter 01189 // pack, do nothing: we don't know which of its arguments to look 01190 // at, so we have to wait until all of the parameter packs in this 01191 // expansion have arguments. 01192 if (isa<SubstTemplateTypeParmPackType>(Param)) 01193 return Sema::TDK_Success; 01194 01195 // Check the cv-qualifiers on the parameter and argument types. 01196 CanQualType CanParam = S.Context.getCanonicalType(Param); 01197 CanQualType CanArg = S.Context.getCanonicalType(Arg); 01198 if (!(TDF & TDF_IgnoreQualifiers)) { 01199 if (TDF & TDF_ParamWithReferenceType) { 01200 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg)) 01201 return Sema::TDK_NonDeducedMismatch; 01202 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) { 01203 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers()) 01204 return Sema::TDK_NonDeducedMismatch; 01205 } 01206 01207 // If the parameter type is not dependent, there is nothing to deduce. 01208 if (!Param->isDependentType()) { 01209 if (!(TDF & TDF_SkipNonDependent)) { 01210 bool NonDeduced = (TDF & TDF_InOverloadResolution)? 01211 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) : 01212 Param != Arg; 01213 if (NonDeduced) { 01214 return Sema::TDK_NonDeducedMismatch; 01215 } 01216 } 01217 return Sema::TDK_Success; 01218 } 01219 } else if (!Param->isDependentType()) { 01220 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(), 01221 ArgUnqualType = CanArg.getUnqualifiedType(); 01222 bool Success = (TDF & TDF_InOverloadResolution)? 01223 S.isSameOrCompatibleFunctionType(ParamUnqualType, 01224 ArgUnqualType) : 01225 ParamUnqualType == ArgUnqualType; 01226 if (Success) 01227 return Sema::TDK_Success; 01228 } 01229 01230 switch (Param->getTypeClass()) { 01231 // Non-canonical types cannot appear here. 01232 #define NON_CANONICAL_TYPE(Class, Base) \ 01233 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class); 01234 #define TYPE(Class, Base) 01235 #include "clang/AST/TypeNodes.def" 01236 01237 case Type::TemplateTypeParm: 01238 case Type::SubstTemplateTypeParmPack: 01239 llvm_unreachable("Type nodes handled above"); 01240 01241 // These types cannot be dependent, so simply check whether the types are 01242 // the same. 01243 case Type::Builtin: 01244 case Type::VariableArray: 01245 case Type::Vector: 01246 case Type::FunctionNoProto: 01247 case Type::Record: 01248 case Type::Enum: 01249 case Type::ObjCObject: 01250 case Type::ObjCInterface: 01251 case Type::ObjCObjectPointer: { 01252 if (TDF & TDF_SkipNonDependent) 01253 return Sema::TDK_Success; 01254 01255 if (TDF & TDF_IgnoreQualifiers) { 01256 Param = Param.getUnqualifiedType(); 01257 Arg = Arg.getUnqualifiedType(); 01258 } 01259 01260 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch; 01261 } 01262 01263 // _Complex T [placeholder extension] 01264 case Type::Complex: 01265 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>()) 01266 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01267 cast<ComplexType>(Param)->getElementType(), 01268 ComplexArg->getElementType(), 01269 Info, Deduced, TDF); 01270 01271 return Sema::TDK_NonDeducedMismatch; 01272 01273 // _Atomic T [extension] 01274 case Type::Atomic: 01275 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>()) 01276 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01277 cast<AtomicType>(Param)->getValueType(), 01278 AtomicArg->getValueType(), 01279 Info, Deduced, TDF); 01280 01281 return Sema::TDK_NonDeducedMismatch; 01282 01283 // T * 01284 case Type::Pointer: { 01285 QualType PointeeType; 01286 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) { 01287 PointeeType = PointerArg->getPointeeType(); 01288 } else if (const ObjCObjectPointerType *PointerArg 01289 = Arg->getAs<ObjCObjectPointerType>()) { 01290 PointeeType = PointerArg->getPointeeType(); 01291 } else { 01292 return Sema::TDK_NonDeducedMismatch; 01293 } 01294 01295 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass); 01296 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01297 cast<PointerType>(Param)->getPointeeType(), 01298 PointeeType, 01299 Info, Deduced, SubTDF); 01300 } 01301 01302 // T & 01303 case Type::LValueReference: { 01304 const LValueReferenceType *ReferenceArg = 01305 Arg->getAs<LValueReferenceType>(); 01306 if (!ReferenceArg) 01307 return Sema::TDK_NonDeducedMismatch; 01308 01309 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01310 cast<LValueReferenceType>(Param)->getPointeeType(), 01311 ReferenceArg->getPointeeType(), Info, Deduced, 0); 01312 } 01313 01314 // T && [C++0x] 01315 case Type::RValueReference: { 01316 const RValueReferenceType *ReferenceArg = 01317 Arg->getAs<RValueReferenceType>(); 01318 if (!ReferenceArg) 01319 return Sema::TDK_NonDeducedMismatch; 01320 01321 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01322 cast<RValueReferenceType>(Param)->getPointeeType(), 01323 ReferenceArg->getPointeeType(), 01324 Info, Deduced, 0); 01325 } 01326 01327 // T [] (implied, but not stated explicitly) 01328 case Type::IncompleteArray: { 01329 const IncompleteArrayType *IncompleteArrayArg = 01330 S.Context.getAsIncompleteArrayType(Arg); 01331 if (!IncompleteArrayArg) 01332 return Sema::TDK_NonDeducedMismatch; 01333 01334 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 01335 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01336 S.Context.getAsIncompleteArrayType(Param)->getElementType(), 01337 IncompleteArrayArg->getElementType(), 01338 Info, Deduced, SubTDF); 01339 } 01340 01341 // T [integer-constant] 01342 case Type::ConstantArray: { 01343 const ConstantArrayType *ConstantArrayArg = 01344 S.Context.getAsConstantArrayType(Arg); 01345 if (!ConstantArrayArg) 01346 return Sema::TDK_NonDeducedMismatch; 01347 01348 const ConstantArrayType *ConstantArrayParm = 01349 S.Context.getAsConstantArrayType(Param); 01350 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize()) 01351 return Sema::TDK_NonDeducedMismatch; 01352 01353 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 01354 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01355 ConstantArrayParm->getElementType(), 01356 ConstantArrayArg->getElementType(), 01357 Info, Deduced, SubTDF); 01358 } 01359 01360 // type [i] 01361 case Type::DependentSizedArray: { 01362 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg); 01363 if (!ArrayArg) 01364 return Sema::TDK_NonDeducedMismatch; 01365 01366 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 01367 01368 // Check the element type of the arrays 01369 const DependentSizedArrayType *DependentArrayParm 01370 = S.Context.getAsDependentSizedArrayType(Param); 01371 if (Sema::TemplateDeductionResult Result 01372 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01373 DependentArrayParm->getElementType(), 01374 ArrayArg->getElementType(), 01375 Info, Deduced, SubTDF)) 01376 return Result; 01377 01378 // Determine the array bound is something we can deduce. 01379 NonTypeTemplateParmDecl *NTTP 01380 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr()); 01381 if (!NTTP) 01382 return Sema::TDK_Success; 01383 01384 // We can perform template argument deduction for the given non-type 01385 // template parameter. 01386 assert(NTTP->getDepth() == 0 && 01387 "Cannot deduce non-type template argument at depth > 0"); 01388 if (const ConstantArrayType *ConstantArrayArg 01389 = dyn_cast<ConstantArrayType>(ArrayArg)) { 01390 llvm::APSInt Size(ConstantArrayArg->getSize()); 01391 return DeduceNonTypeTemplateArgument(S, NTTP, Size, 01392 S.Context.getSizeType(), 01393 /*ArrayBound=*/true, 01394 Info, Deduced); 01395 } 01396 if (const DependentSizedArrayType *DependentArrayArg 01397 = dyn_cast<DependentSizedArrayType>(ArrayArg)) 01398 if (DependentArrayArg->getSizeExpr()) 01399 return DeduceNonTypeTemplateArgument(S, NTTP, 01400 DependentArrayArg->getSizeExpr(), 01401 Info, Deduced); 01402 01403 // Incomplete type does not match a dependently-sized array type 01404 return Sema::TDK_NonDeducedMismatch; 01405 } 01406 01407 // type(*)(T) 01408 // T(*)() 01409 // T(*)(T) 01410 case Type::FunctionProto: { 01411 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList; 01412 const FunctionProtoType *FunctionProtoArg = 01413 dyn_cast<FunctionProtoType>(Arg); 01414 if (!FunctionProtoArg) 01415 return Sema::TDK_NonDeducedMismatch; 01416 01417 const FunctionProtoType *FunctionProtoParam = 01418 cast<FunctionProtoType>(Param); 01419 01420 if (FunctionProtoParam->getTypeQuals() 01421 != FunctionProtoArg->getTypeQuals() || 01422 FunctionProtoParam->getRefQualifier() 01423 != FunctionProtoArg->getRefQualifier() || 01424 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic()) 01425 return Sema::TDK_NonDeducedMismatch; 01426 01427 // Check return types. 01428 if (Sema::TemplateDeductionResult Result = 01429 DeduceTemplateArgumentsByTypeMatch( 01430 S, TemplateParams, FunctionProtoParam->getReturnType(), 01431 FunctionProtoArg->getReturnType(), Info, Deduced, 0)) 01432 return Result; 01433 01434 return DeduceTemplateArguments( 01435 S, TemplateParams, FunctionProtoParam->param_type_begin(), 01436 FunctionProtoParam->getNumParams(), 01437 FunctionProtoArg->param_type_begin(), 01438 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF); 01439 } 01440 01441 case Type::InjectedClassName: { 01442 // Treat a template's injected-class-name as if the template 01443 // specialization type had been used. 01444 Param = cast<InjectedClassNameType>(Param) 01445 ->getInjectedSpecializationType(); 01446 assert(isa<TemplateSpecializationType>(Param) && 01447 "injected class name is not a template specialization type"); 01448 // fall through 01449 } 01450 01451 // template-name<T> (where template-name refers to a class template) 01452 // template-name<i> 01453 // TT<T> 01454 // TT<i> 01455 // TT<> 01456 case Type::TemplateSpecialization: { 01457 const TemplateSpecializationType *SpecParam 01458 = cast<TemplateSpecializationType>(Param); 01459 01460 // Try to deduce template arguments from the template-id. 01461 Sema::TemplateDeductionResult Result 01462 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, 01463 Info, Deduced); 01464 01465 if (Result && (TDF & TDF_DerivedClass)) { 01466 // C++ [temp.deduct.call]p3b3: 01467 // If P is a class, and P has the form template-id, then A can be a 01468 // derived class of the deduced A. Likewise, if P is a pointer to a 01469 // class of the form template-id, A can be a pointer to a derived 01470 // class pointed to by the deduced A. 01471 // 01472 // More importantly: 01473 // These alternatives are considered only if type deduction would 01474 // otherwise fail. 01475 if (const RecordType *RecordT = Arg->getAs<RecordType>()) { 01476 // We cannot inspect base classes as part of deduction when the type 01477 // is incomplete, so either instantiate any templates necessary to 01478 // complete the type, or skip over it if it cannot be completed. 01479 if (S.RequireCompleteType(Info.getLocation(), Arg, 0)) 01480 return Result; 01481 01482 // Use data recursion to crawl through the list of base classes. 01483 // Visited contains the set of nodes we have already visited, while 01484 // ToVisit is our stack of records that we still need to visit. 01485 llvm::SmallPtrSet<const RecordType *, 8> Visited; 01486 SmallVector<const RecordType *, 8> ToVisit; 01487 ToVisit.push_back(RecordT); 01488 bool Successful = false; 01489 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(), 01490 Deduced.end()); 01491 while (!ToVisit.empty()) { 01492 // Retrieve the next class in the inheritance hierarchy. 01493 const RecordType *NextT = ToVisit.pop_back_val(); 01494 01495 // If we have already seen this type, skip it. 01496 if (!Visited.insert(NextT)) 01497 continue; 01498 01499 // If this is a base class, try to perform template argument 01500 // deduction from it. 01501 if (NextT != RecordT) { 01502 TemplateDeductionInfo BaseInfo(Info.getLocation()); 01503 Sema::TemplateDeductionResult BaseResult 01504 = DeduceTemplateArguments(S, TemplateParams, SpecParam, 01505 QualType(NextT, 0), BaseInfo, 01506 Deduced); 01507 01508 // If template argument deduction for this base was successful, 01509 // note that we had some success. Otherwise, ignore any deductions 01510 // from this base class. 01511 if (BaseResult == Sema::TDK_Success) { 01512 Successful = true; 01513 DeducedOrig.clear(); 01514 DeducedOrig.append(Deduced.begin(), Deduced.end()); 01515 Info.Param = BaseInfo.Param; 01516 Info.FirstArg = BaseInfo.FirstArg; 01517 Info.SecondArg = BaseInfo.SecondArg; 01518 } 01519 else 01520 Deduced = DeducedOrig; 01521 } 01522 01523 // Visit base classes 01524 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl()); 01525 for (const auto &Base : Next->bases()) { 01526 assert(Base.getType()->isRecordType() && 01527 "Base class that isn't a record?"); 01528 ToVisit.push_back(Base.getType()->getAs<RecordType>()); 01529 } 01530 } 01531 01532 if (Successful) 01533 return Sema::TDK_Success; 01534 } 01535 01536 } 01537 01538 return Result; 01539 } 01540 01541 // T type::* 01542 // T T::* 01543 // T (type::*)() 01544 // type (T::*)() 01545 // type (type::*)(T) 01546 // type (T::*)(T) 01547 // T (type::*)(T) 01548 // T (T::*)() 01549 // T (T::*)(T) 01550 case Type::MemberPointer: { 01551 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param); 01552 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg); 01553 if (!MemPtrArg) 01554 return Sema::TDK_NonDeducedMismatch; 01555 01556 if (Sema::TemplateDeductionResult Result 01557 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01558 MemPtrParam->getPointeeType(), 01559 MemPtrArg->getPointeeType(), 01560 Info, Deduced, 01561 TDF & TDF_IgnoreQualifiers)) 01562 return Result; 01563 01564 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01565 QualType(MemPtrParam->getClass(), 0), 01566 QualType(MemPtrArg->getClass(), 0), 01567 Info, Deduced, 01568 TDF & TDF_IgnoreQualifiers); 01569 } 01570 01571 // (clang extension) 01572 // 01573 // type(^)(T) 01574 // T(^)() 01575 // T(^)(T) 01576 case Type::BlockPointer: { 01577 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param); 01578 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg); 01579 01580 if (!BlockPtrArg) 01581 return Sema::TDK_NonDeducedMismatch; 01582 01583 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01584 BlockPtrParam->getPointeeType(), 01585 BlockPtrArg->getPointeeType(), 01586 Info, Deduced, 0); 01587 } 01588 01589 // (clang extension) 01590 // 01591 // T __attribute__(((ext_vector_type(<integral constant>)))) 01592 case Type::ExtVector: { 01593 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param); 01594 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) { 01595 // Make sure that the vectors have the same number of elements. 01596 if (VectorParam->getNumElements() != VectorArg->getNumElements()) 01597 return Sema::TDK_NonDeducedMismatch; 01598 01599 // Perform deduction on the element types. 01600 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01601 VectorParam->getElementType(), 01602 VectorArg->getElementType(), 01603 Info, Deduced, TDF); 01604 } 01605 01606 if (const DependentSizedExtVectorType *VectorArg 01607 = dyn_cast<DependentSizedExtVectorType>(Arg)) { 01608 // We can't check the number of elements, since the argument has a 01609 // dependent number of elements. This can only occur during partial 01610 // ordering. 01611 01612 // Perform deduction on the element types. 01613 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01614 VectorParam->getElementType(), 01615 VectorArg->getElementType(), 01616 Info, Deduced, TDF); 01617 } 01618 01619 return Sema::TDK_NonDeducedMismatch; 01620 } 01621 01622 // (clang extension) 01623 // 01624 // T __attribute__(((ext_vector_type(N)))) 01625 case Type::DependentSizedExtVector: { 01626 const DependentSizedExtVectorType *VectorParam 01627 = cast<DependentSizedExtVectorType>(Param); 01628 01629 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) { 01630 // Perform deduction on the element types. 01631 if (Sema::TemplateDeductionResult Result 01632 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01633 VectorParam->getElementType(), 01634 VectorArg->getElementType(), 01635 Info, Deduced, TDF)) 01636 return Result; 01637 01638 // Perform deduction on the vector size, if we can. 01639 NonTypeTemplateParmDecl *NTTP 01640 = getDeducedParameterFromExpr(VectorParam->getSizeExpr()); 01641 if (!NTTP) 01642 return Sema::TDK_Success; 01643 01644 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); 01645 ArgSize = VectorArg->getNumElements(); 01646 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy, 01647 false, Info, Deduced); 01648 } 01649 01650 if (const DependentSizedExtVectorType *VectorArg 01651 = dyn_cast<DependentSizedExtVectorType>(Arg)) { 01652 // Perform deduction on the element types. 01653 if (Sema::TemplateDeductionResult Result 01654 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01655 VectorParam->getElementType(), 01656 VectorArg->getElementType(), 01657 Info, Deduced, TDF)) 01658 return Result; 01659 01660 // Perform deduction on the vector size, if we can. 01661 NonTypeTemplateParmDecl *NTTP 01662 = getDeducedParameterFromExpr(VectorParam->getSizeExpr()); 01663 if (!NTTP) 01664 return Sema::TDK_Success; 01665 01666 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(), 01667 Info, Deduced); 01668 } 01669 01670 return Sema::TDK_NonDeducedMismatch; 01671 } 01672 01673 case Type::TypeOfExpr: 01674 case Type::TypeOf: 01675 case Type::DependentName: 01676 case Type::UnresolvedUsing: 01677 case Type::Decltype: 01678 case Type::UnaryTransform: 01679 case Type::Auto: 01680 case Type::DependentTemplateSpecialization: 01681 case Type::PackExpansion: 01682 // No template argument deduction for these types 01683 return Sema::TDK_Success; 01684 } 01685 01686 llvm_unreachable("Invalid Type Class!"); 01687 } 01688 01689 static Sema::TemplateDeductionResult 01690 DeduceTemplateArguments(Sema &S, 01691 TemplateParameterList *TemplateParams, 01692 const TemplateArgument &Param, 01693 TemplateArgument Arg, 01694 TemplateDeductionInfo &Info, 01695 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 01696 // If the template argument is a pack expansion, perform template argument 01697 // deduction against the pattern of that expansion. This only occurs during 01698 // partial ordering. 01699 if (Arg.isPackExpansion()) 01700 Arg = Arg.getPackExpansionPattern(); 01701 01702 switch (Param.getKind()) { 01703 case TemplateArgument::Null: 01704 llvm_unreachable("Null template argument in parameter list"); 01705 01706 case TemplateArgument::Type: 01707 if (Arg.getKind() == TemplateArgument::Type) 01708 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01709 Param.getAsType(), 01710 Arg.getAsType(), 01711 Info, Deduced, 0); 01712 Info.FirstArg = Param; 01713 Info.SecondArg = Arg; 01714 return Sema::TDK_NonDeducedMismatch; 01715 01716 case TemplateArgument::Template: 01717 if (Arg.getKind() == TemplateArgument::Template) 01718 return DeduceTemplateArguments(S, TemplateParams, 01719 Param.getAsTemplate(), 01720 Arg.getAsTemplate(), Info, Deduced); 01721 Info.FirstArg = Param; 01722 Info.SecondArg = Arg; 01723 return Sema::TDK_NonDeducedMismatch; 01724 01725 case TemplateArgument::TemplateExpansion: 01726 llvm_unreachable("caller should handle pack expansions"); 01727 01728 case TemplateArgument::Declaration: 01729 if (Arg.getKind() == TemplateArgument::Declaration && 01730 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl())) 01731 return Sema::TDK_Success; 01732 01733 Info.FirstArg = Param; 01734 Info.SecondArg = Arg; 01735 return Sema::TDK_NonDeducedMismatch; 01736 01737 case TemplateArgument::NullPtr: 01738 if (Arg.getKind() == TemplateArgument::NullPtr && 01739 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType())) 01740 return Sema::TDK_Success; 01741 01742 Info.FirstArg = Param; 01743 Info.SecondArg = Arg; 01744 return Sema::TDK_NonDeducedMismatch; 01745 01746 case TemplateArgument::Integral: 01747 if (Arg.getKind() == TemplateArgument::Integral) { 01748 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral())) 01749 return Sema::TDK_Success; 01750 01751 Info.FirstArg = Param; 01752 Info.SecondArg = Arg; 01753 return Sema::TDK_NonDeducedMismatch; 01754 } 01755 01756 if (Arg.getKind() == TemplateArgument::Expression) { 01757 Info.FirstArg = Param; 01758 Info.SecondArg = Arg; 01759 return Sema::TDK_NonDeducedMismatch; 01760 } 01761 01762 Info.FirstArg = Param; 01763 Info.SecondArg = Arg; 01764 return Sema::TDK_NonDeducedMismatch; 01765 01766 case TemplateArgument::Expression: { 01767 if (NonTypeTemplateParmDecl *NTTP 01768 = getDeducedParameterFromExpr(Param.getAsExpr())) { 01769 if (Arg.getKind() == TemplateArgument::Integral) 01770 return DeduceNonTypeTemplateArgument(S, NTTP, 01771 Arg.getAsIntegral(), 01772 Arg.getIntegralType(), 01773 /*ArrayBound=*/false, 01774 Info, Deduced); 01775 if (Arg.getKind() == TemplateArgument::Expression) 01776 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(), 01777 Info, Deduced); 01778 if (Arg.getKind() == TemplateArgument::Declaration) 01779 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(), 01780 Info, Deduced); 01781 01782 Info.FirstArg = Param; 01783 Info.SecondArg = Arg; 01784 return Sema::TDK_NonDeducedMismatch; 01785 } 01786 01787 // Can't deduce anything, but that's okay. 01788 return Sema::TDK_Success; 01789 } 01790 case TemplateArgument::Pack: 01791 llvm_unreachable("Argument packs should be expanded by the caller!"); 01792 } 01793 01794 llvm_unreachable("Invalid TemplateArgument Kind!"); 01795 } 01796 01797 /// \brief Determine whether there is a template argument to be used for 01798 /// deduction. 01799 /// 01800 /// This routine "expands" argument packs in-place, overriding its input 01801 /// parameters so that \c Args[ArgIdx] will be the available template argument. 01802 /// 01803 /// \returns true if there is another template argument (which will be at 01804 /// \c Args[ArgIdx]), false otherwise. 01805 static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args, 01806 unsigned &ArgIdx, 01807 unsigned &NumArgs) { 01808 if (ArgIdx == NumArgs) 01809 return false; 01810 01811 const TemplateArgument &Arg = Args[ArgIdx]; 01812 if (Arg.getKind() != TemplateArgument::Pack) 01813 return true; 01814 01815 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?"); 01816 Args = Arg.pack_begin(); 01817 NumArgs = Arg.pack_size(); 01818 ArgIdx = 0; 01819 return ArgIdx < NumArgs; 01820 } 01821 01822 /// \brief Determine whether the given set of template arguments has a pack 01823 /// expansion that is not the last template argument. 01824 static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args, 01825 unsigned NumArgs) { 01826 unsigned ArgIdx = 0; 01827 while (ArgIdx < NumArgs) { 01828 const TemplateArgument &Arg = Args[ArgIdx]; 01829 01830 // Unwrap argument packs. 01831 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) { 01832 Args = Arg.pack_begin(); 01833 NumArgs = Arg.pack_size(); 01834 ArgIdx = 0; 01835 continue; 01836 } 01837 01838 ++ArgIdx; 01839 if (ArgIdx == NumArgs) 01840 return false; 01841 01842 if (Arg.isPackExpansion()) 01843 return true; 01844 } 01845 01846 return false; 01847 } 01848 01849 static Sema::TemplateDeductionResult 01850 DeduceTemplateArguments(Sema &S, 01851 TemplateParameterList *TemplateParams, 01852 const TemplateArgument *Params, unsigned NumParams, 01853 const TemplateArgument *Args, unsigned NumArgs, 01854 TemplateDeductionInfo &Info, 01855 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 01856 // C++0x [temp.deduct.type]p9: 01857 // If the template argument list of P contains a pack expansion that is not 01858 // the last template argument, the entire template argument list is a 01859 // non-deduced context. 01860 if (hasPackExpansionBeforeEnd(Params, NumParams)) 01861 return Sema::TDK_Success; 01862 01863 // C++0x [temp.deduct.type]p9: 01864 // If P has a form that contains <T> or <i>, then each argument Pi of the 01865 // respective template argument list P is compared with the corresponding 01866 // argument Ai of the corresponding template argument list of A. 01867 unsigned ArgIdx = 0, ParamIdx = 0; 01868 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams); 01869 ++ParamIdx) { 01870 if (!Params[ParamIdx].isPackExpansion()) { 01871 // The simple case: deduce template arguments by matching Pi and Ai. 01872 01873 // Check whether we have enough arguments. 01874 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) 01875 return Sema::TDK_Success; 01876 01877 if (Args[ArgIdx].isPackExpansion()) { 01878 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here, 01879 // but applied to pack expansions that are template arguments. 01880 return Sema::TDK_MiscellaneousDeductionFailure; 01881 } 01882 01883 // Perform deduction for this Pi/Ai pair. 01884 if (Sema::TemplateDeductionResult Result 01885 = DeduceTemplateArguments(S, TemplateParams, 01886 Params[ParamIdx], Args[ArgIdx], 01887 Info, Deduced)) 01888 return Result; 01889 01890 // Move to the next argument. 01891 ++ArgIdx; 01892 continue; 01893 } 01894 01895 // The parameter is a pack expansion. 01896 01897 // C++0x [temp.deduct.type]p9: 01898 // If Pi is a pack expansion, then the pattern of Pi is compared with 01899 // each remaining argument in the template argument list of A. Each 01900 // comparison deduces template arguments for subsequent positions in the 01901 // template parameter packs expanded by Pi. 01902 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern(); 01903 01904 // FIXME: If there are no remaining arguments, we can bail out early 01905 // and set any deduced parameter packs to an empty argument pack. 01906 // The latter part of this is a (minor) correctness issue. 01907 01908 // Prepare to deduce the packs within the pattern. 01909 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern); 01910 01911 // Keep track of the deduced template arguments for each parameter pack 01912 // expanded by this pack expansion (the outer index) and for each 01913 // template argument (the inner SmallVectors). 01914 bool HasAnyArguments = false; 01915 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) { 01916 HasAnyArguments = true; 01917 01918 // Deduce template arguments from the pattern. 01919 if (Sema::TemplateDeductionResult Result 01920 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx], 01921 Info, Deduced)) 01922 return Result; 01923 01924 PackScope.nextPackElement(); 01925 } 01926 01927 // Build argument packs for each of the parameter packs expanded by this 01928 // pack expansion. 01929 if (auto Result = PackScope.finish(HasAnyArguments)) 01930 return Result; 01931 } 01932 01933 return Sema::TDK_Success; 01934 } 01935 01936 static Sema::TemplateDeductionResult 01937 DeduceTemplateArguments(Sema &S, 01938 TemplateParameterList *TemplateParams, 01939 const TemplateArgumentList &ParamList, 01940 const TemplateArgumentList &ArgList, 01941 TemplateDeductionInfo &Info, 01942 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 01943 return DeduceTemplateArguments(S, TemplateParams, 01944 ParamList.data(), ParamList.size(), 01945 ArgList.data(), ArgList.size(), 01946 Info, Deduced); 01947 } 01948 01949 /// \brief Determine whether two template arguments are the same. 01950 static bool isSameTemplateArg(ASTContext &Context, 01951 const TemplateArgument &X, 01952 const TemplateArgument &Y) { 01953 if (X.getKind() != Y.getKind()) 01954 return false; 01955 01956 switch (X.getKind()) { 01957 case TemplateArgument::Null: 01958 llvm_unreachable("Comparing NULL template argument"); 01959 01960 case TemplateArgument::Type: 01961 return Context.getCanonicalType(X.getAsType()) == 01962 Context.getCanonicalType(Y.getAsType()); 01963 01964 case TemplateArgument::Declaration: 01965 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl()); 01966 01967 case TemplateArgument::NullPtr: 01968 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()); 01969 01970 case TemplateArgument::Template: 01971 case TemplateArgument::TemplateExpansion: 01972 return Context.getCanonicalTemplateName( 01973 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() == 01974 Context.getCanonicalTemplateName( 01975 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer(); 01976 01977 case TemplateArgument::Integral: 01978 return X.getAsIntegral() == Y.getAsIntegral(); 01979 01980 case TemplateArgument::Expression: { 01981 llvm::FoldingSetNodeID XID, YID; 01982 X.getAsExpr()->Profile(XID, Context, true); 01983 Y.getAsExpr()->Profile(YID, Context, true); 01984 return XID == YID; 01985 } 01986 01987 case TemplateArgument::Pack: 01988 if (X.pack_size() != Y.pack_size()) 01989 return false; 01990 01991 for (TemplateArgument::pack_iterator XP = X.pack_begin(), 01992 XPEnd = X.pack_end(), 01993 YP = Y.pack_begin(); 01994 XP != XPEnd; ++XP, ++YP) 01995 if (!isSameTemplateArg(Context, *XP, *YP)) 01996 return false; 01997 01998 return true; 01999 } 02000 02001 llvm_unreachable("Invalid TemplateArgument Kind!"); 02002 } 02003 02004 /// \brief Allocate a TemplateArgumentLoc where all locations have 02005 /// been initialized to the given location. 02006 /// 02007 /// \param S The semantic analysis object. 02008 /// 02009 /// \param Arg The template argument we are producing template argument 02010 /// location information for. 02011 /// 02012 /// \param NTTPType For a declaration template argument, the type of 02013 /// the non-type template parameter that corresponds to this template 02014 /// argument. 02015 /// 02016 /// \param Loc The source location to use for the resulting template 02017 /// argument. 02018 static TemplateArgumentLoc 02019 getTrivialTemplateArgumentLoc(Sema &S, 02020 const TemplateArgument &Arg, 02021 QualType NTTPType, 02022 SourceLocation Loc) { 02023 switch (Arg.getKind()) { 02024 case TemplateArgument::Null: 02025 llvm_unreachable("Can't get a NULL template argument here"); 02026 02027 case TemplateArgument::Type: 02028 return TemplateArgumentLoc(Arg, 02029 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc)); 02030 02031 case TemplateArgument::Declaration: { 02032 Expr *E 02033 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) 02034 .getAs<Expr>(); 02035 return TemplateArgumentLoc(TemplateArgument(E), E); 02036 } 02037 02038 case TemplateArgument::NullPtr: { 02039 Expr *E 02040 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) 02041 .getAs<Expr>(); 02042 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true), 02043 E); 02044 } 02045 02046 case TemplateArgument::Integral: { 02047 Expr *E 02048 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>(); 02049 return TemplateArgumentLoc(TemplateArgument(E), E); 02050 } 02051 02052 case TemplateArgument::Template: 02053 case TemplateArgument::TemplateExpansion: { 02054 NestedNameSpecifierLocBuilder Builder; 02055 TemplateName Template = Arg.getAsTemplate(); 02056 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) 02057 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc); 02058 else if (QualifiedTemplateName *QTN = 02059 Template.getAsQualifiedTemplateName()) 02060 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc); 02061 02062 if (Arg.getKind() == TemplateArgument::Template) 02063 return TemplateArgumentLoc(Arg, 02064 Builder.getWithLocInContext(S.Context), 02065 Loc); 02066 02067 02068 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context), 02069 Loc, Loc); 02070 } 02071 02072 case TemplateArgument::Expression: 02073 return TemplateArgumentLoc(Arg, Arg.getAsExpr()); 02074 02075 case TemplateArgument::Pack: 02076 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo()); 02077 } 02078 02079 llvm_unreachable("Invalid TemplateArgument Kind!"); 02080 } 02081 02082 02083 /// \brief Convert the given deduced template argument and add it to the set of 02084 /// fully-converted template arguments. 02085 static bool 02086 ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, 02087 DeducedTemplateArgument Arg, 02088 NamedDecl *Template, 02089 QualType NTTPType, 02090 unsigned ArgumentPackIndex, 02091 TemplateDeductionInfo &Info, 02092 bool InFunctionTemplate, 02093 SmallVectorImpl<TemplateArgument> &Output) { 02094 if (Arg.getKind() == TemplateArgument::Pack) { 02095 // This is a template argument pack, so check each of its arguments against 02096 // the template parameter. 02097 SmallVector<TemplateArgument, 2> PackedArgsBuilder; 02098 for (const auto &P : Arg.pack_elements()) { 02099 // When converting the deduced template argument, append it to the 02100 // general output list. We need to do this so that the template argument 02101 // checking logic has all of the prior template arguments available. 02102 DeducedTemplateArgument InnerArg(P); 02103 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound()); 02104 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template, 02105 NTTPType, PackedArgsBuilder.size(), 02106 Info, InFunctionTemplate, Output)) 02107 return true; 02108 02109 // Move the converted template argument into our argument pack. 02110 PackedArgsBuilder.push_back(Output.pop_back_val()); 02111 } 02112 02113 // Create the resulting argument pack. 02114 Output.push_back(TemplateArgument::CreatePackCopy(S.Context, 02115 PackedArgsBuilder.data(), 02116 PackedArgsBuilder.size())); 02117 return false; 02118 } 02119 02120 // Convert the deduced template argument into a template 02121 // argument that we can check, almost as if the user had written 02122 // the template argument explicitly. 02123 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType, 02124 Info.getLocation()); 02125 02126 // Check the template argument, converting it as necessary. 02127 return S.CheckTemplateArgument(Param, ArgLoc, 02128 Template, 02129 Template->getLocation(), 02130 Template->getSourceRange().getEnd(), 02131 ArgumentPackIndex, 02132 Output, 02133 InFunctionTemplate 02134 ? (Arg.wasDeducedFromArrayBound() 02135 ? Sema::CTAK_DeducedFromArrayBound 02136 : Sema::CTAK_Deduced) 02137 : Sema::CTAK_Specified); 02138 } 02139 02140 /// Complete template argument deduction for a class template partial 02141 /// specialization. 02142 static Sema::TemplateDeductionResult 02143 FinishTemplateArgumentDeduction(Sema &S, 02144 ClassTemplatePartialSpecializationDecl *Partial, 02145 const TemplateArgumentList &TemplateArgs, 02146 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 02147 TemplateDeductionInfo &Info) { 02148 // Unevaluated SFINAE context. 02149 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 02150 Sema::SFINAETrap Trap(S); 02151 02152 Sema::ContextRAII SavedContext(S, Partial); 02153 02154 // C++ [temp.deduct.type]p2: 02155 // [...] or if any template argument remains neither deduced nor 02156 // explicitly specified, template argument deduction fails. 02157 SmallVector<TemplateArgument, 4> Builder; 02158 TemplateParameterList *PartialParams = Partial->getTemplateParameters(); 02159 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) { 02160 NamedDecl *Param = PartialParams->getParam(I); 02161 if (Deduced[I].isNull()) { 02162 Info.Param = makeTemplateParameter(Param); 02163 return Sema::TDK_Incomplete; 02164 } 02165 02166 // We have deduced this argument, so it still needs to be 02167 // checked and converted. 02168 02169 // First, for a non-type template parameter type that is 02170 // initialized by a declaration, we need the type of the 02171 // corresponding non-type template parameter. 02172 QualType NTTPType; 02173 if (NonTypeTemplateParmDecl *NTTP 02174 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 02175 NTTPType = NTTP->getType(); 02176 if (NTTPType->isDependentType()) { 02177 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 02178 Builder.data(), Builder.size()); 02179 NTTPType = S.SubstType(NTTPType, 02180 MultiLevelTemplateArgumentList(TemplateArgs), 02181 NTTP->getLocation(), 02182 NTTP->getDeclName()); 02183 if (NTTPType.isNull()) { 02184 Info.Param = makeTemplateParameter(Param); 02185 // FIXME: These template arguments are temporary. Free them! 02186 Info.reset(TemplateArgumentList::CreateCopy(S.Context, 02187 Builder.data(), 02188 Builder.size())); 02189 return Sema::TDK_SubstitutionFailure; 02190 } 02191 } 02192 } 02193 02194 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], 02195 Partial, NTTPType, 0, Info, false, 02196 Builder)) { 02197 Info.Param = makeTemplateParameter(Param); 02198 // FIXME: These template arguments are temporary. Free them! 02199 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 02200 Builder.size())); 02201 return Sema::TDK_SubstitutionFailure; 02202 } 02203 } 02204 02205 // Form the template argument list from the deduced template arguments. 02206 TemplateArgumentList *DeducedArgumentList 02207 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 02208 Builder.size()); 02209 02210 Info.reset(DeducedArgumentList); 02211 02212 // Substitute the deduced template arguments into the template 02213 // arguments of the class template partial specialization, and 02214 // verify that the instantiated template arguments are both valid 02215 // and are equivalent to the template arguments originally provided 02216 // to the class template. 02217 LocalInstantiationScope InstScope(S); 02218 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate(); 02219 const ASTTemplateArgumentListInfo *PartialTemplArgInfo 02220 = Partial->getTemplateArgsAsWritten(); 02221 const TemplateArgumentLoc *PartialTemplateArgs 02222 = PartialTemplArgInfo->getTemplateArgs(); 02223 02224 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc, 02225 PartialTemplArgInfo->RAngleLoc); 02226 02227 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs, 02228 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) { 02229 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx; 02230 if (ParamIdx >= Partial->getTemplateParameters()->size()) 02231 ParamIdx = Partial->getTemplateParameters()->size() - 1; 02232 02233 Decl *Param 02234 = const_cast<NamedDecl *>( 02235 Partial->getTemplateParameters()->getParam(ParamIdx)); 02236 Info.Param = makeTemplateParameter(Param); 02237 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument(); 02238 return Sema::TDK_SubstitutionFailure; 02239 } 02240 02241 SmallVector<TemplateArgument, 4> ConvertedInstArgs; 02242 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(), 02243 InstArgs, false, ConvertedInstArgs)) 02244 return Sema::TDK_SubstitutionFailure; 02245 02246 TemplateParameterList *TemplateParams 02247 = ClassTemplate->getTemplateParameters(); 02248 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { 02249 TemplateArgument InstArg = ConvertedInstArgs.data()[I]; 02250 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) { 02251 Info.Param = makeTemplateParameter(TemplateParams->getParam(I)); 02252 Info.FirstArg = TemplateArgs[I]; 02253 Info.SecondArg = InstArg; 02254 return Sema::TDK_NonDeducedMismatch; 02255 } 02256 } 02257 02258 if (Trap.hasErrorOccurred()) 02259 return Sema::TDK_SubstitutionFailure; 02260 02261 return Sema::TDK_Success; 02262 } 02263 02264 /// \brief Perform template argument deduction to determine whether 02265 /// the given template arguments match the given class template 02266 /// partial specialization per C++ [temp.class.spec.match]. 02267 Sema::TemplateDeductionResult 02268 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 02269 const TemplateArgumentList &TemplateArgs, 02270 TemplateDeductionInfo &Info) { 02271 if (Partial->isInvalidDecl()) 02272 return TDK_Invalid; 02273 02274 // C++ [temp.class.spec.match]p2: 02275 // A partial specialization matches a given actual template 02276 // argument list if the template arguments of the partial 02277 // specialization can be deduced from the actual template argument 02278 // list (14.8.2). 02279 02280 // Unevaluated SFINAE context. 02281 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 02282 SFINAETrap Trap(*this); 02283 02284 SmallVector<DeducedTemplateArgument, 4> Deduced; 02285 Deduced.resize(Partial->getTemplateParameters()->size()); 02286 if (TemplateDeductionResult Result 02287 = ::DeduceTemplateArguments(*this, 02288 Partial->getTemplateParameters(), 02289 Partial->getTemplateArgs(), 02290 TemplateArgs, Info, Deduced)) 02291 return Result; 02292 02293 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 02294 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs, 02295 Info); 02296 if (Inst.isInvalid()) 02297 return TDK_InstantiationDepth; 02298 02299 if (Trap.hasErrorOccurred()) 02300 return Sema::TDK_SubstitutionFailure; 02301 02302 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs, 02303 Deduced, Info); 02304 } 02305 02306 /// Complete template argument deduction for a variable template partial 02307 /// specialization. 02308 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version? 02309 /// May require unifying ClassTemplate(Partial)SpecializationDecl and 02310 /// VarTemplate(Partial)SpecializationDecl with a new data 02311 /// structure Template(Partial)SpecializationDecl, and 02312 /// using Template(Partial)SpecializationDecl as input type. 02313 static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction( 02314 Sema &S, VarTemplatePartialSpecializationDecl *Partial, 02315 const TemplateArgumentList &TemplateArgs, 02316 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 02317 TemplateDeductionInfo &Info) { 02318 // Unevaluated SFINAE context. 02319 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 02320 Sema::SFINAETrap Trap(S); 02321 02322 // C++ [temp.deduct.type]p2: 02323 // [...] or if any template argument remains neither deduced nor 02324 // explicitly specified, template argument deduction fails. 02325 SmallVector<TemplateArgument, 4> Builder; 02326 TemplateParameterList *PartialParams = Partial->getTemplateParameters(); 02327 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) { 02328 NamedDecl *Param = PartialParams->getParam(I); 02329 if (Deduced[I].isNull()) { 02330 Info.Param = makeTemplateParameter(Param); 02331 return Sema::TDK_Incomplete; 02332 } 02333 02334 // We have deduced this argument, so it still needs to be 02335 // checked and converted. 02336 02337 // First, for a non-type template parameter type that is 02338 // initialized by a declaration, we need the type of the 02339 // corresponding non-type template parameter. 02340 QualType NTTPType; 02341 if (NonTypeTemplateParmDecl *NTTP = 02342 dyn_cast<NonTypeTemplateParmDecl>(Param)) { 02343 NTTPType = NTTP->getType(); 02344 if (NTTPType->isDependentType()) { 02345 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 02346 Builder.data(), Builder.size()); 02347 NTTPType = 02348 S.SubstType(NTTPType, MultiLevelTemplateArgumentList(TemplateArgs), 02349 NTTP->getLocation(), NTTP->getDeclName()); 02350 if (NTTPType.isNull()) { 02351 Info.Param = makeTemplateParameter(Param); 02352 // FIXME: These template arguments are temporary. Free them! 02353 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 02354 Builder.size())); 02355 return Sema::TDK_SubstitutionFailure; 02356 } 02357 } 02358 } 02359 02360 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial, NTTPType, 02361 0, Info, false, Builder)) { 02362 Info.Param = makeTemplateParameter(Param); 02363 // FIXME: These template arguments are temporary. Free them! 02364 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 02365 Builder.size())); 02366 return Sema::TDK_SubstitutionFailure; 02367 } 02368 } 02369 02370 // Form the template argument list from the deduced template arguments. 02371 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy( 02372 S.Context, Builder.data(), Builder.size()); 02373 02374 Info.reset(DeducedArgumentList); 02375 02376 // Substitute the deduced template arguments into the template 02377 // arguments of the class template partial specialization, and 02378 // verify that the instantiated template arguments are both valid 02379 // and are equivalent to the template arguments originally provided 02380 // to the class template. 02381 LocalInstantiationScope InstScope(S); 02382 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate(); 02383 const ASTTemplateArgumentListInfo *PartialTemplArgInfo 02384 = Partial->getTemplateArgsAsWritten(); 02385 const TemplateArgumentLoc *PartialTemplateArgs 02386 = PartialTemplArgInfo->getTemplateArgs(); 02387 02388 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc, 02389 PartialTemplArgInfo->RAngleLoc); 02390 02391 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs, 02392 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) { 02393 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx; 02394 if (ParamIdx >= Partial->getTemplateParameters()->size()) 02395 ParamIdx = Partial->getTemplateParameters()->size() - 1; 02396 02397 Decl *Param = const_cast<NamedDecl *>( 02398 Partial->getTemplateParameters()->getParam(ParamIdx)); 02399 Info.Param = makeTemplateParameter(Param); 02400 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument(); 02401 return Sema::TDK_SubstitutionFailure; 02402 } 02403 SmallVector<TemplateArgument, 4> ConvertedInstArgs; 02404 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs, 02405 false, ConvertedInstArgs)) 02406 return Sema::TDK_SubstitutionFailure; 02407 02408 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters(); 02409 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { 02410 TemplateArgument InstArg = ConvertedInstArgs.data()[I]; 02411 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) { 02412 Info.Param = makeTemplateParameter(TemplateParams->getParam(I)); 02413 Info.FirstArg = TemplateArgs[I]; 02414 Info.SecondArg = InstArg; 02415 return Sema::TDK_NonDeducedMismatch; 02416 } 02417 } 02418 02419 if (Trap.hasErrorOccurred()) 02420 return Sema::TDK_SubstitutionFailure; 02421 02422 return Sema::TDK_Success; 02423 } 02424 02425 /// \brief Perform template argument deduction to determine whether 02426 /// the given template arguments match the given variable template 02427 /// partial specialization per C++ [temp.class.spec.match]. 02428 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version? 02429 /// May require unifying ClassTemplate(Partial)SpecializationDecl and 02430 /// VarTemplate(Partial)SpecializationDecl with a new data 02431 /// structure Template(Partial)SpecializationDecl, and 02432 /// using Template(Partial)SpecializationDecl as input type. 02433 Sema::TemplateDeductionResult 02434 Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 02435 const TemplateArgumentList &TemplateArgs, 02436 TemplateDeductionInfo &Info) { 02437 if (Partial->isInvalidDecl()) 02438 return TDK_Invalid; 02439 02440 // C++ [temp.class.spec.match]p2: 02441 // A partial specialization matches a given actual template 02442 // argument list if the template arguments of the partial 02443 // specialization can be deduced from the actual template argument 02444 // list (14.8.2). 02445 02446 // Unevaluated SFINAE context. 02447 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 02448 SFINAETrap Trap(*this); 02449 02450 SmallVector<DeducedTemplateArgument, 4> Deduced; 02451 Deduced.resize(Partial->getTemplateParameters()->size()); 02452 if (TemplateDeductionResult Result = ::DeduceTemplateArguments( 02453 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(), 02454 TemplateArgs, Info, Deduced)) 02455 return Result; 02456 02457 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 02458 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs, 02459 Info); 02460 if (Inst.isInvalid()) 02461 return TDK_InstantiationDepth; 02462 02463 if (Trap.hasErrorOccurred()) 02464 return Sema::TDK_SubstitutionFailure; 02465 02466 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs, 02467 Deduced, Info); 02468 } 02469 02470 /// \brief Determine whether the given type T is a simple-template-id type. 02471 static bool isSimpleTemplateIdType(QualType T) { 02472 if (const TemplateSpecializationType *Spec 02473 = T->getAs<TemplateSpecializationType>()) 02474 return Spec->getTemplateName().getAsTemplateDecl() != nullptr; 02475 02476 return false; 02477 } 02478 02479 /// \brief Substitute the explicitly-provided template arguments into the 02480 /// given function template according to C++ [temp.arg.explicit]. 02481 /// 02482 /// \param FunctionTemplate the function template into which the explicit 02483 /// template arguments will be substituted. 02484 /// 02485 /// \param ExplicitTemplateArgs the explicitly-specified template 02486 /// arguments. 02487 /// 02488 /// \param Deduced the deduced template arguments, which will be populated 02489 /// with the converted and checked explicit template arguments. 02490 /// 02491 /// \param ParamTypes will be populated with the instantiated function 02492 /// parameters. 02493 /// 02494 /// \param FunctionType if non-NULL, the result type of the function template 02495 /// will also be instantiated and the pointed-to value will be updated with 02496 /// the instantiated function type. 02497 /// 02498 /// \param Info if substitution fails for any reason, this object will be 02499 /// populated with more information about the failure. 02500 /// 02501 /// \returns TDK_Success if substitution was successful, or some failure 02502 /// condition. 02503 Sema::TemplateDeductionResult 02504 Sema::SubstituteExplicitTemplateArguments( 02505 FunctionTemplateDecl *FunctionTemplate, 02506 TemplateArgumentListInfo &ExplicitTemplateArgs, 02507 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 02508 SmallVectorImpl<QualType> &ParamTypes, 02509 QualType *FunctionType, 02510 TemplateDeductionInfo &Info) { 02511 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 02512 TemplateParameterList *TemplateParams 02513 = FunctionTemplate->getTemplateParameters(); 02514 02515 if (ExplicitTemplateArgs.size() == 0) { 02516 // No arguments to substitute; just copy over the parameter types and 02517 // fill in the function type. 02518 for (auto P : Function->params()) 02519 ParamTypes.push_back(P->getType()); 02520 02521 if (FunctionType) 02522 *FunctionType = Function->getType(); 02523 return TDK_Success; 02524 } 02525 02526 // Unevaluated SFINAE context. 02527 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 02528 SFINAETrap Trap(*this); 02529 02530 // C++ [temp.arg.explicit]p3: 02531 // Template arguments that are present shall be specified in the 02532 // declaration order of their corresponding template-parameters. The 02533 // template argument list shall not specify more template-arguments than 02534 // there are corresponding template-parameters. 02535 SmallVector<TemplateArgument, 4> Builder; 02536 02537 // Enter a new template instantiation context where we check the 02538 // explicitly-specified template arguments against this function template, 02539 // and then substitute them into the function parameter types. 02540 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 02541 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate, 02542 DeducedArgs, 02543 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution, 02544 Info); 02545 if (Inst.isInvalid()) 02546 return TDK_InstantiationDepth; 02547 02548 if (CheckTemplateArgumentList(FunctionTemplate, 02549 SourceLocation(), 02550 ExplicitTemplateArgs, 02551 true, 02552 Builder) || Trap.hasErrorOccurred()) { 02553 unsigned Index = Builder.size(); 02554 if (Index >= TemplateParams->size()) 02555 Index = TemplateParams->size() - 1; 02556 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index)); 02557 return TDK_InvalidExplicitArguments; 02558 } 02559 02560 // Form the template argument list from the explicitly-specified 02561 // template arguments. 02562 TemplateArgumentList *ExplicitArgumentList 02563 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size()); 02564 Info.reset(ExplicitArgumentList); 02565 02566 // Template argument deduction and the final substitution should be 02567 // done in the context of the templated declaration. Explicit 02568 // argument substitution, on the other hand, needs to happen in the 02569 // calling context. 02570 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 02571 02572 // If we deduced template arguments for a template parameter pack, 02573 // note that the template argument pack is partially substituted and record 02574 // the explicit template arguments. They'll be used as part of deduction 02575 // for this template parameter pack. 02576 for (unsigned I = 0, N = Builder.size(); I != N; ++I) { 02577 const TemplateArgument &Arg = Builder[I]; 02578 if (Arg.getKind() == TemplateArgument::Pack) { 02579 CurrentInstantiationScope->SetPartiallySubstitutedPack( 02580 TemplateParams->getParam(I), 02581 Arg.pack_begin(), 02582 Arg.pack_size()); 02583 break; 02584 } 02585 } 02586 02587 const FunctionProtoType *Proto 02588 = Function->getType()->getAs<FunctionProtoType>(); 02589 assert(Proto && "Function template does not have a prototype?"); 02590 02591 // Instantiate the types of each of the function parameters given the 02592 // explicitly-specified template arguments. If the function has a trailing 02593 // return type, substitute it after the arguments to ensure we substitute 02594 // in lexical order. 02595 if (Proto->hasTrailingReturn()) { 02596 if (SubstParmTypes(Function->getLocation(), 02597 Function->param_begin(), Function->getNumParams(), 02598 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 02599 ParamTypes)) 02600 return TDK_SubstitutionFailure; 02601 } 02602 02603 // Instantiate the return type. 02604 QualType ResultType; 02605 { 02606 // C++11 [expr.prim.general]p3: 02607 // If a declaration declares a member function or member function 02608 // template of a class X, the expression this is a prvalue of type 02609 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 02610 // and the end of the function-definition, member-declarator, or 02611 // declarator. 02612 unsigned ThisTypeQuals = 0; 02613 CXXRecordDecl *ThisContext = nullptr; 02614 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 02615 ThisContext = Method->getParent(); 02616 ThisTypeQuals = Method->getTypeQualifiers(); 02617 } 02618 02619 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals, 02620 getLangOpts().CPlusPlus11); 02621 02622 ResultType = 02623 SubstType(Proto->getReturnType(), 02624 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 02625 Function->getTypeSpecStartLoc(), Function->getDeclName()); 02626 if (ResultType.isNull() || Trap.hasErrorOccurred()) 02627 return TDK_SubstitutionFailure; 02628 } 02629 02630 // Instantiate the types of each of the function parameters given the 02631 // explicitly-specified template arguments if we didn't do so earlier. 02632 if (!Proto->hasTrailingReturn() && 02633 SubstParmTypes(Function->getLocation(), 02634 Function->param_begin(), Function->getNumParams(), 02635 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 02636 ParamTypes)) 02637 return TDK_SubstitutionFailure; 02638 02639 if (FunctionType) { 02640 *FunctionType = BuildFunctionType(ResultType, ParamTypes, 02641 Function->getLocation(), 02642 Function->getDeclName(), 02643 Proto->getExtProtoInfo()); 02644 if (FunctionType->isNull() || Trap.hasErrorOccurred()) 02645 return TDK_SubstitutionFailure; 02646 } 02647 02648 // C++ [temp.arg.explicit]p2: 02649 // Trailing template arguments that can be deduced (14.8.2) may be 02650 // omitted from the list of explicit template-arguments. If all of the 02651 // template arguments can be deduced, they may all be omitted; in this 02652 // case, the empty template argument list <> itself may also be omitted. 02653 // 02654 // Take all of the explicitly-specified arguments and put them into 02655 // the set of deduced template arguments. Explicitly-specified 02656 // parameter packs, however, will be set to NULL since the deduction 02657 // mechanisms handle explicitly-specified argument packs directly. 02658 Deduced.reserve(TemplateParams->size()); 02659 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) { 02660 const TemplateArgument &Arg = ExplicitArgumentList->get(I); 02661 if (Arg.getKind() == TemplateArgument::Pack) 02662 Deduced.push_back(DeducedTemplateArgument()); 02663 else 02664 Deduced.push_back(Arg); 02665 } 02666 02667 return TDK_Success; 02668 } 02669 02670 /// \brief Check whether the deduced argument type for a call to a function 02671 /// template matches the actual argument type per C++ [temp.deduct.call]p4. 02672 static bool 02673 CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg, 02674 QualType DeducedA) { 02675 ASTContext &Context = S.Context; 02676 02677 QualType A = OriginalArg.OriginalArgType; 02678 QualType OriginalParamType = OriginalArg.OriginalParamType; 02679 02680 // Check for type equality (top-level cv-qualifiers are ignored). 02681 if (Context.hasSameUnqualifiedType(A, DeducedA)) 02682 return false; 02683 02684 // Strip off references on the argument types; they aren't needed for 02685 // the following checks. 02686 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>()) 02687 DeducedA = DeducedARef->getPointeeType(); 02688 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) 02689 A = ARef->getPointeeType(); 02690 02691 // C++ [temp.deduct.call]p4: 02692 // [...] However, there are three cases that allow a difference: 02693 // - If the original P is a reference type, the deduced A (i.e., the 02694 // type referred to by the reference) can be more cv-qualified than 02695 // the transformed A. 02696 if (const ReferenceType *OriginalParamRef 02697 = OriginalParamType->getAs<ReferenceType>()) { 02698 // We don't want to keep the reference around any more. 02699 OriginalParamType = OriginalParamRef->getPointeeType(); 02700 02701 Qualifiers AQuals = A.getQualifiers(); 02702 Qualifiers DeducedAQuals = DeducedA.getQualifiers(); 02703 02704 // Under Objective-C++ ARC, the deduced type may have implicitly 02705 // been given strong or (when dealing with a const reference) 02706 // unsafe_unretained lifetime. If so, update the original 02707 // qualifiers to include this lifetime. 02708 if (S.getLangOpts().ObjCAutoRefCount && 02709 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong && 02710 AQuals.getObjCLifetime() == Qualifiers::OCL_None) || 02711 (DeducedAQuals.hasConst() && 02712 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) { 02713 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime()); 02714 } 02715 02716 if (AQuals == DeducedAQuals) { 02717 // Qualifiers match; there's nothing to do. 02718 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) { 02719 return true; 02720 } else { 02721 // Qualifiers are compatible, so have the argument type adopt the 02722 // deduced argument type's qualifiers as if we had performed the 02723 // qualification conversion. 02724 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals); 02725 } 02726 } 02727 02728 // - The transformed A can be another pointer or pointer to member 02729 // type that can be converted to the deduced A via a qualification 02730 // conversion. 02731 // 02732 // Also allow conversions which merely strip [[noreturn]] from function types 02733 // (recursively) as an extension. 02734 // FIXME: Currently, this doesn't play nicely with qualification conversions. 02735 bool ObjCLifetimeConversion = false; 02736 QualType ResultTy; 02737 if ((A->isAnyPointerType() || A->isMemberPointerType()) && 02738 (S.IsQualificationConversion(A, DeducedA, false, 02739 ObjCLifetimeConversion) || 02740 S.IsNoReturnConversion(A, DeducedA, ResultTy))) 02741 return false; 02742 02743 02744 // - If P is a class and P has the form simple-template-id, then the 02745 // transformed A can be a derived class of the deduced A. [...] 02746 // [...] Likewise, if P is a pointer to a class of the form 02747 // simple-template-id, the transformed A can be a pointer to a 02748 // derived class pointed to by the deduced A. 02749 if (const PointerType *OriginalParamPtr 02750 = OriginalParamType->getAs<PointerType>()) { 02751 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) { 02752 if (const PointerType *APtr = A->getAs<PointerType>()) { 02753 if (A->getPointeeType()->isRecordType()) { 02754 OriginalParamType = OriginalParamPtr->getPointeeType(); 02755 DeducedA = DeducedAPtr->getPointeeType(); 02756 A = APtr->getPointeeType(); 02757 } 02758 } 02759 } 02760 } 02761 02762 if (Context.hasSameUnqualifiedType(A, DeducedA)) 02763 return false; 02764 02765 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) && 02766 S.IsDerivedFrom(A, DeducedA)) 02767 return false; 02768 02769 return true; 02770 } 02771 02772 /// \brief Finish template argument deduction for a function template, 02773 /// checking the deduced template arguments for completeness and forming 02774 /// the function template specialization. 02775 /// 02776 /// \param OriginalCallArgs If non-NULL, the original call arguments against 02777 /// which the deduced argument types should be compared. 02778 Sema::TemplateDeductionResult 02779 Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 02780 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 02781 unsigned NumExplicitlySpecified, 02782 FunctionDecl *&Specialization, 02783 TemplateDeductionInfo &Info, 02784 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs) { 02785 TemplateParameterList *TemplateParams 02786 = FunctionTemplate->getTemplateParameters(); 02787 02788 // Unevaluated SFINAE context. 02789 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 02790 SFINAETrap Trap(*this); 02791 02792 // Enter a new template instantiation context while we instantiate the 02793 // actual function declaration. 02794 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 02795 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate, 02796 DeducedArgs, 02797 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution, 02798 Info); 02799 if (Inst.isInvalid()) 02800 return TDK_InstantiationDepth; 02801 02802 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 02803 02804 // C++ [temp.deduct.type]p2: 02805 // [...] or if any template argument remains neither deduced nor 02806 // explicitly specified, template argument deduction fails. 02807 SmallVector<TemplateArgument, 4> Builder; 02808 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 02809 NamedDecl *Param = TemplateParams->getParam(I); 02810 02811 if (!Deduced[I].isNull()) { 02812 if (I < NumExplicitlySpecified) { 02813 // We have already fully type-checked and converted this 02814 // argument, because it was explicitly-specified. Just record the 02815 // presence of this argument. 02816 Builder.push_back(Deduced[I]); 02817 // We may have had explicitly-specified template arguments for a 02818 // template parameter pack (that may or may not have been extended 02819 // via additional deduced arguments). 02820 if (Param->isParameterPack() && CurrentInstantiationScope) { 02821 if (CurrentInstantiationScope->getPartiallySubstitutedPack() == 02822 Param) { 02823 // Forget the partially-substituted pack; its substitution is now 02824 // complete. 02825 CurrentInstantiationScope->ResetPartiallySubstitutedPack(); 02826 } 02827 } 02828 continue; 02829 } 02830 // We have deduced this argument, so it still needs to be 02831 // checked and converted. 02832 02833 // First, for a non-type template parameter type that is 02834 // initialized by a declaration, we need the type of the 02835 // corresponding non-type template parameter. 02836 QualType NTTPType; 02837 if (NonTypeTemplateParmDecl *NTTP 02838 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 02839 NTTPType = NTTP->getType(); 02840 if (NTTPType->isDependentType()) { 02841 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 02842 Builder.data(), Builder.size()); 02843 NTTPType = SubstType(NTTPType, 02844 MultiLevelTemplateArgumentList(TemplateArgs), 02845 NTTP->getLocation(), 02846 NTTP->getDeclName()); 02847 if (NTTPType.isNull()) { 02848 Info.Param = makeTemplateParameter(Param); 02849 // FIXME: These template arguments are temporary. Free them! 02850 Info.reset(TemplateArgumentList::CreateCopy(Context, 02851 Builder.data(), 02852 Builder.size())); 02853 return TDK_SubstitutionFailure; 02854 } 02855 } 02856 } 02857 02858 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I], 02859 FunctionTemplate, NTTPType, 0, Info, 02860 true, Builder)) { 02861 Info.Param = makeTemplateParameter(Param); 02862 // FIXME: These template arguments are temporary. Free them! 02863 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(), 02864 Builder.size())); 02865 return TDK_SubstitutionFailure; 02866 } 02867 02868 continue; 02869 } 02870 02871 // C++0x [temp.arg.explicit]p3: 02872 // A trailing template parameter pack (14.5.3) not otherwise deduced will 02873 // be deduced to an empty sequence of template arguments. 02874 // FIXME: Where did the word "trailing" come from? 02875 if (Param->isTemplateParameterPack()) { 02876 // We may have had explicitly-specified template arguments for this 02877 // template parameter pack. If so, our empty deduction extends the 02878 // explicitly-specified set (C++0x [temp.arg.explicit]p9). 02879 const TemplateArgument *ExplicitArgs; 02880 unsigned NumExplicitArgs; 02881 if (CurrentInstantiationScope && 02882 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs, 02883 &NumExplicitArgs) 02884 == Param) { 02885 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs)); 02886 02887 // Forget the partially-substituted pack; it's substitution is now 02888 // complete. 02889 CurrentInstantiationScope->ResetPartiallySubstitutedPack(); 02890 } else { 02891 Builder.push_back(TemplateArgument::getEmptyPack()); 02892 } 02893 continue; 02894 } 02895 02896 // Substitute into the default template argument, if available. 02897 bool HasDefaultArg = false; 02898 TemplateArgumentLoc DefArg 02899 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate, 02900 FunctionTemplate->getLocation(), 02901 FunctionTemplate->getSourceRange().getEnd(), 02902 Param, 02903 Builder, HasDefaultArg); 02904 02905 // If there was no default argument, deduction is incomplete. 02906 if (DefArg.getArgument().isNull()) { 02907 Info.Param = makeTemplateParameter( 02908 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 02909 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(), 02910 Builder.size())); 02911 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete; 02912 } 02913 02914 // Check whether we can actually use the default argument. 02915 if (CheckTemplateArgument(Param, DefArg, 02916 FunctionTemplate, 02917 FunctionTemplate->getLocation(), 02918 FunctionTemplate->getSourceRange().getEnd(), 02919 0, Builder, 02920 CTAK_Specified)) { 02921 Info.Param = makeTemplateParameter( 02922 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 02923 // FIXME: These template arguments are temporary. Free them! 02924 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(), 02925 Builder.size())); 02926 return TDK_SubstitutionFailure; 02927 } 02928 02929 // If we get here, we successfully used the default template argument. 02930 } 02931 02932 // Form the template argument list from the deduced template arguments. 02933 TemplateArgumentList *DeducedArgumentList 02934 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size()); 02935 Info.reset(DeducedArgumentList); 02936 02937 // Substitute the deduced template arguments into the function template 02938 // declaration to produce the function template specialization. 02939 DeclContext *Owner = FunctionTemplate->getDeclContext(); 02940 if (FunctionTemplate->getFriendObjectKind()) 02941 Owner = FunctionTemplate->getLexicalDeclContext(); 02942 Specialization = cast_or_null<FunctionDecl>( 02943 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, 02944 MultiLevelTemplateArgumentList(*DeducedArgumentList))); 02945 if (!Specialization || Specialization->isInvalidDecl()) 02946 return TDK_SubstitutionFailure; 02947 02948 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() == 02949 FunctionTemplate->getCanonicalDecl()); 02950 02951 // If the template argument list is owned by the function template 02952 // specialization, release it. 02953 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList && 02954 !Trap.hasErrorOccurred()) 02955 Info.take(); 02956 02957 // There may have been an error that did not prevent us from constructing a 02958 // declaration. Mark the declaration invalid and return with a substitution 02959 // failure. 02960 if (Trap.hasErrorOccurred()) { 02961 Specialization->setInvalidDecl(true); 02962 return TDK_SubstitutionFailure; 02963 } 02964 02965 if (OriginalCallArgs) { 02966 // C++ [temp.deduct.call]p4: 02967 // In general, the deduction process attempts to find template argument 02968 // values that will make the deduced A identical to A (after the type A 02969 // is transformed as described above). [...] 02970 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) { 02971 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I]; 02972 unsigned ParamIdx = OriginalArg.ArgIdx; 02973 02974 if (ParamIdx >= Specialization->getNumParams()) 02975 continue; 02976 02977 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType(); 02978 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) 02979 return Sema::TDK_SubstitutionFailure; 02980 } 02981 } 02982 02983 // If we suppressed any diagnostics while performing template argument 02984 // deduction, and if we haven't already instantiated this declaration, 02985 // keep track of these diagnostics. They'll be emitted if this specialization 02986 // is actually used. 02987 if (Info.diag_begin() != Info.diag_end()) { 02988 SuppressedDiagnosticsMap::iterator 02989 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl()); 02990 if (Pos == SuppressedDiagnostics.end()) 02991 SuppressedDiagnostics[Specialization->getCanonicalDecl()] 02992 .append(Info.diag_begin(), Info.diag_end()); 02993 } 02994 02995 return TDK_Success; 02996 } 02997 02998 /// Gets the type of a function for template-argument-deducton 02999 /// purposes when it's considered as part of an overload set. 03000 static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, 03001 FunctionDecl *Fn) { 03002 // We may need to deduce the return type of the function now. 03003 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() && 03004 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false)) 03005 return QualType(); 03006 03007 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 03008 if (Method->isInstance()) { 03009 // An instance method that's referenced in a form that doesn't 03010 // look like a member pointer is just invalid. 03011 if (!R.HasFormOfMemberPointer) return QualType(); 03012 03013 return S.Context.getMemberPointerType(Fn->getType(), 03014 S.Context.getTypeDeclType(Method->getParent()).getTypePtr()); 03015 } 03016 03017 if (!R.IsAddressOfOperand) return Fn->getType(); 03018 return S.Context.getPointerType(Fn->getType()); 03019 } 03020 03021 /// Apply the deduction rules for overload sets. 03022 /// 03023 /// \return the null type if this argument should be treated as an 03024 /// undeduced context 03025 static QualType 03026 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, 03027 Expr *Arg, QualType ParamType, 03028 bool ParamWasReference) { 03029 03030 OverloadExpr::FindResult R = OverloadExpr::find(Arg); 03031 03032 OverloadExpr *Ovl = R.Expression; 03033 03034 // C++0x [temp.deduct.call]p4 03035 unsigned TDF = 0; 03036 if (ParamWasReference) 03037 TDF |= TDF_ParamWithReferenceType; 03038 if (R.IsAddressOfOperand) 03039 TDF |= TDF_IgnoreQualifiers; 03040 03041 // C++0x [temp.deduct.call]p6: 03042 // When P is a function type, pointer to function type, or pointer 03043 // to member function type: 03044 03045 if (!ParamType->isFunctionType() && 03046 !ParamType->isFunctionPointerType() && 03047 !ParamType->isMemberFunctionPointerType()) { 03048 if (Ovl->hasExplicitTemplateArgs()) { 03049 // But we can still look for an explicit specialization. 03050 if (FunctionDecl *ExplicitSpec 03051 = S.ResolveSingleFunctionTemplateSpecialization(Ovl)) 03052 return GetTypeOfFunction(S, R, ExplicitSpec); 03053 } 03054 03055 return QualType(); 03056 } 03057 03058 // Gather the explicit template arguments, if any. 03059 TemplateArgumentListInfo ExplicitTemplateArgs; 03060 if (Ovl->hasExplicitTemplateArgs()) 03061 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 03062 QualType Match; 03063 for (UnresolvedSetIterator I = Ovl->decls_begin(), 03064 E = Ovl->decls_end(); I != E; ++I) { 03065 NamedDecl *D = (*I)->getUnderlyingDecl(); 03066 03067 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) { 03068 // - If the argument is an overload set containing one or more 03069 // function templates, the parameter is treated as a 03070 // non-deduced context. 03071 if (!Ovl->hasExplicitTemplateArgs()) 03072 return QualType(); 03073 03074 // Otherwise, see if we can resolve a function type 03075 FunctionDecl *Specialization = nullptr; 03076 TemplateDeductionInfo Info(Ovl->getNameLoc()); 03077 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs, 03078 Specialization, Info)) 03079 continue; 03080 03081 D = Specialization; 03082 } 03083 03084 FunctionDecl *Fn = cast<FunctionDecl>(D); 03085 QualType ArgType = GetTypeOfFunction(S, R, Fn); 03086 if (ArgType.isNull()) continue; 03087 03088 // Function-to-pointer conversion. 03089 if (!ParamWasReference && ParamType->isPointerType() && 03090 ArgType->isFunctionType()) 03091 ArgType = S.Context.getPointerType(ArgType); 03092 03093 // - If the argument is an overload set (not containing function 03094 // templates), trial argument deduction is attempted using each 03095 // of the members of the set. If deduction succeeds for only one 03096 // of the overload set members, that member is used as the 03097 // argument value for the deduction. If deduction succeeds for 03098 // more than one member of the overload set the parameter is 03099 // treated as a non-deduced context. 03100 03101 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2: 03102 // Type deduction is done independently for each P/A pair, and 03103 // the deduced template argument values are then combined. 03104 // So we do not reject deductions which were made elsewhere. 03105 SmallVector<DeducedTemplateArgument, 8> 03106 Deduced(TemplateParams->size()); 03107 TemplateDeductionInfo Info(Ovl->getNameLoc()); 03108 Sema::TemplateDeductionResult Result 03109 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 03110 ArgType, Info, Deduced, TDF); 03111 if (Result) continue; 03112 if (!Match.isNull()) return QualType(); 03113 Match = ArgType; 03114 } 03115 03116 return Match; 03117 } 03118 03119 /// \brief Perform the adjustments to the parameter and argument types 03120 /// described in C++ [temp.deduct.call]. 03121 /// 03122 /// \returns true if the caller should not attempt to perform any template 03123 /// argument deduction based on this P/A pair because the argument is an 03124 /// overloaded function set that could not be resolved. 03125 static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S, 03126 TemplateParameterList *TemplateParams, 03127 QualType &ParamType, 03128 QualType &ArgType, 03129 Expr *Arg, 03130 unsigned &TDF) { 03131 // C++0x [temp.deduct.call]p3: 03132 // If P is a cv-qualified type, the top level cv-qualifiers of P's type 03133 // are ignored for type deduction. 03134 if (ParamType.hasQualifiers()) 03135 ParamType = ParamType.getUnqualifiedType(); 03136 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>(); 03137 if (ParamRefType) { 03138 QualType PointeeType = ParamRefType->getPointeeType(); 03139 03140 // If the argument has incomplete array type, try to complete its type. 03141 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0)) 03142 ArgType = Arg->getType(); 03143 03144 // [C++0x] If P is an rvalue reference to a cv-unqualified 03145 // template parameter and the argument is an lvalue, the type 03146 // "lvalue reference to A" is used in place of A for type 03147 // deduction. 03148 if (isa<RValueReferenceType>(ParamType)) { 03149 if (!PointeeType.getQualifiers() && 03150 isa<TemplateTypeParmType>(PointeeType) && 03151 Arg->Classify(S.Context).isLValue() && 03152 Arg->getType() != S.Context.OverloadTy && 03153 Arg->getType() != S.Context.BoundMemberTy) 03154 ArgType = S.Context.getLValueReferenceType(ArgType); 03155 } 03156 03157 // [...] If P is a reference type, the type referred to by P is used 03158 // for type deduction. 03159 ParamType = PointeeType; 03160 } 03161 03162 // Overload sets usually make this parameter an undeduced 03163 // context, but there are sometimes special circumstances. 03164 if (ArgType == S.Context.OverloadTy) { 03165 ArgType = ResolveOverloadForDeduction(S, TemplateParams, 03166 Arg, ParamType, 03167 ParamRefType != nullptr); 03168 if (ArgType.isNull()) 03169 return true; 03170 } 03171 03172 if (ParamRefType) { 03173 // C++0x [temp.deduct.call]p3: 03174 // [...] If P is of the form T&&, where T is a template parameter, and 03175 // the argument is an lvalue, the type A& is used in place of A for 03176 // type deduction. 03177 if (ParamRefType->isRValueReferenceType() && 03178 ParamRefType->getAs<TemplateTypeParmType>() && 03179 Arg->isLValue()) 03180 ArgType = S.Context.getLValueReferenceType(ArgType); 03181 } else { 03182 // C++ [temp.deduct.call]p2: 03183 // If P is not a reference type: 03184 // - If A is an array type, the pointer type produced by the 03185 // array-to-pointer standard conversion (4.2) is used in place of 03186 // A for type deduction; otherwise, 03187 if (ArgType->isArrayType()) 03188 ArgType = S.Context.getArrayDecayedType(ArgType); 03189 // - If A is a function type, the pointer type produced by the 03190 // function-to-pointer standard conversion (4.3) is used in place 03191 // of A for type deduction; otherwise, 03192 else if (ArgType->isFunctionType()) 03193 ArgType = S.Context.getPointerType(ArgType); 03194 else { 03195 // - If A is a cv-qualified type, the top level cv-qualifiers of A's 03196 // type are ignored for type deduction. 03197 ArgType = ArgType.getUnqualifiedType(); 03198 } 03199 } 03200 03201 // C++0x [temp.deduct.call]p4: 03202 // In general, the deduction process attempts to find template argument 03203 // values that will make the deduced A identical to A (after the type A 03204 // is transformed as described above). [...] 03205 TDF = TDF_SkipNonDependent; 03206 03207 // - If the original P is a reference type, the deduced A (i.e., the 03208 // type referred to by the reference) can be more cv-qualified than 03209 // the transformed A. 03210 if (ParamRefType) 03211 TDF |= TDF_ParamWithReferenceType; 03212 // - The transformed A can be another pointer or pointer to member 03213 // type that can be converted to the deduced A via a qualification 03214 // conversion (4.4). 03215 if (ArgType->isPointerType() || ArgType->isMemberPointerType() || 03216 ArgType->isObjCObjectPointerType()) 03217 TDF |= TDF_IgnoreQualifiers; 03218 // - If P is a class and P has the form simple-template-id, then the 03219 // transformed A can be a derived class of the deduced A. Likewise, 03220 // if P is a pointer to a class of the form simple-template-id, the 03221 // transformed A can be a pointer to a derived class pointed to by 03222 // the deduced A. 03223 if (isSimpleTemplateIdType(ParamType) || 03224 (isa<PointerType>(ParamType) && 03225 isSimpleTemplateIdType( 03226 ParamType->getAs<PointerType>()->getPointeeType()))) 03227 TDF |= TDF_DerivedClass; 03228 03229 return false; 03230 } 03231 03232 static bool 03233 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate, 03234 QualType T); 03235 03236 /// \brief Perform template argument deduction by matching a parameter type 03237 /// against a single expression, where the expression is an element of 03238 /// an initializer list that was originally matched against a parameter 03239 /// of type \c initializer_list<ParamType>. 03240 static Sema::TemplateDeductionResult 03241 DeduceTemplateArgumentByListElement(Sema &S, 03242 TemplateParameterList *TemplateParams, 03243 QualType ParamType, Expr *Arg, 03244 TemplateDeductionInfo &Info, 03245 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 03246 unsigned TDF) { 03247 // Handle the case where an init list contains another init list as the 03248 // element. 03249 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 03250 QualType X; 03251 if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X)) 03252 return Sema::TDK_Success; // Just ignore this expression. 03253 03254 // Recurse down into the init list. 03255 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 03256 if (Sema::TemplateDeductionResult Result = 03257 DeduceTemplateArgumentByListElement(S, TemplateParams, X, 03258 ILE->getInit(i), 03259 Info, Deduced, TDF)) 03260 return Result; 03261 } 03262 return Sema::TDK_Success; 03263 } 03264 03265 // For all other cases, just match by type. 03266 QualType ArgType = Arg->getType(); 03267 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType, 03268 ArgType, Arg, TDF)) { 03269 Info.Expression = Arg; 03270 return Sema::TDK_FailedOverloadResolution; 03271 } 03272 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 03273 ArgType, Info, Deduced, TDF); 03274 } 03275 03276 /// \brief Perform template argument deduction from a function call 03277 /// (C++ [temp.deduct.call]). 03278 /// 03279 /// \param FunctionTemplate the function template for which we are performing 03280 /// template argument deduction. 03281 /// 03282 /// \param ExplicitTemplateArgs the explicit template arguments provided 03283 /// for this call. 03284 /// 03285 /// \param Args the function call arguments 03286 /// 03287 /// \param Specialization if template argument deduction was successful, 03288 /// this will be set to the function template specialization produced by 03289 /// template argument deduction. 03290 /// 03291 /// \param Info the argument will be updated to provide additional information 03292 /// about template argument deduction. 03293 /// 03294 /// \returns the result of template argument deduction. 03295 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments( 03296 FunctionTemplateDecl *FunctionTemplate, 03297 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 03298 FunctionDecl *&Specialization, TemplateDeductionInfo &Info) { 03299 if (FunctionTemplate->isInvalidDecl()) 03300 return TDK_Invalid; 03301 03302 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 03303 03304 // C++ [temp.deduct.call]p1: 03305 // Template argument deduction is done by comparing each function template 03306 // parameter type (call it P) with the type of the corresponding argument 03307 // of the call (call it A) as described below. 03308 unsigned CheckArgs = Args.size(); 03309 if (Args.size() < Function->getMinRequiredArguments()) 03310 return TDK_TooFewArguments; 03311 else if (Args.size() > Function->getNumParams()) { 03312 const FunctionProtoType *Proto 03313 = Function->getType()->getAs<FunctionProtoType>(); 03314 if (Proto->isTemplateVariadic()) 03315 /* Do nothing */; 03316 else if (Proto->isVariadic()) 03317 CheckArgs = Function->getNumParams(); 03318 else 03319 return TDK_TooManyArguments; 03320 } 03321 03322 // The types of the parameters from which we will perform template argument 03323 // deduction. 03324 LocalInstantiationScope InstScope(*this); 03325 TemplateParameterList *TemplateParams 03326 = FunctionTemplate->getTemplateParameters(); 03327 SmallVector<DeducedTemplateArgument, 4> Deduced; 03328 SmallVector<QualType, 4> ParamTypes; 03329 unsigned NumExplicitlySpecified = 0; 03330 if (ExplicitTemplateArgs) { 03331 TemplateDeductionResult Result = 03332 SubstituteExplicitTemplateArguments(FunctionTemplate, 03333 *ExplicitTemplateArgs, 03334 Deduced, 03335 ParamTypes, 03336 nullptr, 03337 Info); 03338 if (Result) 03339 return Result; 03340 03341 NumExplicitlySpecified = Deduced.size(); 03342 } else { 03343 // Just fill in the parameter types from the function declaration. 03344 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) 03345 ParamTypes.push_back(Function->getParamDecl(I)->getType()); 03346 } 03347 03348 // Deduce template arguments from the function parameters. 03349 Deduced.resize(TemplateParams->size()); 03350 unsigned ArgIdx = 0; 03351 SmallVector<OriginalCallArg, 4> OriginalCallArgs; 03352 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size(); 03353 ParamIdx != NumParams; ++ParamIdx) { 03354 QualType OrigParamType = ParamTypes[ParamIdx]; 03355 QualType ParamType = OrigParamType; 03356 03357 const PackExpansionType *ParamExpansion 03358 = dyn_cast<PackExpansionType>(ParamType); 03359 if (!ParamExpansion) { 03360 // Simple case: matching a function parameter to a function argument. 03361 if (ArgIdx >= CheckArgs) 03362 break; 03363 03364 Expr *Arg = Args[ArgIdx++]; 03365 QualType ArgType = Arg->getType(); 03366 03367 unsigned TDF = 0; 03368 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams, 03369 ParamType, ArgType, Arg, 03370 TDF)) 03371 continue; 03372 03373 // If we have nothing to deduce, we're done. 03374 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType)) 03375 continue; 03376 03377 // If the argument is an initializer list ... 03378 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 03379 // ... then the parameter is an undeduced context, unless the parameter 03380 // type is (reference to cv) std::initializer_list<P'>, in which case 03381 // deduction is done for each element of the initializer list, and the 03382 // result is the deduced type if it's the same for all elements. 03383 QualType X; 03384 // Removing references was already done. 03385 if (!isStdInitializerList(ParamType, &X)) 03386 continue; 03387 03388 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 03389 if (TemplateDeductionResult Result = 03390 DeduceTemplateArgumentByListElement(*this, TemplateParams, X, 03391 ILE->getInit(i), 03392 Info, Deduced, TDF)) 03393 return Result; 03394 } 03395 // Don't track the argument type, since an initializer list has none. 03396 continue; 03397 } 03398 03399 // Keep track of the argument type and corresponding parameter index, 03400 // so we can check for compatibility between the deduced A and A. 03401 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1, 03402 ArgType)); 03403 03404 if (TemplateDeductionResult Result 03405 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 03406 ParamType, ArgType, 03407 Info, Deduced, TDF)) 03408 return Result; 03409 03410 continue; 03411 } 03412 03413 // C++0x [temp.deduct.call]p1: 03414 // For a function parameter pack that occurs at the end of the 03415 // parameter-declaration-list, the type A of each remaining argument of 03416 // the call is compared with the type P of the declarator-id of the 03417 // function parameter pack. Each comparison deduces template arguments 03418 // for subsequent positions in the template parameter packs expanded by 03419 // the function parameter pack. For a function parameter pack that does 03420 // not occur at the end of the parameter-declaration-list, the type of 03421 // the parameter pack is a non-deduced context. 03422 if (ParamIdx + 1 < NumParams) 03423 break; 03424 03425 QualType ParamPattern = ParamExpansion->getPattern(); 03426 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info, 03427 ParamPattern); 03428 03429 bool HasAnyArguments = false; 03430 for (; ArgIdx < Args.size(); ++ArgIdx) { 03431 HasAnyArguments = true; 03432 03433 QualType OrigParamType = ParamPattern; 03434 ParamType = OrigParamType; 03435 Expr *Arg = Args[ArgIdx]; 03436 QualType ArgType = Arg->getType(); 03437 03438 unsigned TDF = 0; 03439 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams, 03440 ParamType, ArgType, Arg, 03441 TDF)) { 03442 // We can't actually perform any deduction for this argument, so stop 03443 // deduction at this point. 03444 ++ArgIdx; 03445 break; 03446 } 03447 03448 // As above, initializer lists need special handling. 03449 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 03450 QualType X; 03451 if (!isStdInitializerList(ParamType, &X)) { 03452 ++ArgIdx; 03453 break; 03454 } 03455 03456 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 03457 if (TemplateDeductionResult Result = 03458 DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, X, 03459 ILE->getInit(i)->getType(), 03460 Info, Deduced, TDF)) 03461 return Result; 03462 } 03463 } else { 03464 03465 // Keep track of the argument type and corresponding argument index, 03466 // so we can check for compatibility between the deduced A and A. 03467 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType)) 03468 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx, 03469 ArgType)); 03470 03471 if (TemplateDeductionResult Result 03472 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 03473 ParamType, ArgType, Info, 03474 Deduced, TDF)) 03475 return Result; 03476 } 03477 03478 PackScope.nextPackElement(); 03479 } 03480 03481 // Build argument packs for each of the parameter packs expanded by this 03482 // pack expansion. 03483 if (auto Result = PackScope.finish(HasAnyArguments)) 03484 return Result; 03485 03486 // After we've matching against a parameter pack, we're done. 03487 break; 03488 } 03489 03490 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 03491 NumExplicitlySpecified, Specialization, 03492 Info, &OriginalCallArgs); 03493 } 03494 03495 QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType, 03496 QualType FunctionType) { 03497 if (ArgFunctionType.isNull()) 03498 return ArgFunctionType; 03499 03500 const FunctionProtoType *FunctionTypeP = 03501 FunctionType->castAs<FunctionProtoType>(); 03502 CallingConv CC = FunctionTypeP->getCallConv(); 03503 bool NoReturn = FunctionTypeP->getNoReturnAttr(); 03504 const FunctionProtoType *ArgFunctionTypeP = 03505 ArgFunctionType->getAs<FunctionProtoType>(); 03506 if (ArgFunctionTypeP->getCallConv() == CC && 03507 ArgFunctionTypeP->getNoReturnAttr() == NoReturn) 03508 return ArgFunctionType; 03509 03510 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC); 03511 EI = EI.withNoReturn(NoReturn); 03512 ArgFunctionTypeP = 03513 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI)); 03514 return QualType(ArgFunctionTypeP, 0); 03515 } 03516 03517 /// \brief Deduce template arguments when taking the address of a function 03518 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to 03519 /// a template. 03520 /// 03521 /// \param FunctionTemplate the function template for which we are performing 03522 /// template argument deduction. 03523 /// 03524 /// \param ExplicitTemplateArgs the explicitly-specified template 03525 /// arguments. 03526 /// 03527 /// \param ArgFunctionType the function type that will be used as the 03528 /// "argument" type (A) when performing template argument deduction from the 03529 /// function template's function type. This type may be NULL, if there is no 03530 /// argument type to compare against, in C++0x [temp.arg.explicit]p3. 03531 /// 03532 /// \param Specialization if template argument deduction was successful, 03533 /// this will be set to the function template specialization produced by 03534 /// template argument deduction. 03535 /// 03536 /// \param Info the argument will be updated to provide additional information 03537 /// about template argument deduction. 03538 /// 03539 /// \returns the result of template argument deduction. 03540 Sema::TemplateDeductionResult 03541 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 03542 TemplateArgumentListInfo *ExplicitTemplateArgs, 03543 QualType ArgFunctionType, 03544 FunctionDecl *&Specialization, 03545 TemplateDeductionInfo &Info, 03546 bool InOverloadResolution) { 03547 if (FunctionTemplate->isInvalidDecl()) 03548 return TDK_Invalid; 03549 03550 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 03551 TemplateParameterList *TemplateParams 03552 = FunctionTemplate->getTemplateParameters(); 03553 QualType FunctionType = Function->getType(); 03554 if (!InOverloadResolution) 03555 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType); 03556 03557 // Substitute any explicit template arguments. 03558 LocalInstantiationScope InstScope(*this); 03559 SmallVector<DeducedTemplateArgument, 4> Deduced; 03560 unsigned NumExplicitlySpecified = 0; 03561 SmallVector<QualType, 4> ParamTypes; 03562 if (ExplicitTemplateArgs) { 03563 if (TemplateDeductionResult Result 03564 = SubstituteExplicitTemplateArguments(FunctionTemplate, 03565 *ExplicitTemplateArgs, 03566 Deduced, ParamTypes, 03567 &FunctionType, Info)) 03568 return Result; 03569 03570 NumExplicitlySpecified = Deduced.size(); 03571 } 03572 03573 // Unevaluated SFINAE context. 03574 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 03575 SFINAETrap Trap(*this); 03576 03577 Deduced.resize(TemplateParams->size()); 03578 03579 // If the function has a deduced return type, substitute it for a dependent 03580 // type so that we treat it as a non-deduced context in what follows. 03581 bool HasDeducedReturnType = false; 03582 if (getLangOpts().CPlusPlus14 && InOverloadResolution && 03583 Function->getReturnType()->getContainedAutoType()) { 03584 FunctionType = SubstAutoType(FunctionType, Context.DependentTy); 03585 HasDeducedReturnType = true; 03586 } 03587 03588 if (!ArgFunctionType.isNull()) { 03589 unsigned TDF = TDF_TopLevelParameterTypeList; 03590 if (InOverloadResolution) TDF |= TDF_InOverloadResolution; 03591 // Deduce template arguments from the function type. 03592 if (TemplateDeductionResult Result 03593 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 03594 FunctionType, ArgFunctionType, 03595 Info, Deduced, TDF)) 03596 return Result; 03597 } 03598 03599 if (TemplateDeductionResult Result 03600 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 03601 NumExplicitlySpecified, 03602 Specialization, Info)) 03603 return Result; 03604 03605 // If the function has a deduced return type, deduce it now, so we can check 03606 // that the deduced function type matches the requested type. 03607 if (HasDeducedReturnType && 03608 Specialization->getReturnType()->isUndeducedType() && 03609 DeduceReturnType(Specialization, Info.getLocation(), false)) 03610 return TDK_MiscellaneousDeductionFailure; 03611 03612 // If the requested function type does not match the actual type of the 03613 // specialization with respect to arguments of compatible pointer to function 03614 // types, template argument deduction fails. 03615 if (!ArgFunctionType.isNull()) { 03616 if (InOverloadResolution && !isSameOrCompatibleFunctionType( 03617 Context.getCanonicalType(Specialization->getType()), 03618 Context.getCanonicalType(ArgFunctionType))) 03619 return TDK_MiscellaneousDeductionFailure; 03620 else if(!InOverloadResolution && 03621 !Context.hasSameType(Specialization->getType(), ArgFunctionType)) 03622 return TDK_MiscellaneousDeductionFailure; 03623 } 03624 03625 return TDK_Success; 03626 } 03627 03628 /// \brief Given a function declaration (e.g. a generic lambda conversion 03629 /// function) that contains an 'auto' in its result type, substitute it 03630 /// with TypeToReplaceAutoWith. Be careful to pass in the type you want 03631 /// to replace 'auto' with and not the actual result type you want 03632 /// to set the function to. 03633 static inline void 03634 SubstAutoWithinFunctionReturnType(FunctionDecl *F, 03635 QualType TypeToReplaceAutoWith, Sema &S) { 03636 assert(!TypeToReplaceAutoWith->getContainedAutoType()); 03637 QualType AutoResultType = F->getReturnType(); 03638 assert(AutoResultType->getContainedAutoType()); 03639 QualType DeducedResultType = S.SubstAutoType(AutoResultType, 03640 TypeToReplaceAutoWith); 03641 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType); 03642 } 03643 03644 /// \brief Given a specialized conversion operator of a generic lambda 03645 /// create the corresponding specializations of the call operator and 03646 /// the static-invoker. If the return type of the call operator is auto, 03647 /// deduce its return type and check if that matches the 03648 /// return type of the destination function ptr. 03649 03650 static inline Sema::TemplateDeductionResult 03651 SpecializeCorrespondingLambdaCallOperatorAndInvoker( 03652 CXXConversionDecl *ConversionSpecialized, 03653 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments, 03654 QualType ReturnTypeOfDestFunctionPtr, 03655 TemplateDeductionInfo &TDInfo, 03656 Sema &S) { 03657 03658 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent(); 03659 assert(LambdaClass && LambdaClass->isGenericLambda()); 03660 03661 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator(); 03662 QualType CallOpResultType = CallOpGeneric->getReturnType(); 03663 const bool GenericLambdaCallOperatorHasDeducedReturnType = 03664 CallOpResultType->getContainedAutoType(); 03665 03666 FunctionTemplateDecl *CallOpTemplate = 03667 CallOpGeneric->getDescribedFunctionTemplate(); 03668 03669 FunctionDecl *CallOpSpecialized = nullptr; 03670 // Use the deduced arguments of the conversion function, to specialize our 03671 // generic lambda's call operator. 03672 if (Sema::TemplateDeductionResult Result 03673 = S.FinishTemplateArgumentDeduction(CallOpTemplate, 03674 DeducedArguments, 03675 0, CallOpSpecialized, TDInfo)) 03676 return Result; 03677 03678 // If we need to deduce the return type, do so (instantiates the callop). 03679 if (GenericLambdaCallOperatorHasDeducedReturnType && 03680 CallOpSpecialized->getReturnType()->isUndeducedType()) 03681 S.DeduceReturnType(CallOpSpecialized, 03682 CallOpSpecialized->getPointOfInstantiation(), 03683 /*Diagnose*/ true); 03684 03685 // Check to see if the return type of the destination ptr-to-function 03686 // matches the return type of the call operator. 03687 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(), 03688 ReturnTypeOfDestFunctionPtr)) 03689 return Sema::TDK_NonDeducedMismatch; 03690 // Since we have succeeded in matching the source and destination 03691 // ptr-to-functions (now including return type), and have successfully 03692 // specialized our corresponding call operator, we are ready to 03693 // specialize the static invoker with the deduced arguments of our 03694 // ptr-to-function. 03695 FunctionDecl *InvokerSpecialized = nullptr; 03696 FunctionTemplateDecl *InvokerTemplate = LambdaClass-> 03697 getLambdaStaticInvoker()->getDescribedFunctionTemplate(); 03698 03699 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result 03700 = S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0, 03701 InvokerSpecialized, TDInfo); 03702 assert(Result == Sema::TDK_Success && 03703 "If the call operator succeeded so should the invoker!"); 03704 // Set the result type to match the corresponding call operator 03705 // specialization's result type. 03706 if (GenericLambdaCallOperatorHasDeducedReturnType && 03707 InvokerSpecialized->getReturnType()->isUndeducedType()) { 03708 // Be sure to get the type to replace 'auto' with and not 03709 // the full result type of the call op specialization 03710 // to substitute into the 'auto' of the invoker and conversion 03711 // function. 03712 // For e.g. 03713 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; }; 03714 // We don't want to subst 'int*' into 'auto' to get int**. 03715 03716 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType() 03717 ->getContainedAutoType() 03718 ->getDeducedType(); 03719 SubstAutoWithinFunctionReturnType(InvokerSpecialized, 03720 TypeToReplaceAutoWith, S); 03721 SubstAutoWithinFunctionReturnType(ConversionSpecialized, 03722 TypeToReplaceAutoWith, S); 03723 } 03724 03725 // Ensure that static invoker doesn't have a const qualifier. 03726 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp 03727 // do not use the CallOperator's TypeSourceInfo which allows 03728 // the const qualifier to leak through. 03729 const FunctionProtoType *InvokerFPT = InvokerSpecialized-> 03730 getType().getTypePtr()->castAs<FunctionProtoType>(); 03731 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo(); 03732 EPI.TypeQuals = 0; 03733 InvokerSpecialized->setType(S.Context.getFunctionType( 03734 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI)); 03735 return Sema::TDK_Success; 03736 } 03737 /// \brief Deduce template arguments for a templated conversion 03738 /// function (C++ [temp.deduct.conv]) and, if successful, produce a 03739 /// conversion function template specialization. 03740 Sema::TemplateDeductionResult 03741 Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate, 03742 QualType ToType, 03743 CXXConversionDecl *&Specialization, 03744 TemplateDeductionInfo &Info) { 03745 if (ConversionTemplate->isInvalidDecl()) 03746 return TDK_Invalid; 03747 03748 CXXConversionDecl *ConversionGeneric 03749 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl()); 03750 03751 QualType FromType = ConversionGeneric->getConversionType(); 03752 03753 // Canonicalize the types for deduction. 03754 QualType P = Context.getCanonicalType(FromType); 03755 QualType A = Context.getCanonicalType(ToType); 03756 03757 // C++0x [temp.deduct.conv]p2: 03758 // If P is a reference type, the type referred to by P is used for 03759 // type deduction. 03760 if (const ReferenceType *PRef = P->getAs<ReferenceType>()) 03761 P = PRef->getPointeeType(); 03762 03763 // C++0x [temp.deduct.conv]p4: 03764 // [...] If A is a reference type, the type referred to by A is used 03765 // for type deduction. 03766 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) 03767 A = ARef->getPointeeType().getUnqualifiedType(); 03768 // C++ [temp.deduct.conv]p3: 03769 // 03770 // If A is not a reference type: 03771 else { 03772 assert(!A->isReferenceType() && "Reference types were handled above"); 03773 03774 // - If P is an array type, the pointer type produced by the 03775 // array-to-pointer standard conversion (4.2) is used in place 03776 // of P for type deduction; otherwise, 03777 if (P->isArrayType()) 03778 P = Context.getArrayDecayedType(P); 03779 // - If P is a function type, the pointer type produced by the 03780 // function-to-pointer standard conversion (4.3) is used in 03781 // place of P for type deduction; otherwise, 03782 else if (P->isFunctionType()) 03783 P = Context.getPointerType(P); 03784 // - If P is a cv-qualified type, the top level cv-qualifiers of 03785 // P's type are ignored for type deduction. 03786 else 03787 P = P.getUnqualifiedType(); 03788 03789 // C++0x [temp.deduct.conv]p4: 03790 // If A is a cv-qualified type, the top level cv-qualifiers of A's 03791 // type are ignored for type deduction. If A is a reference type, the type 03792 // referred to by A is used for type deduction. 03793 A = A.getUnqualifiedType(); 03794 } 03795 03796 // Unevaluated SFINAE context. 03797 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 03798 SFINAETrap Trap(*this); 03799 03800 // C++ [temp.deduct.conv]p1: 03801 // Template argument deduction is done by comparing the return 03802 // type of the template conversion function (call it P) with the 03803 // type that is required as the result of the conversion (call it 03804 // A) as described in 14.8.2.4. 03805 TemplateParameterList *TemplateParams 03806 = ConversionTemplate->getTemplateParameters(); 03807 SmallVector<DeducedTemplateArgument, 4> Deduced; 03808 Deduced.resize(TemplateParams->size()); 03809 03810 // C++0x [temp.deduct.conv]p4: 03811 // In general, the deduction process attempts to find template 03812 // argument values that will make the deduced A identical to 03813 // A. However, there are two cases that allow a difference: 03814 unsigned TDF = 0; 03815 // - If the original A is a reference type, A can be more 03816 // cv-qualified than the deduced A (i.e., the type referred to 03817 // by the reference) 03818 if (ToType->isReferenceType()) 03819 TDF |= TDF_ParamWithReferenceType; 03820 // - The deduced A can be another pointer or pointer to member 03821 // type that can be converted to A via a qualification 03822 // conversion. 03823 // 03824 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when 03825 // both P and A are pointers or member pointers. In this case, we 03826 // just ignore cv-qualifiers completely). 03827 if ((P->isPointerType() && A->isPointerType()) || 03828 (P->isMemberPointerType() && A->isMemberPointerType())) 03829 TDF |= TDF_IgnoreQualifiers; 03830 if (TemplateDeductionResult Result 03831 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 03832 P, A, Info, Deduced, TDF)) 03833 return Result; 03834 03835 // Create an Instantiation Scope for finalizing the operator. 03836 LocalInstantiationScope InstScope(*this); 03837 // Finish template argument deduction. 03838 FunctionDecl *ConversionSpecialized = nullptr; 03839 TemplateDeductionResult Result 03840 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0, 03841 ConversionSpecialized, Info); 03842 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized); 03843 03844 // If the conversion operator is being invoked on a lambda closure to convert 03845 // to a ptr-to-function, use the deduced arguments from the conversion 03846 // function to specialize the corresponding call operator. 03847 // e.g., int (*fp)(int) = [](auto a) { return a; }; 03848 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) { 03849 03850 // Get the return type of the destination ptr-to-function we are converting 03851 // to. This is necessary for matching the lambda call operator's return 03852 // type to that of the destination ptr-to-function's return type. 03853 assert(A->isPointerType() && 03854 "Can only convert from lambda to ptr-to-function"); 03855 const FunctionType *ToFunType = 03856 A->getPointeeType().getTypePtr()->getAs<FunctionType>(); 03857 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType(); 03858 03859 // Create the corresponding specializations of the call operator and 03860 // the static-invoker; and if the return type is auto, 03861 // deduce the return type and check if it matches the 03862 // DestFunctionPtrReturnType. 03863 // For instance: 03864 // auto L = [](auto a) { return f(a); }; 03865 // int (*fp)(int) = L; 03866 // char (*fp2)(int) = L; <-- Not OK. 03867 03868 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker( 03869 Specialization, Deduced, DestFunctionPtrReturnType, 03870 Info, *this); 03871 } 03872 return Result; 03873 } 03874 03875 /// \brief Deduce template arguments for a function template when there is 03876 /// nothing to deduce against (C++0x [temp.arg.explicit]p3). 03877 /// 03878 /// \param FunctionTemplate the function template for which we are performing 03879 /// template argument deduction. 03880 /// 03881 /// \param ExplicitTemplateArgs the explicitly-specified template 03882 /// arguments. 03883 /// 03884 /// \param Specialization if template argument deduction was successful, 03885 /// this will be set to the function template specialization produced by 03886 /// template argument deduction. 03887 /// 03888 /// \param Info the argument will be updated to provide additional information 03889 /// about template argument deduction. 03890 /// 03891 /// \returns the result of template argument deduction. 03892 Sema::TemplateDeductionResult 03893 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 03894 TemplateArgumentListInfo *ExplicitTemplateArgs, 03895 FunctionDecl *&Specialization, 03896 TemplateDeductionInfo &Info, 03897 bool InOverloadResolution) { 03898 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 03899 QualType(), Specialization, Info, 03900 InOverloadResolution); 03901 } 03902 03903 namespace { 03904 /// Substitute the 'auto' type specifier within a type for a given replacement 03905 /// type. 03906 class SubstituteAutoTransform : 03907 public TreeTransform<SubstituteAutoTransform> { 03908 QualType Replacement; 03909 public: 03910 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement) 03911 : TreeTransform<SubstituteAutoTransform>(SemaRef), 03912 Replacement(Replacement) {} 03913 03914 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) { 03915 // If we're building the type pattern to deduce against, don't wrap the 03916 // substituted type in an AutoType. Certain template deduction rules 03917 // apply only when a template type parameter appears directly (and not if 03918 // the parameter is found through desugaring). For instance: 03919 // auto &&lref = lvalue; 03920 // must transform into "rvalue reference to T" not "rvalue reference to 03921 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply. 03922 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) { 03923 QualType Result = Replacement; 03924 TemplateTypeParmTypeLoc NewTL = 03925 TLB.push<TemplateTypeParmTypeLoc>(Result); 03926 NewTL.setNameLoc(TL.getNameLoc()); 03927 return Result; 03928 } else { 03929 bool Dependent = 03930 !Replacement.isNull() && Replacement->isDependentType(); 03931 QualType Result = 03932 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement, 03933 TL.getTypePtr()->isDecltypeAuto(), 03934 Dependent); 03935 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result); 03936 NewTL.setNameLoc(TL.getNameLoc()); 03937 return Result; 03938 } 03939 } 03940 03941 ExprResult TransformLambdaExpr(LambdaExpr *E) { 03942 // Lambdas never need to be transformed. 03943 return E; 03944 } 03945 03946 QualType Apply(TypeLoc TL) { 03947 // Create some scratch storage for the transformed type locations. 03948 // FIXME: We're just going to throw this information away. Don't build it. 03949 TypeLocBuilder TLB; 03950 TLB.reserve(TL.getFullDataSize()); 03951 return TransformType(TLB, TL); 03952 } 03953 }; 03954 } 03955 03956 Sema::DeduceAutoResult 03957 Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) { 03958 return DeduceAutoType(Type->getTypeLoc(), Init, Result); 03959 } 03960 03961 /// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6) 03962 /// 03963 /// \param Type the type pattern using the auto type-specifier. 03964 /// \param Init the initializer for the variable whose type is to be deduced. 03965 /// \param Result if type deduction was successful, this will be set to the 03966 /// deduced type. 03967 Sema::DeduceAutoResult 03968 Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) { 03969 if (Init->getType()->isNonOverloadPlaceholderType()) { 03970 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init); 03971 if (NonPlaceholder.isInvalid()) 03972 return DAR_FailedAlreadyDiagnosed; 03973 Init = NonPlaceholder.get(); 03974 } 03975 03976 if (Init->isTypeDependent() || Type.getType()->isDependentType()) { 03977 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type); 03978 assert(!Result.isNull() && "substituting DependentTy can't fail"); 03979 return DAR_Succeeded; 03980 } 03981 03982 // If this is a 'decltype(auto)' specifier, do the decltype dance. 03983 // Since 'decltype(auto)' can only occur at the top of the type, we 03984 // don't need to go digging for it. 03985 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) { 03986 if (AT->isDecltypeAuto()) { 03987 if (isa<InitListExpr>(Init)) { 03988 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list); 03989 return DAR_FailedAlreadyDiagnosed; 03990 } 03991 03992 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart()); 03993 // FIXME: Support a non-canonical deduced type for 'auto'. 03994 Deduced = Context.getCanonicalType(Deduced); 03995 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type); 03996 if (Result.isNull()) 03997 return DAR_FailedAlreadyDiagnosed; 03998 return DAR_Succeeded; 03999 } 04000 } 04001 04002 SourceLocation Loc = Init->getExprLoc(); 04003 04004 LocalInstantiationScope InstScope(*this); 04005 04006 // Build template<class TemplParam> void Func(FuncParam); 04007 TemplateTypeParmDecl *TemplParam = 04008 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0, 04009 nullptr, false, false); 04010 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0); 04011 NamedDecl *TemplParamPtr = TemplParam; 04012 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr, 04013 Loc); 04014 04015 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type); 04016 assert(!FuncParam.isNull() && 04017 "substituting template parameter for 'auto' failed"); 04018 04019 // Deduce type of TemplParam in Func(Init) 04020 SmallVector<DeducedTemplateArgument, 1> Deduced; 04021 Deduced.resize(1); 04022 QualType InitType = Init->getType(); 04023 unsigned TDF = 0; 04024 04025 TemplateDeductionInfo Info(Loc); 04026 04027 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 04028 if (InitList) { 04029 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) { 04030 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams, 04031 TemplArg, 04032 InitList->getInit(i), 04033 Info, Deduced, TDF)) 04034 return DAR_Failed; 04035 } 04036 } else { 04037 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams, 04038 FuncParam, InitType, Init, 04039 TDF)) 04040 return DAR_Failed; 04041 04042 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam, 04043 InitType, Info, Deduced, TDF)) 04044 return DAR_Failed; 04045 } 04046 04047 if (Deduced[0].getKind() != TemplateArgument::Type) 04048 return DAR_Failed; 04049 04050 QualType DeducedType = Deduced[0].getAsType(); 04051 04052 if (InitList) { 04053 DeducedType = BuildStdInitializerList(DeducedType, Loc); 04054 if (DeducedType.isNull()) 04055 return DAR_FailedAlreadyDiagnosed; 04056 } 04057 04058 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type); 04059 if (Result.isNull()) 04060 return DAR_FailedAlreadyDiagnosed; 04061 04062 // Check that the deduced argument type is compatible with the original 04063 // argument type per C++ [temp.deduct.call]p4. 04064 if (!InitList && !Result.isNull() && 04065 CheckOriginalCallArgDeduction(*this, 04066 Sema::OriginalCallArg(FuncParam,0,InitType), 04067 Result)) { 04068 Result = QualType(); 04069 return DAR_Failed; 04070 } 04071 04072 return DAR_Succeeded; 04073 } 04074 04075 QualType Sema::SubstAutoType(QualType TypeWithAuto, 04076 QualType TypeToReplaceAuto) { 04077 return SubstituteAutoTransform(*this, TypeToReplaceAuto). 04078 TransformType(TypeWithAuto); 04079 } 04080 04081 TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 04082 QualType TypeToReplaceAuto) { 04083 return SubstituteAutoTransform(*this, TypeToReplaceAuto). 04084 TransformType(TypeWithAuto); 04085 } 04086 04087 void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) { 04088 if (isa<InitListExpr>(Init)) 04089 Diag(VDecl->getLocation(), 04090 VDecl->isInitCapture() 04091 ? diag::err_init_capture_deduction_failure_from_init_list 04092 : diag::err_auto_var_deduction_failure_from_init_list) 04093 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange(); 04094 else 04095 Diag(VDecl->getLocation(), 04096 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure 04097 : diag::err_auto_var_deduction_failure) 04098 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 04099 << Init->getSourceRange(); 04100 } 04101 04102 bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 04103 bool Diagnose) { 04104 assert(FD->getReturnType()->isUndeducedType()); 04105 04106 if (FD->getTemplateInstantiationPattern()) 04107 InstantiateFunctionDefinition(Loc, FD); 04108 04109 bool StillUndeduced = FD->getReturnType()->isUndeducedType(); 04110 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) { 04111 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD; 04112 Diag(FD->getLocation(), diag::note_callee_decl) << FD; 04113 } 04114 04115 return StillUndeduced; 04116 } 04117 04118 static void 04119 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 04120 bool OnlyDeduced, 04121 unsigned Level, 04122 llvm::SmallBitVector &Deduced); 04123 04124 /// \brief If this is a non-static member function, 04125 static void 04126 AddImplicitObjectParameterType(ASTContext &Context, 04127 CXXMethodDecl *Method, 04128 SmallVectorImpl<QualType> &ArgTypes) { 04129 // C++11 [temp.func.order]p3: 04130 // [...] The new parameter is of type "reference to cv A," where cv are 04131 // the cv-qualifiers of the function template (if any) and A is 04132 // the class of which the function template is a member. 04133 // 04134 // The standard doesn't say explicitly, but we pick the appropriate kind of 04135 // reference type based on [over.match.funcs]p4. 04136 QualType ArgTy = Context.getTypeDeclType(Method->getParent()); 04137 ArgTy = Context.getQualifiedType(ArgTy, 04138 Qualifiers::fromCVRMask(Method->getTypeQualifiers())); 04139 if (Method->getRefQualifier() == RQ_RValue) 04140 ArgTy = Context.getRValueReferenceType(ArgTy); 04141 else 04142 ArgTy = Context.getLValueReferenceType(ArgTy); 04143 ArgTypes.push_back(ArgTy); 04144 } 04145 04146 /// \brief Determine whether the function template \p FT1 is at least as 04147 /// specialized as \p FT2. 04148 static bool isAtLeastAsSpecializedAs(Sema &S, 04149 SourceLocation Loc, 04150 FunctionTemplateDecl *FT1, 04151 FunctionTemplateDecl *FT2, 04152 TemplatePartialOrderingContext TPOC, 04153 unsigned NumCallArguments1, 04154 SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) { 04155 FunctionDecl *FD1 = FT1->getTemplatedDecl(); 04156 FunctionDecl *FD2 = FT2->getTemplatedDecl(); 04157 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>(); 04158 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>(); 04159 04160 assert(Proto1 && Proto2 && "Function templates must have prototypes"); 04161 TemplateParameterList *TemplateParams = FT2->getTemplateParameters(); 04162 SmallVector<DeducedTemplateArgument, 4> Deduced; 04163 Deduced.resize(TemplateParams->size()); 04164 04165 // C++0x [temp.deduct.partial]p3: 04166 // The types used to determine the ordering depend on the context in which 04167 // the partial ordering is done: 04168 TemplateDeductionInfo Info(Loc); 04169 SmallVector<QualType, 4> Args2; 04170 switch (TPOC) { 04171 case TPOC_Call: { 04172 // - In the context of a function call, the function parameter types are 04173 // used. 04174 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1); 04175 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2); 04176 04177 // C++11 [temp.func.order]p3: 04178 // [...] If only one of the function templates is a non-static 04179 // member, that function template is considered to have a new 04180 // first parameter inserted in its function parameter list. The 04181 // new parameter is of type "reference to cv A," where cv are 04182 // the cv-qualifiers of the function template (if any) and A is 04183 // the class of which the function template is a member. 04184 // 04185 // Note that we interpret this to mean "if one of the function 04186 // templates is a non-static member and the other is a non-member"; 04187 // otherwise, the ordering rules for static functions against non-static 04188 // functions don't make any sense. 04189 // 04190 // C++98/03 doesn't have this provision but we've extended DR532 to cover 04191 // it as wording was broken prior to it. 04192 SmallVector<QualType, 4> Args1; 04193 04194 unsigned NumComparedArguments = NumCallArguments1; 04195 04196 if (!Method2 && Method1 && !Method1->isStatic()) { 04197 // Compare 'this' from Method1 against first parameter from Method2. 04198 AddImplicitObjectParameterType(S.Context, Method1, Args1); 04199 ++NumComparedArguments; 04200 } else if (!Method1 && Method2 && !Method2->isStatic()) { 04201 // Compare 'this' from Method2 against first parameter from Method1. 04202 AddImplicitObjectParameterType(S.Context, Method2, Args2); 04203 } 04204 04205 Args1.insert(Args1.end(), Proto1->param_type_begin(), 04206 Proto1->param_type_end()); 04207 Args2.insert(Args2.end(), Proto2->param_type_begin(), 04208 Proto2->param_type_end()); 04209 04210 // C++ [temp.func.order]p5: 04211 // The presence of unused ellipsis and default arguments has no effect on 04212 // the partial ordering of function templates. 04213 if (Args1.size() > NumComparedArguments) 04214 Args1.resize(NumComparedArguments); 04215 if (Args2.size() > NumComparedArguments) 04216 Args2.resize(NumComparedArguments); 04217 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(), 04218 Args1.data(), Args1.size(), Info, Deduced, 04219 TDF_None, /*PartialOrdering=*/true, 04220 RefParamComparisons)) 04221 return false; 04222 04223 break; 04224 } 04225 04226 case TPOC_Conversion: 04227 // - In the context of a call to a conversion operator, the return types 04228 // of the conversion function templates are used. 04229 if (DeduceTemplateArgumentsByTypeMatch( 04230 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(), 04231 Info, Deduced, TDF_None, 04232 /*PartialOrdering=*/true, RefParamComparisons)) 04233 return false; 04234 break; 04235 04236 case TPOC_Other: 04237 // - In other contexts (14.6.6.2) the function template's function type 04238 // is used. 04239 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 04240 FD2->getType(), FD1->getType(), 04241 Info, Deduced, TDF_None, 04242 /*PartialOrdering=*/true, 04243 RefParamComparisons)) 04244 return false; 04245 break; 04246 } 04247 04248 // C++0x [temp.deduct.partial]p11: 04249 // In most cases, all template parameters must have values in order for 04250 // deduction to succeed, but for partial ordering purposes a template 04251 // parameter may remain without a value provided it is not used in the 04252 // types being used for partial ordering. [ Note: a template parameter used 04253 // in a non-deduced context is considered used. -end note] 04254 unsigned ArgIdx = 0, NumArgs = Deduced.size(); 04255 for (; ArgIdx != NumArgs; ++ArgIdx) 04256 if (Deduced[ArgIdx].isNull()) 04257 break; 04258 04259 if (ArgIdx == NumArgs) { 04260 // All template arguments were deduced. FT1 is at least as specialized 04261 // as FT2. 04262 return true; 04263 } 04264 04265 // Figure out which template parameters were used. 04266 llvm::SmallBitVector UsedParameters(TemplateParams->size()); 04267 switch (TPOC) { 04268 case TPOC_Call: 04269 for (unsigned I = 0, N = Args2.size(); I != N; ++I) 04270 ::MarkUsedTemplateParameters(S.Context, Args2[I], false, 04271 TemplateParams->getDepth(), 04272 UsedParameters); 04273 break; 04274 04275 case TPOC_Conversion: 04276 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false, 04277 TemplateParams->getDepth(), UsedParameters); 04278 break; 04279 04280 case TPOC_Other: 04281 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false, 04282 TemplateParams->getDepth(), 04283 UsedParameters); 04284 break; 04285 } 04286 04287 for (; ArgIdx != NumArgs; ++ArgIdx) 04288 // If this argument had no value deduced but was used in one of the types 04289 // used for partial ordering, then deduction fails. 04290 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx]) 04291 return false; 04292 04293 return true; 04294 } 04295 04296 /// \brief Determine whether this a function template whose parameter-type-list 04297 /// ends with a function parameter pack. 04298 static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) { 04299 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 04300 unsigned NumParams = Function->getNumParams(); 04301 if (NumParams == 0) 04302 return false; 04303 04304 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1); 04305 if (!Last->isParameterPack()) 04306 return false; 04307 04308 // Make sure that no previous parameter is a parameter pack. 04309 while (--NumParams > 0) { 04310 if (Function->getParamDecl(NumParams - 1)->isParameterPack()) 04311 return false; 04312 } 04313 04314 return true; 04315 } 04316 04317 /// \brief Returns the more specialized function template according 04318 /// to the rules of function template partial ordering (C++ [temp.func.order]). 04319 /// 04320 /// \param FT1 the first function template 04321 /// 04322 /// \param FT2 the second function template 04323 /// 04324 /// \param TPOC the context in which we are performing partial ordering of 04325 /// function templates. 04326 /// 04327 /// \param NumCallArguments1 The number of arguments in the call to FT1, used 04328 /// only when \c TPOC is \c TPOC_Call. 04329 /// 04330 /// \param NumCallArguments2 The number of arguments in the call to FT2, used 04331 /// only when \c TPOC is \c TPOC_Call. 04332 /// 04333 /// \returns the more specialized function template. If neither 04334 /// template is more specialized, returns NULL. 04335 FunctionTemplateDecl * 04336 Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 04337 FunctionTemplateDecl *FT2, 04338 SourceLocation Loc, 04339 TemplatePartialOrderingContext TPOC, 04340 unsigned NumCallArguments1, 04341 unsigned NumCallArguments2) { 04342 SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons; 04343 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 04344 NumCallArguments1, nullptr); 04345 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, 04346 NumCallArguments2, 04347 &RefParamComparisons); 04348 04349 if (Better1 != Better2) // We have a clear winner 04350 return Better1? FT1 : FT2; 04351 04352 if (!Better1 && !Better2) // Neither is better than the other 04353 return nullptr; 04354 04355 // C++0x [temp.deduct.partial]p10: 04356 // If for each type being considered a given template is at least as 04357 // specialized for all types and more specialized for some set of types and 04358 // the other template is not more specialized for any types or is not at 04359 // least as specialized for any types, then the given template is more 04360 // specialized than the other template. Otherwise, neither template is more 04361 // specialized than the other. 04362 Better1 = false; 04363 Better2 = false; 04364 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) { 04365 // C++0x [temp.deduct.partial]p9: 04366 // If, for a given type, deduction succeeds in both directions (i.e., the 04367 // types are identical after the transformations above) and both P and A 04368 // were reference types (before being replaced with the type referred to 04369 // above): 04370 04371 // -- if the type from the argument template was an lvalue reference 04372 // and the type from the parameter template was not, the argument 04373 // type is considered to be more specialized than the other; 04374 // otherwise, 04375 if (!RefParamComparisons[I].ArgIsRvalueRef && 04376 RefParamComparisons[I].ParamIsRvalueRef) { 04377 Better2 = true; 04378 if (Better1) 04379 return nullptr; 04380 continue; 04381 } else if (!RefParamComparisons[I].ParamIsRvalueRef && 04382 RefParamComparisons[I].ArgIsRvalueRef) { 04383 Better1 = true; 04384 if (Better2) 04385 return nullptr; 04386 continue; 04387 } 04388 04389 // -- if the type from the argument template is more cv-qualified than 04390 // the type from the parameter template (as described above), the 04391 // argument type is considered to be more specialized than the 04392 // other; otherwise, 04393 switch (RefParamComparisons[I].Qualifiers) { 04394 case NeitherMoreQualified: 04395 break; 04396 04397 case ParamMoreQualified: 04398 Better1 = true; 04399 if (Better2) 04400 return nullptr; 04401 continue; 04402 04403 case ArgMoreQualified: 04404 Better2 = true; 04405 if (Better1) 04406 return nullptr; 04407 continue; 04408 } 04409 04410 // -- neither type is more specialized than the other. 04411 } 04412 04413 assert(!(Better1 && Better2) && "Should have broken out in the loop above"); 04414 if (Better1) 04415 return FT1; 04416 else if (Better2) 04417 return FT2; 04418 04419 // FIXME: This mimics what GCC implements, but doesn't match up with the 04420 // proposed resolution for core issue 692. This area needs to be sorted out, 04421 // but for now we attempt to maintain compatibility. 04422 bool Variadic1 = isVariadicFunctionTemplate(FT1); 04423 bool Variadic2 = isVariadicFunctionTemplate(FT2); 04424 if (Variadic1 != Variadic2) 04425 return Variadic1? FT2 : FT1; 04426 04427 return nullptr; 04428 } 04429 04430 /// \brief Determine if the two templates are equivalent. 04431 static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) { 04432 if (T1 == T2) 04433 return true; 04434 04435 if (!T1 || !T2) 04436 return false; 04437 04438 return T1->getCanonicalDecl() == T2->getCanonicalDecl(); 04439 } 04440 04441 /// \brief Retrieve the most specialized of the given function template 04442 /// specializations. 04443 /// 04444 /// \param SpecBegin the start iterator of the function template 04445 /// specializations that we will be comparing. 04446 /// 04447 /// \param SpecEnd the end iterator of the function template 04448 /// specializations, paired with \p SpecBegin. 04449 /// 04450 /// \param Loc the location where the ambiguity or no-specializations 04451 /// diagnostic should occur. 04452 /// 04453 /// \param NoneDiag partial diagnostic used to diagnose cases where there are 04454 /// no matching candidates. 04455 /// 04456 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one 04457 /// occurs. 04458 /// 04459 /// \param CandidateDiag partial diagnostic used for each function template 04460 /// specialization that is a candidate in the ambiguous ordering. One parameter 04461 /// in this diagnostic should be unbound, which will correspond to the string 04462 /// describing the template arguments for the function template specialization. 04463 /// 04464 /// \returns the most specialized function template specialization, if 04465 /// found. Otherwise, returns SpecEnd. 04466 UnresolvedSetIterator Sema::getMostSpecialized( 04467 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd, 04468 TemplateSpecCandidateSet &FailedCandidates, 04469 SourceLocation Loc, const PartialDiagnostic &NoneDiag, 04470 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, 04471 bool Complain, QualType TargetType) { 04472 if (SpecBegin == SpecEnd) { 04473 if (Complain) { 04474 Diag(Loc, NoneDiag); 04475 FailedCandidates.NoteCandidates(*this, Loc); 04476 } 04477 return SpecEnd; 04478 } 04479 04480 if (SpecBegin + 1 == SpecEnd) 04481 return SpecBegin; 04482 04483 // Find the function template that is better than all of the templates it 04484 // has been compared to. 04485 UnresolvedSetIterator Best = SpecBegin; 04486 FunctionTemplateDecl *BestTemplate 04487 = cast<FunctionDecl>(*Best)->getPrimaryTemplate(); 04488 assert(BestTemplate && "Not a function template specialization?"); 04489 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) { 04490 FunctionTemplateDecl *Challenger 04491 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 04492 assert(Challenger && "Not a function template specialization?"); 04493 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 04494 Loc, TPOC_Other, 0, 0), 04495 Challenger)) { 04496 Best = I; 04497 BestTemplate = Challenger; 04498 } 04499 } 04500 04501 // Make sure that the "best" function template is more specialized than all 04502 // of the others. 04503 bool Ambiguous = false; 04504 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 04505 FunctionTemplateDecl *Challenger 04506 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 04507 if (I != Best && 04508 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 04509 Loc, TPOC_Other, 0, 0), 04510 BestTemplate)) { 04511 Ambiguous = true; 04512 break; 04513 } 04514 } 04515 04516 if (!Ambiguous) { 04517 // We found an answer. Return it. 04518 return Best; 04519 } 04520 04521 // Diagnose the ambiguity. 04522 if (Complain) { 04523 Diag(Loc, AmbigDiag); 04524 04525 // FIXME: Can we order the candidates in some sane way? 04526 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 04527 PartialDiagnostic PD = CandidateDiag; 04528 PD << getTemplateArgumentBindingsText( 04529 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(), 04530 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs()); 04531 if (!TargetType.isNull()) 04532 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(), 04533 TargetType); 04534 Diag((*I)->getLocation(), PD); 04535 } 04536 } 04537 04538 return SpecEnd; 04539 } 04540 04541 /// \brief Returns the more specialized class template partial specialization 04542 /// according to the rules of partial ordering of class template partial 04543 /// specializations (C++ [temp.class.order]). 04544 /// 04545 /// \param PS1 the first class template partial specialization 04546 /// 04547 /// \param PS2 the second class template partial specialization 04548 /// 04549 /// \returns the more specialized class template partial specialization. If 04550 /// neither partial specialization is more specialized, returns NULL. 04551 ClassTemplatePartialSpecializationDecl * 04552 Sema::getMoreSpecializedPartialSpecialization( 04553 ClassTemplatePartialSpecializationDecl *PS1, 04554 ClassTemplatePartialSpecializationDecl *PS2, 04555 SourceLocation Loc) { 04556 // C++ [temp.class.order]p1: 04557 // For two class template partial specializations, the first is at least as 04558 // specialized as the second if, given the following rewrite to two 04559 // function templates, the first function template is at least as 04560 // specialized as the second according to the ordering rules for function 04561 // templates (14.6.6.2): 04562 // - the first function template has the same template parameters as the 04563 // first partial specialization and has a single function parameter 04564 // whose type is a class template specialization with the template 04565 // arguments of the first partial specialization, and 04566 // - the second function template has the same template parameters as the 04567 // second partial specialization and has a single function parameter 04568 // whose type is a class template specialization with the template 04569 // arguments of the second partial specialization. 04570 // 04571 // Rather than synthesize function templates, we merely perform the 04572 // equivalent partial ordering by performing deduction directly on 04573 // the template arguments of the class template partial 04574 // specializations. This computation is slightly simpler than the 04575 // general problem of function template partial ordering, because 04576 // class template partial specializations are more constrained. We 04577 // know that every template parameter is deducible from the class 04578 // template partial specialization's template arguments, for 04579 // example. 04580 SmallVector<DeducedTemplateArgument, 4> Deduced; 04581 TemplateDeductionInfo Info(Loc); 04582 04583 QualType PT1 = PS1->getInjectedSpecializationType(); 04584 QualType PT2 = PS2->getInjectedSpecializationType(); 04585 04586 // Determine whether PS1 is at least as specialized as PS2 04587 Deduced.resize(PS2->getTemplateParameters()->size()); 04588 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this, 04589 PS2->getTemplateParameters(), 04590 PT2, PT1, Info, Deduced, TDF_None, 04591 /*PartialOrdering=*/true, 04592 /*RefParamComparisons=*/nullptr); 04593 if (Better1) { 04594 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end()); 04595 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info); 04596 Better1 = !::FinishTemplateArgumentDeduction( 04597 *this, PS2, PS1->getTemplateArgs(), Deduced, Info); 04598 } 04599 04600 // Determine whether PS2 is at least as specialized as PS1 04601 Deduced.clear(); 04602 Deduced.resize(PS1->getTemplateParameters()->size()); 04603 bool Better2 = !DeduceTemplateArgumentsByTypeMatch( 04604 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None, 04605 /*PartialOrdering=*/true, 04606 /*RefParamComparisons=*/nullptr); 04607 if (Better2) { 04608 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), 04609 Deduced.end()); 04610 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info); 04611 Better2 = !::FinishTemplateArgumentDeduction( 04612 *this, PS1, PS2->getTemplateArgs(), Deduced, Info); 04613 } 04614 04615 if (Better1 == Better2) 04616 return nullptr; 04617 04618 return Better1 ? PS1 : PS2; 04619 } 04620 04621 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version? 04622 /// May require unifying ClassTemplate(Partial)SpecializationDecl and 04623 /// VarTemplate(Partial)SpecializationDecl with a new data 04624 /// structure Template(Partial)SpecializationDecl, and 04625 /// using Template(Partial)SpecializationDecl as input type. 04626 VarTemplatePartialSpecializationDecl * 04627 Sema::getMoreSpecializedPartialSpecialization( 04628 VarTemplatePartialSpecializationDecl *PS1, 04629 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) { 04630 SmallVector<DeducedTemplateArgument, 4> Deduced; 04631 TemplateDeductionInfo Info(Loc); 04632 04633 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && 04634 "the partial specializations being compared should specialize" 04635 " the same template."); 04636 TemplateName Name(PS1->getSpecializedTemplate()); 04637 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 04638 QualType PT1 = Context.getTemplateSpecializationType( 04639 CanonTemplate, PS1->getTemplateArgs().data(), 04640 PS1->getTemplateArgs().size()); 04641 QualType PT2 = Context.getTemplateSpecializationType( 04642 CanonTemplate, PS2->getTemplateArgs().data(), 04643 PS2->getTemplateArgs().size()); 04644 04645 // Determine whether PS1 is at least as specialized as PS2 04646 Deduced.resize(PS2->getTemplateParameters()->size()); 04647 bool Better1 = !DeduceTemplateArgumentsByTypeMatch( 04648 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None, 04649 /*PartialOrdering=*/true, 04650 /*RefParamComparisons=*/nullptr); 04651 if (Better1) { 04652 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), 04653 Deduced.end()); 04654 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info); 04655 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2, 04656 PS1->getTemplateArgs(), 04657 Deduced, Info); 04658 } 04659 04660 // Determine whether PS2 is at least as specialized as PS1 04661 Deduced.clear(); 04662 Deduced.resize(PS1->getTemplateParameters()->size()); 04663 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this, 04664 PS1->getTemplateParameters(), 04665 PT1, PT2, Info, Deduced, TDF_None, 04666 /*PartialOrdering=*/true, 04667 /*RefParamComparisons=*/nullptr); 04668 if (Better2) { 04669 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end()); 04670 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info); 04671 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1, 04672 PS2->getTemplateArgs(), 04673 Deduced, Info); 04674 } 04675 04676 if (Better1 == Better2) 04677 return nullptr; 04678 04679 return Better1? PS1 : PS2; 04680 } 04681 04682 static void 04683 MarkUsedTemplateParameters(ASTContext &Ctx, 04684 const TemplateArgument &TemplateArg, 04685 bool OnlyDeduced, 04686 unsigned Depth, 04687 llvm::SmallBitVector &Used); 04688 04689 /// \brief Mark the template parameters that are used by the given 04690 /// expression. 04691 static void 04692 MarkUsedTemplateParameters(ASTContext &Ctx, 04693 const Expr *E, 04694 bool OnlyDeduced, 04695 unsigned Depth, 04696 llvm::SmallBitVector &Used) { 04697 // We can deduce from a pack expansion. 04698 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E)) 04699 E = Expansion->getPattern(); 04700 04701 // Skip through any implicit casts we added while type-checking, and any 04702 // substitutions performed by template alias expansion. 04703 while (1) { 04704 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 04705 E = ICE->getSubExpr(); 04706 else if (const SubstNonTypeTemplateParmExpr *Subst = 04707 dyn_cast<SubstNonTypeTemplateParmExpr>(E)) 04708 E = Subst->getReplacement(); 04709 else 04710 break; 04711 } 04712 04713 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to 04714 // find other occurrences of template parameters. 04715 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 04716 if (!DRE) 04717 return; 04718 04719 const NonTypeTemplateParmDecl *NTTP 04720 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 04721 if (!NTTP) 04722 return; 04723 04724 if (NTTP->getDepth() == Depth) 04725 Used[NTTP->getIndex()] = true; 04726 } 04727 04728 /// \brief Mark the template parameters that are used by the given 04729 /// nested name specifier. 04730 static void 04731 MarkUsedTemplateParameters(ASTContext &Ctx, 04732 NestedNameSpecifier *NNS, 04733 bool OnlyDeduced, 04734 unsigned Depth, 04735 llvm::SmallBitVector &Used) { 04736 if (!NNS) 04737 return; 04738 04739 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth, 04740 Used); 04741 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0), 04742 OnlyDeduced, Depth, Used); 04743 } 04744 04745 /// \brief Mark the template parameters that are used by the given 04746 /// template name. 04747 static void 04748 MarkUsedTemplateParameters(ASTContext &Ctx, 04749 TemplateName Name, 04750 bool OnlyDeduced, 04751 unsigned Depth, 04752 llvm::SmallBitVector &Used) { 04753 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 04754 if (TemplateTemplateParmDecl *TTP 04755 = dyn_cast<TemplateTemplateParmDecl>(Template)) { 04756 if (TTP->getDepth() == Depth) 04757 Used[TTP->getIndex()] = true; 04758 } 04759 return; 04760 } 04761 04762 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) 04763 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced, 04764 Depth, Used); 04765 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) 04766 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced, 04767 Depth, Used); 04768 } 04769 04770 /// \brief Mark the template parameters that are used by the given 04771 /// type. 04772 static void 04773 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 04774 bool OnlyDeduced, 04775 unsigned Depth, 04776 llvm::SmallBitVector &Used) { 04777 if (T.isNull()) 04778 return; 04779 04780 // Non-dependent types have nothing deducible 04781 if (!T->isDependentType()) 04782 return; 04783 04784 T = Ctx.getCanonicalType(T); 04785 switch (T->getTypeClass()) { 04786 case Type::Pointer: 04787 MarkUsedTemplateParameters(Ctx, 04788 cast<PointerType>(T)->getPointeeType(), 04789 OnlyDeduced, 04790 Depth, 04791 Used); 04792 break; 04793 04794 case Type::BlockPointer: 04795 MarkUsedTemplateParameters(Ctx, 04796 cast<BlockPointerType>(T)->getPointeeType(), 04797 OnlyDeduced, 04798 Depth, 04799 Used); 04800 break; 04801 04802 case Type::LValueReference: 04803 case Type::RValueReference: 04804 MarkUsedTemplateParameters(Ctx, 04805 cast<ReferenceType>(T)->getPointeeType(), 04806 OnlyDeduced, 04807 Depth, 04808 Used); 04809 break; 04810 04811 case Type::MemberPointer: { 04812 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr()); 04813 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced, 04814 Depth, Used); 04815 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0), 04816 OnlyDeduced, Depth, Used); 04817 break; 04818 } 04819 04820 case Type::DependentSizedArray: 04821 MarkUsedTemplateParameters(Ctx, 04822 cast<DependentSizedArrayType>(T)->getSizeExpr(), 04823 OnlyDeduced, Depth, Used); 04824 // Fall through to check the element type 04825 04826 case Type::ConstantArray: 04827 case Type::IncompleteArray: 04828 MarkUsedTemplateParameters(Ctx, 04829 cast<ArrayType>(T)->getElementType(), 04830 OnlyDeduced, Depth, Used); 04831 break; 04832 04833 case Type::Vector: 04834 case Type::ExtVector: 04835 MarkUsedTemplateParameters(Ctx, 04836 cast<VectorType>(T)->getElementType(), 04837 OnlyDeduced, Depth, Used); 04838 break; 04839 04840 case Type::DependentSizedExtVector: { 04841 const DependentSizedExtVectorType *VecType 04842 = cast<DependentSizedExtVectorType>(T); 04843 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced, 04844 Depth, Used); 04845 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, 04846 Depth, Used); 04847 break; 04848 } 04849 04850 case Type::FunctionProto: { 04851 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 04852 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth, 04853 Used); 04854 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) 04855 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced, 04856 Depth, Used); 04857 break; 04858 } 04859 04860 case Type::TemplateTypeParm: { 04861 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T); 04862 if (TTP->getDepth() == Depth) 04863 Used[TTP->getIndex()] = true; 04864 break; 04865 } 04866 04867 case Type::SubstTemplateTypeParmPack: { 04868 const SubstTemplateTypeParmPackType *Subst 04869 = cast<SubstTemplateTypeParmPackType>(T); 04870 MarkUsedTemplateParameters(Ctx, 04871 QualType(Subst->getReplacedParameter(), 0), 04872 OnlyDeduced, Depth, Used); 04873 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), 04874 OnlyDeduced, Depth, Used); 04875 break; 04876 } 04877 04878 case Type::InjectedClassName: 04879 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType(); 04880 // fall through 04881 04882 case Type::TemplateSpecialization: { 04883 const TemplateSpecializationType *Spec 04884 = cast<TemplateSpecializationType>(T); 04885 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced, 04886 Depth, Used); 04887 04888 // C++0x [temp.deduct.type]p9: 04889 // If the template argument list of P contains a pack expansion that is 04890 // not the last template argument, the entire template argument list is a 04891 // non-deduced context. 04892 if (OnlyDeduced && 04893 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs())) 04894 break; 04895 04896 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 04897 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 04898 Used); 04899 break; 04900 } 04901 04902 case Type::Complex: 04903 if (!OnlyDeduced) 04904 MarkUsedTemplateParameters(Ctx, 04905 cast<ComplexType>(T)->getElementType(), 04906 OnlyDeduced, Depth, Used); 04907 break; 04908 04909 case Type::Atomic: 04910 if (!OnlyDeduced) 04911 MarkUsedTemplateParameters(Ctx, 04912 cast<AtomicType>(T)->getValueType(), 04913 OnlyDeduced, Depth, Used); 04914 break; 04915 04916 case Type::DependentName: 04917 if (!OnlyDeduced) 04918 MarkUsedTemplateParameters(Ctx, 04919 cast<DependentNameType>(T)->getQualifier(), 04920 OnlyDeduced, Depth, Used); 04921 break; 04922 04923 case Type::DependentTemplateSpecialization: { 04924 const DependentTemplateSpecializationType *Spec 04925 = cast<DependentTemplateSpecializationType>(T); 04926 if (!OnlyDeduced) 04927 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(), 04928 OnlyDeduced, Depth, Used); 04929 04930 // C++0x [temp.deduct.type]p9: 04931 // If the template argument list of P contains a pack expansion that is not 04932 // the last template argument, the entire template argument list is a 04933 // non-deduced context. 04934 if (OnlyDeduced && 04935 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs())) 04936 break; 04937 04938 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 04939 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 04940 Used); 04941 break; 04942 } 04943 04944 case Type::TypeOf: 04945 if (!OnlyDeduced) 04946 MarkUsedTemplateParameters(Ctx, 04947 cast<TypeOfType>(T)->getUnderlyingType(), 04948 OnlyDeduced, Depth, Used); 04949 break; 04950 04951 case Type::TypeOfExpr: 04952 if (!OnlyDeduced) 04953 MarkUsedTemplateParameters(Ctx, 04954 cast<TypeOfExprType>(T)->getUnderlyingExpr(), 04955 OnlyDeduced, Depth, Used); 04956 break; 04957 04958 case Type::Decltype: 04959 if (!OnlyDeduced) 04960 MarkUsedTemplateParameters(Ctx, 04961 cast<DecltypeType>(T)->getUnderlyingExpr(), 04962 OnlyDeduced, Depth, Used); 04963 break; 04964 04965 case Type::UnaryTransform: 04966 if (!OnlyDeduced) 04967 MarkUsedTemplateParameters(Ctx, 04968 cast<UnaryTransformType>(T)->getUnderlyingType(), 04969 OnlyDeduced, Depth, Used); 04970 break; 04971 04972 case Type::PackExpansion: 04973 MarkUsedTemplateParameters(Ctx, 04974 cast<PackExpansionType>(T)->getPattern(), 04975 OnlyDeduced, Depth, Used); 04976 break; 04977 04978 case Type::Auto: 04979 MarkUsedTemplateParameters(Ctx, 04980 cast<AutoType>(T)->getDeducedType(), 04981 OnlyDeduced, Depth, Used); 04982 04983 // None of these types have any template parameters in them. 04984 case Type::Builtin: 04985 case Type::VariableArray: 04986 case Type::FunctionNoProto: 04987 case Type::Record: 04988 case Type::Enum: 04989 case Type::ObjCInterface: 04990 case Type::ObjCObject: 04991 case Type::ObjCObjectPointer: 04992 case Type::UnresolvedUsing: 04993 #define TYPE(Class, Base) 04994 #define ABSTRACT_TYPE(Class, Base) 04995 #define DEPENDENT_TYPE(Class, Base) 04996 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 04997 #include "clang/AST/TypeNodes.def" 04998 break; 04999 } 05000 } 05001 05002 /// \brief Mark the template parameters that are used by this 05003 /// template argument. 05004 static void 05005 MarkUsedTemplateParameters(ASTContext &Ctx, 05006 const TemplateArgument &TemplateArg, 05007 bool OnlyDeduced, 05008 unsigned Depth, 05009 llvm::SmallBitVector &Used) { 05010 switch (TemplateArg.getKind()) { 05011 case TemplateArgument::Null: 05012 case TemplateArgument::Integral: 05013 case TemplateArgument::Declaration: 05014 break; 05015 05016 case TemplateArgument::NullPtr: 05017 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced, 05018 Depth, Used); 05019 break; 05020 05021 case TemplateArgument::Type: 05022 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced, 05023 Depth, Used); 05024 break; 05025 05026 case TemplateArgument::Template: 05027 case TemplateArgument::TemplateExpansion: 05028 MarkUsedTemplateParameters(Ctx, 05029 TemplateArg.getAsTemplateOrTemplatePattern(), 05030 OnlyDeduced, Depth, Used); 05031 break; 05032 05033 case TemplateArgument::Expression: 05034 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced, 05035 Depth, Used); 05036 break; 05037 05038 case TemplateArgument::Pack: 05039 for (const auto &P : TemplateArg.pack_elements()) 05040 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used); 05041 break; 05042 } 05043 } 05044 05045 /// \brief Mark which template parameters can be deduced from a given 05046 /// template argument list. 05047 /// 05048 /// \param TemplateArgs the template argument list from which template 05049 /// parameters will be deduced. 05050 /// 05051 /// \param Used a bit vector whose elements will be set to \c true 05052 /// to indicate when the corresponding template parameter will be 05053 /// deduced. 05054 void 05055 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 05056 bool OnlyDeduced, unsigned Depth, 05057 llvm::SmallBitVector &Used) { 05058 // C++0x [temp.deduct.type]p9: 05059 // If the template argument list of P contains a pack expansion that is not 05060 // the last template argument, the entire template argument list is a 05061 // non-deduced context. 05062 if (OnlyDeduced && 05063 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size())) 05064 return; 05065 05066 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 05067 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced, 05068 Depth, Used); 05069 } 05070 05071 /// \brief Marks all of the template parameters that will be deduced by a 05072 /// call to the given function template. 05073 void Sema::MarkDeducedTemplateParameters( 05074 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, 05075 llvm::SmallBitVector &Deduced) { 05076 TemplateParameterList *TemplateParams 05077 = FunctionTemplate->getTemplateParameters(); 05078 Deduced.clear(); 05079 Deduced.resize(TemplateParams->size()); 05080 05081 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 05082 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) 05083 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(), 05084 true, TemplateParams->getDepth(), Deduced); 05085 } 05086 05087 bool hasDeducibleTemplateParameters(Sema &S, 05088 FunctionTemplateDecl *FunctionTemplate, 05089 QualType T) { 05090 if (!T->isDependentType()) 05091 return false; 05092 05093 TemplateParameterList *TemplateParams 05094 = FunctionTemplate->getTemplateParameters(); 05095 llvm::SmallBitVector Deduced(TemplateParams->size()); 05096 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(), 05097 Deduced); 05098 05099 return Deduced.any(); 05100 }