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