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