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