]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/Sema/SemaTemplate.cpp
Merge ^/vendor/lvm-project/master up to its last change (upstream commit
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / Sema / SemaTemplate.cpp
1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
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 //  This file implements semantic analysis for C++ templates.
9 //===----------------------------------------------------------------------===//
10
11 #include "TreeTransform.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclFriend.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/AST/TypeVisitor.h"
20 #include "clang/Basic/Builtins.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/PartialDiagnostic.h"
23 #include "clang/Basic/Stack.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/Overload.h"
28 #include "clang/Sema/ParsedTemplate.h"
29 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/SemaInternal.h"
31 #include "clang/Sema/Template.h"
32 #include "clang/Sema/TemplateDeduction.h"
33 #include "llvm/ADT/SmallBitVector.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/StringExtras.h"
36
37 #include <iterator>
38 using namespace clang;
39 using namespace sema;
40
41 // Exported for use by Parser.
42 SourceRange
43 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
44                               unsigned N) {
45   if (!N) return SourceRange();
46   return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
47 }
48
49 /// \brief Determine whether the declaration found is acceptable as the name
50 /// of a template and, if so, return that template declaration. Otherwise,
51 /// returns null.
52 ///
53 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
54 /// is true. In all other cases it will return a TemplateDecl (or null).
55 NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
56                                        bool AllowFunctionTemplates,
57                                        bool AllowDependent) {
58   D = D->getUnderlyingDecl();
59
60   if (isa<TemplateDecl>(D)) {
61     if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
62       return nullptr;
63
64     return D;
65   }
66
67   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
68     // C++ [temp.local]p1:
69     //   Like normal (non-template) classes, class templates have an
70     //   injected-class-name (Clause 9). The injected-class-name
71     //   can be used with or without a template-argument-list. When
72     //   it is used without a template-argument-list, it is
73     //   equivalent to the injected-class-name followed by the
74     //   template-parameters of the class template enclosed in
75     //   <>. When it is used with a template-argument-list, it
76     //   refers to the specified class template specialization,
77     //   which could be the current specialization or another
78     //   specialization.
79     if (Record->isInjectedClassName()) {
80       Record = cast<CXXRecordDecl>(Record->getDeclContext());
81       if (Record->getDescribedClassTemplate())
82         return Record->getDescribedClassTemplate();
83
84       if (ClassTemplateSpecializationDecl *Spec
85             = dyn_cast<ClassTemplateSpecializationDecl>(Record))
86         return Spec->getSpecializedTemplate();
87     }
88
89     return nullptr;
90   }
91
92   // 'using Dependent::foo;' can resolve to a template name.
93   // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
94   // injected-class-name).
95   if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
96     return D;
97
98   return nullptr;
99 }
100
101 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
102                                          bool AllowFunctionTemplates,
103                                          bool AllowDependent) {
104   LookupResult::Filter filter = R.makeFilter();
105   while (filter.hasNext()) {
106     NamedDecl *Orig = filter.next();
107     if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
108       filter.erase();
109   }
110   filter.done();
111 }
112
113 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
114                                          bool AllowFunctionTemplates,
115                                          bool AllowDependent,
116                                          bool AllowNonTemplateFunctions) {
117   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
118     if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
119       return true;
120     if (AllowNonTemplateFunctions &&
121         isa<FunctionDecl>((*I)->getUnderlyingDecl()))
122       return true;
123   }
124
125   return false;
126 }
127
128 TemplateNameKind Sema::isTemplateName(Scope *S,
129                                       CXXScopeSpec &SS,
130                                       bool hasTemplateKeyword,
131                                       const UnqualifiedId &Name,
132                                       ParsedType ObjectTypePtr,
133                                       bool EnteringContext,
134                                       TemplateTy &TemplateResult,
135                                       bool &MemberOfUnknownSpecialization) {
136   assert(getLangOpts().CPlusPlus && "No template names in C!");
137
138   DeclarationName TName;
139   MemberOfUnknownSpecialization = false;
140
141   switch (Name.getKind()) {
142   case UnqualifiedIdKind::IK_Identifier:
143     TName = DeclarationName(Name.Identifier);
144     break;
145
146   case UnqualifiedIdKind::IK_OperatorFunctionId:
147     TName = Context.DeclarationNames.getCXXOperatorName(
148                                               Name.OperatorFunctionId.Operator);
149     break;
150
151   case UnqualifiedIdKind::IK_LiteralOperatorId:
152     TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
153     break;
154
155   default:
156     return TNK_Non_template;
157   }
158
159   QualType ObjectType = ObjectTypePtr.get();
160
161   AssumedTemplateKind AssumedTemplate;
162   LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
163   if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
164                          MemberOfUnknownSpecialization, SourceLocation(),
165                          &AssumedTemplate))
166     return TNK_Non_template;
167
168   if (AssumedTemplate != AssumedTemplateKind::None) {
169     TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
170     // Let the parser know whether we found nothing or found functions; if we
171     // found nothing, we want to more carefully check whether this is actually
172     // a function template name versus some other kind of undeclared identifier.
173     return AssumedTemplate == AssumedTemplateKind::FoundNothing
174                ? TNK_Undeclared_template
175                : TNK_Function_template;
176   }
177
178   if (R.empty())
179     return TNK_Non_template;
180
181   NamedDecl *D = nullptr;
182   if (R.isAmbiguous()) {
183     // If we got an ambiguity involving a non-function template, treat this
184     // as a template name, and pick an arbitrary template for error recovery.
185     bool AnyFunctionTemplates = false;
186     for (NamedDecl *FoundD : R) {
187       if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
188         if (isa<FunctionTemplateDecl>(FoundTemplate))
189           AnyFunctionTemplates = true;
190         else {
191           D = FoundTemplate;
192           break;
193         }
194       }
195     }
196
197     // If we didn't find any templates at all, this isn't a template name.
198     // Leave the ambiguity for a later lookup to diagnose.
199     if (!D && !AnyFunctionTemplates) {
200       R.suppressDiagnostics();
201       return TNK_Non_template;
202     }
203
204     // If the only templates were function templates, filter out the rest.
205     // We'll diagnose the ambiguity later.
206     if (!D)
207       FilterAcceptableTemplateNames(R);
208   }
209
210   // At this point, we have either picked a single template name declaration D
211   // or we have a non-empty set of results R containing either one template name
212   // declaration or a set of function templates.
213
214   TemplateName Template;
215   TemplateNameKind TemplateKind;
216
217   unsigned ResultCount = R.end() - R.begin();
218   if (!D && ResultCount > 1) {
219     // We assume that we'll preserve the qualifier from a function
220     // template name in other ways.
221     Template = Context.getOverloadedTemplateName(R.begin(), R.end());
222     TemplateKind = TNK_Function_template;
223
224     // We'll do this lookup again later.
225     R.suppressDiagnostics();
226   } else {
227     if (!D) {
228       D = getAsTemplateNameDecl(*R.begin());
229       assert(D && "unambiguous result is not a template name");
230     }
231
232     if (isa<UnresolvedUsingValueDecl>(D)) {
233       // We don't yet know whether this is a template-name or not.
234       MemberOfUnknownSpecialization = true;
235       return TNK_Non_template;
236     }
237
238     TemplateDecl *TD = cast<TemplateDecl>(D);
239
240     if (SS.isSet() && !SS.isInvalid()) {
241       NestedNameSpecifier *Qualifier = SS.getScopeRep();
242       Template = Context.getQualifiedTemplateName(Qualifier,
243                                                   hasTemplateKeyword, TD);
244     } else {
245       Template = TemplateName(TD);
246     }
247
248     if (isa<FunctionTemplateDecl>(TD)) {
249       TemplateKind = TNK_Function_template;
250
251       // We'll do this lookup again later.
252       R.suppressDiagnostics();
253     } else {
254       assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
255              isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
256              isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
257       TemplateKind =
258           isa<VarTemplateDecl>(TD) ? TNK_Var_template :
259           isa<ConceptDecl>(TD) ? TNK_Concept_template :
260           TNK_Type_template;
261     }
262   }
263
264   TemplateResult = TemplateTy::make(Template);
265   return TemplateKind;
266 }
267
268 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
269                                 SourceLocation NameLoc,
270                                 ParsedTemplateTy *Template) {
271   CXXScopeSpec SS;
272   bool MemberOfUnknownSpecialization = false;
273
274   // We could use redeclaration lookup here, but we don't need to: the
275   // syntactic form of a deduction guide is enough to identify it even
276   // if we can't look up the template name at all.
277   LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
278   if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
279                          /*EnteringContext*/ false,
280                          MemberOfUnknownSpecialization))
281     return false;
282
283   if (R.empty()) return false;
284   if (R.isAmbiguous()) {
285     // FIXME: Diagnose an ambiguity if we find at least one template.
286     R.suppressDiagnostics();
287     return false;
288   }
289
290   // We only treat template-names that name type templates as valid deduction
291   // guide names.
292   TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
293   if (!TD || !getAsTypeTemplateDecl(TD))
294     return false;
295
296   if (Template)
297     *Template = TemplateTy::make(TemplateName(TD));
298   return true;
299 }
300
301 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
302                                        SourceLocation IILoc,
303                                        Scope *S,
304                                        const CXXScopeSpec *SS,
305                                        TemplateTy &SuggestedTemplate,
306                                        TemplateNameKind &SuggestedKind) {
307   // We can't recover unless there's a dependent scope specifier preceding the
308   // template name.
309   // FIXME: Typo correction?
310   if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
311       computeDeclContext(*SS))
312     return false;
313
314   // The code is missing a 'template' keyword prior to the dependent template
315   // name.
316   NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
317   Diag(IILoc, diag::err_template_kw_missing)
318     << Qualifier << II.getName()
319     << FixItHint::CreateInsertion(IILoc, "template ");
320   SuggestedTemplate
321     = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
322   SuggestedKind = TNK_Dependent_template_name;
323   return true;
324 }
325
326 bool Sema::LookupTemplateName(LookupResult &Found,
327                               Scope *S, CXXScopeSpec &SS,
328                               QualType ObjectType,
329                               bool EnteringContext,
330                               bool &MemberOfUnknownSpecialization,
331                               SourceLocation TemplateKWLoc,
332                               AssumedTemplateKind *ATK) {
333   if (ATK)
334     *ATK = AssumedTemplateKind::None;
335
336   Found.setTemplateNameLookup(true);
337
338   // Determine where to perform name lookup
339   MemberOfUnknownSpecialization = false;
340   DeclContext *LookupCtx = nullptr;
341   bool IsDependent = false;
342   if (!ObjectType.isNull()) {
343     // This nested-name-specifier occurs in a member access expression, e.g.,
344     // x->B::f, and we are looking into the type of the object.
345     assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
346     LookupCtx = computeDeclContext(ObjectType);
347     IsDependent = !LookupCtx && ObjectType->isDependentType();
348     assert((IsDependent || !ObjectType->isIncompleteType() ||
349             ObjectType->castAs<TagType>()->isBeingDefined()) &&
350            "Caller should have completed object type");
351
352     // Template names cannot appear inside an Objective-C class or object type
353     // or a vector type.
354     //
355     // FIXME: This is wrong. For example:
356     //
357     //   template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
358     //   Vec<int> vi;
359     //   vi.Vec<int>::~Vec<int>();
360     //
361     // ... should be accepted but we will not treat 'Vec' as a template name
362     // here. The right thing to do would be to check if the name is a valid
363     // vector component name, and look up a template name if not. And similarly
364     // for lookups into Objective-C class and object types, where the same
365     // problem can arise.
366     if (ObjectType->isObjCObjectOrInterfaceType() ||
367         ObjectType->isVectorType()) {
368       Found.clear();
369       return false;
370     }
371   } else if (SS.isSet()) {
372     // This nested-name-specifier occurs after another nested-name-specifier,
373     // so long into the context associated with the prior nested-name-specifier.
374     LookupCtx = computeDeclContext(SS, EnteringContext);
375     IsDependent = !LookupCtx;
376
377     // The declaration context must be complete.
378     if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
379       return true;
380   }
381
382   bool ObjectTypeSearchedInScope = false;
383   bool AllowFunctionTemplatesInLookup = true;
384   if (LookupCtx) {
385     // Perform "qualified" name lookup into the declaration context we
386     // computed, which is either the type of the base of a member access
387     // expression or the declaration context associated with a prior
388     // nested-name-specifier.
389     LookupQualifiedName(Found, LookupCtx);
390
391     // FIXME: The C++ standard does not clearly specify what happens in the
392     // case where the object type is dependent, and implementations vary. In
393     // Clang, we treat a name after a . or -> as a template-name if lookup
394     // finds a non-dependent member or member of the current instantiation that
395     // is a type template, or finds no such members and lookup in the context
396     // of the postfix-expression finds a type template. In the latter case, the
397     // name is nonetheless dependent, and we may resolve it to a member of an
398     // unknown specialization when we come to instantiate the template.
399     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
400   }
401
402   if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
403     // C++ [basic.lookup.classref]p1:
404     //   In a class member access expression (5.2.5), if the . or -> token is
405     //   immediately followed by an identifier followed by a <, the
406     //   identifier must be looked up to determine whether the < is the
407     //   beginning of a template argument list (14.2) or a less-than operator.
408     //   The identifier is first looked up in the class of the object
409     //   expression. If the identifier is not found, it is then looked up in
410     //   the context of the entire postfix-expression and shall name a class
411     //   template.
412     if (S)
413       LookupName(Found, S);
414
415     if (!ObjectType.isNull()) {
416       //  FIXME: We should filter out all non-type templates here, particularly
417       //  variable templates and concepts. But the exclusion of alias templates
418       //  and template template parameters is a wording defect.
419       AllowFunctionTemplatesInLookup = false;
420       ObjectTypeSearchedInScope = true;
421     }
422
423     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
424   }
425
426   if (Found.isAmbiguous())
427     return false;
428
429   if (ATK && !SS.isSet() && ObjectType.isNull() && TemplateKWLoc.isInvalid()) {
430     // C++2a [temp.names]p2:
431     //   A name is also considered to refer to a template if it is an
432     //   unqualified-id followed by a < and name lookup finds either one or more
433     //   functions or finds nothing.
434     //
435     // To keep our behavior consistent, we apply the "finds nothing" part in
436     // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
437     // successfully form a call to an undeclared template-id.
438     bool AllFunctions =
439         getLangOpts().CPlusPlus2a &&
440         std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
441           return isa<FunctionDecl>(ND->getUnderlyingDecl());
442         });
443     if (AllFunctions || (Found.empty() && !IsDependent)) {
444       // If lookup found any functions, or if this is a name that can only be
445       // used for a function, then strongly assume this is a function
446       // template-id.
447       *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
448                  ? AssumedTemplateKind::FoundNothing
449                  : AssumedTemplateKind::FoundFunctions;
450       Found.clear();
451       return false;
452     }
453   }
454
455   if (Found.empty() && !IsDependent) {
456     // If we did not find any names, attempt to correct any typos.
457     DeclarationName Name = Found.getLookupName();
458     Found.clear();
459     // Simple filter callback that, for keywords, only accepts the C++ *_cast
460     DefaultFilterCCC FilterCCC{};
461     FilterCCC.WantTypeSpecifiers = false;
462     FilterCCC.WantExpressionKeywords = false;
463     FilterCCC.WantRemainingKeywords = false;
464     FilterCCC.WantCXXNamedCasts = true;
465     if (TypoCorrection Corrected =
466             CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
467                         &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
468       if (auto *ND = Corrected.getFoundDecl())
469         Found.addDecl(ND);
470       FilterAcceptableTemplateNames(Found);
471       if (Found.isAmbiguous()) {
472         Found.clear();
473       } else if (!Found.empty()) {
474         Found.setLookupName(Corrected.getCorrection());
475         if (LookupCtx) {
476           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
477           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
478                                   Name.getAsString() == CorrectedStr;
479           diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
480                                     << Name << LookupCtx << DroppedSpecifier
481                                     << SS.getRange());
482         } else {
483           diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
484         }
485       }
486     }
487   }
488
489   NamedDecl *ExampleLookupResult =
490       Found.empty() ? nullptr : Found.getRepresentativeDecl();
491   FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
492   if (Found.empty()) {
493     if (IsDependent) {
494       MemberOfUnknownSpecialization = true;
495       return false;
496     }
497
498     // If a 'template' keyword was used, a lookup that finds only non-template
499     // names is an error.
500     if (ExampleLookupResult && TemplateKWLoc.isValid()) {
501       Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
502         << Found.getLookupName() << SS.getRange();
503       Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
504            diag::note_template_kw_refers_to_non_template)
505           << Found.getLookupName();
506       return true;
507     }
508
509     return false;
510   }
511
512   if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
513       !getLangOpts().CPlusPlus11) {
514     // C++03 [basic.lookup.classref]p1:
515     //   [...] If the lookup in the class of the object expression finds a
516     //   template, the name is also looked up in the context of the entire
517     //   postfix-expression and [...]
518     //
519     // Note: C++11 does not perform this second lookup.
520     LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
521                             LookupOrdinaryName);
522     FoundOuter.setTemplateNameLookup(true);
523     LookupName(FoundOuter, S);
524     // FIXME: We silently accept an ambiguous lookup here, in violation of
525     // [basic.lookup]/1.
526     FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
527
528     NamedDecl *OuterTemplate;
529     if (FoundOuter.empty()) {
530       //   - if the name is not found, the name found in the class of the
531       //     object expression is used, otherwise
532     } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
533                !(OuterTemplate =
534                      getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
535       //   - if the name is found in the context of the entire
536       //     postfix-expression and does not name a class template, the name
537       //     found in the class of the object expression is used, otherwise
538       FoundOuter.clear();
539     } else if (!Found.isSuppressingDiagnostics()) {
540       //   - if the name found is a class template, it must refer to the same
541       //     entity as the one found in the class of the object expression,
542       //     otherwise the program is ill-formed.
543       if (!Found.isSingleResult() ||
544           getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
545               OuterTemplate->getCanonicalDecl()) {
546         Diag(Found.getNameLoc(),
547              diag::ext_nested_name_member_ref_lookup_ambiguous)
548           << Found.getLookupName()
549           << ObjectType;
550         Diag(Found.getRepresentativeDecl()->getLocation(),
551              diag::note_ambig_member_ref_object_type)
552           << ObjectType;
553         Diag(FoundOuter.getFoundDecl()->getLocation(),
554              diag::note_ambig_member_ref_scope);
555
556         // Recover by taking the template that we found in the object
557         // expression's type.
558       }
559     }
560   }
561
562   return false;
563 }
564
565 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
566                                               SourceLocation Less,
567                                               SourceLocation Greater) {
568   if (TemplateName.isInvalid())
569     return;
570
571   DeclarationNameInfo NameInfo;
572   CXXScopeSpec SS;
573   LookupNameKind LookupKind;
574
575   DeclContext *LookupCtx = nullptr;
576   NamedDecl *Found = nullptr;
577   bool MissingTemplateKeyword = false;
578
579   // Figure out what name we looked up.
580   if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
581     NameInfo = DRE->getNameInfo();
582     SS.Adopt(DRE->getQualifierLoc());
583     LookupKind = LookupOrdinaryName;
584     Found = DRE->getFoundDecl();
585   } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
586     NameInfo = ME->getMemberNameInfo();
587     SS.Adopt(ME->getQualifierLoc());
588     LookupKind = LookupMemberName;
589     LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
590     Found = ME->getMemberDecl();
591   } else if (auto *DSDRE =
592                  dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
593     NameInfo = DSDRE->getNameInfo();
594     SS.Adopt(DSDRE->getQualifierLoc());
595     MissingTemplateKeyword = true;
596   } else if (auto *DSME =
597                  dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
598     NameInfo = DSME->getMemberNameInfo();
599     SS.Adopt(DSME->getQualifierLoc());
600     MissingTemplateKeyword = true;
601   } else {
602     llvm_unreachable("unexpected kind of potential template name");
603   }
604
605   // If this is a dependent-scope lookup, diagnose that the 'template' keyword
606   // was missing.
607   if (MissingTemplateKeyword) {
608     Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
609         << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
610     return;
611   }
612
613   // Try to correct the name by looking for templates and C++ named casts.
614   struct TemplateCandidateFilter : CorrectionCandidateCallback {
615     Sema &S;
616     TemplateCandidateFilter(Sema &S) : S(S) {
617       WantTypeSpecifiers = false;
618       WantExpressionKeywords = false;
619       WantRemainingKeywords = false;
620       WantCXXNamedCasts = true;
621     };
622     bool ValidateCandidate(const TypoCorrection &Candidate) override {
623       if (auto *ND = Candidate.getCorrectionDecl())
624         return S.getAsTemplateNameDecl(ND);
625       return Candidate.isKeyword();
626     }
627
628     std::unique_ptr<CorrectionCandidateCallback> clone() override {
629       return std::make_unique<TemplateCandidateFilter>(*this);
630     }
631   };
632
633   DeclarationName Name = NameInfo.getName();
634   TemplateCandidateFilter CCC(*this);
635   if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
636                                              CTK_ErrorRecovery, LookupCtx)) {
637     auto *ND = Corrected.getFoundDecl();
638     if (ND)
639       ND = getAsTemplateNameDecl(ND);
640     if (ND || Corrected.isKeyword()) {
641       if (LookupCtx) {
642         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
643         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
644                                 Name.getAsString() == CorrectedStr;
645         diagnoseTypo(Corrected,
646                      PDiag(diag::err_non_template_in_member_template_id_suggest)
647                          << Name << LookupCtx << DroppedSpecifier
648                          << SS.getRange(), false);
649       } else {
650         diagnoseTypo(Corrected,
651                      PDiag(diag::err_non_template_in_template_id_suggest)
652                          << Name, false);
653       }
654       if (Found)
655         Diag(Found->getLocation(),
656              diag::note_non_template_in_template_id_found);
657       return;
658     }
659   }
660
661   Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
662     << Name << SourceRange(Less, Greater);
663   if (Found)
664     Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
665 }
666
667 /// ActOnDependentIdExpression - Handle a dependent id-expression that
668 /// was just parsed.  This is only possible with an explicit scope
669 /// specifier naming a dependent type.
670 ExprResult
671 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
672                                  SourceLocation TemplateKWLoc,
673                                  const DeclarationNameInfo &NameInfo,
674                                  bool isAddressOfOperand,
675                            const TemplateArgumentListInfo *TemplateArgs) {
676   DeclContext *DC = getFunctionLevelDeclContext();
677
678   // C++11 [expr.prim.general]p12:
679   //   An id-expression that denotes a non-static data member or non-static
680   //   member function of a class can only be used:
681   //   (...)
682   //   - if that id-expression denotes a non-static data member and it
683   //     appears in an unevaluated operand.
684   //
685   // If this might be the case, form a DependentScopeDeclRefExpr instead of a
686   // CXXDependentScopeMemberExpr. The former can instantiate to either
687   // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
688   // always a MemberExpr.
689   bool MightBeCxx11UnevalField =
690       getLangOpts().CPlusPlus11 && isUnevaluatedContext();
691
692   // Check if the nested name specifier is an enum type.
693   bool IsEnum = false;
694   if (NestedNameSpecifier *NNS = SS.getScopeRep())
695     IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
696
697   if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
698       isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
699     QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
700
701     // Since the 'this' expression is synthesized, we don't need to
702     // perform the double-lookup check.
703     NamedDecl *FirstQualifierInScope = nullptr;
704
705     return CXXDependentScopeMemberExpr::Create(
706         Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
707         /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
708         FirstQualifierInScope, NameInfo, TemplateArgs);
709   }
710
711   return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
712 }
713
714 ExprResult
715 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
716                                 SourceLocation TemplateKWLoc,
717                                 const DeclarationNameInfo &NameInfo,
718                                 const TemplateArgumentListInfo *TemplateArgs) {
719   // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
720   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
721   if (!QualifierLoc)
722     return ExprError();
723
724   return DependentScopeDeclRefExpr::Create(
725       Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
726 }
727
728
729 /// Determine whether we would be unable to instantiate this template (because
730 /// it either has no definition, or is in the process of being instantiated).
731 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
732                                           NamedDecl *Instantiation,
733                                           bool InstantiatedFromMember,
734                                           const NamedDecl *Pattern,
735                                           const NamedDecl *PatternDef,
736                                           TemplateSpecializationKind TSK,
737                                           bool Complain /*= true*/) {
738   assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
739          isa<VarDecl>(Instantiation));
740
741   bool IsEntityBeingDefined = false;
742   if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
743     IsEntityBeingDefined = TD->isBeingDefined();
744
745   if (PatternDef && !IsEntityBeingDefined) {
746     NamedDecl *SuggestedDef = nullptr;
747     if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
748                               /*OnlyNeedComplete*/false)) {
749       // If we're allowed to diagnose this and recover, do so.
750       bool Recover = Complain && !isSFINAEContext();
751       if (Complain)
752         diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
753                               Sema::MissingImportKind::Definition, Recover);
754       return !Recover;
755     }
756     return false;
757   }
758
759   if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
760     return true;
761
762   llvm::Optional<unsigned> Note;
763   QualType InstantiationTy;
764   if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
765     InstantiationTy = Context.getTypeDeclType(TD);
766   if (PatternDef) {
767     Diag(PointOfInstantiation,
768          diag::err_template_instantiate_within_definition)
769       << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
770       << InstantiationTy;
771     // Not much point in noting the template declaration here, since
772     // we're lexically inside it.
773     Instantiation->setInvalidDecl();
774   } else if (InstantiatedFromMember) {
775     if (isa<FunctionDecl>(Instantiation)) {
776       Diag(PointOfInstantiation,
777            diag::err_explicit_instantiation_undefined_member)
778         << /*member function*/ 1 << Instantiation->getDeclName()
779         << Instantiation->getDeclContext();
780       Note = diag::note_explicit_instantiation_here;
781     } else {
782       assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
783       Diag(PointOfInstantiation,
784            diag::err_implicit_instantiate_member_undefined)
785         << InstantiationTy;
786       Note = diag::note_member_declared_at;
787     }
788   } else {
789     if (isa<FunctionDecl>(Instantiation)) {
790       Diag(PointOfInstantiation,
791            diag::err_explicit_instantiation_undefined_func_template)
792         << Pattern;
793       Note = diag::note_explicit_instantiation_here;
794     } else if (isa<TagDecl>(Instantiation)) {
795       Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
796         << (TSK != TSK_ImplicitInstantiation)
797         << InstantiationTy;
798       Note = diag::note_template_decl_here;
799     } else {
800       assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
801       if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
802         Diag(PointOfInstantiation,
803              diag::err_explicit_instantiation_undefined_var_template)
804           << Instantiation;
805         Instantiation->setInvalidDecl();
806       } else
807         Diag(PointOfInstantiation,
808              diag::err_explicit_instantiation_undefined_member)
809           << /*static data member*/ 2 << Instantiation->getDeclName()
810           << Instantiation->getDeclContext();
811       Note = diag::note_explicit_instantiation_here;
812     }
813   }
814   if (Note) // Diagnostics were emitted.
815     Diag(Pattern->getLocation(), Note.getValue());
816
817   // In general, Instantiation isn't marked invalid to get more than one
818   // error for multiple undefined instantiations. But the code that does
819   // explicit declaration -> explicit definition conversion can't handle
820   // invalid declarations, so mark as invalid in that case.
821   if (TSK == TSK_ExplicitInstantiationDeclaration)
822     Instantiation->setInvalidDecl();
823   return true;
824 }
825
826 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
827 /// that the template parameter 'PrevDecl' is being shadowed by a new
828 /// declaration at location Loc. Returns true to indicate that this is
829 /// an error, and false otherwise.
830 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
831   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
832
833   // C++ [temp.local]p4:
834   //   A template-parameter shall not be redeclared within its
835   //   scope (including nested scopes).
836   //
837   // Make this a warning when MSVC compatibility is requested.
838   unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
839                                              : diag::err_template_param_shadow;
840   Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
841   Diag(PrevDecl->getLocation(), diag::note_template_param_here);
842 }
843
844 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
845 /// the parameter D to reference the templated declaration and return a pointer
846 /// to the template declaration. Otherwise, do nothing to D and return null.
847 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
848   if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
849     D = Temp->getTemplatedDecl();
850     return Temp;
851   }
852   return nullptr;
853 }
854
855 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
856                                              SourceLocation EllipsisLoc) const {
857   assert(Kind == Template &&
858          "Only template template arguments can be pack expansions here");
859   assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
860          "Template template argument pack expansion without packs");
861   ParsedTemplateArgument Result(*this);
862   Result.EllipsisLoc = EllipsisLoc;
863   return Result;
864 }
865
866 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
867                                             const ParsedTemplateArgument &Arg) {
868
869   switch (Arg.getKind()) {
870   case ParsedTemplateArgument::Type: {
871     TypeSourceInfo *DI;
872     QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
873     if (!DI)
874       DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
875     return TemplateArgumentLoc(TemplateArgument(T), DI);
876   }
877
878   case ParsedTemplateArgument::NonType: {
879     Expr *E = static_cast<Expr *>(Arg.getAsExpr());
880     return TemplateArgumentLoc(TemplateArgument(E), E);
881   }
882
883   case ParsedTemplateArgument::Template: {
884     TemplateName Template = Arg.getAsTemplate().get();
885     TemplateArgument TArg;
886     if (Arg.getEllipsisLoc().isValid())
887       TArg = TemplateArgument(Template, Optional<unsigned int>());
888     else
889       TArg = Template;
890     return TemplateArgumentLoc(TArg,
891                                Arg.getScopeSpec().getWithLocInContext(
892                                                               SemaRef.Context),
893                                Arg.getLocation(),
894                                Arg.getEllipsisLoc());
895   }
896   }
897
898   llvm_unreachable("Unhandled parsed template argument");
899 }
900
901 /// Translates template arguments as provided by the parser
902 /// into template arguments used by semantic analysis.
903 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
904                                       TemplateArgumentListInfo &TemplateArgs) {
905  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
906    TemplateArgs.addArgument(translateTemplateArgument(*this,
907                                                       TemplateArgsIn[I]));
908 }
909
910 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
911                                                  SourceLocation Loc,
912                                                  IdentifierInfo *Name) {
913   NamedDecl *PrevDecl = SemaRef.LookupSingleName(
914       S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
915   if (PrevDecl && PrevDecl->isTemplateParameter())
916     SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
917 }
918
919 /// Convert a parsed type into a parsed template argument. This is mostly
920 /// trivial, except that we may have parsed a C++17 deduced class template
921 /// specialization type, in which case we should form a template template
922 /// argument instead of a type template argument.
923 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
924   TypeSourceInfo *TInfo;
925   QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
926   if (T.isNull())
927     return ParsedTemplateArgument();
928   assert(TInfo && "template argument with no location");
929
930   // If we might have formed a deduced template specialization type, convert
931   // it to a template template argument.
932   if (getLangOpts().CPlusPlus17) {
933     TypeLoc TL = TInfo->getTypeLoc();
934     SourceLocation EllipsisLoc;
935     if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
936       EllipsisLoc = PET.getEllipsisLoc();
937       TL = PET.getPatternLoc();
938     }
939
940     CXXScopeSpec SS;
941     if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
942       SS.Adopt(ET.getQualifierLoc());
943       TL = ET.getNamedTypeLoc();
944     }
945
946     if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
947       TemplateName Name = DTST.getTypePtr()->getTemplateName();
948       if (SS.isSet())
949         Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
950                                                 /*HasTemplateKeyword*/ false,
951                                                 Name.getAsTemplateDecl());
952       ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
953                                     DTST.getTemplateNameLoc());
954       if (EllipsisLoc.isValid())
955         Result = Result.getTemplatePackExpansion(EllipsisLoc);
956       return Result;
957     }
958   }
959
960   // This is a normal type template argument. Note, if the type template
961   // argument is an injected-class-name for a template, it has a dual nature
962   // and can be used as either a type or a template. We handle that in
963   // convertTypeTemplateArgumentToTemplate.
964   return ParsedTemplateArgument(ParsedTemplateArgument::Type,
965                                 ParsedType.get().getAsOpaquePtr(),
966                                 TInfo->getTypeLoc().getBeginLoc());
967 }
968
969 /// ActOnTypeParameter - Called when a C++ template type parameter
970 /// (e.g., "typename T") has been parsed. Typename specifies whether
971 /// the keyword "typename" was used to declare the type parameter
972 /// (otherwise, "class" was used), and KeyLoc is the location of the
973 /// "class" or "typename" keyword. ParamName is the name of the
974 /// parameter (NULL indicates an unnamed template parameter) and
975 /// ParamNameLoc is the location of the parameter name (if any).
976 /// If the type parameter has a default argument, it will be added
977 /// later via ActOnTypeParameterDefault.
978 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
979                                     SourceLocation EllipsisLoc,
980                                     SourceLocation KeyLoc,
981                                     IdentifierInfo *ParamName,
982                                     SourceLocation ParamNameLoc,
983                                     unsigned Depth, unsigned Position,
984                                     SourceLocation EqualLoc,
985                                     ParsedType DefaultArg,
986                                     bool HasTypeConstraint) {
987   assert(S->isTemplateParamScope() &&
988          "Template type parameter not in template parameter scope!");
989
990   bool IsParameterPack = EllipsisLoc.isValid();
991   TemplateTypeParmDecl *Param
992     = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
993                                    KeyLoc, ParamNameLoc, Depth, Position,
994                                    ParamName, Typename, IsParameterPack,
995                                    HasTypeConstraint);
996   Param->setAccess(AS_public);
997
998   if (Param->isParameterPack())
999     if (auto *LSI = getEnclosingLambda())
1000       LSI->LocalPacks.push_back(Param);
1001
1002   if (ParamName) {
1003     maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1004
1005     // Add the template parameter into the current scope.
1006     S->AddDecl(Param);
1007     IdResolver.AddDecl(Param);
1008   }
1009
1010   // C++0x [temp.param]p9:
1011   //   A default template-argument may be specified for any kind of
1012   //   template-parameter that is not a template parameter pack.
1013   if (DefaultArg && IsParameterPack) {
1014     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1015     DefaultArg = nullptr;
1016   }
1017
1018   // Handle the default argument, if provided.
1019   if (DefaultArg) {
1020     TypeSourceInfo *DefaultTInfo;
1021     GetTypeFromParser(DefaultArg, &DefaultTInfo);
1022
1023     assert(DefaultTInfo && "expected source information for type");
1024
1025     // Check for unexpanded parameter packs.
1026     if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1027                                         UPPC_DefaultArgument))
1028       return Param;
1029
1030     // Check the template argument itself.
1031     if (CheckTemplateArgument(Param, DefaultTInfo)) {
1032       Param->setInvalidDecl();
1033       return Param;
1034     }
1035
1036     Param->setDefaultArgument(DefaultTInfo);
1037   }
1038
1039   return Param;
1040 }
1041
1042 /// Convert the parser's template argument list representation into our form.
1043 static TemplateArgumentListInfo
1044 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1045   TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1046                                         TemplateId.RAngleLoc);
1047   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1048                                      TemplateId.NumArgs);
1049   S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1050   return TemplateArgs;
1051 }
1052
1053 bool Sema::ActOnTypeConstraint(TemplateIdAnnotation *TypeConstr,
1054                                TemplateTypeParmDecl *ConstrainedParameter,
1055                                SourceLocation EllipsisLoc) {
1056   ConceptDecl *CD =
1057       cast<ConceptDecl>(TypeConstr->Template.get().getAsTemplateDecl());
1058
1059   // C++2a [temp.param]p4:
1060   //     [...] The concept designated by a type-constraint shall be a type
1061   //     concept ([temp.concept]).
1062   if (!CD->isTypeConcept()) {
1063     Diag(TypeConstr->TemplateNameLoc,
1064          diag::err_type_constraint_non_type_concept);
1065     return true;
1066   }
1067
1068   bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1069
1070   if (!WereArgsSpecified &&
1071       CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1072     Diag(TypeConstr->TemplateNameLoc,
1073          diag::err_type_constraint_missing_arguments) << CD;
1074     return true;
1075   }
1076
1077   TemplateArgumentListInfo TemplateArgs;
1078   if (TypeConstr->LAngleLoc.isValid()) {
1079     TemplateArgs =
1080         makeTemplateArgumentListInfo(*this, *TypeConstr);
1081   }
1082   return AttachTypeConstraint(
1083       TypeConstr->SS.isSet() ? TypeConstr->SS.getWithLocInContext(Context) :
1084       NestedNameSpecifierLoc(),
1085       DeclarationNameInfo(DeclarationName(TypeConstr->Name),
1086                           TypeConstr->TemplateNameLoc), CD,
1087       TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1088       ConstrainedParameter, EllipsisLoc);
1089 }
1090
1091 /// Attach a type-constraint to a template parameter.
1092 /// \returns true if an error occured. This can happen if the
1093 /// immediately-declared constraint could not be formed (e.g. incorrect number
1094 /// of arguments for the named concept).
1095 bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1096                                 DeclarationNameInfo NameInfo,
1097                                 ConceptDecl *NamedConcept,
1098                                 const TemplateArgumentListInfo *TemplateArgs,
1099                                 TemplateTypeParmDecl *ConstrainedParameter,
1100                                 SourceLocation EllipsisLoc) {
1101   // C++2a [temp.param]p4:
1102   //     [...] If Q is of the form C<A1, ..., An>, then let E' be
1103   //     C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1104   const ASTTemplateArgumentListInfo *ArgsAsWritten =
1105     TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1106                                                        *TemplateArgs) : nullptr;
1107
1108   QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1109   TemplateArgumentListInfo ConstraintArgs;
1110   ConstraintArgs.addArgument(
1111     TemplateArgumentLoc(
1112         TemplateArgument(ParamAsArgument),
1113         TemplateArgumentLocInfo(
1114             Context.getTrivialTypeSourceInfo(ParamAsArgument,
1115                 ConstrainedParameter->getLocation()))));
1116   if (TemplateArgs) {
1117     ConstraintArgs.setRAngleLoc(TemplateArgs->getRAngleLoc());
1118     ConstraintArgs.setLAngleLoc(TemplateArgs->getLAngleLoc());
1119     for (const TemplateArgumentLoc &ArgLoc : TemplateArgs->arguments())
1120       ConstraintArgs.addArgument(ArgLoc);
1121   }
1122
1123   // C++2a [temp.param]p4:
1124   //     [...] This constraint-expression E is called the immediately-declared
1125   //     constraint of T. [...]
1126   CXXScopeSpec SS;
1127   SS.Adopt(NS);
1128   ExprResult ImmediatelyDeclaredConstraint = CheckConceptTemplateId(SS,
1129       /*TemplateKWLoc=*/SourceLocation(), NameInfo, /*FoundDecl=*/NamedConcept,
1130       NamedConcept, &ConstraintArgs);
1131   if (ImmediatelyDeclaredConstraint.isInvalid())
1132     return true;
1133
1134   if (ConstrainedParameter->isParameterPack()) {
1135     // C++2a [temp.param]p4:
1136     //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1137     //
1138     // We have the following case:
1139     //
1140     // template<typename T> concept C1 = true;
1141     // template<C1... T> struct s1;
1142     //
1143     // The constraint: (C1<T> && ...)
1144     ImmediatelyDeclaredConstraint =
1145         BuildCXXFoldExpr(/*LParenLoc=*/SourceLocation(),
1146                          ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1147                          EllipsisLoc, /*RHS=*/nullptr,
1148                          /*RParenLoc=*/SourceLocation(),
1149                          /*NumExpansions=*/None).get();
1150     if (ImmediatelyDeclaredConstraint.isInvalid())
1151       return true;
1152   }
1153
1154   ConstrainedParameter->setTypeConstraint(NS, NameInfo,
1155                                           /*FoundDecl=*/NamedConcept,
1156                                           NamedConcept, ArgsAsWritten,
1157                                           ImmediatelyDeclaredConstraint.get());
1158   return false;
1159 }
1160
1161 /// Check that the type of a non-type template parameter is
1162 /// well-formed.
1163 ///
1164 /// \returns the (possibly-promoted) parameter type if valid;
1165 /// otherwise, produces a diagnostic and returns a NULL type.
1166 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1167                                                  SourceLocation Loc) {
1168   if (TSI->getType()->isUndeducedType()) {
1169     // C++17 [temp.dep.expr]p3:
1170     //   An id-expression is type-dependent if it contains
1171     //    - an identifier associated by name lookup with a non-type
1172     //      template-parameter declared with a type that contains a
1173     //      placeholder type (7.1.7.4),
1174     TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1175   }
1176
1177   return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1178 }
1179
1180 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1181                                                  SourceLocation Loc) {
1182   // We don't allow variably-modified types as the type of non-type template
1183   // parameters.
1184   if (T->isVariablyModifiedType()) {
1185     Diag(Loc, diag::err_variably_modified_nontype_template_param)
1186       << T;
1187     return QualType();
1188   }
1189
1190   // C++ [temp.param]p4:
1191   //
1192   // A non-type template-parameter shall have one of the following
1193   // (optionally cv-qualified) types:
1194   //
1195   //       -- integral or enumeration type,
1196   if (T->isIntegralOrEnumerationType() ||
1197       //   -- pointer to object or pointer to function,
1198       T->isPointerType() ||
1199       //   -- reference to object or reference to function,
1200       T->isReferenceType() ||
1201       //   -- pointer to member,
1202       T->isMemberPointerType() ||
1203       //   -- std::nullptr_t.
1204       T->isNullPtrType() ||
1205       // Allow use of auto in template parameter declarations.
1206       T->isUndeducedType()) {
1207     // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1208     // are ignored when determining its type.
1209     return T.getUnqualifiedType();
1210   }
1211
1212   // C++ [temp.param]p8:
1213   //
1214   //   A non-type template-parameter of type "array of T" or
1215   //   "function returning T" is adjusted to be of type "pointer to
1216   //   T" or "pointer to function returning T", respectively.
1217   if (T->isArrayType() || T->isFunctionType())
1218     return Context.getDecayedType(T);
1219
1220   // If T is a dependent type, we can't do the check now, so we
1221   // assume that it is well-formed. Note that stripping off the
1222   // qualifiers here is not really correct if T turns out to be
1223   // an array type, but we'll recompute the type everywhere it's
1224   // used during instantiation, so that should be OK. (Using the
1225   // qualified type is equally wrong.)
1226   if (T->isDependentType())
1227     return T.getUnqualifiedType();
1228
1229   Diag(Loc, diag::err_template_nontype_parm_bad_type)
1230     << T;
1231
1232   return QualType();
1233 }
1234
1235 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1236                                           unsigned Depth,
1237                                           unsigned Position,
1238                                           SourceLocation EqualLoc,
1239                                           Expr *Default) {
1240   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1241
1242   // Check that we have valid decl-specifiers specified.
1243   auto CheckValidDeclSpecifiers = [this, &D] {
1244     // C++ [temp.param]
1245     // p1 
1246     //   template-parameter:
1247     //     ...
1248     //     parameter-declaration
1249     // p2 
1250     //   ... A storage class shall not be specified in a template-parameter
1251     //   declaration.
1252     // [dcl.typedef]p1:
1253     //   The typedef specifier [...] shall not be used in the decl-specifier-seq
1254     //   of a parameter-declaration
1255     const DeclSpec &DS = D.getDeclSpec();
1256     auto EmitDiag = [this](SourceLocation Loc) {
1257       Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1258           << FixItHint::CreateRemoval(Loc);
1259     };
1260     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1261       EmitDiag(DS.getStorageClassSpecLoc());
1262
1263     if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1264       EmitDiag(DS.getThreadStorageClassSpecLoc());
1265
1266     // [dcl.inline]p1:
1267     //   The inline specifier can be applied only to the declaration or
1268     //   definition of a variable or function.
1269
1270     if (DS.isInlineSpecified())
1271       EmitDiag(DS.getInlineSpecLoc());
1272
1273     // [dcl.constexpr]p1:
1274     //   The constexpr specifier shall be applied only to the definition of a
1275     //   variable or variable template or the declaration of a function or
1276     //   function template.
1277
1278     if (DS.hasConstexprSpecifier())
1279       EmitDiag(DS.getConstexprSpecLoc());
1280
1281     // [dcl.fct.spec]p1:
1282     //   Function-specifiers can be used only in function declarations.
1283
1284     if (DS.isVirtualSpecified())
1285       EmitDiag(DS.getVirtualSpecLoc());
1286
1287     if (DS.hasExplicitSpecifier())
1288       EmitDiag(DS.getExplicitSpecLoc());
1289
1290     if (DS.isNoreturnSpecified())
1291       EmitDiag(DS.getNoreturnSpecLoc());
1292   };
1293
1294   CheckValidDeclSpecifiers();
1295
1296   if (TInfo->getType()->isUndeducedType()) {
1297     Diag(D.getIdentifierLoc(),
1298          diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1299       << QualType(TInfo->getType()->getContainedAutoType(), 0);
1300   }
1301
1302   assert(S->isTemplateParamScope() &&
1303          "Non-type template parameter not in template parameter scope!");
1304   bool Invalid = false;
1305
1306   QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1307   if (T.isNull()) {
1308     T = Context.IntTy; // Recover with an 'int' type.
1309     Invalid = true;
1310   }
1311
1312   CheckFunctionOrTemplateParamDeclarator(S, D);
1313
1314   IdentifierInfo *ParamName = D.getIdentifier();
1315   bool IsParameterPack = D.hasEllipsis();
1316   NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1317       Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1318       D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1319       TInfo);
1320   Param->setAccess(AS_public);
1321
1322   if (Invalid)
1323     Param->setInvalidDecl();
1324
1325   if (Param->isParameterPack())
1326     if (auto *LSI = getEnclosingLambda())
1327       LSI->LocalPacks.push_back(Param);
1328
1329   if (ParamName) {
1330     maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1331                                          ParamName);
1332
1333     // Add the template parameter into the current scope.
1334     S->AddDecl(Param);
1335     IdResolver.AddDecl(Param);
1336   }
1337
1338   // C++0x [temp.param]p9:
1339   //   A default template-argument may be specified for any kind of
1340   //   template-parameter that is not a template parameter pack.
1341   if (Default && IsParameterPack) {
1342     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1343     Default = nullptr;
1344   }
1345
1346   // Check the well-formedness of the default template argument, if provided.
1347   if (Default) {
1348     // Check for unexpanded parameter packs.
1349     if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1350       return Param;
1351
1352     TemplateArgument Converted;
1353     ExprResult DefaultRes =
1354         CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1355     if (DefaultRes.isInvalid()) {
1356       Param->setInvalidDecl();
1357       return Param;
1358     }
1359     Default = DefaultRes.get();
1360
1361     Param->setDefaultArgument(Default);
1362   }
1363
1364   return Param;
1365 }
1366
1367 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1368 /// parameter (e.g. T in template <template \<typename> class T> class array)
1369 /// has been parsed. S is the current scope.
1370 NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1371                                            SourceLocation TmpLoc,
1372                                            TemplateParameterList *Params,
1373                                            SourceLocation EllipsisLoc,
1374                                            IdentifierInfo *Name,
1375                                            SourceLocation NameLoc,
1376                                            unsigned Depth,
1377                                            unsigned Position,
1378                                            SourceLocation EqualLoc,
1379                                            ParsedTemplateArgument Default) {
1380   assert(S->isTemplateParamScope() &&
1381          "Template template parameter not in template parameter scope!");
1382
1383   // Construct the parameter object.
1384   bool IsParameterPack = EllipsisLoc.isValid();
1385   TemplateTemplateParmDecl *Param =
1386     TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1387                                      NameLoc.isInvalid()? TmpLoc : NameLoc,
1388                                      Depth, Position, IsParameterPack,
1389                                      Name, Params);
1390   Param->setAccess(AS_public);
1391
1392   if (Param->isParameterPack())
1393     if (auto *LSI = getEnclosingLambda())
1394       LSI->LocalPacks.push_back(Param);
1395
1396   // If the template template parameter has a name, then link the identifier
1397   // into the scope and lookup mechanisms.
1398   if (Name) {
1399     maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1400
1401     S->AddDecl(Param);
1402     IdResolver.AddDecl(Param);
1403   }
1404
1405   if (Params->size() == 0) {
1406     Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1407     << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1408     Param->setInvalidDecl();
1409   }
1410
1411   // C++0x [temp.param]p9:
1412   //   A default template-argument may be specified for any kind of
1413   //   template-parameter that is not a template parameter pack.
1414   if (IsParameterPack && !Default.isInvalid()) {
1415     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1416     Default = ParsedTemplateArgument();
1417   }
1418
1419   if (!Default.isInvalid()) {
1420     // Check only that we have a template template argument. We don't want to
1421     // try to check well-formedness now, because our template template parameter
1422     // might have dependent types in its template parameters, which we wouldn't
1423     // be able to match now.
1424     //
1425     // If none of the template template parameter's template arguments mention
1426     // other template parameters, we could actually perform more checking here.
1427     // However, it isn't worth doing.
1428     TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1429     if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1430       Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1431         << DefaultArg.getSourceRange();
1432       return Param;
1433     }
1434
1435     // Check for unexpanded parameter packs.
1436     if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1437                                         DefaultArg.getArgument().getAsTemplate(),
1438                                         UPPC_DefaultArgument))
1439       return Param;
1440
1441     Param->setDefaultArgument(Context, DefaultArg);
1442   }
1443
1444   return Param;
1445 }
1446
1447 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1448 /// constrained by RequiresClause, that contains the template parameters in
1449 /// Params.
1450 TemplateParameterList *
1451 Sema::ActOnTemplateParameterList(unsigned Depth,
1452                                  SourceLocation ExportLoc,
1453                                  SourceLocation TemplateLoc,
1454                                  SourceLocation LAngleLoc,
1455                                  ArrayRef<NamedDecl *> Params,
1456                                  SourceLocation RAngleLoc,
1457                                  Expr *RequiresClause) {
1458   if (ExportLoc.isValid())
1459     Diag(ExportLoc, diag::warn_template_export_unsupported);
1460
1461   return TemplateParameterList::Create(
1462       Context, TemplateLoc, LAngleLoc,
1463       llvm::makeArrayRef(Params.data(), Params.size()),
1464       RAngleLoc, RequiresClause);
1465 }
1466
1467 static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1468                                    const CXXScopeSpec &SS) {
1469   if (SS.isSet())
1470     T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1471 }
1472
1473 DeclResult Sema::CheckClassTemplate(
1474     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1475     CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1476     const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1477     AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1478     SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1479     TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1480   assert(TemplateParams && TemplateParams->size() > 0 &&
1481          "No template parameters");
1482   assert(TUK != TUK_Reference && "Can only declare or define class templates");
1483   bool Invalid = false;
1484
1485   // Check that we can declare a template here.
1486   if (CheckTemplateDeclScope(S, TemplateParams))
1487     return true;
1488
1489   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1490   assert(Kind != TTK_Enum && "can't build template of enumerated type");
1491
1492   // There is no such thing as an unnamed class template.
1493   if (!Name) {
1494     Diag(KWLoc, diag::err_template_unnamed_class);
1495     return true;
1496   }
1497
1498   // Find any previous declaration with this name. For a friend with no
1499   // scope explicitly specified, we only look for tag declarations (per
1500   // C++11 [basic.lookup.elab]p2).
1501   DeclContext *SemanticContext;
1502   LookupResult Previous(*this, Name, NameLoc,
1503                         (SS.isEmpty() && TUK == TUK_Friend)
1504                           ? LookupTagName : LookupOrdinaryName,
1505                         forRedeclarationInCurContext());
1506   if (SS.isNotEmpty() && !SS.isInvalid()) {
1507     SemanticContext = computeDeclContext(SS, true);
1508     if (!SemanticContext) {
1509       // FIXME: Horrible, horrible hack! We can't currently represent this
1510       // in the AST, and historically we have just ignored such friend
1511       // class templates, so don't complain here.
1512       Diag(NameLoc, TUK == TUK_Friend
1513                         ? diag::warn_template_qualified_friend_ignored
1514                         : diag::err_template_qualified_declarator_no_match)
1515           << SS.getScopeRep() << SS.getRange();
1516       return TUK != TUK_Friend;
1517     }
1518
1519     if (RequireCompleteDeclContext(SS, SemanticContext))
1520       return true;
1521
1522     // If we're adding a template to a dependent context, we may need to
1523     // rebuilding some of the types used within the template parameter list,
1524     // now that we know what the current instantiation is.
1525     if (SemanticContext->isDependentContext()) {
1526       ContextRAII SavedContext(*this, SemanticContext);
1527       if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1528         Invalid = true;
1529     } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1530       diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1531
1532     LookupQualifiedName(Previous, SemanticContext);
1533   } else {
1534     SemanticContext = CurContext;
1535
1536     // C++14 [class.mem]p14:
1537     //   If T is the name of a class, then each of the following shall have a
1538     //   name different from T:
1539     //    -- every member template of class T
1540     if (TUK != TUK_Friend &&
1541         DiagnoseClassNameShadow(SemanticContext,
1542                                 DeclarationNameInfo(Name, NameLoc)))
1543       return true;
1544
1545     LookupName(Previous, S);
1546   }
1547
1548   if (Previous.isAmbiguous())
1549     return true;
1550
1551   NamedDecl *PrevDecl = nullptr;
1552   if (Previous.begin() != Previous.end())
1553     PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1554
1555   if (PrevDecl && PrevDecl->isTemplateParameter()) {
1556     // Maybe we will complain about the shadowed template parameter.
1557     DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1558     // Just pretend that we didn't see the previous declaration.
1559     PrevDecl = nullptr;
1560   }
1561
1562   // If there is a previous declaration with the same name, check
1563   // whether this is a valid redeclaration.
1564   ClassTemplateDecl *PrevClassTemplate =
1565       dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1566
1567   // We may have found the injected-class-name of a class template,
1568   // class template partial specialization, or class template specialization.
1569   // In these cases, grab the template that is being defined or specialized.
1570   if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1571       cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1572     PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1573     PrevClassTemplate
1574       = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1575     if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1576       PrevClassTemplate
1577         = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1578             ->getSpecializedTemplate();
1579     }
1580   }
1581
1582   if (TUK == TUK_Friend) {
1583     // C++ [namespace.memdef]p3:
1584     //   [...] When looking for a prior declaration of a class or a function
1585     //   declared as a friend, and when the name of the friend class or
1586     //   function is neither a qualified name nor a template-id, scopes outside
1587     //   the innermost enclosing namespace scope are not considered.
1588     if (!SS.isSet()) {
1589       DeclContext *OutermostContext = CurContext;
1590       while (!OutermostContext->isFileContext())
1591         OutermostContext = OutermostContext->getLookupParent();
1592
1593       if (PrevDecl &&
1594           (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1595            OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1596         SemanticContext = PrevDecl->getDeclContext();
1597       } else {
1598         // Declarations in outer scopes don't matter. However, the outermost
1599         // context we computed is the semantic context for our new
1600         // declaration.
1601         PrevDecl = PrevClassTemplate = nullptr;
1602         SemanticContext = OutermostContext;
1603
1604         // Check that the chosen semantic context doesn't already contain a
1605         // declaration of this name as a non-tag type.
1606         Previous.clear(LookupOrdinaryName);
1607         DeclContext *LookupContext = SemanticContext;
1608         while (LookupContext->isTransparentContext())
1609           LookupContext = LookupContext->getLookupParent();
1610         LookupQualifiedName(Previous, LookupContext);
1611
1612         if (Previous.isAmbiguous())
1613           return true;
1614
1615         if (Previous.begin() != Previous.end())
1616           PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1617       }
1618     }
1619   } else if (PrevDecl &&
1620              !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1621                             S, SS.isValid()))
1622     PrevDecl = PrevClassTemplate = nullptr;
1623
1624   if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1625           PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1626     if (SS.isEmpty() &&
1627         !(PrevClassTemplate &&
1628           PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1629               SemanticContext->getRedeclContext()))) {
1630       Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1631       Diag(Shadow->getTargetDecl()->getLocation(),
1632            diag::note_using_decl_target);
1633       Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1634       // Recover by ignoring the old declaration.
1635       PrevDecl = PrevClassTemplate = nullptr;
1636     }
1637   }
1638
1639   if (PrevClassTemplate) {
1640     // Ensure that the template parameter lists are compatible. Skip this check
1641     // for a friend in a dependent context: the template parameter list itself
1642     // could be dependent.
1643     if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1644         !TemplateParameterListsAreEqual(TemplateParams,
1645                                    PrevClassTemplate->getTemplateParameters(),
1646                                         /*Complain=*/true,
1647                                         TPL_TemplateMatch))
1648       return true;
1649
1650     // C++ [temp.class]p4:
1651     //   In a redeclaration, partial specialization, explicit
1652     //   specialization or explicit instantiation of a class template,
1653     //   the class-key shall agree in kind with the original class
1654     //   template declaration (7.1.5.3).
1655     RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1656     if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1657                                       TUK == TUK_Definition,  KWLoc, Name)) {
1658       Diag(KWLoc, diag::err_use_with_wrong_tag)
1659         << Name
1660         << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1661       Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1662       Kind = PrevRecordDecl->getTagKind();
1663     }
1664
1665     // Check for redefinition of this class template.
1666     if (TUK == TUK_Definition) {
1667       if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1668         // If we have a prior definition that is not visible, treat this as
1669         // simply making that previous definition visible.
1670         NamedDecl *Hidden = nullptr;
1671         if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1672           SkipBody->ShouldSkip = true;
1673           SkipBody->Previous = Def;
1674           auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1675           assert(Tmpl && "original definition of a class template is not a "
1676                          "class template?");
1677           makeMergedDefinitionVisible(Hidden);
1678           makeMergedDefinitionVisible(Tmpl);
1679         } else {
1680           Diag(NameLoc, diag::err_redefinition) << Name;
1681           Diag(Def->getLocation(), diag::note_previous_definition);
1682           // FIXME: Would it make sense to try to "forget" the previous
1683           // definition, as part of error recovery?
1684           return true;
1685         }
1686       }
1687     }
1688   } else if (PrevDecl) {
1689     // C++ [temp]p5:
1690     //   A class template shall not have the same name as any other
1691     //   template, class, function, object, enumeration, enumerator,
1692     //   namespace, or type in the same scope (3.3), except as specified
1693     //   in (14.5.4).
1694     Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1695     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1696     return true;
1697   }
1698
1699   // Check the template parameter list of this declaration, possibly
1700   // merging in the template parameter list from the previous class
1701   // template declaration. Skip this check for a friend in a dependent
1702   // context, because the template parameter list might be dependent.
1703   if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1704       CheckTemplateParameterList(
1705           TemplateParams,
1706           PrevClassTemplate
1707               ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1708               : nullptr,
1709           (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1710            SemanticContext->isDependentContext())
1711               ? TPC_ClassTemplateMember
1712               : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1713           SkipBody))
1714     Invalid = true;
1715
1716   if (SS.isSet()) {
1717     // If the name of the template was qualified, we must be defining the
1718     // template out-of-line.
1719     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1720       Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1721                                       : diag::err_member_decl_does_not_match)
1722         << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1723       Invalid = true;
1724     }
1725   }
1726
1727   // If this is a templated friend in a dependent context we should not put it
1728   // on the redecl chain. In some cases, the templated friend can be the most
1729   // recent declaration tricking the template instantiator to make substitutions
1730   // there.
1731   // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1732   bool ShouldAddRedecl
1733     = !(TUK == TUK_Friend && CurContext->isDependentContext());
1734
1735   CXXRecordDecl *NewClass =
1736     CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1737                           PrevClassTemplate && ShouldAddRedecl ?
1738                             PrevClassTemplate->getTemplatedDecl() : nullptr,
1739                           /*DelayTypeCreation=*/true);
1740   SetNestedNameSpecifier(*this, NewClass, SS);
1741   if (NumOuterTemplateParamLists > 0)
1742     NewClass->setTemplateParameterListsInfo(
1743         Context, llvm::makeArrayRef(OuterTemplateParamLists,
1744                                     NumOuterTemplateParamLists));
1745
1746   // Add alignment attributes if necessary; these attributes are checked when
1747   // the ASTContext lays out the structure.
1748   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
1749     AddAlignmentAttributesForRecord(NewClass);
1750     AddMsStructLayoutForRecord(NewClass);
1751   }
1752
1753   ClassTemplateDecl *NewTemplate
1754     = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1755                                 DeclarationName(Name), TemplateParams,
1756                                 NewClass);
1757
1758   if (ShouldAddRedecl)
1759     NewTemplate->setPreviousDecl(PrevClassTemplate);
1760
1761   NewClass->setDescribedClassTemplate(NewTemplate);
1762
1763   if (ModulePrivateLoc.isValid())
1764     NewTemplate->setModulePrivate();
1765
1766   // Build the type for the class template declaration now.
1767   QualType T = NewTemplate->getInjectedClassNameSpecialization();
1768   T = Context.getInjectedClassNameType(NewClass, T);
1769   assert(T->isDependentType() && "Class template type is not dependent?");
1770   (void)T;
1771
1772   // If we are providing an explicit specialization of a member that is a
1773   // class template, make a note of that.
1774   if (PrevClassTemplate &&
1775       PrevClassTemplate->getInstantiatedFromMemberTemplate())
1776     PrevClassTemplate->setMemberSpecialization();
1777
1778   // Set the access specifier.
1779   if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1780     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1781
1782   // Set the lexical context of these templates
1783   NewClass->setLexicalDeclContext(CurContext);
1784   NewTemplate->setLexicalDeclContext(CurContext);
1785
1786   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
1787     NewClass->startDefinition();
1788
1789   ProcessDeclAttributeList(S, NewClass, Attr);
1790
1791   if (PrevClassTemplate)
1792     mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1793
1794   AddPushedVisibilityAttribute(NewClass);
1795   inferGslOwnerPointerAttribute(NewClass);
1796
1797   if (TUK != TUK_Friend) {
1798     // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1799     Scope *Outer = S;
1800     while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1801       Outer = Outer->getParent();
1802     PushOnScopeChains(NewTemplate, Outer);
1803   } else {
1804     if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1805       NewTemplate->setAccess(PrevClassTemplate->getAccess());
1806       NewClass->setAccess(PrevClassTemplate->getAccess());
1807     }
1808
1809     NewTemplate->setObjectOfFriendDecl();
1810
1811     // Friend templates are visible in fairly strange ways.
1812     if (!CurContext->isDependentContext()) {
1813       DeclContext *DC = SemanticContext->getRedeclContext();
1814       DC->makeDeclVisibleInContext(NewTemplate);
1815       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1816         PushOnScopeChains(NewTemplate, EnclosingScope,
1817                           /* AddToContext = */ false);
1818     }
1819
1820     FriendDecl *Friend = FriendDecl::Create(
1821         Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1822     Friend->setAccess(AS_public);
1823     CurContext->addDecl(Friend);
1824   }
1825
1826   if (PrevClassTemplate)
1827     CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1828
1829   if (Invalid) {
1830     NewTemplate->setInvalidDecl();
1831     NewClass->setInvalidDecl();
1832   }
1833
1834   ActOnDocumentableDecl(NewTemplate);
1835
1836   if (SkipBody && SkipBody->ShouldSkip)
1837     return SkipBody->Previous;
1838
1839   return NewTemplate;
1840 }
1841
1842 namespace {
1843 /// Tree transform to "extract" a transformed type from a class template's
1844 /// constructor to a deduction guide.
1845 class ExtractTypeForDeductionGuide
1846   : public TreeTransform<ExtractTypeForDeductionGuide> {
1847 public:
1848   typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1849   ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1850
1851   TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1852
1853   QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1854     return TransformType(
1855         TLB,
1856         TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1857   }
1858 };
1859
1860 /// Transform to convert portions of a constructor declaration into the
1861 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1862 struct ConvertConstructorToDeductionGuideTransform {
1863   ConvertConstructorToDeductionGuideTransform(Sema &S,
1864                                               ClassTemplateDecl *Template)
1865       : SemaRef(S), Template(Template) {}
1866
1867   Sema &SemaRef;
1868   ClassTemplateDecl *Template;
1869
1870   DeclContext *DC = Template->getDeclContext();
1871   CXXRecordDecl *Primary = Template->getTemplatedDecl();
1872   DeclarationName DeductionGuideName =
1873       SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1874
1875   QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1876
1877   // Index adjustment to apply to convert depth-1 template parameters into
1878   // depth-0 template parameters.
1879   unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1880
1881   /// Transform a constructor declaration into a deduction guide.
1882   NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1883                                   CXXConstructorDecl *CD) {
1884     SmallVector<TemplateArgument, 16> SubstArgs;
1885
1886     LocalInstantiationScope Scope(SemaRef);
1887
1888     // C++ [over.match.class.deduct]p1:
1889     // -- For each constructor of the class template designated by the
1890     //    template-name, a function template with the following properties:
1891
1892     //    -- The template parameters are the template parameters of the class
1893     //       template followed by the template parameters (including default
1894     //       template arguments) of the constructor, if any.
1895     TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1896     if (FTD) {
1897       TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1898       SmallVector<NamedDecl *, 16> AllParams;
1899       AllParams.reserve(TemplateParams->size() + InnerParams->size());
1900       AllParams.insert(AllParams.begin(),
1901                        TemplateParams->begin(), TemplateParams->end());
1902       SubstArgs.reserve(InnerParams->size());
1903
1904       // Later template parameters could refer to earlier ones, so build up
1905       // a list of substituted template arguments as we go.
1906       for (NamedDecl *Param : *InnerParams) {
1907         MultiLevelTemplateArgumentList Args;
1908         Args.addOuterTemplateArguments(SubstArgs);
1909         Args.addOuterRetainedLevel();
1910         NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1911         if (!NewParam)
1912           return nullptr;
1913         AllParams.push_back(NewParam);
1914         SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1915             SemaRef.Context.getInjectedTemplateArg(NewParam)));
1916       }
1917       TemplateParams = TemplateParameterList::Create(
1918           SemaRef.Context, InnerParams->getTemplateLoc(),
1919           InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1920           /*FIXME: RequiresClause*/ nullptr);
1921     }
1922
1923     // If we built a new template-parameter-list, track that we need to
1924     // substitute references to the old parameters into references to the
1925     // new ones.
1926     MultiLevelTemplateArgumentList Args;
1927     if (FTD) {
1928       Args.addOuterTemplateArguments(SubstArgs);
1929       Args.addOuterRetainedLevel();
1930     }
1931
1932     FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1933                                    .getAsAdjusted<FunctionProtoTypeLoc>();
1934     assert(FPTL && "no prototype for constructor declaration");
1935
1936     // Transform the type of the function, adjusting the return type and
1937     // replacing references to the old parameters with references to the
1938     // new ones.
1939     TypeLocBuilder TLB;
1940     SmallVector<ParmVarDecl*, 8> Params;
1941     QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1942     if (NewType.isNull())
1943       return nullptr;
1944     TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1945
1946     return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
1947                                NewTInfo, CD->getBeginLoc(), CD->getLocation(),
1948                                CD->getEndLoc());
1949   }
1950
1951   /// Build a deduction guide with the specified parameter types.
1952   NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1953     SourceLocation Loc = Template->getLocation();
1954
1955     // Build the requested type.
1956     FunctionProtoType::ExtProtoInfo EPI;
1957     EPI.HasTrailingReturn = true;
1958     QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1959                                                 DeductionGuideName, EPI);
1960     TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1961
1962     FunctionProtoTypeLoc FPTL =
1963         TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1964
1965     // Build the parameters, needed during deduction / substitution.
1966     SmallVector<ParmVarDecl*, 4> Params;
1967     for (auto T : ParamTypes) {
1968       ParmVarDecl *NewParam = ParmVarDecl::Create(
1969           SemaRef.Context, DC, Loc, Loc, nullptr, T,
1970           SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1971       NewParam->setScopeInfo(0, Params.size());
1972       FPTL.setParam(Params.size(), NewParam);
1973       Params.push_back(NewParam);
1974     }
1975
1976     return buildDeductionGuide(Template->getTemplateParameters(),
1977                                ExplicitSpecifier(), TSI, Loc, Loc, Loc);
1978   }
1979
1980 private:
1981   /// Transform a constructor template parameter into a deduction guide template
1982   /// parameter, rebuilding any internal references to earlier parameters and
1983   /// renumbering as we go.
1984   NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1985                                         MultiLevelTemplateArgumentList &Args) {
1986     if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1987       // TemplateTypeParmDecl's index cannot be changed after creation, so
1988       // substitute it directly.
1989       auto *NewTTP = TemplateTypeParmDecl::Create(
1990           SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1991           /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
1992           TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1993           TTP->isParameterPack(), TTP->hasTypeConstraint(),
1994           TTP->isExpandedParameterPack() ?
1995           llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
1996       if (const auto *TC = TTP->getTypeConstraint()) {
1997         TemplateArgumentListInfo TransformedArgs;
1998         const auto *ArgsAsWritten = TC->getTemplateArgsAsWritten();
1999         if (SemaRef.Subst(ArgsAsWritten->getTemplateArgs(),
2000                           ArgsAsWritten->NumTemplateArgs, TransformedArgs,
2001                           Args))
2002           SemaRef.AttachTypeConstraint(
2003               TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2004               TC->getNamedConcept(), &TransformedArgs, NewTTP,
2005               NewTTP->isParameterPack()
2006                  ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2007                      ->getEllipsisLoc()
2008                  : SourceLocation());
2009       }
2010       if (TTP->hasDefaultArgument()) {
2011         TypeSourceInfo *InstantiatedDefaultArg =
2012             SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2013                               TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2014         if (InstantiatedDefaultArg)
2015           NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2016       }
2017       SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2018                                                            NewTTP);
2019       return NewTTP;
2020     }
2021
2022     if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2023       return transformTemplateParameterImpl(TTP, Args);
2024
2025     return transformTemplateParameterImpl(
2026         cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2027   }
2028   template<typename TemplateParmDecl>
2029   TemplateParmDecl *
2030   transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2031                                  MultiLevelTemplateArgumentList &Args) {
2032     // Ask the template instantiator to do the heavy lifting for us, then adjust
2033     // the index of the parameter once it's done.
2034     auto *NewParam =
2035         cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2036     assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2037     NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2038     return NewParam;
2039   }
2040
2041   QualType transformFunctionProtoType(TypeLocBuilder &TLB,
2042                                       FunctionProtoTypeLoc TL,
2043                                       SmallVectorImpl<ParmVarDecl*> &Params,
2044                                       MultiLevelTemplateArgumentList &Args) {
2045     SmallVector<QualType, 4> ParamTypes;
2046     const FunctionProtoType *T = TL.getTypePtr();
2047
2048     //    -- The types of the function parameters are those of the constructor.
2049     for (auto *OldParam : TL.getParams()) {
2050       ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
2051       if (!NewParam)
2052         return QualType();
2053       ParamTypes.push_back(NewParam->getType());
2054       Params.push_back(NewParam);
2055     }
2056
2057     //    -- The return type is the class template specialization designated by
2058     //       the template-name and template arguments corresponding to the
2059     //       template parameters obtained from the class template.
2060     //
2061     // We use the injected-class-name type of the primary template instead.
2062     // This has the convenient property that it is different from any type that
2063     // the user can write in a deduction-guide (because they cannot enter the
2064     // context of the template), so implicit deduction guides can never collide
2065     // with explicit ones.
2066     QualType ReturnType = DeducedType;
2067     TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2068
2069     // Resolving a wording defect, we also inherit the variadicness of the
2070     // constructor.
2071     FunctionProtoType::ExtProtoInfo EPI;
2072     EPI.Variadic = T->isVariadic();
2073     EPI.HasTrailingReturn = true;
2074
2075     QualType Result = SemaRef.BuildFunctionType(
2076         ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2077     if (Result.isNull())
2078       return QualType();
2079
2080     FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2081     NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2082     NewTL.setLParenLoc(TL.getLParenLoc());
2083     NewTL.setRParenLoc(TL.getRParenLoc());
2084     NewTL.setExceptionSpecRange(SourceRange());
2085     NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2086     for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2087       NewTL.setParam(I, Params[I]);
2088
2089     return Result;
2090   }
2091
2092   ParmVarDecl *
2093   transformFunctionTypeParam(ParmVarDecl *OldParam,
2094                              MultiLevelTemplateArgumentList &Args) {
2095     TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2096     TypeSourceInfo *NewDI;
2097     if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2098       // Expand out the one and only element in each inner pack.
2099       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2100       NewDI =
2101           SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2102                             OldParam->getLocation(), OldParam->getDeclName());
2103       if (!NewDI) return nullptr;
2104       NewDI =
2105           SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2106                                      PackTL.getTypePtr()->getNumExpansions());
2107     } else
2108       NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2109                                 OldParam->getDeclName());
2110     if (!NewDI)
2111       return nullptr;
2112
2113     // Extract the type. This (for instance) replaces references to typedef
2114     // members of the current instantiations with the definitions of those
2115     // typedefs, avoiding triggering instantiation of the deduced type during
2116     // deduction.
2117     NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
2118
2119     // Resolving a wording defect, we also inherit default arguments from the
2120     // constructor.
2121     ExprResult NewDefArg;
2122     if (OldParam->hasDefaultArg()) {
2123       NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
2124       if (NewDefArg.isInvalid())
2125         return nullptr;
2126     }
2127
2128     ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2129                                                 OldParam->getInnerLocStart(),
2130                                                 OldParam->getLocation(),
2131                                                 OldParam->getIdentifier(),
2132                                                 NewDI->getType(),
2133                                                 NewDI,
2134                                                 OldParam->getStorageClass(),
2135                                                 NewDefArg.get());
2136     NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2137                            OldParam->getFunctionScopeIndex());
2138     SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2139     return NewParam;
2140   }
2141
2142   NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
2143                                  ExplicitSpecifier ES, TypeSourceInfo *TInfo,
2144                                  SourceLocation LocStart, SourceLocation Loc,
2145                                  SourceLocation LocEnd) {
2146     DeclarationNameInfo Name(DeductionGuideName, Loc);
2147     ArrayRef<ParmVarDecl *> Params =
2148         TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2149
2150     // Build the implicit deduction guide template.
2151     auto *Guide =
2152         CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2153                                       TInfo->getType(), TInfo, LocEnd);
2154     Guide->setImplicit();
2155     Guide->setParams(Params);
2156
2157     for (auto *Param : Params)
2158       Param->setDeclContext(Guide);
2159
2160     auto *GuideTemplate = FunctionTemplateDecl::Create(
2161         SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2162     GuideTemplate->setImplicit();
2163     Guide->setDescribedFunctionTemplate(GuideTemplate);
2164
2165     if (isa<CXXRecordDecl>(DC)) {
2166       Guide->setAccess(AS_public);
2167       GuideTemplate->setAccess(AS_public);
2168     }
2169
2170     DC->addDecl(GuideTemplate);
2171     return GuideTemplate;
2172   }
2173 };
2174 }
2175
2176 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2177                                           SourceLocation Loc) {
2178   if (CXXRecordDecl *DefRecord =
2179           cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2180     TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2181     Template = DescribedTemplate ? DescribedTemplate : Template;
2182   }
2183
2184   DeclContext *DC = Template->getDeclContext();
2185   if (DC->isDependentContext())
2186     return;
2187
2188   ConvertConstructorToDeductionGuideTransform Transform(
2189       *this, cast<ClassTemplateDecl>(Template));
2190   if (!isCompleteType(Loc, Transform.DeducedType))
2191     return;
2192
2193   // Check whether we've already declared deduction guides for this template.
2194   // FIXME: Consider storing a flag on the template to indicate this.
2195   auto Existing = DC->lookup(Transform.DeductionGuideName);
2196   for (auto *D : Existing)
2197     if (D->isImplicit())
2198       return;
2199
2200   // In case we were expanding a pack when we attempted to declare deduction
2201   // guides, turn off pack expansion for everything we're about to do.
2202   ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2203   // Create a template instantiation record to track the "instantiation" of
2204   // constructors into deduction guides.
2205   // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2206   // this substitution process actually fail?
2207   InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2208   if (BuildingDeductionGuides.isInvalid())
2209     return;
2210
2211   // Convert declared constructors into deduction guide templates.
2212   // FIXME: Skip constructors for which deduction must necessarily fail (those
2213   // for which some class template parameter without a default argument never
2214   // appears in a deduced context).
2215   bool AddedAny = false;
2216   for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2217     D = D->getUnderlyingDecl();
2218     if (D->isInvalidDecl() || D->isImplicit())
2219       continue;
2220     D = cast<NamedDecl>(D->getCanonicalDecl());
2221
2222     auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2223     auto *CD =
2224         dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2225     // Class-scope explicit specializations (MS extension) do not result in
2226     // deduction guides.
2227     if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2228       continue;
2229
2230     Transform.transformConstructor(FTD, CD);
2231     AddedAny = true;
2232   }
2233
2234   // C++17 [over.match.class.deduct]
2235   //    --  If C is not defined or does not declare any constructors, an
2236   //    additional function template derived as above from a hypothetical
2237   //    constructor C().
2238   if (!AddedAny)
2239     Transform.buildSimpleDeductionGuide(None);
2240
2241   //    -- An additional function template derived as above from a hypothetical
2242   //    constructor C(C), called the copy deduction candidate.
2243   cast<CXXDeductionGuideDecl>(
2244       cast<FunctionTemplateDecl>(
2245           Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2246           ->getTemplatedDecl())
2247       ->setIsCopyDeductionCandidate();
2248 }
2249
2250 /// Diagnose the presence of a default template argument on a
2251 /// template parameter, which is ill-formed in certain contexts.
2252 ///
2253 /// \returns true if the default template argument should be dropped.
2254 static bool DiagnoseDefaultTemplateArgument(Sema &S,
2255                                             Sema::TemplateParamListContext TPC,
2256                                             SourceLocation ParamLoc,
2257                                             SourceRange DefArgRange) {
2258   switch (TPC) {
2259   case Sema::TPC_ClassTemplate:
2260   case Sema::TPC_VarTemplate:
2261   case Sema::TPC_TypeAliasTemplate:
2262     return false;
2263
2264   case Sema::TPC_FunctionTemplate:
2265   case Sema::TPC_FriendFunctionTemplateDefinition:
2266     // C++ [temp.param]p9:
2267     //   A default template-argument shall not be specified in a
2268     //   function template declaration or a function template
2269     //   definition [...]
2270     //   If a friend function template declaration specifies a default
2271     //   template-argument, that declaration shall be a definition and shall be
2272     //   the only declaration of the function template in the translation unit.
2273     // (C++98/03 doesn't have this wording; see DR226).
2274     S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2275          diag::warn_cxx98_compat_template_parameter_default_in_function_template
2276            : diag::ext_template_parameter_default_in_function_template)
2277       << DefArgRange;
2278     return false;
2279
2280   case Sema::TPC_ClassTemplateMember:
2281     // C++0x [temp.param]p9:
2282     //   A default template-argument shall not be specified in the
2283     //   template-parameter-lists of the definition of a member of a
2284     //   class template that appears outside of the member's class.
2285     S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2286       << DefArgRange;
2287     return true;
2288
2289   case Sema::TPC_FriendClassTemplate:
2290   case Sema::TPC_FriendFunctionTemplate:
2291     // C++ [temp.param]p9:
2292     //   A default template-argument shall not be specified in a
2293     //   friend template declaration.
2294     S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2295       << DefArgRange;
2296     return true;
2297
2298     // FIXME: C++0x [temp.param]p9 allows default template-arguments
2299     // for friend function templates if there is only a single
2300     // declaration (and it is a definition). Strange!
2301   }
2302
2303   llvm_unreachable("Invalid TemplateParamListContext!");
2304 }
2305
2306 /// Check for unexpanded parameter packs within the template parameters
2307 /// of a template template parameter, recursively.
2308 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2309                                              TemplateTemplateParmDecl *TTP) {
2310   // A template template parameter which is a parameter pack is also a pack
2311   // expansion.
2312   if (TTP->isParameterPack())
2313     return false;
2314
2315   TemplateParameterList *Params = TTP->getTemplateParameters();
2316   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2317     NamedDecl *P = Params->getParam(I);
2318     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2319       if (!TTP->isParameterPack())
2320         if (const TypeConstraint *TC = TTP->getTypeConstraint())
2321           if (TC->hasExplicitTemplateArgs())
2322             for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2323               if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2324                                                     Sema::UPPC_TypeConstraint))
2325                 return true;
2326       continue;
2327     }
2328
2329     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2330       if (!NTTP->isParameterPack() &&
2331           S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2332                                             NTTP->getTypeSourceInfo(),
2333                                       Sema::UPPC_NonTypeTemplateParameterType))
2334         return true;
2335
2336       continue;
2337     }
2338
2339     if (TemplateTemplateParmDecl *InnerTTP
2340                                         = dyn_cast<TemplateTemplateParmDecl>(P))
2341       if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2342         return true;
2343   }
2344
2345   return false;
2346 }
2347
2348 /// Checks the validity of a template parameter list, possibly
2349 /// considering the template parameter list from a previous
2350 /// declaration.
2351 ///
2352 /// If an "old" template parameter list is provided, it must be
2353 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
2354 /// template parameter list.
2355 ///
2356 /// \param NewParams Template parameter list for a new template
2357 /// declaration. This template parameter list will be updated with any
2358 /// default arguments that are carried through from the previous
2359 /// template parameter list.
2360 ///
2361 /// \param OldParams If provided, template parameter list from a
2362 /// previous declaration of the same template. Default template
2363 /// arguments will be merged from the old template parameter list to
2364 /// the new template parameter list.
2365 ///
2366 /// \param TPC Describes the context in which we are checking the given
2367 /// template parameter list.
2368 ///
2369 /// \param SkipBody If we might have already made a prior merged definition
2370 /// of this template visible, the corresponding body-skipping information.
2371 /// Default argument redefinition is not an error when skipping such a body,
2372 /// because (under the ODR) we can assume the default arguments are the same
2373 /// as the prior merged definition.
2374 ///
2375 /// \returns true if an error occurred, false otherwise.
2376 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2377                                       TemplateParameterList *OldParams,
2378                                       TemplateParamListContext TPC,
2379                                       SkipBodyInfo *SkipBody) {
2380   bool Invalid = false;
2381
2382   // C++ [temp.param]p10:
2383   //   The set of default template-arguments available for use with a
2384   //   template declaration or definition is obtained by merging the
2385   //   default arguments from the definition (if in scope) and all
2386   //   declarations in scope in the same way default function
2387   //   arguments are (8.3.6).
2388   bool SawDefaultArgument = false;
2389   SourceLocation PreviousDefaultArgLoc;
2390
2391   // Dummy initialization to avoid warnings.
2392   TemplateParameterList::iterator OldParam = NewParams->end();
2393   if (OldParams)
2394     OldParam = OldParams->begin();
2395
2396   bool RemoveDefaultArguments = false;
2397   for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2398                                     NewParamEnd = NewParams->end();
2399        NewParam != NewParamEnd; ++NewParam) {
2400     // Variables used to diagnose redundant default arguments
2401     bool RedundantDefaultArg = false;
2402     SourceLocation OldDefaultLoc;
2403     SourceLocation NewDefaultLoc;
2404
2405     // Variable used to diagnose missing default arguments
2406     bool MissingDefaultArg = false;
2407
2408     // Variable used to diagnose non-final parameter packs
2409     bool SawParameterPack = false;
2410
2411     if (TemplateTypeParmDecl *NewTypeParm
2412           = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2413       // Check the presence of a default argument here.
2414       if (NewTypeParm->hasDefaultArgument() &&
2415           DiagnoseDefaultTemplateArgument(*this, TPC,
2416                                           NewTypeParm->getLocation(),
2417                NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2418                                                        .getSourceRange()))
2419         NewTypeParm->removeDefaultArgument();
2420
2421       // Merge default arguments for template type parameters.
2422       TemplateTypeParmDecl *OldTypeParm
2423           = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2424       if (NewTypeParm->isParameterPack()) {
2425         assert(!NewTypeParm->hasDefaultArgument() &&
2426                "Parameter packs can't have a default argument!");
2427         SawParameterPack = true;
2428       } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2429                  NewTypeParm->hasDefaultArgument() &&
2430                  (!SkipBody || !SkipBody->ShouldSkip)) {
2431         OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2432         NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2433         SawDefaultArgument = true;
2434         RedundantDefaultArg = true;
2435         PreviousDefaultArgLoc = NewDefaultLoc;
2436       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2437         // Merge the default argument from the old declaration to the
2438         // new declaration.
2439         NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2440         PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2441       } else if (NewTypeParm->hasDefaultArgument()) {
2442         SawDefaultArgument = true;
2443         PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2444       } else if (SawDefaultArgument)
2445         MissingDefaultArg = true;
2446     } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2447                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2448       // Check for unexpanded parameter packs.
2449       if (!NewNonTypeParm->isParameterPack() &&
2450           DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2451                                           NewNonTypeParm->getTypeSourceInfo(),
2452                                           UPPC_NonTypeTemplateParameterType)) {
2453         Invalid = true;
2454         continue;
2455       }
2456
2457       // Check the presence of a default argument here.
2458       if (NewNonTypeParm->hasDefaultArgument() &&
2459           DiagnoseDefaultTemplateArgument(*this, TPC,
2460                                           NewNonTypeParm->getLocation(),
2461                     NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2462         NewNonTypeParm->removeDefaultArgument();
2463       }
2464
2465       // Merge default arguments for non-type template parameters
2466       NonTypeTemplateParmDecl *OldNonTypeParm
2467         = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2468       if (NewNonTypeParm->isParameterPack()) {
2469         assert(!NewNonTypeParm->hasDefaultArgument() &&
2470                "Parameter packs can't have a default argument!");
2471         if (!NewNonTypeParm->isPackExpansion())
2472           SawParameterPack = true;
2473       } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2474                  NewNonTypeParm->hasDefaultArgument() &&
2475                  (!SkipBody || !SkipBody->ShouldSkip)) {
2476         OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2477         NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2478         SawDefaultArgument = true;
2479         RedundantDefaultArg = true;
2480         PreviousDefaultArgLoc = NewDefaultLoc;
2481       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2482         // Merge the default argument from the old declaration to the
2483         // new declaration.
2484         NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2485         PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2486       } else if (NewNonTypeParm->hasDefaultArgument()) {
2487         SawDefaultArgument = true;
2488         PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2489       } else if (SawDefaultArgument)
2490         MissingDefaultArg = true;
2491     } else {
2492       TemplateTemplateParmDecl *NewTemplateParm
2493         = cast<TemplateTemplateParmDecl>(*NewParam);
2494
2495       // Check for unexpanded parameter packs, recursively.
2496       if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2497         Invalid = true;
2498         continue;
2499       }
2500
2501       // Check the presence of a default argument here.
2502       if (NewTemplateParm->hasDefaultArgument() &&
2503           DiagnoseDefaultTemplateArgument(*this, TPC,
2504                                           NewTemplateParm->getLocation(),
2505                      NewTemplateParm->getDefaultArgument().getSourceRange()))
2506         NewTemplateParm->removeDefaultArgument();
2507
2508       // Merge default arguments for template template parameters
2509       TemplateTemplateParmDecl *OldTemplateParm
2510         = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2511       if (NewTemplateParm->isParameterPack()) {
2512         assert(!NewTemplateParm->hasDefaultArgument() &&
2513                "Parameter packs can't have a default argument!");
2514         if (!NewTemplateParm->isPackExpansion())
2515           SawParameterPack = true;
2516       } else if (OldTemplateParm &&
2517                  hasVisibleDefaultArgument(OldTemplateParm) &&
2518                  NewTemplateParm->hasDefaultArgument() &&
2519                  (!SkipBody || !SkipBody->ShouldSkip)) {
2520         OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2521         NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2522         SawDefaultArgument = true;
2523         RedundantDefaultArg = true;
2524         PreviousDefaultArgLoc = NewDefaultLoc;
2525       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2526         // Merge the default argument from the old declaration to the
2527         // new declaration.
2528         NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2529         PreviousDefaultArgLoc
2530           = OldTemplateParm->getDefaultArgument().getLocation();
2531       } else if (NewTemplateParm->hasDefaultArgument()) {
2532         SawDefaultArgument = true;
2533         PreviousDefaultArgLoc
2534           = NewTemplateParm->getDefaultArgument().getLocation();
2535       } else if (SawDefaultArgument)
2536         MissingDefaultArg = true;
2537     }
2538
2539     // C++11 [temp.param]p11:
2540     //   If a template parameter of a primary class template or alias template
2541     //   is a template parameter pack, it shall be the last template parameter.
2542     if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2543         (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2544          TPC == TPC_TypeAliasTemplate)) {
2545       Diag((*NewParam)->getLocation(),
2546            diag::err_template_param_pack_must_be_last_template_parameter);
2547       Invalid = true;
2548     }
2549
2550     if (RedundantDefaultArg) {
2551       // C++ [temp.param]p12:
2552       //   A template-parameter shall not be given default arguments
2553       //   by two different declarations in the same scope.
2554       Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2555       Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2556       Invalid = true;
2557     } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2558       // C++ [temp.param]p11:
2559       //   If a template-parameter of a class template has a default
2560       //   template-argument, each subsequent template-parameter shall either
2561       //   have a default template-argument supplied or be a template parameter
2562       //   pack.
2563       Diag((*NewParam)->getLocation(),
2564            diag::err_template_param_default_arg_missing);
2565       Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2566       Invalid = true;
2567       RemoveDefaultArguments = true;
2568     }
2569
2570     // If we have an old template parameter list that we're merging
2571     // in, move on to the next parameter.
2572     if (OldParams)
2573       ++OldParam;
2574   }
2575
2576   // We were missing some default arguments at the end of the list, so remove
2577   // all of the default arguments.
2578   if (RemoveDefaultArguments) {
2579     for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2580                                       NewParamEnd = NewParams->end();
2581          NewParam != NewParamEnd; ++NewParam) {
2582       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2583         TTP->removeDefaultArgument();
2584       else if (NonTypeTemplateParmDecl *NTTP
2585                                 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2586         NTTP->removeDefaultArgument();
2587       else
2588         cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2589     }
2590   }
2591
2592   return Invalid;
2593 }
2594
2595 namespace {
2596
2597 /// A class which looks for a use of a certain level of template
2598 /// parameter.
2599 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2600   typedef RecursiveASTVisitor<DependencyChecker> super;
2601
2602   unsigned Depth;
2603
2604   // Whether we're looking for a use of a template parameter that makes the
2605   // overall construct type-dependent / a dependent type. This is strictly
2606   // best-effort for now; we may fail to match at all for a dependent type
2607   // in some cases if this is set.
2608   bool IgnoreNonTypeDependent;
2609
2610   bool Match;
2611   SourceLocation MatchLoc;
2612
2613   DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2614       : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2615         Match(false) {}
2616
2617   DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2618       : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2619     NamedDecl *ND = Params->getParam(0);
2620     if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2621       Depth = PD->getDepth();
2622     } else if (NonTypeTemplateParmDecl *PD =
2623                  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2624       Depth = PD->getDepth();
2625     } else {
2626       Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2627     }
2628   }
2629
2630   bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2631     if (ParmDepth >= Depth) {
2632       Match = true;
2633       MatchLoc = Loc;
2634       return true;
2635     }
2636     return false;
2637   }
2638
2639   bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2640     // Prune out non-type-dependent expressions if requested. This can
2641     // sometimes result in us failing to find a template parameter reference
2642     // (if a value-dependent expression creates a dependent type), but this
2643     // mode is best-effort only.
2644     if (auto *E = dyn_cast_or_null<Expr>(S))
2645       if (IgnoreNonTypeDependent && !E->isTypeDependent())
2646         return true;
2647     return super::TraverseStmt(S, Q);
2648   }
2649
2650   bool TraverseTypeLoc(TypeLoc TL) {
2651     if (IgnoreNonTypeDependent && !TL.isNull() &&
2652         !TL.getType()->isDependentType())
2653       return true;
2654     return super::TraverseTypeLoc(TL);
2655   }
2656
2657   bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2658     return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2659   }
2660
2661   bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2662     // For a best-effort search, keep looking until we find a location.
2663     return IgnoreNonTypeDependent || !Matches(T->getDepth());
2664   }
2665
2666   bool TraverseTemplateName(TemplateName N) {
2667     if (TemplateTemplateParmDecl *PD =
2668           dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2669       if (Matches(PD->getDepth()))
2670         return false;
2671     return super::TraverseTemplateName(N);
2672   }
2673
2674   bool VisitDeclRefExpr(DeclRefExpr *E) {
2675     if (NonTypeTemplateParmDecl *PD =
2676           dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2677       if (Matches(PD->getDepth(), E->getExprLoc()))
2678         return false;
2679     return super::VisitDeclRefExpr(E);
2680   }
2681
2682   bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2683     return TraverseType(T->getReplacementType());
2684   }
2685
2686   bool
2687   VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2688     return TraverseTemplateArgument(T->getArgumentPack());
2689   }
2690
2691   bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2692     return TraverseType(T->getInjectedSpecializationType());
2693   }
2694 };
2695 } // end anonymous namespace
2696
2697 /// Determines whether a given type depends on the given parameter
2698 /// list.
2699 static bool
2700 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2701   if (!Params->size())
2702     return false;
2703
2704   DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2705   Checker.TraverseType(T);
2706   return Checker.Match;
2707 }
2708
2709 // Find the source range corresponding to the named type in the given
2710 // nested-name-specifier, if any.
2711 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2712                                                        QualType T,
2713                                                        const CXXScopeSpec &SS) {
2714   NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2715   while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2716     if (const Type *CurType = NNS->getAsType()) {
2717       if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2718         return NNSLoc.getTypeLoc().getSourceRange();
2719     } else
2720       break;
2721
2722     NNSLoc = NNSLoc.getPrefix();
2723   }
2724
2725   return SourceRange();
2726 }
2727
2728 /// Match the given template parameter lists to the given scope
2729 /// specifier, returning the template parameter list that applies to the
2730 /// name.
2731 ///
2732 /// \param DeclStartLoc the start of the declaration that has a scope
2733 /// specifier or a template parameter list.
2734 ///
2735 /// \param DeclLoc The location of the declaration itself.
2736 ///
2737 /// \param SS the scope specifier that will be matched to the given template
2738 /// parameter lists. This scope specifier precedes a qualified name that is
2739 /// being declared.
2740 ///
2741 /// \param TemplateId The template-id following the scope specifier, if there
2742 /// is one. Used to check for a missing 'template<>'.
2743 ///
2744 /// \param ParamLists the template parameter lists, from the outermost to the
2745 /// innermost template parameter lists.
2746 ///
2747 /// \param IsFriend Whether to apply the slightly different rules for
2748 /// matching template parameters to scope specifiers in friend
2749 /// declarations.
2750 ///
2751 /// \param IsMemberSpecialization will be set true if the scope specifier
2752 /// denotes a fully-specialized type, and therefore this is a declaration of
2753 /// a member specialization.
2754 ///
2755 /// \returns the template parameter list, if any, that corresponds to the
2756 /// name that is preceded by the scope specifier @p SS. This template
2757 /// parameter list may have template parameters (if we're declaring a
2758 /// template) or may have no template parameters (if we're declaring a
2759 /// template specialization), or may be NULL (if what we're declaring isn't
2760 /// itself a template).
2761 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2762     SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2763     TemplateIdAnnotation *TemplateId,
2764     ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2765     bool &IsMemberSpecialization, bool &Invalid) {
2766   IsMemberSpecialization = false;
2767   Invalid = false;
2768
2769   // The sequence of nested types to which we will match up the template
2770   // parameter lists. We first build this list by starting with the type named
2771   // by the nested-name-specifier and walking out until we run out of types.
2772   SmallVector<QualType, 4> NestedTypes;
2773   QualType T;
2774   if (SS.getScopeRep()) {
2775     if (CXXRecordDecl *Record
2776               = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2777       T = Context.getTypeDeclType(Record);
2778     else
2779       T = QualType(SS.getScopeRep()->getAsType(), 0);
2780   }
2781
2782   // If we found an explicit specialization that prevents us from needing
2783   // 'template<>' headers, this will be set to the location of that
2784   // explicit specialization.
2785   SourceLocation ExplicitSpecLoc;
2786
2787   while (!T.isNull()) {
2788     NestedTypes.push_back(T);
2789
2790     // Retrieve the parent of a record type.
2791     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2792       // If this type is an explicit specialization, we're done.
2793       if (ClassTemplateSpecializationDecl *Spec
2794           = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2795         if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2796             Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2797           ExplicitSpecLoc = Spec->getLocation();
2798           break;
2799         }
2800       } else if (Record->getTemplateSpecializationKind()
2801                                                 == TSK_ExplicitSpecialization) {
2802         ExplicitSpecLoc = Record->getLocation();
2803         break;
2804       }
2805
2806       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2807         T = Context.getTypeDeclType(Parent);
2808       else
2809         T = QualType();
2810       continue;
2811     }
2812
2813     if (const TemplateSpecializationType *TST
2814                                      = T->getAs<TemplateSpecializationType>()) {
2815       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2816         if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2817           T = Context.getTypeDeclType(Parent);
2818         else
2819           T = QualType();
2820         continue;
2821       }
2822     }
2823
2824     // Look one step prior in a dependent template specialization type.
2825     if (const DependentTemplateSpecializationType *DependentTST
2826                           = T->getAs<DependentTemplateSpecializationType>()) {
2827       if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2828         T = QualType(NNS->getAsType(), 0);
2829       else
2830         T = QualType();
2831       continue;
2832     }
2833
2834     // Look one step prior in a dependent name type.
2835     if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2836       if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2837         T = QualType(NNS->getAsType(), 0);
2838       else
2839         T = QualType();
2840       continue;
2841     }
2842
2843     // Retrieve the parent of an enumeration type.
2844     if (const EnumType *EnumT = T->getAs<EnumType>()) {
2845       // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2846       // check here.
2847       EnumDecl *Enum = EnumT->getDecl();
2848
2849       // Get to the parent type.
2850       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2851         T = Context.getTypeDeclType(Parent);
2852       else
2853         T = QualType();
2854       continue;
2855     }
2856
2857     T = QualType();
2858   }
2859   // Reverse the nested types list, since we want to traverse from the outermost
2860   // to the innermost while checking template-parameter-lists.
2861   std::reverse(NestedTypes.begin(), NestedTypes.end());
2862
2863   // C++0x [temp.expl.spec]p17:
2864   //   A member or a member template may be nested within many
2865   //   enclosing class templates. In an explicit specialization for
2866   //   such a member, the member declaration shall be preceded by a
2867   //   template<> for each enclosing class template that is
2868   //   explicitly specialized.
2869   bool SawNonEmptyTemplateParameterList = false;
2870
2871   auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2872     if (SawNonEmptyTemplateParameterList) {
2873       Diag(DeclLoc, diag::err_specialize_member_of_template)
2874         << !Recovery << Range;
2875       Invalid = true;
2876       IsMemberSpecialization = false;
2877       return true;
2878     }
2879
2880     return false;
2881   };
2882
2883   auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2884     // Check that we can have an explicit specialization here.
2885     if (CheckExplicitSpecialization(Range, true))
2886       return true;
2887
2888     // We don't have a template header, but we should.
2889     SourceLocation ExpectedTemplateLoc;
2890     if (!ParamLists.empty())
2891       ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2892     else
2893       ExpectedTemplateLoc = DeclStartLoc;
2894
2895     Diag(DeclLoc, diag::err_template_spec_needs_header)
2896       << Range
2897       << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2898     return false;
2899   };
2900
2901   unsigned ParamIdx = 0;
2902   for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2903        ++TypeIdx) {
2904     T = NestedTypes[TypeIdx];
2905
2906     // Whether we expect a 'template<>' header.
2907     bool NeedEmptyTemplateHeader = false;
2908
2909     // Whether we expect a template header with parameters.
2910     bool NeedNonemptyTemplateHeader = false;
2911
2912     // For a dependent type, the set of template parameters that we
2913     // expect to see.
2914     TemplateParameterList *ExpectedTemplateParams = nullptr;
2915
2916     // C++0x [temp.expl.spec]p15:
2917     //   A member or a member template may be nested within many enclosing
2918     //   class templates. In an explicit specialization for such a member, the
2919     //   member declaration shall be preceded by a template<> for each
2920     //   enclosing class template that is explicitly specialized.
2921     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2922       if (ClassTemplatePartialSpecializationDecl *Partial
2923             = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2924         ExpectedTemplateParams = Partial->getTemplateParameters();
2925         NeedNonemptyTemplateHeader = true;
2926       } else if (Record->isDependentType()) {
2927         if (Record->getDescribedClassTemplate()) {
2928           ExpectedTemplateParams = Record->getDescribedClassTemplate()
2929                                                       ->getTemplateParameters();
2930           NeedNonemptyTemplateHeader = true;
2931         }
2932       } else if (ClassTemplateSpecializationDecl *Spec
2933                      = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2934         // C++0x [temp.expl.spec]p4:
2935         //   Members of an explicitly specialized class template are defined
2936         //   in the same manner as members of normal classes, and not using
2937         //   the template<> syntax.
2938         if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2939           NeedEmptyTemplateHeader = true;
2940         else
2941           continue;
2942       } else if (Record->getTemplateSpecializationKind()) {
2943         if (Record->getTemplateSpecializationKind()
2944                                                 != TSK_ExplicitSpecialization &&
2945             TypeIdx == NumTypes - 1)
2946           IsMemberSpecialization = true;
2947
2948         continue;
2949       }
2950     } else if (const TemplateSpecializationType *TST
2951                                      = T->getAs<TemplateSpecializationType>()) {
2952       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2953         ExpectedTemplateParams = Template->getTemplateParameters();
2954         NeedNonemptyTemplateHeader = true;
2955       }
2956     } else if (T->getAs<DependentTemplateSpecializationType>()) {
2957       // FIXME:  We actually could/should check the template arguments here
2958       // against the corresponding template parameter list.
2959       NeedNonemptyTemplateHeader = false;
2960     }
2961
2962     // C++ [temp.expl.spec]p16:
2963     //   In an explicit specialization declaration for a member of a class
2964     //   template or a member template that ap- pears in namespace scope, the
2965     //   member template and some of its enclosing class templates may remain
2966     //   unspecialized, except that the declaration shall not explicitly
2967     //   specialize a class member template if its en- closing class templates
2968     //   are not explicitly specialized as well.
2969     if (ParamIdx < ParamLists.size()) {
2970       if (ParamLists[ParamIdx]->size() == 0) {
2971         if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2972                                         false))
2973           return nullptr;
2974       } else
2975         SawNonEmptyTemplateParameterList = true;
2976     }
2977
2978     if (NeedEmptyTemplateHeader) {
2979       // If we're on the last of the types, and we need a 'template<>' header
2980       // here, then it's a member specialization.
2981       if (TypeIdx == NumTypes - 1)
2982         IsMemberSpecialization = true;
2983
2984       if (ParamIdx < ParamLists.size()) {
2985         if (ParamLists[ParamIdx]->size() > 0) {
2986           // The header has template parameters when it shouldn't. Complain.
2987           Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2988                diag::err_template_param_list_matches_nontemplate)
2989             << T
2990             << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2991                            ParamLists[ParamIdx]->getRAngleLoc())
2992             << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2993           Invalid = true;
2994           return nullptr;
2995         }
2996
2997         // Consume this template header.
2998         ++ParamIdx;
2999         continue;
3000       }
3001
3002       if (!IsFriend)
3003         if (DiagnoseMissingExplicitSpecialization(
3004                 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3005           return nullptr;
3006
3007       continue;
3008     }
3009
3010     if (NeedNonemptyTemplateHeader) {
3011       // In friend declarations we can have template-ids which don't
3012       // depend on the corresponding template parameter lists.  But
3013       // assume that empty parameter lists are supposed to match this
3014       // template-id.
3015       if (IsFriend && T->isDependentType()) {
3016         if (ParamIdx < ParamLists.size() &&
3017             DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3018           ExpectedTemplateParams = nullptr;
3019         else
3020           continue;
3021       }
3022
3023       if (ParamIdx < ParamLists.size()) {
3024         // Check the template parameter list, if we can.
3025         if (ExpectedTemplateParams &&
3026             !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3027                                             ExpectedTemplateParams,
3028                                             true, TPL_TemplateMatch))
3029           Invalid = true;
3030
3031         if (!Invalid &&
3032             CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3033                                        TPC_ClassTemplateMember))
3034           Invalid = true;
3035
3036         ++ParamIdx;
3037         continue;
3038       }
3039
3040       Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3041         << T
3042         << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3043       Invalid = true;
3044       continue;
3045     }
3046   }
3047
3048   // If there were at least as many template-ids as there were template
3049   // parameter lists, then there are no template parameter lists remaining for
3050   // the declaration itself.
3051   if (ParamIdx >= ParamLists.size()) {
3052     if (TemplateId && !IsFriend) {
3053       // We don't have a template header for the declaration itself, but we
3054       // should.
3055       DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3056                                                         TemplateId->RAngleLoc));
3057
3058       // Fabricate an empty template parameter list for the invented header.
3059       return TemplateParameterList::Create(Context, SourceLocation(),
3060                                            SourceLocation(), None,
3061                                            SourceLocation(), nullptr);
3062     }
3063
3064     return nullptr;
3065   }
3066
3067   // If there were too many template parameter lists, complain about that now.
3068   if (ParamIdx < ParamLists.size() - 1) {
3069     bool HasAnyExplicitSpecHeader = false;
3070     bool AllExplicitSpecHeaders = true;
3071     for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3072       if (ParamLists[I]->size() == 0)
3073         HasAnyExplicitSpecHeader = true;
3074       else
3075         AllExplicitSpecHeaders = false;
3076     }
3077
3078     Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3079          AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
3080                                 : diag::err_template_spec_extra_headers)
3081         << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3082                        ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3083
3084     // If there was a specialization somewhere, such that 'template<>' is
3085     // not required, and there were any 'template<>' headers, note where the
3086     // specialization occurred.
3087     if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
3088       Diag(ExplicitSpecLoc,
3089            diag::note_explicit_template_spec_does_not_need_header)
3090         << NestedTypes.back();
3091
3092     // We have a template parameter list with no corresponding scope, which
3093     // means that the resulting template declaration can't be instantiated
3094     // properly (we'll end up with dependent nodes when we shouldn't).
3095     if (!AllExplicitSpecHeaders)
3096       Invalid = true;
3097   }
3098
3099   // C++ [temp.expl.spec]p16:
3100   //   In an explicit specialization declaration for a member of a class
3101   //   template or a member template that ap- pears in namespace scope, the
3102   //   member template and some of its enclosing class templates may remain
3103   //   unspecialized, except that the declaration shall not explicitly
3104   //   specialize a class member template if its en- closing class templates
3105   //   are not explicitly specialized as well.
3106   if (ParamLists.back()->size() == 0 &&
3107       CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3108                                   false))
3109     return nullptr;
3110
3111   // Return the last template parameter list, which corresponds to the
3112   // entity being declared.
3113   return ParamLists.back();
3114 }
3115
3116 void Sema::NoteAllFoundTemplates(TemplateName Name) {
3117   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3118     Diag(Template->getLocation(), diag::note_template_declared_here)
3119         << (isa<FunctionTemplateDecl>(Template)
3120                 ? 0
3121                 : isa<ClassTemplateDecl>(Template)
3122                       ? 1
3123                       : isa<VarTemplateDecl>(Template)
3124                             ? 2
3125                             : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3126         << Template->getDeclName();
3127     return;
3128   }
3129
3130   if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3131     for (OverloadedTemplateStorage::iterator I = OST->begin(),
3132                                           IEnd = OST->end();
3133          I != IEnd; ++I)
3134       Diag((*I)->getLocation(), diag::note_template_declared_here)
3135         << 0 << (*I)->getDeclName();
3136
3137     return;
3138   }
3139 }
3140
3141 static QualType
3142 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3143                            const SmallVectorImpl<TemplateArgument> &Converted,
3144                            SourceLocation TemplateLoc,
3145                            TemplateArgumentListInfo &TemplateArgs) {
3146   ASTContext &Context = SemaRef.getASTContext();
3147   switch (BTD->getBuiltinTemplateKind()) {
3148   case BTK__make_integer_seq: {
3149     // Specializations of __make_integer_seq<S, T, N> are treated like
3150     // S<T, 0, ..., N-1>.
3151
3152     // C++14 [inteseq.intseq]p1:
3153     //   T shall be an integer type.
3154     if (!Converted[1].getAsType()->isIntegralType(Context)) {
3155       SemaRef.Diag(TemplateArgs[1].getLocation(),
3156                    diag::err_integer_sequence_integral_element_type);
3157       return QualType();
3158     }
3159
3160     // C++14 [inteseq.make]p1:
3161     //   If N is negative the program is ill-formed.
3162     TemplateArgument NumArgsArg = Converted[2];
3163     llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3164     if (NumArgs < 0) {
3165       SemaRef.Diag(TemplateArgs[2].getLocation(),
3166                    diag::err_integer_sequence_negative_length);
3167       return QualType();
3168     }
3169
3170     QualType ArgTy = NumArgsArg.getIntegralType();
3171     TemplateArgumentListInfo SyntheticTemplateArgs;
3172     // The type argument gets reused as the first template argument in the
3173     // synthetic template argument list.
3174     SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3175     // Expand N into 0 ... N-1.
3176     for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3177          I < NumArgs; ++I) {
3178       TemplateArgument TA(Context, I, ArgTy);
3179       SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3180           TA, ArgTy, TemplateArgs[2].getLocation()));
3181     }
3182     // The first template argument will be reused as the template decl that
3183     // our synthetic template arguments will be applied to.
3184     return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3185                                        TemplateLoc, SyntheticTemplateArgs);
3186   }
3187
3188   case BTK__type_pack_element:
3189     // Specializations of
3190     //    __type_pack_element<Index, T_1, ..., T_N>
3191     // are treated like T_Index.
3192     assert(Converted.size() == 2 &&
3193       "__type_pack_element should be given an index and a parameter pack");
3194
3195     // If the Index is out of bounds, the program is ill-formed.
3196     TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3197     llvm::APSInt Index = IndexArg.getAsIntegral();
3198     assert(Index >= 0 && "the index used with __type_pack_element should be of "
3199                          "type std::size_t, and hence be non-negative");
3200     if (Index >= Ts.pack_size()) {
3201       SemaRef.Diag(TemplateArgs[0].getLocation(),
3202                    diag::err_type_pack_element_out_of_bounds);
3203       return QualType();
3204     }
3205
3206     // We simply return the type at index `Index`.
3207     auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3208     return Nth->getAsType();
3209   }
3210   llvm_unreachable("unexpected BuiltinTemplateDecl!");
3211 }
3212
3213 /// Determine whether this alias template is "enable_if_t".
3214 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3215   return AliasTemplate->getName().equals("enable_if_t");
3216 }
3217
3218 /// Collect all of the separable terms in the given condition, which
3219 /// might be a conjunction.
3220 ///
3221 /// FIXME: The right answer is to convert the logical expression into
3222 /// disjunctive normal form, so we can find the first failed term
3223 /// within each possible clause.
3224 static void collectConjunctionTerms(Expr *Clause,
3225                                     SmallVectorImpl<Expr *> &Terms) {
3226   if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3227     if (BinOp->getOpcode() == BO_LAnd) {
3228       collectConjunctionTerms(BinOp->getLHS(), Terms);
3229       collectConjunctionTerms(BinOp->getRHS(), Terms);
3230     }
3231
3232     return;
3233   }
3234
3235   Terms.push_back(Clause);
3236 }
3237
3238 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3239 // a left-hand side that is value-dependent but never true. Identify
3240 // the idiom and ignore that term.
3241 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3242   // Top-level '||'.
3243   auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3244   if (!BinOp) return Cond;
3245
3246   if (BinOp->getOpcode() != BO_LOr) return Cond;
3247
3248   // With an inner '==' that has a literal on the right-hand side.
3249   Expr *LHS = BinOp->getLHS();
3250   auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3251   if (!InnerBinOp) return Cond;
3252
3253   if (InnerBinOp->getOpcode() != BO_EQ ||
3254       !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3255     return Cond;
3256
3257   // If the inner binary operation came from a macro expansion named
3258   // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3259   // of the '||', which is the real, user-provided condition.
3260   SourceLocation Loc = InnerBinOp->getExprLoc();
3261   if (!Loc.isMacroID()) return Cond;
3262
3263   StringRef MacroName = PP.getImmediateMacroName(Loc);
3264   if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3265     return BinOp->getRHS();
3266
3267   return Cond;
3268 }
3269
3270 namespace {
3271
3272 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3273 // within failing boolean expression, such as substituting template parameters
3274 // for actual types.
3275 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3276 public:
3277   explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3278       : Policy(P) {}
3279
3280   bool handledStmt(Stmt *E, raw_ostream &OS) override {
3281     const auto *DR = dyn_cast<DeclRefExpr>(E);
3282     if (DR && DR->getQualifier()) {
3283       // If this is a qualified name, expand the template arguments in nested
3284       // qualifiers.
3285       DR->getQualifier()->print(OS, Policy, true);
3286       // Then print the decl itself.
3287       const ValueDecl *VD = DR->getDecl();
3288       OS << VD->getName();
3289       if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3290         // This is a template variable, print the expanded template arguments.
3291         printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3292       }
3293       return true;
3294     }
3295     return false;
3296   }
3297
3298 private:
3299   const PrintingPolicy Policy;
3300 };
3301
3302 } // end anonymous namespace
3303
3304 std::pair<Expr *, std::string>
3305 Sema::findFailedBooleanCondition(Expr *Cond) {
3306   Cond = lookThroughRangesV3Condition(PP, Cond);
3307
3308   // Separate out all of the terms in a conjunction.
3309   SmallVector<Expr *, 4> Terms;
3310   collectConjunctionTerms(Cond, Terms);
3311
3312   // Determine which term failed.
3313   Expr *FailedCond = nullptr;
3314   for (Expr *Term : Terms) {
3315     Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3316
3317     // Literals are uninteresting.
3318     if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3319         isa<IntegerLiteral>(TermAsWritten))
3320       continue;
3321
3322     // The initialization of the parameter from the argument is
3323     // a constant-evaluated context.
3324     EnterExpressionEvaluationContext ConstantEvaluated(
3325       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3326
3327     bool Succeeded;
3328     if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3329         !Succeeded) {
3330       FailedCond = TermAsWritten;
3331       break;
3332     }
3333   }
3334   if (!FailedCond)
3335     FailedCond = Cond->IgnoreParenImpCasts();
3336
3337   std::string Description;
3338   {
3339     llvm::raw_string_ostream Out(Description);
3340     PrintingPolicy Policy = getPrintingPolicy();
3341     Policy.PrintCanonicalTypes = true;
3342     FailedBooleanConditionPrinterHelper Helper(Policy);
3343     FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3344   }
3345   return { FailedCond, Description };
3346 }
3347
3348 QualType Sema::CheckTemplateIdType(TemplateName Name,
3349                                    SourceLocation TemplateLoc,
3350                                    TemplateArgumentListInfo &TemplateArgs) {
3351   DependentTemplateName *DTN
3352     = Name.getUnderlying().getAsDependentTemplateName();
3353   if (DTN && DTN->isIdentifier())
3354     // When building a template-id where the template-name is dependent,
3355     // assume the template is a type template. Either our assumption is
3356     // correct, or the code is ill-formed and will be diagnosed when the
3357     // dependent name is substituted.
3358     return Context.getDependentTemplateSpecializationType(ETK_None,
3359                                                           DTN->getQualifier(),
3360                                                           DTN->getIdentifier(),
3361                                                           TemplateArgs);
3362
3363   TemplateDecl *Template = Name.getAsTemplateDecl();
3364   if (!Template || isa<FunctionTemplateDecl>(Template) ||
3365       isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3366     // We might have a substituted template template parameter pack. If so,
3367     // build a template specialization type for it.
3368     if (Name.getAsSubstTemplateTemplateParmPack())
3369       return Context.getTemplateSpecializationType(Name, TemplateArgs);
3370
3371     Diag(TemplateLoc, diag::err_template_id_not_a_type)
3372       << Name;
3373     NoteAllFoundTemplates(Name);
3374     return QualType();
3375   }
3376
3377   // Check that the template argument list is well-formed for this
3378   // template.
3379   SmallVector<TemplateArgument, 4> Converted;
3380   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3381                                 false, Converted,
3382                                 /*UpdateArgsWithConversion=*/true))
3383     return QualType();
3384
3385   QualType CanonType;
3386
3387   bool InstantiationDependent = false;
3388   if (TypeAliasTemplateDecl *AliasTemplate =
3389           dyn_cast<TypeAliasTemplateDecl>(Template)) {
3390
3391     // Find the canonical type for this type alias template specialization.
3392     TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3393     if (Pattern->isInvalidDecl())
3394       return QualType();
3395
3396     TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3397                                            Converted);
3398
3399     // Only substitute for the innermost template argument list.
3400     MultiLevelTemplateArgumentList TemplateArgLists;
3401     TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3402     unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3403     for (unsigned I = 0; I < Depth; ++I)
3404       TemplateArgLists.addOuterTemplateArguments(None);
3405
3406     LocalInstantiationScope Scope(*this);
3407     InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3408     if (Inst.isInvalid())
3409       return QualType();
3410
3411     CanonType = SubstType(Pattern->getUnderlyingType(),
3412                           TemplateArgLists, AliasTemplate->getLocation(),
3413                           AliasTemplate->getDeclName());
3414     if (CanonType.isNull()) {
3415       // If this was enable_if and we failed to find the nested type
3416       // within enable_if in a SFINAE context, dig out the specific
3417       // enable_if condition that failed and present that instead.
3418       if (isEnableIfAliasTemplate(AliasTemplate)) {
3419         if (auto DeductionInfo = isSFINAEContext()) {
3420           if (*DeductionInfo &&
3421               (*DeductionInfo)->hasSFINAEDiagnostic() &&
3422               (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3423                 diag::err_typename_nested_not_found_enable_if &&
3424               TemplateArgs[0].getArgument().getKind()
3425                 == TemplateArgument::Expression) {
3426             Expr *FailedCond;
3427             std::string FailedDescription;
3428             std::tie(FailedCond, FailedDescription) =
3429               findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3430
3431             // Remove the old SFINAE diagnostic.
3432             PartialDiagnosticAt OldDiag =
3433               {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3434             (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3435
3436             // Add a new SFINAE diagnostic specifying which condition
3437             // failed.
3438             (*DeductionInfo)->addSFINAEDiagnostic(
3439               OldDiag.first,
3440               PDiag(diag::err_typename_nested_not_found_requirement)
3441                 << FailedDescription
3442                 << FailedCond->getSourceRange());
3443           }
3444         }
3445       }
3446
3447       return QualType();
3448     }
3449   } else if (Name.isDependent() ||
3450              TemplateSpecializationType::anyDependentTemplateArguments(
3451                TemplateArgs, InstantiationDependent)) {
3452     // This class template specialization is a dependent
3453     // type. Therefore, its canonical type is another class template
3454     // specialization type that contains all of the converted
3455     // arguments in canonical form. This ensures that, e.g., A<T> and
3456     // A<T, T> have identical types when A is declared as:
3457     //
3458     //   template<typename T, typename U = T> struct A;
3459     CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3460
3461     // This might work out to be a current instantiation, in which
3462     // case the canonical type needs to be the InjectedClassNameType.
3463     //
3464     // TODO: in theory this could be a simple hashtable lookup; most
3465     // changes to CurContext don't change the set of current
3466     // instantiations.
3467     if (isa<ClassTemplateDecl>(Template)) {
3468       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3469         // If we get out to a namespace, we're done.
3470         if (Ctx->isFileContext()) break;
3471
3472         // If this isn't a record, keep looking.
3473         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3474         if (!Record) continue;
3475
3476         // Look for one of the two cases with InjectedClassNameTypes
3477         // and check whether it's the same template.
3478         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3479             !Record->getDescribedClassTemplate())
3480           continue;
3481
3482         // Fetch the injected class name type and check whether its
3483         // injected type is equal to the type we just built.
3484         QualType ICNT = Context.getTypeDeclType(Record);
3485         QualType Injected = cast<InjectedClassNameType>(ICNT)
3486           ->getInjectedSpecializationType();
3487
3488         if (CanonType != Injected->getCanonicalTypeInternal())
3489           continue;
3490
3491         // If so, the canonical type of this TST is the injected
3492         // class name type of the record we just found.
3493         assert(ICNT.isCanonical());
3494         CanonType = ICNT;
3495         break;
3496       }
3497     }
3498   } else if (ClassTemplateDecl *ClassTemplate
3499                = dyn_cast<ClassTemplateDecl>(Template)) {
3500     // Find the class template specialization declaration that
3501     // corresponds to these arguments.
3502     void *InsertPos = nullptr;
3503     ClassTemplateSpecializationDecl *Decl
3504       = ClassTemplate->findSpecialization(Converted, InsertPos);
3505     if (!Decl) {
3506       // This is the first time we have referenced this class template
3507       // specialization. Create the canonical declaration and add it to
3508       // the set of specializations.
3509       Decl = ClassTemplateSpecializationDecl::Create(
3510           Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3511           ClassTemplate->getDeclContext(),
3512           ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3513           ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
3514       ClassTemplate->AddSpecialization(Decl, InsertPos);
3515       if (ClassTemplate->isOutOfLine())
3516         Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3517     }
3518
3519     if (Decl->getSpecializationKind() == TSK_Undeclared) {
3520       MultiLevelTemplateArgumentList TemplateArgLists;
3521       TemplateArgLists.addOuterTemplateArguments(Converted);
3522       InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3523                               Decl);
3524     }
3525
3526     // Diagnose uses of this specialization.
3527     (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3528
3529     CanonType = Context.getTypeDeclType(Decl);
3530     assert(isa<RecordType>(CanonType) &&
3531            "type of non-dependent specialization is not a RecordType");
3532   } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3533     CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3534                                            TemplateArgs);
3535   }
3536
3537   // Build the fully-sugared type for this class template
3538   // specialization, which refers back to the class template
3539   // specialization we created or found.
3540   return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3541 }
3542
3543 void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3544                                            TemplateNameKind &TNK,
3545                                            SourceLocation NameLoc,
3546                                            IdentifierInfo *&II) {
3547   assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3548
3549   TemplateName Name = ParsedName.get();
3550   auto *ATN = Name.getAsAssumedTemplateName();
3551   assert(ATN && "not an assumed template name");
3552   II = ATN->getDeclName().getAsIdentifierInfo();
3553
3554   if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3555     // Resolved to a type template name.
3556     ParsedName = TemplateTy::make(Name);
3557     TNK = TNK_Type_template;
3558   }
3559 }
3560
3561 bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3562                                             SourceLocation NameLoc,
3563                                             bool Diagnose) {
3564   // We assumed this undeclared identifier to be an (ADL-only) function
3565   // template name, but it was used in a context where a type was required.
3566   // Try to typo-correct it now.
3567   AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3568   assert(ATN && "not an assumed template name");
3569
3570   LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3571   struct CandidateCallback : CorrectionCandidateCallback {
3572     bool ValidateCandidate(const TypoCorrection &TC) override {
3573       return TC.getCorrectionDecl() &&
3574              getAsTypeTemplateDecl(TC.getCorrectionDecl());
3575     }
3576     std::unique_ptr<CorrectionCandidateCallback> clone() override {
3577       return std::make_unique<CandidateCallback>(*this);
3578     }
3579   } FilterCCC;
3580
3581   TypoCorrection Corrected =
3582       CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3583                   FilterCCC, CTK_ErrorRecovery);
3584   if (Corrected && Corrected.getFoundDecl()) {
3585     diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3586                                 << ATN->getDeclName());
3587     Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3588     return false;
3589   }
3590
3591   if (Diagnose)
3592     Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3593   return true;
3594 }
3595
3596 TypeResult Sema::ActOnTemplateIdType(
3597     Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3598     TemplateTy TemplateD, IdentifierInfo *TemplateII,
3599     SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3600     ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3601     bool IsCtorOrDtorName, bool IsClassName) {
3602   if (SS.isInvalid())
3603     return true;
3604
3605   if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3606     DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3607
3608     // C++ [temp.res]p3:
3609     //   A qualified-id that refers to a type and in which the
3610     //   nested-name-specifier depends on a template-parameter (14.6.2)
3611     //   shall be prefixed by the keyword typename to indicate that the
3612     //   qualified-id denotes a type, forming an
3613     //   elaborated-type-specifier (7.1.5.3).
3614     if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3615       Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3616         << SS.getScopeRep() << TemplateII->getName();
3617       // Recover as if 'typename' were specified.
3618       // FIXME: This is not quite correct recovery as we don't transform SS
3619       // into the corresponding dependent form (and we don't diagnose missing
3620       // 'template' keywords within SS as a result).
3621       return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3622                                TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3623                                TemplateArgsIn, RAngleLoc);
3624     }
3625
3626     // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3627     // it's not actually allowed to be used as a type in most cases. Because
3628     // we annotate it before we know whether it's valid, we have to check for
3629     // this case here.
3630     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3631     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3632       Diag(TemplateIILoc,
3633            TemplateKWLoc.isInvalid()
3634                ? diag::err_out_of_line_qualified_id_type_names_constructor
3635                : diag::ext_out_of_line_qualified_id_type_names_constructor)
3636         << TemplateII << 0 /*injected-class-name used as template name*/
3637         << 1 /*if any keyword was present, it was 'template'*/;
3638     }
3639   }
3640
3641   TemplateName Template = TemplateD.get();
3642   if (Template.getAsAssumedTemplateName() &&
3643       resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3644     return true;
3645
3646   // Translate the parser's template argument list in our AST format.
3647   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3648   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3649
3650   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3651     QualType T
3652       = Context.getDependentTemplateSpecializationType(ETK_None,
3653                                                        DTN->getQualifier(),
3654                                                        DTN->getIdentifier(),
3655                                                        TemplateArgs);
3656     // Build type-source information.
3657     TypeLocBuilder TLB;
3658     DependentTemplateSpecializationTypeLoc SpecTL
3659       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3660     SpecTL.setElaboratedKeywordLoc(SourceLocation());
3661     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3662     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3663     SpecTL.setTemplateNameLoc(TemplateIILoc);
3664     SpecTL.setLAngleLoc(LAngleLoc);
3665     SpecTL.setRAngleLoc(RAngleLoc);
3666     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3667       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3668     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3669   }
3670
3671   QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3672   if (Result.isNull())
3673     return true;
3674
3675   // Build type-source information.
3676   TypeLocBuilder TLB;
3677   TemplateSpecializationTypeLoc SpecTL
3678     = TLB.push<TemplateSpecializationTypeLoc>(Result);
3679   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3680   SpecTL.setTemplateNameLoc(TemplateIILoc);
3681   SpecTL.setLAngleLoc(LAngleLoc);
3682   SpecTL.setRAngleLoc(RAngleLoc);
3683   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3684     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3685
3686   // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3687   // constructor or destructor name (in such a case, the scope specifier
3688   // will be attached to the enclosing Decl or Expr node).
3689   if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3690     // Create an elaborated-type-specifier containing the nested-name-specifier.
3691     Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3692     ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3693     ElabTL.setElaboratedKeywordLoc(SourceLocation());
3694     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3695   }
3696
3697   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3698 }
3699
3700 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3701                                         TypeSpecifierType TagSpec,
3702                                         SourceLocation TagLoc,
3703                                         CXXScopeSpec &SS,
3704                                         SourceLocation TemplateKWLoc,
3705                                         TemplateTy TemplateD,
3706                                         SourceLocation TemplateLoc,
3707                                         SourceLocation LAngleLoc,
3708                                         ASTTemplateArgsPtr TemplateArgsIn,
3709                                         SourceLocation RAngleLoc) {
3710   TemplateName Template = TemplateD.get();
3711
3712   // Translate the parser's template argument list in our AST format.
3713   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3714   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3715
3716   // Determine the tag kind
3717   TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3718   ElaboratedTypeKeyword Keyword
3719     = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3720
3721   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3722     QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3723                                                           DTN->getQualifier(),
3724                                                           DTN->getIdentifier(),
3725                                                                 TemplateArgs);
3726
3727     // Build type-source information.
3728     TypeLocBuilder TLB;
3729     DependentTemplateSpecializationTypeLoc SpecTL
3730       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3731     SpecTL.setElaboratedKeywordLoc(TagLoc);
3732     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3733     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3734     SpecTL.setTemplateNameLoc(TemplateLoc);
3735     SpecTL.setLAngleLoc(LAngleLoc);
3736     SpecTL.setRAngleLoc(RAngleLoc);
3737     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3738       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3739     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3740   }
3741
3742   if (TypeAliasTemplateDecl *TAT =
3743         dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3744     // C++0x [dcl.type.elab]p2:
3745     //   If the identifier resolves to a typedef-name or the simple-template-id
3746     //   resolves to an alias template specialization, the
3747     //   elaborated-type-specifier is ill-formed.
3748     Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3749         << TAT << NTK_TypeAliasTemplate << TagKind;
3750     Diag(TAT->getLocation(), diag::note_declared_at);
3751   }
3752
3753   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3754   if (Result.isNull())
3755     return TypeResult(true);
3756
3757   // Check the tag kind
3758   if (const RecordType *RT = Result->getAs<RecordType>()) {
3759     RecordDecl *D = RT->getDecl();
3760
3761     IdentifierInfo *Id = D->getIdentifier();
3762     assert(Id && "templated class must have an identifier");
3763
3764     if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3765                                       TagLoc, Id)) {
3766       Diag(TagLoc, diag::err_use_with_wrong_tag)
3767         << Result
3768         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3769       Diag(D->getLocation(), diag::note_previous_use);
3770     }
3771   }
3772
3773   // Provide source-location information for the template specialization.
3774   TypeLocBuilder TLB;
3775   TemplateSpecializationTypeLoc SpecTL
3776     = TLB.push<TemplateSpecializationTypeLoc>(Result);
3777   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3778   SpecTL.setTemplateNameLoc(TemplateLoc);
3779   SpecTL.setLAngleLoc(LAngleLoc);
3780   SpecTL.setRAngleLoc(RAngleLoc);
3781   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3782     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3783
3784   // Construct an elaborated type containing the nested-name-specifier (if any)
3785   // and tag keyword.
3786   Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3787   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3788   ElabTL.setElaboratedKeywordLoc(TagLoc);
3789   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3790   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3791 }
3792
3793 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3794                                              NamedDecl *PrevDecl,
3795                                              SourceLocation Loc,
3796                                              bool IsPartialSpecialization);
3797
3798 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3799
3800 static bool isTemplateArgumentTemplateParameter(
3801     const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3802   switch (Arg.getKind()) {
3803   case TemplateArgument::Null:
3804   case TemplateArgument::NullPtr:
3805   case TemplateArgument::Integral:
3806   case TemplateArgument::Declaration:
3807   case TemplateArgument::Pack:
3808   case TemplateArgument::TemplateExpansion:
3809     return false;
3810
3811   case TemplateArgument::Type: {
3812     QualType Type = Arg.getAsType();
3813     const TemplateTypeParmType *TPT =
3814         Arg.getAsType()->getAs<TemplateTypeParmType>();
3815     return TPT && !Type.hasQualifiers() &&
3816            TPT->getDepth() == Depth && TPT->getIndex() == Index;
3817   }
3818
3819   case TemplateArgument::Expression: {
3820     DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3821     if (!DRE || !DRE->getDecl())
3822       return false;
3823     const NonTypeTemplateParmDecl *NTTP =
3824         dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3825     return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3826   }
3827
3828   case TemplateArgument::Template:
3829     const TemplateTemplateParmDecl *TTP =
3830         dyn_cast_or_null<TemplateTemplateParmDecl>(
3831             Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3832     return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3833   }
3834   llvm_unreachable("unexpected kind of template argument");
3835 }
3836
3837 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3838                                     ArrayRef<TemplateArgument> Args) {
3839   if (Params->size() != Args.size())
3840     return false;
3841
3842   unsigned Depth = Params->getDepth();
3843
3844   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3845     TemplateArgument Arg = Args[I];
3846
3847     // If the parameter is a pack expansion, the argument must be a pack
3848     // whose only element is a pack expansion.
3849     if (Params->getParam(I)->isParameterPack()) {
3850       if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3851           !Arg.pack_begin()->isPackExpansion())
3852         return false;
3853       Arg = Arg.pack_begin()->getPackExpansionPattern();
3854     }
3855
3856     if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3857       return false;
3858   }
3859
3860   return true;
3861 }
3862
3863 template<typename PartialSpecDecl>
3864 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3865   if (Partial->getDeclContext()->isDependentContext())
3866     return;
3867
3868   // FIXME: Get the TDK from deduction in order to provide better diagnostics
3869   // for non-substitution-failure issues?
3870   TemplateDeductionInfo Info(Partial->getLocation());
3871   if (S.isMoreSpecializedThanPrimary(Partial, Info))
3872     return;
3873
3874   auto *Template = Partial->getSpecializedTemplate();
3875   S.Diag(Partial->getLocation(),
3876          diag::ext_partial_spec_not_more_specialized_than_primary)
3877       << isa<VarTemplateDecl>(Template);
3878
3879   if (Info.hasSFINAEDiagnostic()) {
3880     PartialDiagnosticAt Diag = {SourceLocation(),
3881                                 PartialDiagnostic::NullDiagnostic()};
3882     Info.takeSFINAEDiagnostic(Diag);
3883     SmallString<128> SFINAEArgString;
3884     Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3885     S.Diag(Diag.first,
3886            diag::note_partial_spec_not_more_specialized_than_primary)
3887       << SFINAEArgString;
3888   }
3889
3890   S.Diag(Template->getLocation(), diag::note_template_decl_here);
3891   SmallVector<const Expr *, 3> PartialAC, TemplateAC;
3892   Template->getAssociatedConstraints(TemplateAC);
3893   Partial->getAssociatedConstraints(PartialAC);
3894   S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
3895                                                   TemplateAC);
3896 }
3897
3898 static void
3899 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3900                            const llvm::SmallBitVector &DeducibleParams) {
3901   for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3902     if (!DeducibleParams[I]) {
3903       NamedDecl *Param = TemplateParams->getParam(I);
3904       if (Param->getDeclName())
3905         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3906             << Param->getDeclName();
3907       else
3908         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3909             << "(anonymous)";
3910     }
3911   }
3912 }
3913
3914
3915 template<typename PartialSpecDecl>
3916 static void checkTemplatePartialSpecialization(Sema &S,
3917                                                PartialSpecDecl *Partial) {
3918   // C++1z [temp.class.spec]p8: (DR1495)
3919   //   - The specialization shall be more specialized than the primary
3920   //     template (14.5.5.2).
3921   checkMoreSpecializedThanPrimary(S, Partial);
3922
3923   // C++ [temp.class.spec]p8: (DR1315)
3924   //   - Each template-parameter shall appear at least once in the
3925   //     template-id outside a non-deduced context.
3926   // C++1z [temp.class.spec.match]p3 (P0127R2)
3927   //   If the template arguments of a partial specialization cannot be
3928   //   deduced because of the structure of its template-parameter-list
3929   //   and the template-id, the program is ill-formed.
3930   auto *TemplateParams = Partial->getTemplateParameters();
3931   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3932   S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3933                                TemplateParams->getDepth(), DeducibleParams);
3934
3935   if (!DeducibleParams.all()) {
3936     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3937     S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3938       << isa<VarTemplatePartialSpecializationDecl>(Partial)
3939       << (NumNonDeducible > 1)
3940       << SourceRange(Partial->getLocation(),
3941                      Partial->getTemplateArgsAsWritten()->RAngleLoc);
3942     noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3943   }
3944 }
3945
3946 void Sema::CheckTemplatePartialSpecialization(
3947     ClassTemplatePartialSpecializationDecl *Partial) {
3948   checkTemplatePartialSpecialization(*this, Partial);
3949 }
3950
3951 void Sema::CheckTemplatePartialSpecialization(
3952     VarTemplatePartialSpecializationDecl *Partial) {
3953   checkTemplatePartialSpecialization(*this, Partial);
3954 }
3955
3956 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3957   // C++1z [temp.param]p11:
3958   //   A template parameter of a deduction guide template that does not have a
3959   //   default-argument shall be deducible from the parameter-type-list of the
3960   //   deduction guide template.
3961   auto *TemplateParams = TD->getTemplateParameters();
3962   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3963   MarkDeducedTemplateParameters(TD, DeducibleParams);
3964   for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3965     // A parameter pack is deducible (to an empty pack).
3966     auto *Param = TemplateParams->getParam(I);
3967     if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3968       DeducibleParams[I] = true;
3969   }
3970
3971   if (!DeducibleParams.all()) {
3972     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3973     Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3974       << (NumNonDeducible > 1);
3975     noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3976   }
3977 }
3978
3979 DeclResult Sema::ActOnVarTemplateSpecialization(
3980     Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3981     TemplateParameterList *TemplateParams, StorageClass SC,
3982     bool IsPartialSpecialization) {
3983   // D must be variable template id.
3984   assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
3985          "Variable template specialization is declared with a template it.");
3986
3987   TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3988   TemplateArgumentListInfo TemplateArgs =
3989       makeTemplateArgumentListInfo(*this, *TemplateId);
3990   SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3991   SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3992   SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3993
3994   TemplateName Name = TemplateId->Template.get();
3995
3996   // The template-id must name a variable template.
3997   VarTemplateDecl *VarTemplate =
3998       dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3999   if (!VarTemplate) {
4000     NamedDecl *FnTemplate;
4001     if (auto *OTS = Name.getAsOverloadedTemplate())
4002       FnTemplate = *OTS->begin();
4003     else
4004       FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4005     if (FnTemplate)
4006       return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4007                << FnTemplate->getDeclName();
4008     return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4009              << IsPartialSpecialization;
4010   }
4011
4012   // Check for unexpanded parameter packs in any of the template arguments.
4013   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4014     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4015                                         UPPC_PartialSpecialization))
4016       return true;
4017
4018   // Check that the template argument list is well-formed for this
4019   // template.
4020   SmallVector<TemplateArgument, 4> Converted;
4021   if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4022                                 false, Converted,
4023                                 /*UpdateArgsWithConversion=*/true))
4024     return true;
4025
4026   // Find the variable template (partial) specialization declaration that
4027   // corresponds to these arguments.
4028   if (IsPartialSpecialization) {
4029     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4030                                                TemplateArgs.size(), Converted))
4031       return true;
4032
4033     // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4034     // also do them during instantiation.
4035     bool InstantiationDependent;
4036     if (!Name.isDependent() &&
4037         !TemplateSpecializationType::anyDependentTemplateArguments(
4038             TemplateArgs.arguments(),
4039             InstantiationDependent)) {
4040       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4041           << VarTemplate->getDeclName();
4042       IsPartialSpecialization = false;
4043     }
4044
4045     if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4046                                 Converted) &&
4047         (!Context.getLangOpts().ConceptsTS ||
4048          !TemplateParams->hasAssociatedConstraints())) {
4049       // C++ [temp.class.spec]p9b3:
4050       //
4051       //   -- The argument list of the specialization shall not be identical
4052       //      to the implicit argument list of the primary template.
4053       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4054         << /*variable template*/ 1
4055         << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4056         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4057       // FIXME: Recover from this by treating the declaration as a redeclaration
4058       // of the primary template.
4059       return true;
4060     }
4061   }
4062
4063   void *InsertPos = nullptr;
4064   VarTemplateSpecializationDecl *PrevDecl = nullptr;
4065
4066   if (IsPartialSpecialization)
4067     PrevDecl = VarTemplate->findPartialSpecialization(Converted, TemplateParams,
4068                                                       InsertPos);
4069   else
4070     PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
4071
4072   VarTemplateSpecializationDecl *Specialization = nullptr;
4073
4074   // Check whether we can declare a variable template specialization in
4075   // the current scope.
4076   if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4077                                        TemplateNameLoc,
4078                                        IsPartialSpecialization))
4079     return true;
4080
4081   if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4082     // Since the only prior variable template specialization with these
4083     // arguments was referenced but not declared,  reuse that
4084     // declaration node as our own, updating its source location and
4085     // the list of outer template parameters to reflect our new declaration.
4086     Specialization = PrevDecl;
4087     Specialization->setLocation(TemplateNameLoc);
4088     PrevDecl = nullptr;
4089   } else if (IsPartialSpecialization) {
4090     // Create a new class template partial specialization declaration node.
4091     VarTemplatePartialSpecializationDecl *PrevPartial =
4092         cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4093     VarTemplatePartialSpecializationDecl *Partial =
4094         VarTemplatePartialSpecializationDecl::Create(
4095             Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4096             TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4097             Converted, TemplateArgs);
4098
4099     if (!PrevPartial)
4100       VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4101     Specialization = Partial;
4102
4103     // If we are providing an explicit specialization of a member variable
4104     // template specialization, make a note of that.
4105     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4106       PrevPartial->setMemberSpecialization();
4107
4108     CheckTemplatePartialSpecialization(Partial);
4109   } else {
4110     // Create a new class template specialization declaration node for
4111     // this explicit specialization or friend declaration.
4112     Specialization = VarTemplateSpecializationDecl::Create(
4113         Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4114         VarTemplate, DI->getType(), DI, SC, Converted);
4115     Specialization->setTemplateArgsInfo(TemplateArgs);
4116
4117     if (!PrevDecl)
4118       VarTemplate->AddSpecialization(Specialization, InsertPos);
4119   }
4120
4121   // C++ [temp.expl.spec]p6:
4122   //   If a template, a member template or the member of a class template is
4123   //   explicitly specialized then that specialization shall be declared
4124   //   before the first use of that specialization that would cause an implicit
4125   //   instantiation to take place, in every translation unit in which such a
4126   //   use occurs; no diagnostic is required.
4127   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4128     bool Okay = false;
4129     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4130       // Is there any previous explicit specialization declaration?
4131       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4132         Okay = true;
4133         break;
4134       }
4135     }
4136
4137     if (!Okay) {
4138       SourceRange Range(TemplateNameLoc, RAngleLoc);
4139       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4140           << Name << Range;
4141
4142       Diag(PrevDecl->getPointOfInstantiation(),
4143            diag::note_instantiation_required_here)
4144           << (PrevDecl->getTemplateSpecializationKind() !=
4145               TSK_ImplicitInstantiation);
4146       return true;
4147     }
4148   }
4149
4150   Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4151   Specialization->setLexicalDeclContext(CurContext);
4152
4153   // Add the specialization into its lexical context, so that it can
4154   // be seen when iterating through the list of declarations in that
4155   // context. However, specializations are not found by name lookup.
4156   CurContext->addDecl(Specialization);
4157
4158   // Note that this is an explicit specialization.
4159   Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4160
4161   if (PrevDecl) {
4162     // Check that this isn't a redefinition of this specialization,
4163     // merging with previous declarations.
4164     LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4165                           forRedeclarationInCurContext());
4166     PrevSpec.addDecl(PrevDecl);
4167     D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4168   } else if (Specialization->isStaticDataMember() &&
4169              Specialization->isOutOfLine()) {
4170     Specialization->setAccess(VarTemplate->getAccess());
4171   }
4172
4173   return Specialization;
4174 }
4175
4176 namespace {
4177 /// A partial specialization whose template arguments have matched
4178 /// a given template-id.
4179 struct PartialSpecMatchResult {
4180   VarTemplatePartialSpecializationDecl *Partial;
4181   TemplateArgumentList *Args;
4182 };
4183 } // end anonymous namespace
4184
4185 DeclResult
4186 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4187                          SourceLocation TemplateNameLoc,
4188                          const TemplateArgumentListInfo &TemplateArgs) {
4189   assert(Template && "A variable template id without template?");
4190
4191   // Check that the template argument list is well-formed for this template.
4192   SmallVector<TemplateArgument, 4> Converted;
4193   if (CheckTemplateArgumentList(
4194           Template, TemplateNameLoc,
4195           const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4196           Converted, /*UpdateArgsWithConversion=*/true))
4197     return true;
4198
4199   // Find the variable template specialization declaration that
4200   // corresponds to these arguments.
4201   void *InsertPos = nullptr;
4202   if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
4203           Converted, InsertPos)) {
4204     checkSpecializationVisibility(TemplateNameLoc, Spec);
4205     // If we already have a variable template specialization, return it.
4206     return Spec;
4207   }
4208
4209   // This is the first time we have referenced this variable template
4210   // specialization. Create the canonical declaration and add it to
4211   // the set of specializations, based on the closest partial specialization
4212   // that it represents. That is,
4213   VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4214   TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4215                                        Converted);
4216   TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4217   bool AmbiguousPartialSpec = false;
4218   typedef PartialSpecMatchResult MatchResult;
4219   SmallVector<MatchResult, 4> Matched;
4220   SourceLocation PointOfInstantiation = TemplateNameLoc;
4221   TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4222                                             /*ForTakingAddress=*/false);
4223
4224   // 1. Attempt to find the closest partial specialization that this
4225   // specializes, if any.
4226   // If any of the template arguments is dependent, then this is probably
4227   // a placeholder for an incomplete declarative context; which must be
4228   // complete by instantiation time. Thus, do not search through the partial
4229   // specializations yet.
4230   // TODO: Unify with InstantiateClassTemplateSpecialization()?
4231   //       Perhaps better after unification of DeduceTemplateArguments() and
4232   //       getMoreSpecializedPartialSpecialization().
4233   bool InstantiationDependent = false;
4234   if (!TemplateSpecializationType::anyDependentTemplateArguments(
4235           TemplateArgs, InstantiationDependent)) {
4236
4237     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4238     Template->getPartialSpecializations(PartialSpecs);
4239
4240     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4241       VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4242       TemplateDeductionInfo Info(FailedCandidates.getLocation());
4243
4244       if (TemplateDeductionResult Result =
4245               DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4246         // Store the failed-deduction information for use in diagnostics, later.
4247         // TODO: Actually use the failed-deduction info?
4248         FailedCandidates.addCandidate().set(
4249             DeclAccessPair::make(Template, AS_public), Partial,
4250             MakeDeductionFailureInfo(Context, Result, Info));
4251         (void)Result;
4252       } else {
4253         Matched.push_back(PartialSpecMatchResult());
4254         Matched.back().Partial = Partial;
4255         Matched.back().Args = Info.take();
4256       }
4257     }
4258
4259     if (Matched.size() >= 1) {
4260       SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4261       if (Matched.size() == 1) {
4262         //   -- If exactly one matching specialization is found, the
4263         //      instantiation is generated from that specialization.
4264         // We don't need to do anything for this.
4265       } else {
4266         //   -- If more than one matching specialization is found, the
4267         //      partial order rules (14.5.4.2) are used to determine
4268         //      whether one of the specializations is more specialized
4269         //      than the others. If none of the specializations is more
4270         //      specialized than all of the other matching
4271         //      specializations, then the use of the variable template is
4272         //      ambiguous and the program is ill-formed.
4273         for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4274                                                    PEnd = Matched.end();
4275              P != PEnd; ++P) {
4276           if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4277                                                       PointOfInstantiation) ==
4278               P->Partial)
4279             Best = P;
4280         }
4281
4282         // Determine if the best partial specialization is more specialized than
4283         // the others.
4284         for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4285                                                    PEnd = Matched.end();
4286              P != PEnd; ++P) {
4287           if (P != Best && getMoreSpecializedPartialSpecialization(
4288                                P->Partial, Best->Partial,
4289                                PointOfInstantiation) != Best->Partial) {
4290             AmbiguousPartialSpec = true;
4291             break;
4292           }
4293         }
4294       }
4295
4296       // Instantiate using the best variable template partial specialization.
4297       InstantiationPattern = Best->Partial;
4298       InstantiationArgs = Best->Args;
4299     } else {
4300       //   -- If no match is found, the instantiation is generated
4301       //      from the primary template.
4302       // InstantiationPattern = Template->getTemplatedDecl();
4303     }
4304   }
4305
4306   // 2. Create the canonical declaration.
4307   // Note that we do not instantiate a definition until we see an odr-use
4308   // in DoMarkVarDeclReferenced().
4309   // FIXME: LateAttrs et al.?
4310   VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4311       Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4312       Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4313   if (!Decl)
4314     return true;
4315
4316   if (AmbiguousPartialSpec) {
4317     // Partial ordering did not produce a clear winner. Complain.
4318     Decl->setInvalidDecl();
4319     Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4320         << Decl;
4321
4322     // Print the matching partial specializations.
4323     for (MatchResult P : Matched)
4324       Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4325           << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4326                                              *P.Args);
4327     return true;
4328   }
4329
4330   if (VarTemplatePartialSpecializationDecl *D =
4331           dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4332     Decl->setInstantiationOf(D, InstantiationArgs);
4333
4334   checkSpecializationVisibility(TemplateNameLoc, Decl);
4335
4336   assert(Decl && "No variable template specialization?");
4337   return Decl;
4338 }
4339
4340 ExprResult
4341 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4342                          const DeclarationNameInfo &NameInfo,
4343                          VarTemplateDecl *Template, SourceLocation TemplateLoc,
4344                          const TemplateArgumentListInfo *TemplateArgs) {
4345
4346   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4347                                        *TemplateArgs);
4348   if (Decl.isInvalid())
4349     return ExprError();
4350
4351   VarDecl *Var = cast<VarDecl>(Decl.get());
4352   if (!Var->getTemplateSpecializationKind())
4353     Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4354                                        NameInfo.getLoc());
4355
4356   // Build an ordinary singleton decl ref.
4357   return BuildDeclarationNameExpr(SS, NameInfo, Var,
4358                                   /*FoundD=*/nullptr, TemplateArgs);
4359 }
4360
4361 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4362                                             SourceLocation Loc) {
4363   Diag(Loc, diag::err_template_missing_args)
4364     << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4365   if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4366     Diag(TD->getLocation(), diag::note_template_decl_here)
4367       << TD->getTemplateParameters()->getSourceRange();
4368   }
4369 }
4370
4371 ExprResult
4372 Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4373                              SourceLocation TemplateKWLoc,
4374                              const DeclarationNameInfo &ConceptNameInfo,
4375                              NamedDecl *FoundDecl,
4376                              ConceptDecl *NamedConcept,
4377                              const TemplateArgumentListInfo *TemplateArgs) {
4378   assert(NamedConcept && "A concept template id without a template?");
4379
4380   llvm::SmallVector<TemplateArgument, 4> Converted;
4381   if (CheckTemplateArgumentList(NamedConcept, ConceptNameInfo.getLoc(),
4382                            const_cast<TemplateArgumentListInfo&>(*TemplateArgs),
4383                                 /*PartialTemplateArgs=*/false, Converted,
4384                                 /*UpdateArgsWithConversion=*/false))
4385     return ExprError();
4386
4387   ConstraintSatisfaction Satisfaction;
4388   bool AreArgsDependent = false;
4389   for (TemplateArgument &Arg : Converted) {
4390     if (Arg.isDependent()) {
4391       AreArgsDependent = true;
4392       break;
4393     }
4394   }
4395   if (!AreArgsDependent &&
4396       CheckConstraintSatisfaction(NamedConcept,
4397                                   {NamedConcept->getConstraintExpr()},
4398                                   Converted,
4399                                   SourceRange(SS.isSet() ? SS.getBeginLoc() :
4400                                                        ConceptNameInfo.getLoc(),
4401                                                 TemplateArgs->getRAngleLoc()),
4402                                     Satisfaction))
4403       return ExprError();
4404
4405   return ConceptSpecializationExpr::Create(Context,
4406       SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4407       TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4408       ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), Converted,
4409       AreArgsDependent ? nullptr : &Satisfaction);
4410 }
4411
4412 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4413                                      SourceLocation TemplateKWLoc,
4414                                      LookupResult &R,
4415                                      bool RequiresADL,
4416                                  const TemplateArgumentListInfo *TemplateArgs) {
4417   // FIXME: Can we do any checking at this point? I guess we could check the
4418   // template arguments that we have against the template name, if the template
4419   // name refers to a single template. That's not a terribly common case,
4420   // though.
4421   // foo<int> could identify a single function unambiguously
4422   // This approach does NOT work, since f<int>(1);
4423   // gets resolved prior to resorting to overload resolution
4424   // i.e., template<class T> void f(double);
4425   //       vs template<class T, class U> void f(U);
4426
4427   // These should be filtered out by our callers.
4428   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4429
4430   // Non-function templates require a template argument list.
4431   if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4432     if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4433       diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4434       return ExprError();
4435     }
4436   }
4437
4438   auto AnyDependentArguments = [&]() -> bool {
4439     bool InstantiationDependent;
4440     return TemplateArgs &&
4441            TemplateSpecializationType::anyDependentTemplateArguments(
4442                *TemplateArgs, InstantiationDependent);
4443   };
4444
4445   // In C++1y, check variable template ids.
4446   if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
4447     return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4448                               R.getAsSingle<VarTemplateDecl>(),
4449                               TemplateKWLoc, TemplateArgs);
4450   }
4451
4452   if (R.getAsSingle<ConceptDecl>()) {
4453     return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4454                                   R.getFoundDecl(),
4455                                   R.getAsSingle<ConceptDecl>(), TemplateArgs);
4456   }
4457
4458   // We don't want lookup warnings at this point.
4459   R.suppressDiagnostics();
4460
4461   UnresolvedLookupExpr *ULE
4462     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4463                                    SS.getWithLocInContext(Context),
4464                                    TemplateKWLoc,
4465                                    R.getLookupNameInfo(),
4466                                    RequiresADL, TemplateArgs,
4467                                    R.begin(), R.end());
4468
4469   return ULE;
4470 }
4471
4472 // We actually only call this from template instantiation.
4473 ExprResult
4474 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4475                                    SourceLocation TemplateKWLoc,
4476                                    const DeclarationNameInfo &NameInfo,
4477                              const TemplateArgumentListInfo *TemplateArgs) {
4478
4479   assert(TemplateArgs || TemplateKWLoc.isValid());
4480   DeclContext *DC;
4481   if (!(DC = computeDeclContext(SS, false)) ||
4482       DC->isDependentContext() ||
4483       RequireCompleteDeclContext(SS, DC))
4484     return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4485
4486   bool MemberOfUnknownSpecialization;
4487   LookupResult R(*this, NameInfo, LookupOrdinaryName);
4488   if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4489                          /*Entering*/false, MemberOfUnknownSpecialization,
4490                          TemplateKWLoc))
4491     return ExprError();
4492
4493   if (R.isAmbiguous())
4494     return ExprError();
4495
4496   if (R.empty()) {
4497     Diag(NameInfo.getLoc(), diag::err_no_member)
4498       << NameInfo.getName() << DC << SS.getRange();
4499     return ExprError();
4500   }
4501
4502   if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4503     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4504       << SS.getScopeRep()
4505       << NameInfo.getName().getAsString() << SS.getRange();
4506     Diag(Temp->getLocation(), diag::note_referenced_class_template);
4507     return ExprError();
4508   }
4509
4510   return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4511 }
4512
4513 /// Form a dependent template name.
4514 ///
4515 /// This action forms a dependent template name given the template
4516 /// name and its (presumably dependent) scope specifier. For
4517 /// example, given "MetaFun::template apply", the scope specifier \p
4518 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4519 /// of the "template" keyword, and "apply" is the \p Name.
4520 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
4521                                                   CXXScopeSpec &SS,
4522                                                   SourceLocation TemplateKWLoc,
4523                                                   const UnqualifiedId &Name,
4524                                                   ParsedType ObjectType,
4525                                                   bool EnteringContext,
4526                                                   TemplateTy &Result,
4527                                                   bool AllowInjectedClassName) {
4528   if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4529     Diag(TemplateKWLoc,
4530          getLangOpts().CPlusPlus11 ?
4531            diag::warn_cxx98_compat_template_outside_of_template :
4532            diag::ext_template_outside_of_template)
4533       << FixItHint::CreateRemoval(TemplateKWLoc);
4534
4535   DeclContext *LookupCtx = nullptr;
4536   if (SS.isSet())
4537     LookupCtx = computeDeclContext(SS, EnteringContext);
4538   if (!LookupCtx && ObjectType)
4539     LookupCtx = computeDeclContext(ObjectType.get());
4540   if (LookupCtx) {
4541     // C++0x [temp.names]p5:
4542     //   If a name prefixed by the keyword template is not the name of
4543     //   a template, the program is ill-formed. [Note: the keyword
4544     //   template may not be applied to non-template members of class
4545     //   templates. -end note ] [ Note: as is the case with the
4546     //   typename prefix, the template prefix is allowed in cases
4547     //   where it is not strictly necessary; i.e., when the
4548     //   nested-name-specifier or the expression on the left of the ->
4549     //   or . is not dependent on a template-parameter, or the use
4550     //   does not appear in the scope of a template. -end note]
4551     //
4552     // Note: C++03 was more strict here, because it banned the use of
4553     // the "template" keyword prior to a template-name that was not a
4554     // dependent name. C++ DR468 relaxed this requirement (the
4555     // "template" keyword is now permitted). We follow the C++0x
4556     // rules, even in C++03 mode with a warning, retroactively applying the DR.
4557     bool MemberOfUnknownSpecialization;
4558     TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4559                                           ObjectType, EnteringContext, Result,
4560                                           MemberOfUnknownSpecialization);
4561     if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
4562       // This is a dependent template. Handle it below.
4563     } else if (TNK == TNK_Non_template) {
4564       // Do the lookup again to determine if this is a "nothing found" case or
4565       // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4566       // need to do this.
4567       DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4568       LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4569                      LookupOrdinaryName);
4570       bool MOUS;
4571       if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
4572                               MOUS, TemplateKWLoc) && !R.isAmbiguous())
4573         Diag(Name.getBeginLoc(), diag::err_no_member)
4574             << DNI.getName() << LookupCtx << SS.getRange();
4575       return TNK_Non_template;
4576     } else {
4577       // We found something; return it.
4578       auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4579       if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4580           Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4581           Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4582         // C++14 [class.qual]p2:
4583         //   In a lookup in which function names are not ignored and the
4584         //   nested-name-specifier nominates a class C, if the name specified
4585         //   [...] is the injected-class-name of C, [...] the name is instead
4586         //   considered to name the constructor
4587         //
4588         // We don't get here if naming the constructor would be valid, so we
4589         // just reject immediately and recover by treating the
4590         // injected-class-name as naming the template.
4591         Diag(Name.getBeginLoc(),
4592              diag::ext_out_of_line_qualified_id_type_names_constructor)
4593             << Name.Identifier
4594             << 0 /*injected-class-name used as template name*/
4595             << 1 /*'template' keyword was used*/;
4596       }
4597       return TNK;
4598     }
4599   }
4600
4601   NestedNameSpecifier *Qualifier = SS.getScopeRep();
4602
4603   switch (Name.getKind()) {
4604   case UnqualifiedIdKind::IK_Identifier:
4605     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4606                                                               Name.Identifier));
4607     return TNK_Dependent_template_name;
4608
4609   case UnqualifiedIdKind::IK_OperatorFunctionId:
4610     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4611                                              Name.OperatorFunctionId.Operator));
4612     return TNK_Function_template;
4613
4614   case UnqualifiedIdKind::IK_LiteralOperatorId:
4615     llvm_unreachable("literal operator id cannot have a dependent scope");
4616
4617   default:
4618     break;
4619   }
4620
4621   Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4622       << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4623       << TemplateKWLoc;
4624   return TNK_Non_template;
4625 }
4626
4627 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4628                                      TemplateArgumentLoc &AL,
4629                           SmallVectorImpl<TemplateArgument> &Converted) {
4630   const TemplateArgument &Arg = AL.getArgument();
4631   QualType ArgType;
4632   TypeSourceInfo *TSI = nullptr;
4633
4634   // Check template type parameter.
4635   switch(Arg.getKind()) {
4636   case TemplateArgument::Type:
4637     // C++ [temp.arg.type]p1:
4638     //   A template-argument for a template-parameter which is a
4639     //   type shall be a type-id.
4640     ArgType = Arg.getAsType();
4641     TSI = AL.getTypeSourceInfo();
4642     break;
4643   case TemplateArgument::Template:
4644   case TemplateArgument::TemplateExpansion: {
4645     // We have a template type parameter but the template argument
4646     // is a template without any arguments.
4647     SourceRange SR = AL.getSourceRange();
4648     TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4649     diagnoseMissingTemplateArguments(Name, SR.getEnd());
4650     return true;
4651   }
4652   case TemplateArgument::Expression: {
4653     // We have a template type parameter but the template argument is an
4654     // expression; see if maybe it is missing the "typename" keyword.
4655     CXXScopeSpec SS;
4656     DeclarationNameInfo NameInfo;
4657
4658     if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4659       SS.Adopt(ArgExpr->getQualifierLoc());
4660       NameInfo = ArgExpr->getNameInfo();
4661     } else if (DependentScopeDeclRefExpr *ArgExpr =
4662                dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4663       SS.Adopt(ArgExpr->getQualifierLoc());
4664       NameInfo = ArgExpr->getNameInfo();
4665     } else if (CXXDependentScopeMemberExpr *ArgExpr =
4666                dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4667       if (ArgExpr->isImplicitAccess()) {
4668         SS.Adopt(ArgExpr->getQualifierLoc());
4669         NameInfo = ArgExpr->getMemberNameInfo();
4670       }
4671     }
4672
4673     if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4674       LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4675       LookupParsedName(Result, CurScope, &SS);
4676
4677       if (Result.getAsSingle<TypeDecl>() ||
4678           Result.getResultKind() ==
4679               LookupResult::NotFoundInCurrentInstantiation) {
4680         // Suggest that the user add 'typename' before the NNS.
4681         SourceLocation Loc = AL.getSourceRange().getBegin();
4682         Diag(Loc, getLangOpts().MSVCCompat
4683                       ? diag::ext_ms_template_type_arg_missing_typename
4684                       : diag::err_template_arg_must_be_type_suggest)
4685             << FixItHint::CreateInsertion(Loc, "typename ");
4686         Diag(Param->getLocation(), diag::note_template_param_here);
4687
4688         // Recover by synthesizing a type using the location information that we
4689         // already have.
4690         ArgType =
4691             Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4692         TypeLocBuilder TLB;
4693         DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4694         TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4695         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4696         TL.setNameLoc(NameInfo.getLoc());
4697         TSI = TLB.getTypeSourceInfo(Context, ArgType);
4698
4699         // Overwrite our input TemplateArgumentLoc so that we can recover
4700         // properly.
4701         AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4702                                  TemplateArgumentLocInfo(TSI));
4703
4704         break;
4705       }
4706     }
4707     // fallthrough
4708     LLVM_FALLTHROUGH;
4709   }
4710   default: {
4711     // We have a template type parameter but the template argument
4712     // is not a type.
4713     SourceRange SR = AL.getSourceRange();
4714     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4715     Diag(Param->getLocation(), diag::note_template_param_here);
4716
4717     return true;
4718   }
4719   }
4720
4721   if (CheckTemplateArgument(Param, TSI))
4722     return true;
4723
4724   // Add the converted template type argument.
4725   ArgType = Context.getCanonicalType(ArgType);
4726
4727   // Objective-C ARC:
4728   //   If an explicitly-specified template argument type is a lifetime type
4729   //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4730   if (getLangOpts().ObjCAutoRefCount &&
4731       ArgType->isObjCLifetimeType() &&
4732       !ArgType.getObjCLifetime()) {
4733     Qualifiers Qs;
4734     Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4735     ArgType = Context.getQualifiedType(ArgType, Qs);
4736   }
4737
4738   Converted.push_back(TemplateArgument(ArgType));
4739   return false;
4740 }
4741
4742 /// Substitute template arguments into the default template argument for
4743 /// the given template type parameter.
4744 ///
4745 /// \param SemaRef the semantic analysis object for which we are performing
4746 /// the substitution.
4747 ///
4748 /// \param Template the template that we are synthesizing template arguments
4749 /// for.
4750 ///
4751 /// \param TemplateLoc the location of the template name that started the
4752 /// template-id we are checking.
4753 ///
4754 /// \param RAngleLoc the location of the right angle bracket ('>') that
4755 /// terminates the template-id.
4756 ///
4757 /// \param Param the template template parameter whose default we are
4758 /// substituting into.
4759 ///
4760 /// \param Converted the list of template arguments provided for template
4761 /// parameters that precede \p Param in the template parameter list.
4762 /// \returns the substituted template argument, or NULL if an error occurred.
4763 static TypeSourceInfo *
4764 SubstDefaultTemplateArgument(Sema &SemaRef,
4765                              TemplateDecl *Template,
4766                              SourceLocation TemplateLoc,
4767                              SourceLocation RAngleLoc,
4768                              TemplateTypeParmDecl *Param,
4769                              SmallVectorImpl<TemplateArgument> &Converted) {
4770   TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4771
4772   // If the argument type is dependent, instantiate it now based
4773   // on the previously-computed template arguments.
4774   if (ArgType->getType()->isInstantiationDependentType()) {
4775     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4776                                      Param, Template, Converted,
4777                                      SourceRange(TemplateLoc, RAngleLoc));
4778     if (Inst.isInvalid())
4779       return nullptr;
4780
4781     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4782
4783     // Only substitute for the innermost template argument list.
4784     MultiLevelTemplateArgumentList TemplateArgLists;
4785     TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4786     for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4787       TemplateArgLists.addOuterTemplateArguments(None);
4788
4789     Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4790     ArgType =
4791         SemaRef.SubstType(ArgType, TemplateArgLists,
4792                           Param->getDefaultArgumentLoc(), Param->getDeclName());
4793   }
4794
4795   return ArgType;
4796 }
4797
4798 /// Substitute template arguments into the default template argument for
4799 /// the given non-type template parameter.
4800 ///
4801 /// \param SemaRef the semantic analysis object for which we are performing
4802 /// the substitution.
4803 ///
4804 /// \param Template the template that we are synthesizing template arguments
4805 /// for.
4806 ///
4807 /// \param TemplateLoc the location of the template name that started the
4808 /// template-id we are checking.
4809 ///
4810 /// \param RAngleLoc the location of the right angle bracket ('>') that
4811 /// terminates the template-id.
4812 ///
4813 /// \param Param the non-type template parameter whose default we are
4814 /// substituting into.
4815 ///
4816 /// \param Converted the list of template arguments provided for template
4817 /// parameters that precede \p Param in the template parameter list.
4818 ///
4819 /// \returns the substituted template argument, or NULL if an error occurred.
4820 static ExprResult
4821 SubstDefaultTemplateArgument(Sema &SemaRef,
4822                              TemplateDecl *Template,
4823                              SourceLocation TemplateLoc,
4824                              SourceLocation RAngleLoc,
4825                              NonTypeTemplateParmDecl *Param,
4826                         SmallVectorImpl<TemplateArgument> &Converted) {
4827   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4828                                    Param, Template, Converted,
4829                                    SourceRange(TemplateLoc, RAngleLoc));
4830   if (Inst.isInvalid())
4831     return ExprError();
4832
4833   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4834
4835   // Only substitute for the innermost template argument list.
4836   MultiLevelTemplateArgumentList TemplateArgLists;
4837   TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4838   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4839     TemplateArgLists.addOuterTemplateArguments(None);
4840
4841   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4842   EnterExpressionEvaluationContext ConstantEvaluated(
4843       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4844   return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4845 }
4846
4847 /// Substitute template arguments into the default template argument for
4848 /// the given template template parameter.
4849 ///
4850 /// \param SemaRef the semantic analysis object for which we are performing
4851 /// the substitution.
4852 ///
4853 /// \param Template the template that we are synthesizing template arguments
4854 /// for.
4855 ///
4856 /// \param TemplateLoc the location of the template name that started the
4857 /// template-id we are checking.
4858 ///
4859 /// \param RAngleLoc the location of the right angle bracket ('>') that
4860 /// terminates the template-id.
4861 ///
4862 /// \param Param the template template parameter whose default we are
4863 /// substituting into.
4864 ///
4865 /// \param Converted the list of template arguments provided for template
4866 /// parameters that precede \p Param in the template parameter list.
4867 ///
4868 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4869 /// source-location information) that precedes the template name.
4870 ///
4871 /// \returns the substituted template argument, or NULL if an error occurred.
4872 static TemplateName
4873 SubstDefaultTemplateArgument(Sema &SemaRef,
4874                              TemplateDecl *Template,
4875                              SourceLocation TemplateLoc,
4876                              SourceLocation RAngleLoc,
4877                              TemplateTemplateParmDecl *Param,
4878                        SmallVectorImpl<TemplateArgument> &Converted,
4879                              NestedNameSpecifierLoc &QualifierLoc) {
4880   Sema::InstantiatingTemplate Inst(
4881       SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4882       SourceRange(TemplateLoc, RAngleLoc));
4883   if (Inst.isInvalid())
4884     return TemplateName();
4885
4886   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4887
4888   // Only substitute for the innermost template argument list.
4889   MultiLevelTemplateArgumentList TemplateArgLists;
4890   TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4891   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4892     TemplateArgLists.addOuterTemplateArguments(None);
4893
4894   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4895   // Substitute into the nested-name-specifier first,
4896   QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4897   if (QualifierLoc) {
4898     QualifierLoc =
4899         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4900     if (!QualifierLoc)
4901       return TemplateName();
4902   }
4903
4904   return SemaRef.SubstTemplateName(
4905              QualifierLoc,
4906              Param->getDefaultArgument().getArgument().getAsTemplate(),
4907              Param->getDefaultArgument().getTemplateNameLoc(),
4908              TemplateArgLists);
4909 }
4910
4911 /// If the given template parameter has a default template
4912 /// argument, substitute into that default template argument and
4913 /// return the corresponding template argument.
4914 TemplateArgumentLoc
4915 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4916                                               SourceLocation TemplateLoc,
4917                                               SourceLocation RAngleLoc,
4918                                               Decl *Param,
4919                                               SmallVectorImpl<TemplateArgument>
4920                                                 &Converted,
4921                                               bool &HasDefaultArg) {
4922   HasDefaultArg = false;
4923
4924   if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4925     if (!hasVisibleDefaultArgument(TypeParm))
4926       return TemplateArgumentLoc();
4927
4928     HasDefaultArg = true;
4929     TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4930                                                       TemplateLoc,
4931                                                       RAngleLoc,
4932                                                       TypeParm,
4933                                                       Converted);
4934     if (DI)
4935       return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4936
4937     return TemplateArgumentLoc();
4938   }
4939
4940   if (NonTypeTemplateParmDecl *NonTypeParm
4941         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4942     if (!hasVisibleDefaultArgument(NonTypeParm))
4943       return TemplateArgumentLoc();
4944
4945     HasDefaultArg = true;
4946     ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4947                                                   TemplateLoc,
4948                                                   RAngleLoc,
4949                                                   NonTypeParm,
4950                                                   Converted);
4951     if (Arg.isInvalid())
4952       return TemplateArgumentLoc();
4953
4954     Expr *ArgE = Arg.getAs<Expr>();
4955     return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4956   }
4957
4958   TemplateTemplateParmDecl *TempTempParm
4959     = cast<TemplateTemplateParmDecl>(Param);
4960   if (!hasVisibleDefaultArgument(TempTempParm))
4961     return TemplateArgumentLoc();
4962
4963   HasDefaultArg = true;
4964   NestedNameSpecifierLoc QualifierLoc;
4965   TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4966                                                     TemplateLoc,
4967                                                     RAngleLoc,
4968                                                     TempTempParm,
4969                                                     Converted,
4970                                                     QualifierLoc);
4971   if (TName.isNull())
4972     return TemplateArgumentLoc();
4973
4974   return TemplateArgumentLoc(TemplateArgument(TName),
4975                 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4976                 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4977 }
4978
4979 /// Convert a template-argument that we parsed as a type into a template, if
4980 /// possible. C++ permits injected-class-names to perform dual service as
4981 /// template template arguments and as template type arguments.
4982 static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4983   // Extract and step over any surrounding nested-name-specifier.
4984   NestedNameSpecifierLoc QualLoc;
4985   if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4986     if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4987       return TemplateArgumentLoc();
4988
4989     QualLoc = ETLoc.getQualifierLoc();
4990     TLoc = ETLoc.getNamedTypeLoc();
4991   }
4992
4993   // If this type was written as an injected-class-name, it can be used as a
4994   // template template argument.
4995   if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4996     return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4997                                QualLoc, InjLoc.getNameLoc());
4998
4999   // If this type was written as an injected-class-name, it may have been
5000   // converted to a RecordType during instantiation. If the RecordType is
5001   // *not* wrapped in a TemplateSpecializationType and denotes a class
5002   // template specialization, it must have come from an injected-class-name.
5003   if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5004     if (auto *CTSD =
5005             dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5006       return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
5007                                  QualLoc, RecLoc.getNameLoc());
5008
5009   return TemplateArgumentLoc();
5010 }
5011
5012 /// Check that the given template argument corresponds to the given
5013 /// template parameter.
5014 ///
5015 /// \param Param The template parameter against which the argument will be
5016 /// checked.
5017 ///
5018 /// \param Arg The template argument, which may be updated due to conversions.
5019 ///
5020 /// \param Template The template in which the template argument resides.
5021 ///
5022 /// \param TemplateLoc The location of the template name for the template
5023 /// whose argument list we're matching.
5024 ///
5025 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
5026 /// the template argument list.
5027 ///
5028 /// \param ArgumentPackIndex The index into the argument pack where this
5029 /// argument will be placed. Only valid if the parameter is a parameter pack.
5030 ///
5031 /// \param Converted The checked, converted argument will be added to the
5032 /// end of this small vector.
5033 ///
5034 /// \param CTAK Describes how we arrived at this particular template argument:
5035 /// explicitly written, deduced, etc.
5036 ///
5037 /// \returns true on error, false otherwise.
5038 bool Sema::CheckTemplateArgument(NamedDecl *Param,
5039                                  TemplateArgumentLoc &Arg,
5040                                  NamedDecl *Template,
5041                                  SourceLocation TemplateLoc,
5042                                  SourceLocation RAngleLoc,
5043                                  unsigned ArgumentPackIndex,
5044                             SmallVectorImpl<TemplateArgument> &Converted,
5045                                  CheckTemplateArgumentKind CTAK) {
5046   // Check template type parameters.
5047   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5048     return CheckTemplateTypeArgument(TTP, Arg, Converted);
5049
5050   // Check non-type template parameters.
5051   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5052     // Do substitution on the type of the non-type template parameter
5053     // with the template arguments we've seen thus far.  But if the
5054     // template has a dependent context then we cannot substitute yet.
5055     QualType NTTPType = NTTP->getType();
5056     if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5057       NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5058
5059     if (NTTPType->isInstantiationDependentType() &&
5060         !isa<TemplateTemplateParmDecl>(Template) &&
5061         !Template->getDeclContext()->isDependentContext()) {
5062       // Do substitution on the type of the non-type template parameter.
5063       InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5064                                  NTTP, Converted,
5065                                  SourceRange(TemplateLoc, RAngleLoc));
5066       if (Inst.isInvalid())
5067         return true;
5068
5069       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
5070                                         Converted);
5071
5072       // If the parameter is a pack expansion, expand this slice of the pack.
5073       if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5074         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5075                                                            ArgumentPackIndex);
5076         NTTPType = SubstType(PET->getPattern(),
5077                              MultiLevelTemplateArgumentList(TemplateArgs),
5078                              NTTP->getLocation(),
5079                              NTTP->getDeclName());
5080       } else {
5081         NTTPType = SubstType(NTTPType,
5082                              MultiLevelTemplateArgumentList(TemplateArgs),
5083                              NTTP->getLocation(),
5084                              NTTP->getDeclName());
5085       }
5086
5087       // If that worked, check the non-type template parameter type
5088       // for validity.
5089       if (!NTTPType.isNull())
5090         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5091                                                      NTTP->getLocation());
5092       if (NTTPType.isNull())
5093         return true;
5094     }
5095
5096     switch (Arg.getArgument().getKind()) {
5097     case TemplateArgument::Null:
5098       llvm_unreachable("Should never see a NULL template argument here");
5099
5100     case TemplateArgument::Expression: {
5101       TemplateArgument Result;
5102       unsigned CurSFINAEErrors = NumSFINAEErrors;
5103       ExprResult Res =
5104         CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
5105                               Result, CTAK);
5106       if (Res.isInvalid())
5107         return true;
5108       // If the current template argument causes an error, give up now.
5109       if (CurSFINAEErrors < NumSFINAEErrors)
5110         return true;
5111
5112       // If the resulting expression is new, then use it in place of the
5113       // old expression in the template argument.
5114       if (Res.get() != Arg.getArgument().getAsExpr()) {
5115         TemplateArgument TA(Res.get());
5116         Arg = TemplateArgumentLoc(TA, Res.get());
5117       }
5118
5119       Converted.push_back(Result);
5120       break;
5121     }
5122
5123     case TemplateArgument::Declaration:
5124     case TemplateArgument::Integral:
5125     case TemplateArgument::NullPtr:
5126       // We've already checked this template argument, so just copy
5127       // it to the list of converted arguments.
5128       Converted.push_back(Arg.getArgument());
5129       break;
5130
5131     case TemplateArgument::Template:
5132     case TemplateArgument::TemplateExpansion:
5133       // We were given a template template argument. It may not be ill-formed;
5134       // see below.
5135       if (DependentTemplateName *DTN
5136             = Arg.getArgument().getAsTemplateOrTemplatePattern()
5137                                               .getAsDependentTemplateName()) {
5138         // We have a template argument such as \c T::template X, which we
5139         // parsed as a template template argument. However, since we now
5140         // know that we need a non-type template argument, convert this
5141         // template name into an expression.
5142
5143         DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5144                                      Arg.getTemplateNameLoc());
5145
5146         CXXScopeSpec SS;
5147         SS.Adopt(Arg.getTemplateQualifierLoc());
5148         // FIXME: the template-template arg was a DependentTemplateName,
5149         // so it was provided with a template keyword. However, its source
5150         // location is not stored in the template argument structure.
5151         SourceLocation TemplateKWLoc;
5152         ExprResult E = DependentScopeDeclRefExpr::Create(
5153             Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5154             nullptr);
5155
5156         // If we parsed the template argument as a pack expansion, create a
5157         // pack expansion expression.
5158         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5159           E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5160           if (E.isInvalid())
5161             return true;
5162         }
5163
5164         TemplateArgument Result;
5165         E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
5166         if (E.isInvalid())
5167           return true;
5168
5169         Converted.push_back(Result);
5170         break;
5171       }
5172
5173       // We have a template argument that actually does refer to a class
5174       // template, alias template, or template template parameter, and
5175       // therefore cannot be a non-type template argument.
5176       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5177         << Arg.getSourceRange();
5178
5179       Diag(Param->getLocation(), diag::note_template_param_here);
5180       return true;
5181
5182     case TemplateArgument::Type: {
5183       // We have a non-type template parameter but the template
5184       // argument is a type.
5185
5186       // C++ [temp.arg]p2:
5187       //   In a template-argument, an ambiguity between a type-id and
5188       //   an expression is resolved to a type-id, regardless of the
5189       //   form of the corresponding template-parameter.
5190       //
5191       // We warn specifically about this case, since it can be rather
5192       // confusing for users.
5193       QualType T = Arg.getArgument().getAsType();
5194       SourceRange SR = Arg.getSourceRange();
5195       if (T->isFunctionType())
5196         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5197       else
5198         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5199       Diag(Param->getLocation(), diag::note_template_param_here);
5200       return true;
5201     }
5202
5203     case TemplateArgument::Pack:
5204       llvm_unreachable("Caller must expand template argument packs");
5205     }
5206
5207     return false;
5208   }
5209
5210
5211   // Check template template parameters.
5212   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5213
5214   TemplateParameterList *Params = TempParm->getTemplateParameters();
5215   if (TempParm->isExpandedParameterPack())
5216     Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5217
5218   // Substitute into the template parameter list of the template
5219   // template parameter, since previously-supplied template arguments
5220   // may appear within the template template parameter.
5221   //
5222   // FIXME: Skip this if the parameters aren't instantiation-dependent.
5223   {
5224     // Set up a template instantiation context.
5225     LocalInstantiationScope Scope(*this);
5226     InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5227                                TempParm, Converted,
5228                                SourceRange(TemplateLoc, RAngleLoc));
5229     if (Inst.isInvalid())
5230       return true;
5231
5232     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5233     Params = SubstTemplateParams(Params, CurContext,
5234                                  MultiLevelTemplateArgumentList(TemplateArgs));
5235     if (!Params)
5236       return true;
5237   }
5238
5239   // C++1z [temp.local]p1: (DR1004)
5240   //   When [the injected-class-name] is used [...] as a template-argument for
5241   //   a template template-parameter [...] it refers to the class template
5242   //   itself.
5243   if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5244     TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5245         Arg.getTypeSourceInfo()->getTypeLoc());
5246     if (!ConvertedArg.getArgument().isNull())
5247       Arg = ConvertedArg;
5248   }
5249
5250   switch (Arg.getArgument().getKind()) {
5251   case TemplateArgument::Null:
5252     llvm_unreachable("Should never see a NULL template argument here");
5253
5254   case TemplateArgument::Template:
5255   case TemplateArgument::TemplateExpansion:
5256     if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
5257       return true;
5258
5259     Converted.push_back(Arg.getArgument());
5260     break;
5261
5262   case TemplateArgument::Expression:
5263   case TemplateArgument::Type:
5264     // We have a template template parameter but the template
5265     // argument does not refer to a template.
5266     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5267       << getLangOpts().CPlusPlus11;
5268     return true;
5269
5270   case TemplateArgument::Declaration:
5271     llvm_unreachable("Declaration argument with template template parameter");
5272   case TemplateArgument::Integral:
5273     llvm_unreachable("Integral argument with template template parameter");
5274   case TemplateArgument::NullPtr:
5275     llvm_unreachable("Null pointer argument with template template parameter");
5276
5277   case TemplateArgument::Pack:
5278     llvm_unreachable("Caller must expand template argument packs");
5279   }
5280
5281   return false;
5282 }
5283
5284 /// Check whether the template parameter is a pack expansion, and if so,
5285 /// determine the number of parameters produced by that expansion. For instance:
5286 ///
5287 /// \code
5288 /// template<typename ...Ts> struct A {
5289 ///   template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
5290 /// };
5291 /// \endcode
5292 ///
5293 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
5294 /// is not a pack expansion, so returns an empty Optional.
5295 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
5296   if (TemplateTypeParmDecl *TTP
5297         = dyn_cast<TemplateTypeParmDecl>(Param)) {
5298     if (TTP->isExpandedParameterPack())
5299       return TTP->getNumExpansionParameters();
5300   }
5301
5302   if (NonTypeTemplateParmDecl *NTTP
5303         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5304     if (NTTP->isExpandedParameterPack())
5305       return NTTP->getNumExpansionTypes();
5306   }
5307
5308   if (TemplateTemplateParmDecl *TTP
5309         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5310     if (TTP->isExpandedParameterPack())
5311       return TTP->getNumExpansionTemplateParameters();
5312   }
5313
5314   return None;
5315 }
5316
5317 /// Diagnose a missing template argument.
5318 template<typename TemplateParmDecl>
5319 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5320                                     TemplateDecl *TD,
5321                                     const TemplateParmDecl *D,
5322                                     TemplateArgumentListInfo &Args) {
5323   // Dig out the most recent declaration of the template parameter; there may be
5324   // declarations of the template that are more recent than TD.
5325   D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5326                                  ->getTemplateParameters()
5327                                  ->getParam(D->getIndex()));
5328
5329   // If there's a default argument that's not visible, diagnose that we're
5330   // missing a module import.
5331   llvm::SmallVector<Module*, 8> Modules;
5332   if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5333     S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5334                             D->getDefaultArgumentLoc(), Modules,
5335                             Sema::MissingImportKind::DefaultArgument,
5336                             /*Recover*/true);
5337     return true;
5338   }
5339
5340   // FIXME: If there's a more recent default argument that *is* visible,
5341   // diagnose that it was declared too late.
5342
5343   TemplateParameterList *Params = TD->getTemplateParameters();
5344
5345   S.Diag(Loc, diag::err_template_arg_list_different_arity)
5346     << /*not enough args*/0
5347     << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5348     << TD;
5349   S.Diag(TD->getLocation(), diag::note_template_decl_here)
5350     << Params->getSourceRange();
5351   return true;
5352 }
5353
5354 /// Check that the given template argument list is well-formed
5355 /// for specializing the given template.
5356 bool Sema::CheckTemplateArgumentList(
5357     TemplateDecl *Template, SourceLocation TemplateLoc,
5358     TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5359     SmallVectorImpl<TemplateArgument> &Converted,
5360     bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5361
5362   if (ConstraintsNotSatisfied)
5363     *ConstraintsNotSatisfied = false;
5364
5365   // Make a copy of the template arguments for processing.  Only make the
5366   // changes at the end when successful in matching the arguments to the
5367   // template.
5368   TemplateArgumentListInfo NewArgs = TemplateArgs;
5369
5370   // Make sure we get the template parameter list from the most
5371   // recentdeclaration, since that is the only one that has is guaranteed to
5372   // have all the default template argument information.
5373   TemplateParameterList *Params =
5374       cast<TemplateDecl>(Template->getMostRecentDecl())
5375           ->getTemplateParameters();
5376
5377   SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5378
5379   // C++ [temp.arg]p1:
5380   //   [...] The type and form of each template-argument specified in
5381   //   a template-id shall match the type and form specified for the
5382   //   corresponding parameter declared by the template in its
5383   //   template-parameter-list.
5384   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5385   SmallVector<TemplateArgument, 2> ArgumentPack;
5386   unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5387   LocalInstantiationScope InstScope(*this, true);
5388   for (TemplateParameterList::iterator Param = Params->begin(),
5389                                        ParamEnd = Params->end();
5390        Param != ParamEnd; /* increment in loop */) {
5391     // If we have an expanded parameter pack, make sure we don't have too
5392     // many arguments.
5393     if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5394       if (*Expansions == ArgumentPack.size()) {
5395         // We're done with this parameter pack. Pack up its arguments and add
5396         // them to the list.
5397         Converted.push_back(
5398             TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5399         ArgumentPack.clear();
5400
5401         // This argument is assigned to the next parameter.
5402         ++Param;
5403         continue;
5404       } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5405         // Not enough arguments for this parameter pack.
5406         Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5407           << /*not enough args*/0
5408           << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5409           << Template;
5410         Diag(Template->getLocation(), diag::note_template_decl_here)
5411           << Params->getSourceRange();
5412         return true;
5413       }
5414     }
5415
5416     if (ArgIdx < NumArgs) {
5417       // Check the template argument we were given.
5418       if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
5419                                 TemplateLoc, RAngleLoc,
5420                                 ArgumentPack.size(), Converted))
5421         return true;
5422
5423       bool PackExpansionIntoNonPack =
5424           NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5425           (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5426       if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
5427                                        isa<ConceptDecl>(Template))) {
5428         // Core issue 1430: we have a pack expansion as an argument to an
5429         // alias template, and it's not part of a parameter pack. This
5430         // can't be canonicalized, so reject it now.
5431         // As for concepts - we cannot normalize constraints where this
5432         // situation exists.
5433         Diag(NewArgs[ArgIdx].getLocation(),
5434              diag::err_template_expansion_into_fixed_list)
5435           << (isa<ConceptDecl>(Template) ? 1 : 0)
5436           << NewArgs[ArgIdx].getSourceRange();
5437         Diag((*Param)->getLocation(), diag::note_template_param_here);
5438         return true;
5439       }
5440
5441       // We're now done with this argument.
5442       ++ArgIdx;
5443
5444       if ((*Param)->isTemplateParameterPack()) {
5445         // The template parameter was a template parameter pack, so take the
5446         // deduced argument and place it on the argument pack. Note that we
5447         // stay on the same template parameter so that we can deduce more
5448         // arguments.
5449         ArgumentPack.push_back(Converted.pop_back_val());
5450       } else {
5451         // Move to the next template parameter.
5452         ++Param;
5453       }
5454
5455       // If we just saw a pack expansion into a non-pack, then directly convert
5456       // the remaining arguments, because we don't know what parameters they'll
5457       // match up with.
5458       if (PackExpansionIntoNonPack) {
5459         if (!ArgumentPack.empty()) {
5460           // If we were part way through filling in an expanded parameter pack,
5461           // fall back to just producing individual arguments.
5462           Converted.insert(Converted.end(),
5463                            ArgumentPack.begin(), ArgumentPack.end());
5464           ArgumentPack.clear();
5465         }
5466
5467         while (ArgIdx < NumArgs) {
5468           Converted.push_back(NewArgs[ArgIdx].getArgument());
5469           ++ArgIdx;
5470         }
5471
5472         return false;
5473       }
5474
5475       continue;
5476     }
5477
5478     // If we're checking a partial template argument list, we're done.
5479     if (PartialTemplateArgs) {
5480       if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
5481         Converted.push_back(
5482             TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5483       return false;
5484     }
5485
5486     // If we have a template parameter pack with no more corresponding
5487     // arguments, just break out now and we'll fill in the argument pack below.
5488     if ((*Param)->isTemplateParameterPack()) {
5489       assert(!getExpandedPackSize(*Param) &&
5490              "Should have dealt with this already");
5491
5492       // A non-expanded parameter pack before the end of the parameter list
5493       // only occurs for an ill-formed template parameter list, unless we've
5494       // got a partial argument list for a function template, so just bail out.
5495       if (Param + 1 != ParamEnd)
5496         return true;
5497
5498       Converted.push_back(
5499           TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5500       ArgumentPack.clear();
5501
5502       ++Param;
5503       continue;
5504     }
5505
5506     // Check whether we have a default argument.
5507     TemplateArgumentLoc Arg;
5508
5509     // Retrieve the default template argument from the template
5510     // parameter. For each kind of template parameter, we substitute the
5511     // template arguments provided thus far and any "outer" template arguments
5512     // (when the template parameter was part of a nested template) into
5513     // the default argument.
5514     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5515       if (!hasVisibleDefaultArgument(TTP))
5516         return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5517                                        NewArgs);
5518
5519       TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5520                                                              Template,
5521                                                              TemplateLoc,
5522                                                              RAngleLoc,
5523                                                              TTP,
5524                                                              Converted);
5525       if (!ArgType)
5526         return true;
5527
5528       Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5529                                 ArgType);
5530     } else if (NonTypeTemplateParmDecl *NTTP
5531                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5532       if (!hasVisibleDefaultArgument(NTTP))
5533         return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5534                                        NewArgs);
5535
5536       ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5537                                                               TemplateLoc,
5538                                                               RAngleLoc,
5539                                                               NTTP,
5540                                                               Converted);
5541       if (E.isInvalid())
5542         return true;
5543
5544       Expr *Ex = E.getAs<Expr>();
5545       Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5546     } else {
5547       TemplateTemplateParmDecl *TempParm
5548         = cast<TemplateTemplateParmDecl>(*Param);
5549
5550       if (!hasVisibleDefaultArgument(TempParm))
5551         return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5552                                        NewArgs);
5553
5554       NestedNameSpecifierLoc QualifierLoc;
5555       TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5556                                                        TemplateLoc,
5557                                                        RAngleLoc,
5558                                                        TempParm,
5559                                                        Converted,
5560                                                        QualifierLoc);
5561       if (Name.isNull())
5562         return true;
5563
5564       Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5565                            TempParm->getDefaultArgument().getTemplateNameLoc());
5566     }
5567
5568     // Introduce an instantiation record that describes where we are using
5569     // the default template argument. We're not actually instantiating a
5570     // template here, we just create this object to put a note into the
5571     // context stack.
5572     InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5573                                SourceRange(TemplateLoc, RAngleLoc));
5574     if (Inst.isInvalid())
5575       return true;
5576
5577     // Check the default template argument.
5578     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5579                               RAngleLoc, 0, Converted))
5580       return true;
5581
5582     // Core issue 150 (assumed resolution): if this is a template template
5583     // parameter, keep track of the default template arguments from the
5584     // template definition.
5585     if (isTemplateTemplateParameter)
5586       NewArgs.addArgument(Arg);
5587
5588     // Move to the next template parameter and argument.
5589     ++Param;
5590     ++ArgIdx;
5591   }
5592
5593   // If we're performing a partial argument substitution, allow any trailing
5594   // pack expansions; they might be empty. This can happen even if
5595   // PartialTemplateArgs is false (the list of arguments is complete but
5596   // still dependent).
5597   if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5598       CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5599     while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5600       Converted.push_back(NewArgs[ArgIdx++].getArgument());
5601   }
5602
5603   // If we have any leftover arguments, then there were too many arguments.
5604   // Complain and fail.
5605   if (ArgIdx < NumArgs) {
5606     Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5607         << /*too many args*/1
5608         << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5609         << Template
5610         << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5611     Diag(Template->getLocation(), diag::note_template_decl_here)
5612         << Params->getSourceRange();
5613     return true;
5614   }
5615
5616   // No problems found with the new argument list, propagate changes back
5617   // to caller.
5618   if (UpdateArgsWithConversions)
5619     TemplateArgs = std::move(NewArgs);
5620
5621   if (!PartialTemplateArgs &&
5622       EnsureTemplateArgumentListConstraints(
5623         Template, Converted, SourceRange(TemplateLoc,
5624                                          TemplateArgs.getRAngleLoc()))) {
5625     if (ConstraintsNotSatisfied)
5626       *ConstraintsNotSatisfied = true;
5627     return true;
5628   }
5629
5630   return false;
5631 }
5632
5633 namespace {
5634   class UnnamedLocalNoLinkageFinder
5635     : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5636   {
5637     Sema &S;
5638     SourceRange SR;
5639
5640     typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5641
5642   public:
5643     UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5644
5645     bool Visit(QualType T) {
5646       return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5647     }
5648
5649 #define TYPE(Class, Parent) \
5650     bool Visit##Class##Type(const Class##Type *);
5651 #define ABSTRACT_TYPE(Class, Parent) \
5652     bool Visit##Class##Type(const Class##Type *) { return false; }
5653 #define NON_CANONICAL_TYPE(Class, Parent) \
5654     bool Visit##Class##Type(const Class##Type *) { return false; }
5655 #include "clang/AST/TypeNodes.inc"
5656
5657     bool VisitTagDecl(const TagDecl *Tag);
5658     bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5659   };
5660 } // end anonymous namespace
5661
5662 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5663   return false;
5664 }
5665
5666 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5667   return Visit(T->getElementType());
5668 }
5669
5670 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5671   return Visit(T->getPointeeType());
5672 }
5673
5674 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5675                                                     const BlockPointerType* T) {
5676   return Visit(T->getPointeeType());
5677 }
5678
5679 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5680                                                 const LValueReferenceType* T) {
5681   return Visit(T->getPointeeType());
5682 }
5683
5684 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5685                                                 const RValueReferenceType* T) {
5686   return Visit(T->getPointeeType());
5687 }
5688
5689 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5690                                                   const MemberPointerType* T) {
5691   return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5692 }
5693
5694 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5695                                                   const ConstantArrayType* T) {
5696   return Visit(T->getElementType());
5697 }
5698
5699 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5700                                                  const IncompleteArrayType* T) {
5701   return Visit(T->getElementType());
5702 }
5703
5704 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5705                                                    const VariableArrayType* T) {
5706   return Visit(T->getElementType());
5707 }
5708
5709 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5710                                             const DependentSizedArrayType* T) {
5711   return Visit(T->getElementType());
5712 }
5713
5714 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5715                                          const DependentSizedExtVectorType* T) {
5716   return Visit(T->getElementType());
5717 }
5718
5719 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5720     const DependentAddressSpaceType *T) {
5721   return Visit(T->getPointeeType());
5722 }
5723
5724 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5725   return Visit(T->getElementType());
5726 }
5727
5728 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5729     const DependentVectorType *T) {
5730   return Visit(T->getElementType());
5731 }
5732
5733 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5734   return Visit(T->getElementType());
5735 }
5736
5737 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5738                                                   const FunctionProtoType* T) {
5739   for (const auto &A : T->param_types()) {
5740     if (Visit(A))
5741       return true;
5742   }
5743
5744   return Visit(T->getReturnType());
5745 }
5746
5747 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5748                                                const FunctionNoProtoType* T) {
5749   return Visit(T->getReturnType());
5750 }
5751
5752 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5753                                                   const UnresolvedUsingType*) {
5754   return false;
5755 }
5756
5757 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5758   return false;
5759 }
5760
5761 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5762   return Visit(T->getUnderlyingType());
5763 }
5764
5765 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5766   return false;
5767 }
5768
5769 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5770                                                     const UnaryTransformType*) {
5771   return false;
5772 }
5773
5774 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5775   return Visit(T->getDeducedType());
5776 }
5777
5778 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5779     const DeducedTemplateSpecializationType *T) {
5780   return Visit(T->getDeducedType());
5781 }
5782
5783 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5784   return VisitTagDecl(T->getDecl());
5785 }
5786
5787 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5788   return VisitTagDecl(T->getDecl());
5789 }
5790
5791 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5792                                                  const TemplateTypeParmType*) {
5793   return false;
5794 }
5795
5796 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5797                                         const SubstTemplateTypeParmPackType *) {
5798   return false;
5799 }
5800
5801 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5802                                             const TemplateSpecializationType*) {
5803   return false;
5804 }
5805
5806 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5807                                               const InjectedClassNameType* T) {
5808   return VisitTagDecl(T->getDecl());
5809 }
5810
5811 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5812                                                    const DependentNameType* T) {
5813   return VisitNestedNameSpecifier(T->getQualifier());
5814 }
5815
5816 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5817                                  const DependentTemplateSpecializationType* T) {
5818   return VisitNestedNameSpecifier(T->getQualifier());
5819 }
5820
5821 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5822                                                    const PackExpansionType* T) {
5823   return Visit(T->getPattern());
5824 }
5825
5826 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5827   return false;
5828 }
5829
5830 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5831                                                    const ObjCInterfaceType *) {
5832   return false;
5833 }
5834
5835 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5836                                                 const ObjCObjectPointerType *) {
5837   return false;
5838 }
5839
5840 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5841   return Visit(T->getValueType());
5842 }
5843
5844 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5845   return false;
5846 }
5847
5848 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5849   if (Tag->getDeclContext()->isFunctionOrMethod()) {
5850     S.Diag(SR.getBegin(),
5851            S.getLangOpts().CPlusPlus11 ?
5852              diag::warn_cxx98_compat_template_arg_local_type :
5853              diag::ext_template_arg_local_type)
5854       << S.Context.getTypeDeclType(Tag) << SR;
5855     return true;
5856   }
5857
5858   if (!Tag->hasNameForLinkage()) {
5859     S.Diag(SR.getBegin(),
5860            S.getLangOpts().CPlusPlus11 ?
5861              diag::warn_cxx98_compat_template_arg_unnamed_type :
5862              diag::ext_template_arg_unnamed_type) << SR;
5863     S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5864     return true;
5865   }
5866
5867   return false;
5868 }
5869
5870 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5871                                                     NestedNameSpecifier *NNS) {
5872   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5873     return true;
5874
5875   switch (NNS->getKind()) {
5876   case NestedNameSpecifier::Identifier:
5877   case NestedNameSpecifier::Namespace:
5878   case NestedNameSpecifier::NamespaceAlias:
5879   case NestedNameSpecifier::Global:
5880   case NestedNameSpecifier::Super:
5881     return false;
5882
5883   case NestedNameSpecifier::TypeSpec:
5884   case NestedNameSpecifier::TypeSpecWithTemplate:
5885     return Visit(QualType(NNS->getAsType(), 0));
5886   }
5887   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5888 }
5889
5890 /// Check a template argument against its corresponding
5891 /// template type parameter.
5892 ///
5893 /// This routine implements the semantics of C++ [temp.arg.type]. It
5894 /// returns true if an error occurred, and false otherwise.
5895 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5896                                  TypeSourceInfo *ArgInfo) {
5897   assert(ArgInfo && "invalid TypeSourceInfo");
5898   QualType Arg = ArgInfo->getType();
5899   SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5900
5901   if (Arg->isVariablyModifiedType()) {
5902     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5903   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5904     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5905   }
5906
5907   // C++03 [temp.arg.type]p2:
5908   //   A local type, a type with no linkage, an unnamed type or a type
5909   //   compounded from any of these types shall not be used as a
5910   //   template-argument for a template type-parameter.
5911   //
5912   // C++11 allows these, and even in C++03 we allow them as an extension with
5913   // a warning.
5914   if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5915     UnnamedLocalNoLinkageFinder Finder(*this, SR);
5916     (void)Finder.Visit(Context.getCanonicalType(Arg));
5917   }
5918
5919   return false;
5920 }
5921
5922 enum NullPointerValueKind {
5923   NPV_NotNullPointer,
5924   NPV_NullPointer,
5925   NPV_Error
5926 };
5927
5928 /// Determine whether the given template argument is a null pointer
5929 /// value of the appropriate type.
5930 static NullPointerValueKind
5931 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5932                                    QualType ParamType, Expr *Arg,
5933                                    Decl *Entity = nullptr) {
5934   if (Arg->isValueDependent() || Arg->isTypeDependent())
5935     return NPV_NotNullPointer;
5936
5937   // dllimport'd entities aren't constant but are available inside of template
5938   // arguments.
5939   if (Entity && Entity->hasAttr<DLLImportAttr>())
5940     return NPV_NotNullPointer;
5941
5942   if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5943     llvm_unreachable(
5944         "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5945
5946   if (!S.getLangOpts().CPlusPlus11)
5947     return NPV_NotNullPointer;
5948
5949   // Determine whether we have a constant expression.
5950   ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5951   if (ArgRV.isInvalid())
5952     return NPV_Error;
5953   Arg = ArgRV.get();
5954
5955   Expr::EvalResult EvalResult;
5956   SmallVector<PartialDiagnosticAt, 8> Notes;
5957   EvalResult.Diag = &Notes;
5958   if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5959       EvalResult.HasSideEffects) {
5960     SourceLocation DiagLoc = Arg->getExprLoc();
5961
5962     // If our only note is the usual "invalid subexpression" note, just point
5963     // the caret at its location rather than producing an essentially
5964     // redundant note.
5965     if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5966         diag::note_invalid_subexpr_in_const_expr) {
5967       DiagLoc = Notes[0].first;
5968       Notes.clear();
5969     }
5970
5971     S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5972       << Arg->getType() << Arg->getSourceRange();
5973     for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5974       S.Diag(Notes[I].first, Notes[I].second);
5975
5976     S.Diag(Param->getLocation(), diag::note_template_param_here);
5977     return NPV_Error;
5978   }
5979
5980   // C++11 [temp.arg.nontype]p1:
5981   //   - an address constant expression of type std::nullptr_t
5982   if (Arg->getType()->isNullPtrType())
5983     return NPV_NullPointer;
5984
5985   //   - a constant expression that evaluates to a null pointer value (4.10); or
5986   //   - a constant expression that evaluates to a null member pointer value
5987   //     (4.11); or
5988   if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5989       (EvalResult.Val.isMemberPointer() &&
5990        !EvalResult.Val.getMemberPointerDecl())) {
5991     // If our expression has an appropriate type, we've succeeded.
5992     bool ObjCLifetimeConversion;
5993     if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5994         S.IsQualificationConversion(Arg->getType(), ParamType, false,
5995                                      ObjCLifetimeConversion))
5996       return NPV_NullPointer;
5997
5998     // The types didn't match, but we know we got a null pointer; complain,
5999     // then recover as if the types were correct.
6000     S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6001       << Arg->getType() << ParamType << Arg->getSourceRange();
6002     S.Diag(Param->getLocation(), diag::note_template_param_here);
6003     return NPV_NullPointer;
6004   }
6005
6006   // If we don't have a null pointer value, but we do have a NULL pointer
6007   // constant, suggest a cast to the appropriate type.
6008   if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
6009     std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6010     S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6011         << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6012         << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
6013                                       ")");
6014     S.Diag(Param->getLocation(), diag::note_template_param_here);
6015     return NPV_NullPointer;
6016   }
6017
6018   // FIXME: If we ever want to support general, address-constant expressions
6019   // as non-type template arguments, we should return the ExprResult here to
6020   // be interpreted by the caller.
6021   return NPV_NotNullPointer;
6022 }
6023
6024 /// Checks whether the given template argument is compatible with its
6025 /// template parameter.
6026 static bool CheckTemplateArgumentIsCompatibleWithParameter(
6027     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6028     Expr *Arg, QualType ArgType) {
6029   bool ObjCLifetimeConversion;
6030   if (ParamType->isPointerType() &&
6031       !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6032       S.IsQualificationConversion(ArgType, ParamType, false,
6033                                   ObjCLifetimeConversion)) {
6034     // For pointer-to-object types, qualification conversions are
6035     // permitted.
6036   } else {
6037     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6038       if (!ParamRef->getPointeeType()->isFunctionType()) {
6039         // C++ [temp.arg.nontype]p5b3:
6040         //   For a non-type template-parameter of type reference to
6041         //   object, no conversions apply. The type referred to by the
6042         //   reference may be more cv-qualified than the (otherwise
6043         //   identical) type of the template- argument. The
6044         //   template-parameter is bound directly to the
6045         //   template-argument, which shall be an lvalue.
6046
6047         // FIXME: Other qualifiers?
6048         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6049         unsigned ArgQuals = ArgType.getCVRQualifiers();
6050
6051         if ((ParamQuals | ArgQuals) != ParamQuals) {
6052           S.Diag(Arg->getBeginLoc(),
6053                  diag::err_template_arg_ref_bind_ignores_quals)
6054               << ParamType << Arg->getType() << Arg->getSourceRange();
6055           S.Diag(Param->getLocation(), diag::note_template_param_here);
6056           return true;
6057         }
6058       }
6059     }
6060
6061     // At this point, the template argument refers to an object or
6062     // function with external linkage. We now need to check whether the
6063     // argument and parameter types are compatible.
6064     if (!S.Context.hasSameUnqualifiedType(ArgType,
6065                                           ParamType.getNonReferenceType())) {
6066       // We can't perform this conversion or binding.
6067       if (ParamType->isReferenceType())
6068         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6069             << ParamType << ArgIn->getType() << Arg->getSourceRange();
6070       else
6071         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6072             << ArgIn->getType() << ParamType << Arg->getSourceRange();
6073       S.Diag(Param->getLocation(), diag::note_template_param_here);
6074       return true;
6075     }
6076   }
6077
6078   return false;
6079 }
6080
6081 /// Checks whether the given template argument is the address
6082 /// of an object or function according to C++ [temp.arg.nontype]p1.
6083 static bool
6084 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
6085                                                NonTypeTemplateParmDecl *Param,
6086                                                QualType ParamType,
6087                                                Expr *ArgIn,
6088                                                TemplateArgument &Converted) {
6089   bool Invalid = false;
6090   Expr *Arg = ArgIn;
6091   QualType ArgType = Arg->getType();
6092
6093   bool AddressTaken = false;
6094   SourceLocation AddrOpLoc;
6095   if (S.getLangOpts().MicrosoftExt) {
6096     // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6097     // dereference and address-of operators.
6098     Arg = Arg->IgnoreParenCasts();
6099
6100     bool ExtWarnMSTemplateArg = false;
6101     UnaryOperatorKind FirstOpKind;
6102     SourceLocation FirstOpLoc;
6103     while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6104       UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6105       if (UnOpKind == UO_Deref)
6106         ExtWarnMSTemplateArg = true;
6107       if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6108         Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6109         if (!AddrOpLoc.isValid()) {
6110           FirstOpKind = UnOpKind;
6111           FirstOpLoc = UnOp->getOperatorLoc();
6112         }
6113       } else
6114         break;
6115     }
6116     if (FirstOpLoc.isValid()) {
6117       if (ExtWarnMSTemplateArg)
6118         S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6119             << ArgIn->getSourceRange();
6120
6121       if (FirstOpKind == UO_AddrOf)
6122         AddressTaken = true;
6123       else if (Arg->getType()->isPointerType()) {
6124         // We cannot let pointers get dereferenced here, that is obviously not a
6125         // constant expression.
6126         assert(FirstOpKind == UO_Deref);
6127         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6128             << Arg->getSourceRange();
6129       }
6130     }
6131   } else {
6132     // See through any implicit casts we added to fix the type.
6133     Arg = Arg->IgnoreImpCasts();
6134
6135     // C++ [temp.arg.nontype]p1:
6136     //
6137     //   A template-argument for a non-type, non-template
6138     //   template-parameter shall be one of: [...]
6139     //
6140     //     -- the address of an object or function with external
6141     //        linkage, including function templates and function
6142     //        template-ids but excluding non-static class members,
6143     //        expressed as & id-expression where the & is optional if
6144     //        the name refers to a function or array, or if the
6145     //        corresponding template-parameter is a reference; or
6146
6147     // In C++98/03 mode, give an extension warning on any extra parentheses.
6148     // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6149     bool ExtraParens = false;
6150     while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6151       if (!Invalid && !ExtraParens) {
6152         S.Diag(Arg->getBeginLoc(),
6153                S.getLangOpts().CPlusPlus11
6154                    ? diag::warn_cxx98_compat_template_arg_extra_parens
6155                    : diag::ext_template_arg_extra_parens)
6156             << Arg->getSourceRange();
6157         ExtraParens = true;
6158       }
6159
6160       Arg = Parens->getSubExpr();
6161     }
6162
6163     while (SubstNonTypeTemplateParmExpr *subst =
6164                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6165       Arg = subst->getReplacement()->IgnoreImpCasts();
6166
6167     if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6168       if (UnOp->getOpcode() == UO_AddrOf) {
6169         Arg = UnOp->getSubExpr();
6170         AddressTaken = true;
6171         AddrOpLoc = UnOp->getOperatorLoc();
6172       }
6173     }
6174
6175     while (SubstNonTypeTemplateParmExpr *subst =
6176                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6177       Arg = subst->getReplacement()->IgnoreImpCasts();
6178   }
6179
6180   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
6181   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6182
6183   // If our parameter has pointer type, check for a null template value.
6184   if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6185     switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6186                                                Entity)) {
6187     case NPV_NullPointer:
6188       S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6189       Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6190                                    /*isNullPtr=*/true);
6191       return false;
6192
6193     case NPV_Error:
6194       return true;
6195
6196     case NPV_NotNullPointer:
6197       break;
6198     }
6199   }
6200
6201   // Stop checking the precise nature of the argument if it is value dependent,
6202   // it should be checked when instantiated.
6203   if (Arg->isValueDependent()) {
6204     Converted = TemplateArgument(ArgIn);
6205     return false;
6206   }
6207
6208   if (isa<CXXUuidofExpr>(Arg)) {
6209     if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
6210                                                        ArgIn, Arg, ArgType))
6211       return true;
6212
6213     Converted = TemplateArgument(ArgIn);
6214     return false;
6215   }
6216
6217   if (!DRE) {
6218     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6219         << Arg->getSourceRange();
6220     S.Diag(Param->getLocation(), diag::note_template_param_here);
6221     return true;
6222   }
6223
6224   // Cannot refer to non-static data members
6225   if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6226     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6227         << Entity << Arg->getSourceRange();
6228     S.Diag(Param->getLocation(), diag::note_template_param_here);
6229     return true;
6230   }
6231
6232   // Cannot refer to non-static member functions
6233   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6234     if (!Method->isStatic()) {
6235       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6236           << Method << Arg->getSourceRange();
6237       S.Diag(Param->getLocation(), diag::note_template_param_here);
6238       return true;
6239     }
6240   }
6241
6242   FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6243   VarDecl *Var = dyn_cast<VarDecl>(Entity);
6244
6245   // A non-type template argument must refer to an object or function.
6246   if (!Func && !Var) {
6247     // We found something, but we don't know specifically what it is.
6248     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6249         << Arg->getSourceRange();
6250     S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6251     return true;
6252   }
6253
6254   // Address / reference template args must have external linkage in C++98.
6255   if (Entity->getFormalLinkage() == InternalLinkage) {
6256     S.Diag(Arg->getBeginLoc(),
6257            S.getLangOpts().CPlusPlus11
6258                ? diag::warn_cxx98_compat_template_arg_object_internal
6259                : diag::ext_template_arg_object_internal)
6260         << !Func << Entity << Arg->getSourceRange();
6261     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6262       << !Func;
6263   } else if (!Entity->hasLinkage()) {
6264     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6265         << !Func << Entity << Arg->getSourceRange();
6266     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6267       << !Func;
6268     return true;
6269   }
6270
6271   if (Func) {
6272     // If the template parameter has pointer type, the function decays.
6273     if (ParamType->isPointerType() && !AddressTaken)
6274       ArgType = S.Context.getPointerType(Func->getType());
6275     else if (AddressTaken && ParamType->isReferenceType()) {
6276       // If we originally had an address-of operator, but the
6277       // parameter has reference type, complain and (if things look
6278       // like they will work) drop the address-of operator.
6279       if (!S.Context.hasSameUnqualifiedType(Func->getType(),
6280                                             ParamType.getNonReferenceType())) {
6281         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6282           << ParamType;
6283         S.Diag(Param->getLocation(), diag::note_template_param_here);
6284         return true;
6285       }
6286
6287       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6288         << ParamType
6289         << FixItHint::CreateRemoval(AddrOpLoc);
6290       S.Diag(Param->getLocation(), diag::note_template_param_here);
6291
6292       ArgType = Func->getType();
6293     }
6294   } else {
6295     // A value of reference type is not an object.
6296     if (Var->getType()->isReferenceType()) {
6297       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6298           << Var->getType() << Arg->getSourceRange();
6299       S.Diag(Param->getLocation(), diag::note_template_param_here);
6300       return true;
6301     }
6302
6303     // A template argument must have static storage duration.
6304     if (Var->getTLSKind()) {
6305       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6306           << Arg->getSourceRange();
6307       S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6308       return true;
6309     }
6310
6311     // If the template parameter has pointer type, we must have taken
6312     // the address of this object.
6313     if (ParamType->isReferenceType()) {
6314       if (AddressTaken) {
6315         // If we originally had an address-of operator, but the
6316         // parameter has reference type, complain and (if things look
6317         // like they will work) drop the address-of operator.
6318         if (!S.Context.hasSameUnqualifiedType(Var->getType(),
6319                                             ParamType.getNonReferenceType())) {
6320           S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6321             << ParamType;
6322           S.Diag(Param->getLocation(), diag::note_template_param_here);
6323           return true;
6324         }
6325
6326         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6327           << ParamType
6328           << FixItHint::CreateRemoval(AddrOpLoc);
6329         S.Diag(Param->getLocation(), diag::note_template_param_here);
6330
6331         ArgType = Var->getType();
6332       }
6333     } else if (!AddressTaken && ParamType->isPointerType()) {
6334       if (Var->getType()->isArrayType()) {
6335         // Array-to-pointer decay.
6336         ArgType = S.Context.getArrayDecayedType(Var->getType());
6337       } else {
6338         // If the template parameter has pointer type but the address of
6339         // this object was not taken, complain and (possibly) recover by
6340         // taking the address of the entity.
6341         ArgType = S.Context.getPointerType(Var->getType());
6342         if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6343           S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6344               << ParamType;
6345           S.Diag(Param->getLocation(), diag::note_template_param_here);
6346           return true;
6347         }
6348
6349         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6350             << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6351
6352         S.Diag(Param->getLocation(), diag::note_template_param_here);
6353       }
6354     }
6355   }
6356
6357   if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6358                                                      Arg, ArgType))
6359     return true;
6360
6361   // Create the template argument.
6362   Converted =
6363       TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
6364   S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6365   return false;
6366 }
6367
6368 /// Checks whether the given template argument is a pointer to
6369 /// member constant according to C++ [temp.arg.nontype]p1.
6370 static bool CheckTemplateArgumentPointerToMember(Sema &S,
6371                                                  NonTypeTemplateParmDecl *Param,
6372                                                  QualType ParamType,
6373                                                  Expr *&ResultArg,
6374                                                  TemplateArgument &Converted) {
6375   bool Invalid = false;
6376
6377   Expr *Arg = ResultArg;
6378   bool ObjCLifetimeConversion;
6379
6380   // C++ [temp.arg.nontype]p1:
6381   //
6382   //   A template-argument for a non-type, non-template
6383   //   template-parameter shall be one of: [...]
6384   //
6385   //     -- a pointer to member expressed as described in 5.3.1.
6386   DeclRefExpr *DRE = nullptr;
6387
6388   // In C++98/03 mode, give an extension warning on any extra parentheses.
6389   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6390   bool ExtraParens = false;
6391   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6392     if (!Invalid && !ExtraParens) {
6393       S.Diag(Arg->getBeginLoc(),
6394              S.getLangOpts().CPlusPlus11
6395                  ? diag::warn_cxx98_compat_template_arg_extra_parens
6396                  : diag::ext_template_arg_extra_parens)
6397           << Arg->getSourceRange();
6398       ExtraParens = true;
6399     }
6400
6401     Arg = Parens->getSubExpr();
6402   }
6403
6404   while (SubstNonTypeTemplateParmExpr *subst =
6405            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6406     Arg = subst->getReplacement()->IgnoreImpCasts();
6407
6408   // A pointer-to-member constant written &Class::member.
6409   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6410     if (UnOp->getOpcode() == UO_AddrOf) {
6411       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6412       if (DRE && !DRE->getQualifier())
6413         DRE = nullptr;
6414     }
6415   }
6416   // A constant of pointer-to-member type.
6417   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6418     ValueDecl *VD = DRE->getDecl();
6419     if (VD->getType()->isMemberPointerType()) {
6420       if (isa<NonTypeTemplateParmDecl>(VD)) {
6421         if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6422           Converted = TemplateArgument(Arg);
6423         } else {
6424           VD = cast<ValueDecl>(VD->getCanonicalDecl());
6425           Converted = TemplateArgument(VD, ParamType);
6426         }
6427         return Invalid;
6428       }
6429     }
6430
6431     DRE = nullptr;
6432   }
6433
6434   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6435
6436   // Check for a null pointer value.
6437   switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6438                                              Entity)) {
6439   case NPV_Error:
6440     return true;
6441   case NPV_NullPointer:
6442     S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6443     Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6444                                  /*isNullPtr*/true);
6445     return false;
6446   case NPV_NotNullPointer:
6447     break;
6448   }
6449
6450   if (S.IsQualificationConversion(ResultArg->getType(),
6451                                   ParamType.getNonReferenceType(), false,
6452                                   ObjCLifetimeConversion)) {
6453     ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6454                                     ResultArg->getValueKind())
6455                     .get();
6456   } else if (!S.Context.hasSameUnqualifiedType(
6457                  ResultArg->getType(), ParamType.getNonReferenceType())) {
6458     // We can't perform this conversion.
6459     S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6460         << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6461     S.Diag(Param->getLocation(), diag::note_template_param_here);
6462     return true;
6463   }
6464
6465   if (!DRE)
6466     return S.Diag(Arg->getBeginLoc(),
6467                   diag::err_template_arg_not_pointer_to_member_form)
6468            << Arg->getSourceRange();
6469
6470   if (isa<FieldDecl>(DRE->getDecl()) ||
6471       isa<IndirectFieldDecl>(DRE->getDecl()) ||
6472       isa<CXXMethodDecl>(DRE->getDecl())) {
6473     assert((isa<FieldDecl>(DRE->getDecl()) ||
6474             isa<IndirectFieldDecl>(DRE->getDecl()) ||
6475             !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6476            "Only non-static member pointers can make it here");
6477
6478     // Okay: this is the address of a non-static member, and therefore
6479     // a member pointer constant.
6480     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6481       Converted = TemplateArgument(Arg);
6482     } else {
6483       ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
6484       Converted = TemplateArgument(D, ParamType);
6485     }
6486     return Invalid;
6487   }
6488
6489   // We found something else, but we don't know specifically what it is.
6490   S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6491       << Arg->getSourceRange();
6492   S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6493   return true;
6494 }
6495
6496 /// Check a template argument against its corresponding
6497 /// non-type template parameter.
6498 ///
6499 /// This routine implements the semantics of C++ [temp.arg.nontype].
6500 /// If an error occurred, it returns ExprError(); otherwise, it
6501 /// returns the converted template argument. \p ParamType is the
6502 /// type of the non-type template parameter after it has been instantiated.
6503 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6504                                        QualType ParamType, Expr *Arg,
6505                                        TemplateArgument &Converted,
6506                                        CheckTemplateArgumentKind CTAK) {
6507   SourceLocation StartLoc = Arg->getBeginLoc();
6508
6509   // If the parameter type somehow involves auto, deduce the type now.
6510   if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
6511     // During template argument deduction, we allow 'decltype(auto)' to
6512     // match an arbitrary dependent argument.
6513     // FIXME: The language rules don't say what happens in this case.
6514     // FIXME: We get an opaque dependent type out of decltype(auto) if the
6515     // expression is merely instantiation-dependent; is this enough?
6516     if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6517       auto *AT = dyn_cast<AutoType>(ParamType);
6518       if (AT && AT->isDecltypeAuto()) {
6519         Converted = TemplateArgument(Arg);
6520         return Arg;
6521       }
6522     }
6523
6524     // When checking a deduced template argument, deduce from its type even if
6525     // the type is dependent, in order to check the types of non-type template
6526     // arguments line up properly in partial ordering.
6527     Optional<unsigned> Depth = Param->getDepth() + 1;
6528     Expr *DeductionArg = Arg;
6529     if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6530       DeductionArg = PE->getPattern();
6531     if (DeduceAutoType(
6532             Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
6533             DeductionArg, ParamType, Depth) == DAR_Failed) {
6534       Diag(Arg->getExprLoc(),
6535            diag::err_non_type_template_parm_type_deduction_failure)
6536         << Param->getDeclName() << Param->getType() << Arg->getType()
6537         << Arg->getSourceRange();
6538       Diag(Param->getLocation(), diag::note_template_param_here);
6539       return ExprError();
6540     }
6541     // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6542     // an error. The error message normally references the parameter
6543     // declaration, but here we'll pass the argument location because that's
6544     // where the parameter type is deduced.
6545     ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6546     if (ParamType.isNull()) {
6547       Diag(Param->getLocation(), diag::note_template_param_here);
6548       return ExprError();
6549     }
6550   }
6551
6552   // We should have already dropped all cv-qualifiers by now.
6553   assert(!ParamType.hasQualifiers() &&
6554          "non-type template parameter type cannot be qualified");
6555
6556   if (CTAK == CTAK_Deduced &&
6557       !Context.hasSameType(ParamType.getNonLValueExprType(Context),
6558                            Arg->getType())) {
6559     // FIXME: If either type is dependent, we skip the check. This isn't
6560     // correct, since during deduction we're supposed to have replaced each
6561     // template parameter with some unique (non-dependent) placeholder.
6562     // FIXME: If the argument type contains 'auto', we carry on and fail the
6563     // type check in order to force specific types to be more specialized than
6564     // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6565     // work.
6566     if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6567         !Arg->getType()->getContainedAutoType()) {
6568       Converted = TemplateArgument(Arg);
6569       return Arg;
6570     }
6571     // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6572     // we should actually be checking the type of the template argument in P,
6573     // not the type of the template argument deduced from A, against the
6574     // template parameter type.
6575     Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6576       << Arg->getType()
6577       << ParamType.getUnqualifiedType();
6578     Diag(Param->getLocation(), diag::note_template_param_here);
6579     return ExprError();
6580   }
6581
6582   // If either the parameter has a dependent type or the argument is
6583   // type-dependent, there's nothing we can check now. The argument only
6584   // contains an unexpanded pack during partial ordering, and there's
6585   // nothing more we can check in that case.
6586   if (ParamType->isDependentType() || Arg->isTypeDependent() ||
6587       Arg->containsUnexpandedParameterPack()) {
6588     // Force the argument to the type of the parameter to maintain invariants.
6589     auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6590     if (PE)
6591       Arg = PE->getPattern();
6592     ExprResult E = ImpCastExprToType(
6593         Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6594         ParamType->isLValueReferenceType() ? VK_LValue :
6595         ParamType->isRValueReferenceType() ? VK_XValue : VK_RValue);
6596     if (E.isInvalid())
6597       return ExprError();
6598     if (PE) {
6599       // Recreate a pack expansion if we unwrapped one.
6600       E = new (Context)
6601           PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6602                             PE->getNumExpansions());
6603     }
6604     Converted = TemplateArgument(E.get());
6605     return E;
6606   }
6607
6608   // The initialization of the parameter from the argument is
6609   // a constant-evaluated context.
6610   EnterExpressionEvaluationContext ConstantEvaluated(
6611       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6612
6613   if (getLangOpts().CPlusPlus17) {
6614     // C++17 [temp.arg.nontype]p1:
6615     //   A template-argument for a non-type template parameter shall be
6616     //   a converted constant expression of the type of the template-parameter.
6617     APValue Value;
6618     ExprResult ArgResult = CheckConvertedConstantExpression(
6619         Arg, ParamType, Value, CCEK_TemplateArg);
6620     if (ArgResult.isInvalid())
6621       return ExprError();
6622
6623     // For a value-dependent argument, CheckConvertedConstantExpression is
6624     // permitted (and expected) to be unable to determine a value.
6625     if (ArgResult.get()->isValueDependent()) {
6626       Converted = TemplateArgument(ArgResult.get());
6627       return ArgResult;
6628     }
6629
6630     QualType CanonParamType = Context.getCanonicalType(ParamType);
6631
6632     // Convert the APValue to a TemplateArgument.
6633     switch (Value.getKind()) {
6634     case APValue::None:
6635       assert(ParamType->isNullPtrType());
6636       Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6637       break;
6638     case APValue::Indeterminate:
6639       llvm_unreachable("result of constant evaluation should be initialized");
6640       break;
6641     case APValue::Int:
6642       assert(ParamType->isIntegralOrEnumerationType());
6643       Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6644       break;
6645     case APValue::MemberPointer: {
6646       assert(ParamType->isMemberPointerType());
6647
6648       // FIXME: We need TemplateArgument representation and mangling for these.
6649       if (!Value.getMemberPointerPath().empty()) {
6650         Diag(Arg->getBeginLoc(),
6651              diag::err_template_arg_member_ptr_base_derived_not_supported)
6652             << Value.getMemberPointerDecl() << ParamType
6653             << Arg->getSourceRange();
6654         return ExprError();
6655       }
6656
6657       auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6658       Converted = VD ? TemplateArgument(VD, CanonParamType)
6659                      : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6660       break;
6661     }
6662     case APValue::LValue: {
6663       //   For a non-type template-parameter of pointer or reference type,
6664       //   the value of the constant expression shall not refer to
6665       assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6666              ParamType->isNullPtrType());
6667       // -- a temporary object
6668       // -- a string literal
6669       // -- the result of a typeid expression, or
6670       // -- a predefined __func__ variable
6671       APValue::LValueBase Base = Value.getLValueBase();
6672       auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6673       if (Base && !VD) {
6674         auto *E = Base.dyn_cast<const Expr *>();
6675         if (E && isa<CXXUuidofExpr>(E)) {
6676           Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
6677           break;
6678         }
6679         Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6680             << Arg->getSourceRange();
6681         return ExprError();
6682       }
6683       // -- a subobject
6684       if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6685           VD && VD->getType()->isArrayType() &&
6686           Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6687           !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6688         // Per defect report (no number yet):
6689         //   ... other than a pointer to the first element of a complete array
6690         //       object.
6691       } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6692                  Value.isLValueOnePastTheEnd()) {
6693         Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6694           << Value.getAsString(Context, ParamType);
6695         return ExprError();
6696       }
6697       assert((VD || !ParamType->isReferenceType()) &&
6698              "null reference should not be a constant expression");
6699       assert((!VD || !ParamType->isNullPtrType()) &&
6700              "non-null value of type nullptr_t?");
6701       Converted = VD ? TemplateArgument(VD, CanonParamType)
6702                      : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6703       break;
6704     }
6705     case APValue::AddrLabelDiff:
6706       return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6707     case APValue::FixedPoint:
6708     case APValue::Float:
6709     case APValue::ComplexInt:
6710     case APValue::ComplexFloat:
6711     case APValue::Vector:
6712     case APValue::Array:
6713     case APValue::Struct:
6714     case APValue::Union:
6715       llvm_unreachable("invalid kind for template argument");
6716     }
6717
6718     return ArgResult.get();
6719   }
6720
6721   // C++ [temp.arg.nontype]p5:
6722   //   The following conversions are performed on each expression used
6723   //   as a non-type template-argument. If a non-type
6724   //   template-argument cannot be converted to the type of the
6725   //   corresponding template-parameter then the program is
6726   //   ill-formed.
6727   if (ParamType->isIntegralOrEnumerationType()) {
6728     // C++11:
6729     //   -- for a non-type template-parameter of integral or
6730     //      enumeration type, conversions permitted in a converted
6731     //      constant expression are applied.
6732     //
6733     // C++98:
6734     //   -- for a non-type template-parameter of integral or
6735     //      enumeration type, integral promotions (4.5) and integral
6736     //      conversions (4.7) are applied.
6737
6738     if (getLangOpts().CPlusPlus11) {
6739       // C++ [temp.arg.nontype]p1:
6740       //   A template-argument for a non-type, non-template template-parameter
6741       //   shall be one of:
6742       //
6743       //     -- for a non-type template-parameter of integral or enumeration
6744       //        type, a converted constant expression of the type of the
6745       //        template-parameter; or
6746       llvm::APSInt Value;
6747       ExprResult ArgResult =
6748         CheckConvertedConstantExpression(Arg, ParamType, Value,
6749                                          CCEK_TemplateArg);
6750       if (ArgResult.isInvalid())
6751         return ExprError();
6752
6753       // We can't check arbitrary value-dependent arguments.
6754       if (ArgResult.get()->isValueDependent()) {
6755         Converted = TemplateArgument(ArgResult.get());
6756         return ArgResult;
6757       }
6758
6759       // Widen the argument value to sizeof(parameter type). This is almost
6760       // always a no-op, except when the parameter type is bool. In
6761       // that case, this may extend the argument from 1 bit to 8 bits.
6762       QualType IntegerType = ParamType;
6763       if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6764         IntegerType = Enum->getDecl()->getIntegerType();
6765       Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6766
6767       Converted = TemplateArgument(Context, Value,
6768                                    Context.getCanonicalType(ParamType));
6769       return ArgResult;
6770     }
6771
6772     ExprResult ArgResult = DefaultLvalueConversion(Arg);
6773     if (ArgResult.isInvalid())
6774       return ExprError();
6775     Arg = ArgResult.get();
6776
6777     QualType ArgType = Arg->getType();
6778
6779     // C++ [temp.arg.nontype]p1:
6780     //   A template-argument for a non-type, non-template
6781     //   template-parameter shall be one of:
6782     //
6783     //     -- an integral constant-expression of integral or enumeration
6784     //        type; or
6785     //     -- the name of a non-type template-parameter; or
6786     llvm::APSInt Value;
6787     if (!ArgType->isIntegralOrEnumerationType()) {
6788       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6789           << ArgType << Arg->getSourceRange();
6790       Diag(Param->getLocation(), diag::note_template_param_here);
6791       return ExprError();
6792     } else if (!Arg->isValueDependent()) {
6793       class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6794         QualType T;
6795
6796       public:
6797         TmplArgICEDiagnoser(QualType T) : T(T) { }
6798
6799         void diagnoseNotICE(Sema &S, SourceLocation Loc,
6800                             SourceRange SR) override {
6801           S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6802         }
6803       } Diagnoser(ArgType);
6804
6805       Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6806                                             false).get();
6807       if (!Arg)
6808         return ExprError();
6809     }
6810
6811     // From here on out, all we care about is the unqualified form
6812     // of the argument type.
6813     ArgType = ArgType.getUnqualifiedType();
6814
6815     // Try to convert the argument to the parameter's type.
6816     if (Context.hasSameType(ParamType, ArgType)) {
6817       // Okay: no conversion necessary
6818     } else if (ParamType->isBooleanType()) {
6819       // This is an integral-to-boolean conversion.
6820       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6821     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6822                !ParamType->isEnumeralType()) {
6823       // This is an integral promotion or conversion.
6824       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6825     } else {
6826       // We can't perform this conversion.
6827       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6828           << Arg->getType() << ParamType << Arg->getSourceRange();
6829       Diag(Param->getLocation(), diag::note_template_param_here);
6830       return ExprError();
6831     }
6832
6833     // Add the value of this argument to the list of converted
6834     // arguments. We use the bitwidth and signedness of the template
6835     // parameter.
6836     if (Arg->isValueDependent()) {
6837       // The argument is value-dependent. Create a new
6838       // TemplateArgument with the converted expression.
6839       Converted = TemplateArgument(Arg);
6840       return Arg;
6841     }
6842
6843     QualType IntegerType = Context.getCanonicalType(ParamType);
6844     if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6845       IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6846
6847     if (ParamType->isBooleanType()) {
6848       // Value must be zero or one.
6849       Value = Value != 0;
6850       unsigned AllowedBits = Context.getTypeSize(IntegerType);
6851       if (Value.getBitWidth() != AllowedBits)
6852         Value = Value.extOrTrunc(AllowedBits);
6853       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6854     } else {
6855       llvm::APSInt OldValue = Value;
6856
6857       // Coerce the template argument's value to the value it will have
6858       // based on the template parameter's type.
6859       unsigned AllowedBits = Context.getTypeSize(IntegerType);
6860       if (Value.getBitWidth() != AllowedBits)
6861         Value = Value.extOrTrunc(AllowedBits);
6862       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6863
6864       // Complain if an unsigned parameter received a negative value.
6865       if (IntegerType->isUnsignedIntegerOrEnumerationType()
6866                && (OldValue.isSigned() && OldValue.isNegative())) {
6867         Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6868             << OldValue.toString(10) << Value.toString(10) << Param->getType()
6869             << Arg->getSourceRange();
6870         Diag(Param->getLocation(), diag::note_template_param_here);
6871       }
6872
6873       // Complain if we overflowed the template parameter's type.
6874       unsigned RequiredBits;
6875       if (IntegerType->isUnsignedIntegerOrEnumerationType())
6876         RequiredBits = OldValue.getActiveBits();
6877       else if (OldValue.isUnsigned())
6878         RequiredBits = OldValue.getActiveBits() + 1;
6879       else
6880         RequiredBits = OldValue.getMinSignedBits();
6881       if (RequiredBits > AllowedBits) {
6882         Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6883             << OldValue.toString(10) << Value.toString(10) << Param->getType()
6884             << Arg->getSourceRange();
6885         Diag(Param->getLocation(), diag::note_template_param_here);
6886       }
6887     }
6888
6889     Converted = TemplateArgument(Context, Value,
6890                                  ParamType->isEnumeralType()
6891                                    ? Context.getCanonicalType(ParamType)
6892                                    : IntegerType);
6893     return Arg;
6894   }
6895
6896   QualType ArgType = Arg->getType();
6897   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6898
6899   // Handle pointer-to-function, reference-to-function, and
6900   // pointer-to-member-function all in (roughly) the same way.
6901   if (// -- For a non-type template-parameter of type pointer to
6902       //    function, only the function-to-pointer conversion (4.3) is
6903       //    applied. If the template-argument represents a set of
6904       //    overloaded functions (or a pointer to such), the matching
6905       //    function is selected from the set (13.4).
6906       (ParamType->isPointerType() &&
6907        ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6908       // -- For a non-type template-parameter of type reference to
6909       //    function, no conversions apply. If the template-argument
6910       //    represents a set of overloaded functions, the matching
6911       //    function is selected from the set (13.4).
6912       (ParamType->isReferenceType() &&
6913        ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6914       // -- For a non-type template-parameter of type pointer to
6915       //    member function, no conversions apply. If the
6916       //    template-argument represents a set of overloaded member
6917       //    functions, the matching member function is selected from
6918       //    the set (13.4).
6919       (ParamType->isMemberPointerType() &&
6920        ParamType->castAs<MemberPointerType>()->getPointeeType()
6921          ->isFunctionType())) {
6922
6923     if (Arg->getType() == Context.OverloadTy) {
6924       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6925                                                                 true,
6926                                                                 FoundResult)) {
6927         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6928           return ExprError();
6929
6930         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6931         ArgType = Arg->getType();
6932       } else
6933         return ExprError();
6934     }
6935
6936     if (!ParamType->isMemberPointerType()) {
6937       if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6938                                                          ParamType,
6939                                                          Arg, Converted))
6940         return ExprError();
6941       return Arg;
6942     }
6943
6944     if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6945                                              Converted))
6946       return ExprError();
6947     return Arg;
6948   }
6949
6950   if (ParamType->isPointerType()) {
6951     //   -- for a non-type template-parameter of type pointer to
6952     //      object, qualification conversions (4.4) and the
6953     //      array-to-pointer conversion (4.2) are applied.
6954     // C++0x also allows a value of std::nullptr_t.
6955     assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
6956            "Only object pointers allowed here");
6957
6958     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6959                                                        ParamType,
6960                                                        Arg, Converted))
6961       return ExprError();
6962     return Arg;
6963   }
6964
6965   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6966     //   -- For a non-type template-parameter of type reference to
6967     //      object, no conversions apply. The type referred to by the
6968     //      reference may be more cv-qualified than the (otherwise
6969     //      identical) type of the template-argument. The
6970     //      template-parameter is bound directly to the
6971     //      template-argument, which must be an lvalue.
6972     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
6973            "Only object references allowed here");
6974
6975     if (Arg->getType() == Context.OverloadTy) {
6976       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6977                                                  ParamRefType->getPointeeType(),
6978                                                                 true,
6979                                                                 FoundResult)) {
6980         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6981           return ExprError();
6982
6983         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6984         ArgType = Arg->getType();
6985       } else
6986         return ExprError();
6987     }
6988
6989     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6990                                                        ParamType,
6991                                                        Arg, Converted))
6992       return ExprError();
6993     return Arg;
6994   }
6995
6996   // Deal with parameters of type std::nullptr_t.
6997   if (ParamType->isNullPtrType()) {
6998     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6999       Converted = TemplateArgument(Arg);
7000       return Arg;
7001     }
7002
7003     switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7004     case NPV_NotNullPointer:
7005       Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7006         << Arg->getType() << ParamType;
7007       Diag(Param->getLocation(), diag::note_template_param_here);
7008       return ExprError();
7009
7010     case NPV_Error:
7011       return ExprError();
7012
7013     case NPV_NullPointer:
7014       Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7015       Converted = TemplateArgument(Context.getCanonicalType(ParamType),
7016                                    /*isNullPtr*/true);
7017       return Arg;
7018     }
7019   }
7020
7021   //     -- For a non-type template-parameter of type pointer to data
7022   //        member, qualification conversions (4.4) are applied.
7023   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7024
7025   if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
7026                                            Converted))
7027     return ExprError();
7028   return Arg;
7029 }
7030
7031 static void DiagnoseTemplateParameterListArityMismatch(
7032     Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7033     Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7034
7035 /// Check a template argument against its corresponding
7036 /// template template parameter.
7037 ///
7038 /// This routine implements the semantics of C++ [temp.arg.template].
7039 /// It returns true if an error occurred, and false otherwise.
7040 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7041                                          TemplateParameterList *Params,
7042                                          TemplateArgumentLoc &Arg) {
7043   TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7044   TemplateDecl *Template = Name.getAsTemplateDecl();
7045   if (!Template) {
7046     // Any dependent template name is fine.
7047     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7048     return false;
7049   }
7050
7051   if (Template->isInvalidDecl())
7052     return true;
7053
7054   // C++0x [temp.arg.template]p1:
7055   //   A template-argument for a template template-parameter shall be
7056   //   the name of a class template or an alias template, expressed as an
7057   //   id-expression. When the template-argument names a class template, only
7058   //   primary class templates are considered when matching the
7059   //   template template argument with the corresponding parameter;
7060   //   partial specializations are not considered even if their
7061   //   parameter lists match that of the template template parameter.
7062   //
7063   // Note that we also allow template template parameters here, which
7064   // will happen when we are dealing with, e.g., class template
7065   // partial specializations.
7066   if (!isa<ClassTemplateDecl>(Template) &&
7067       !isa<TemplateTemplateParmDecl>(Template) &&
7068       !isa<TypeAliasTemplateDecl>(Template) &&
7069       !isa<BuiltinTemplateDecl>(Template)) {
7070     assert(isa<FunctionTemplateDecl>(Template) &&
7071            "Only function templates are possible here");
7072     Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7073     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7074       << Template;
7075   }
7076
7077   // C++1z [temp.arg.template]p3: (DR 150)
7078   //   A template-argument matches a template template-parameter P when P
7079   //   is at least as specialized as the template-argument A.
7080   // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
7081   //  defect report resolution from C++17 and shouldn't be introduced by
7082   //  concepts.
7083   if (getLangOpts().RelaxedTemplateTemplateArgs) {
7084     // Quick check for the common case:
7085     //   If P contains a parameter pack, then A [...] matches P if each of A's
7086     //   template parameters matches the corresponding template parameter in
7087     //   the template-parameter-list of P.
7088     if (TemplateParameterListsAreEqual(
7089             Template->getTemplateParameters(), Params, false,
7090             TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
7091         // If the argument has no associated constraints, then the parameter is
7092         // definitely at least as specialized as the argument.
7093         // Otherwise - we need a more thorough check.
7094         !Template->hasAssociatedConstraints())
7095       return false;
7096
7097     if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
7098                                                           Arg.getLocation())) {
7099       // C++2a[temp.func.order]p2
7100       //   [...] If both deductions succeed, the partial ordering selects the
7101       //   more constrained template as described by the rules in
7102       //   [temp.constr.order].
7103       SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7104       Params->getAssociatedConstraints(ParamsAC);
7105       Template->getAssociatedConstraints(TemplateAC);
7106       bool IsParamAtLeastAsConstrained;
7107       if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7108                                  IsParamAtLeastAsConstrained))
7109         return true;
7110       if (!IsParamAtLeastAsConstrained) {
7111         Diag(Arg.getLocation(),
7112              diag::err_template_template_parameter_not_at_least_as_constrained)
7113             << Template << Param << Arg.getSourceRange();
7114         Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7115         Diag(Template->getLocation(), diag::note_entity_declared_at)
7116             << Template;
7117         MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7118                                                       TemplateAC);
7119         return true;
7120       }
7121       return false;
7122     }
7123     // FIXME: Produce better diagnostics for deduction failures.
7124   }
7125
7126   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7127                                          Params,
7128                                          true,
7129                                          TPL_TemplateTemplateArgumentMatch,
7130                                          Arg.getLocation());
7131 }
7132
7133 /// Given a non-type template argument that refers to a
7134 /// declaration and the type of its corresponding non-type template
7135 /// parameter, produce an expression that properly refers to that
7136 /// declaration.
7137 ExprResult
7138 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7139                                               QualType ParamType,
7140                                               SourceLocation Loc) {
7141   // C++ [temp.param]p8:
7142   //
7143   //   A non-type template-parameter of type "array of T" or
7144   //   "function returning T" is adjusted to be of type "pointer to
7145   //   T" or "pointer to function returning T", respectively.
7146   if (ParamType->isArrayType())
7147     ParamType = Context.getArrayDecayedType(ParamType);
7148   else if (ParamType->isFunctionType())
7149     ParamType = Context.getPointerType(ParamType);
7150
7151   // For a NULL non-type template argument, return nullptr casted to the
7152   // parameter's type.
7153   if (Arg.getKind() == TemplateArgument::NullPtr) {
7154     return ImpCastExprToType(
7155              new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7156                              ParamType,
7157                              ParamType->getAs<MemberPointerType>()
7158                                ? CK_NullToMemberPointer
7159                                : CK_NullToPointer);
7160   }
7161   assert(Arg.getKind() == TemplateArgument::Declaration &&
7162          "Only declaration template arguments permitted here");
7163
7164   ValueDecl *VD = Arg.getAsDecl();
7165
7166   CXXScopeSpec SS;
7167   if (ParamType->isMemberPointerType()) {
7168     // If this is a pointer to member, we need to use a qualified name to
7169     // form a suitable pointer-to-member constant.
7170     assert(VD->getDeclContext()->isRecord() &&
7171            (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7172             isa<IndirectFieldDecl>(VD)));
7173     QualType ClassType
7174       = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7175     NestedNameSpecifier *Qualifier
7176       = NestedNameSpecifier::Create(Context, nullptr, false,
7177                                     ClassType.getTypePtr());
7178     SS.MakeTrivial(Context, Qualifier, Loc);
7179   }
7180
7181   ExprResult RefExpr = BuildDeclarationNameExpr(
7182       SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7183   if (RefExpr.isInvalid())
7184     return ExprError();
7185
7186   // For a pointer, the argument declaration is the pointee. Take its address.
7187   QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7188   if (ParamType->isPointerType() && !ElemT.isNull() &&
7189       Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7190     // Decay an array argument if we want a pointer to its first element.
7191     RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7192     if (RefExpr.isInvalid())
7193       return ExprError();
7194   } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7195     // For any other pointer, take the address (or form a pointer-to-member).
7196     RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7197     if (RefExpr.isInvalid())
7198       return ExprError();
7199   } else {
7200     assert(ParamType->isReferenceType() &&
7201            "unexpected type for decl template argument");
7202   }
7203
7204   // At this point we should have the right value category.
7205   assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7206          "value kind mismatch for non-type template argument");
7207
7208   // The type of the template parameter can differ from the type of the
7209   // argument in various ways; convert it now if necessary.
7210   QualType DestExprType = ParamType.getNonLValueExprType(Context);
7211   if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7212     CastKind CK;
7213     QualType Ignored;
7214     if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7215         IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7216       CK = CK_NoOp;
7217     } else if (ParamType->isVoidPointerType() &&
7218                RefExpr.get()->getType()->isPointerType()) {
7219       CK = CK_BitCast;
7220     } else {
7221       // FIXME: Pointers to members can need conversion derived-to-base or
7222       // base-to-derived conversions. We currently don't retain enough
7223       // information to convert properly (we need to track a cast path or
7224       // subobject number in the template argument).
7225       llvm_unreachable(
7226           "unexpected conversion required for non-type template argument");
7227     }
7228     RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7229                                 RefExpr.get()->getValueKind());
7230   }
7231
7232   return RefExpr;
7233 }
7234
7235 /// Construct a new expression that refers to the given
7236 /// integral template argument with the given source-location
7237 /// information.
7238 ///
7239 /// This routine takes care of the mapping from an integral template
7240 /// argument (which may have any integral type) to the appropriate
7241 /// literal value.
7242 ExprResult
7243 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7244                                                   SourceLocation Loc) {
7245   assert(Arg.getKind() == TemplateArgument::Integral &&
7246          "Operation is only valid for integral template arguments");
7247   QualType OrigT = Arg.getIntegralType();
7248
7249   // If this is an enum type that we're instantiating, we need to use an integer
7250   // type the same size as the enumerator.  We don't want to build an
7251   // IntegerLiteral with enum type.  The integer type of an enum type can be of
7252   // any integral type with C++11 enum classes, make sure we create the right
7253   // type of literal for it.
7254   QualType T = OrigT;
7255   if (const EnumType *ET = OrigT->getAs<EnumType>())
7256     T = ET->getDecl()->getIntegerType();
7257
7258   Expr *E;
7259   if (T->isAnyCharacterType()) {
7260     CharacterLiteral::CharacterKind Kind;
7261     if (T->isWideCharType())
7262       Kind = CharacterLiteral::Wide;
7263     else if (T->isChar8Type() && getLangOpts().Char8)
7264       Kind = CharacterLiteral::UTF8;
7265     else if (T->isChar16Type())
7266       Kind = CharacterLiteral::UTF16;
7267     else if (T->isChar32Type())
7268       Kind = CharacterLiteral::UTF32;
7269     else
7270       Kind = CharacterLiteral::Ascii;
7271
7272     E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
7273                                        Kind, T, Loc);
7274   } else if (T->isBooleanType()) {
7275     E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
7276                                          T, Loc);
7277   } else if (T->isNullPtrType()) {
7278     E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
7279   } else {
7280     E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
7281   }
7282
7283   if (OrigT->isEnumeralType()) {
7284     // FIXME: This is a hack. We need a better way to handle substituted
7285     // non-type template parameters.
7286     E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
7287                                nullptr,
7288                                Context.getTrivialTypeSourceInfo(OrigT, Loc),
7289                                Loc, Loc);
7290   }
7291
7292   return E;
7293 }
7294
7295 /// Match two template parameters within template parameter lists.
7296 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
7297                                        bool Complain,
7298                                      Sema::TemplateParameterListEqualKind Kind,
7299                                        SourceLocation TemplateArgLoc) {
7300   // Check the actual kind (type, non-type, template).
7301   if (Old->getKind() != New->getKind()) {
7302     if (Complain) {
7303       unsigned NextDiag = diag::err_template_param_different_kind;
7304       if (TemplateArgLoc.isValid()) {
7305         S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7306         NextDiag = diag::note_template_param_different_kind;
7307       }
7308       S.Diag(New->getLocation(), NextDiag)
7309         << (Kind != Sema::TPL_TemplateMatch);
7310       S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7311         << (Kind != Sema::TPL_TemplateMatch);
7312     }
7313
7314     return false;
7315   }
7316
7317   // Check that both are parameter packs or neither are parameter packs.
7318   // However, if we are matching a template template argument to a
7319   // template template parameter, the template template parameter can have
7320   // a parameter pack where the template template argument does not.
7321   if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7322       !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7323         Old->isTemplateParameterPack())) {
7324     if (Complain) {
7325       unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7326       if (TemplateArgLoc.isValid()) {
7327         S.Diag(TemplateArgLoc,
7328              diag::err_template_arg_template_params_mismatch);
7329         NextDiag = diag::note_template_parameter_pack_non_pack;
7330       }
7331
7332       unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7333                       : isa<NonTypeTemplateParmDecl>(New)? 1
7334                       : 2;
7335       S.Diag(New->getLocation(), NextDiag)
7336         << ParamKind << New->isParameterPack();
7337       S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7338         << ParamKind << Old->isParameterPack();
7339     }
7340
7341     return false;
7342   }
7343
7344   // For non-type template parameters, check the type of the parameter.
7345   if (NonTypeTemplateParmDecl *OldNTTP
7346                                     = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7347     NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7348
7349     // If we are matching a template template argument to a template
7350     // template parameter and one of the non-type template parameter types
7351     // is dependent, then we must wait until template instantiation time
7352     // to actually compare the arguments.
7353     if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
7354         (!OldNTTP->getType()->isDependentType() &&
7355          !NewNTTP->getType()->isDependentType()))
7356       if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
7357         if (Complain) {
7358           unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7359           if (TemplateArgLoc.isValid()) {
7360             S.Diag(TemplateArgLoc,
7361                    diag::err_template_arg_template_params_mismatch);
7362             NextDiag = diag::note_template_nontype_parm_different_type;
7363           }
7364           S.Diag(NewNTTP->getLocation(), NextDiag)
7365             << NewNTTP->getType()
7366             << (Kind != Sema::TPL_TemplateMatch);
7367           S.Diag(OldNTTP->getLocation(),
7368                  diag::note_template_nontype_parm_prev_declaration)
7369             << OldNTTP->getType();
7370         }
7371
7372         return false;
7373       }
7374   }
7375   // For template template parameters, check the template parameter types.
7376   // The template parameter lists of template template
7377   // parameters must agree.
7378   else if (TemplateTemplateParmDecl *OldTTP
7379                                     = dyn_cast<TemplateTemplateParmDecl>(Old)) {
7380     TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7381     if (!S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7382                                           OldTTP->getTemplateParameters(),
7383                                           Complain,
7384                                         (Kind == Sema::TPL_TemplateMatch
7385                                            ? Sema::TPL_TemplateTemplateParmMatch
7386                                            : Kind),
7387                                           TemplateArgLoc))
7388       return false;
7389   } else if (Kind != Sema::TPL_TemplateTemplateArgumentMatch) {
7390     const Expr *NewC = nullptr, *OldC = nullptr;
7391     if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7392       NewC = TC->getImmediatelyDeclaredConstraint();
7393     if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7394       OldC = TC->getImmediatelyDeclaredConstraint();
7395
7396     auto Diagnose = [&] {
7397       S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7398            diag::err_template_different_type_constraint);
7399       S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7400            diag::note_template_prev_declaration) << /*declaration*/0;
7401     };
7402
7403     if (!NewC != !OldC) {
7404       if (Complain)
7405         Diagnose();
7406       return false;
7407     }
7408
7409     if (NewC) {
7410       llvm::FoldingSetNodeID OldCID, NewCID;
7411       OldC->Profile(OldCID, S.Context, /*Canonical=*/true);
7412       NewC->Profile(NewCID, S.Context, /*Canonical=*/true);
7413       if (OldCID != NewCID) {
7414         if (Complain)
7415           Diagnose();
7416         return false;
7417       }
7418     }
7419   }
7420
7421   return true;
7422 }
7423
7424 /// Diagnose a known arity mismatch when comparing template argument
7425 /// lists.
7426 static
7427 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
7428                                                 TemplateParameterList *New,
7429                                                 TemplateParameterList *Old,
7430                                       Sema::TemplateParameterListEqualKind Kind,
7431                                                 SourceLocation TemplateArgLoc) {
7432   unsigned NextDiag = diag::err_template_param_list_different_arity;
7433   if (TemplateArgLoc.isValid()) {
7434     S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7435     NextDiag = diag::note_template_param_list_different_arity;
7436   }
7437   S.Diag(New->getTemplateLoc(), NextDiag)
7438     << (New->size() > Old->size())
7439     << (Kind != Sema::TPL_TemplateMatch)
7440     << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7441   S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7442     << (Kind != Sema::TPL_TemplateMatch)
7443     << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7444 }
7445
7446 /// Determine whether the given template parameter lists are
7447 /// equivalent.
7448 ///
7449 /// \param New  The new template parameter list, typically written in the
7450 /// source code as part of a new template declaration.
7451 ///
7452 /// \param Old  The old template parameter list, typically found via
7453 /// name lookup of the template declared with this template parameter
7454 /// list.
7455 ///
7456 /// \param Complain  If true, this routine will produce a diagnostic if
7457 /// the template parameter lists are not equivalent.
7458 ///
7459 /// \param Kind describes how we are to match the template parameter lists.
7460 ///
7461 /// \param TemplateArgLoc If this source location is valid, then we
7462 /// are actually checking the template parameter list of a template
7463 /// argument (New) against the template parameter list of its
7464 /// corresponding template template parameter (Old). We produce
7465 /// slightly different diagnostics in this scenario.
7466 ///
7467 /// \returns True if the template parameter lists are equal, false
7468 /// otherwise.
7469 bool
7470 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7471                                      TemplateParameterList *Old,
7472                                      bool Complain,
7473                                      TemplateParameterListEqualKind Kind,
7474                                      SourceLocation TemplateArgLoc) {
7475   if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7476     if (Complain)
7477       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7478                                                  TemplateArgLoc);
7479
7480     return false;
7481   }
7482
7483   // C++0x [temp.arg.template]p3:
7484   //   A template-argument matches a template template-parameter (call it P)
7485   //   when each of the template parameters in the template-parameter-list of
7486   //   the template-argument's corresponding class template or alias template
7487   //   (call it A) matches the corresponding template parameter in the
7488   //   template-parameter-list of P. [...]
7489   TemplateParameterList::iterator NewParm = New->begin();
7490   TemplateParameterList::iterator NewParmEnd = New->end();
7491   for (TemplateParameterList::iterator OldParm = Old->begin(),
7492                                     OldParmEnd = Old->end();
7493        OldParm != OldParmEnd; ++OldParm) {
7494     if (Kind != TPL_TemplateTemplateArgumentMatch ||
7495         !(*OldParm)->isTemplateParameterPack()) {
7496       if (NewParm == NewParmEnd) {
7497         if (Complain)
7498           DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7499                                                      TemplateArgLoc);
7500
7501         return false;
7502       }
7503
7504       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7505                                       Kind, TemplateArgLoc))
7506         return false;
7507
7508       ++NewParm;
7509       continue;
7510     }
7511
7512     // C++0x [temp.arg.template]p3:
7513     //   [...] When P's template- parameter-list contains a template parameter
7514     //   pack (14.5.3), the template parameter pack will match zero or more
7515     //   template parameters or template parameter packs in the
7516     //   template-parameter-list of A with the same type and form as the
7517     //   template parameter pack in P (ignoring whether those template
7518     //   parameters are template parameter packs).
7519     for (; NewParm != NewParmEnd; ++NewParm) {
7520       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7521                                       Kind, TemplateArgLoc))
7522         return false;
7523     }
7524   }
7525
7526   // Make sure we exhausted all of the arguments.
7527   if (NewParm != NewParmEnd) {
7528     if (Complain)
7529       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7530                                                  TemplateArgLoc);
7531
7532     return false;
7533   }
7534
7535   if (Kind != TPL_TemplateTemplateArgumentMatch) {
7536     const Expr *NewRC = New->getRequiresClause();
7537     const Expr *OldRC = Old->getRequiresClause();
7538
7539     auto Diagnose = [&] {
7540       Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7541            diag::err_template_different_requires_clause);
7542       Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7543            diag::note_template_prev_declaration) << /*declaration*/0;
7544     };
7545
7546     if (!NewRC != !OldRC) {
7547       if (Complain)
7548         Diagnose();
7549       return false;
7550     }
7551
7552     if (NewRC) {
7553       llvm::FoldingSetNodeID OldRCID, NewRCID;
7554       OldRC->Profile(OldRCID, Context, /*Canonical=*/true);
7555       NewRC->Profile(NewRCID, Context, /*Canonical=*/true);
7556       if (OldRCID != NewRCID) {
7557         if (Complain)
7558           Diagnose();
7559         return false;
7560       }
7561     }
7562   }
7563
7564   return true;
7565 }
7566
7567 /// Check whether a template can be declared within this scope.
7568 ///
7569 /// If the template declaration is valid in this scope, returns
7570 /// false. Otherwise, issues a diagnostic and returns true.
7571 bool
7572 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
7573   if (!S)
7574     return false;
7575
7576   // Find the nearest enclosing declaration scope.
7577   while ((S->getFlags() & Scope::DeclScope) == 0 ||
7578          (S->getFlags() & Scope::TemplateParamScope) != 0)
7579     S = S->getParent();
7580
7581   // C++ [temp]p4:
7582   //   A template [...] shall not have C linkage.
7583   DeclContext *Ctx = S->getEntity();
7584   assert(Ctx && "Unknown context");
7585   if (Ctx->isExternCContext()) {
7586     Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7587         << TemplateParams->getSourceRange();
7588     if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7589       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7590     return true;
7591   }
7592   Ctx = Ctx->getRedeclContext();
7593
7594   // C++ [temp]p2:
7595   //   A template-declaration can appear only as a namespace scope or
7596   //   class scope declaration.
7597   if (Ctx) {
7598     if (Ctx->isFileContext())
7599       return false;
7600     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7601       // C++ [temp.mem]p2:
7602       //   A local class shall not have member templates.
7603       if (RD->isLocalClass())
7604         return Diag(TemplateParams->getTemplateLoc(),
7605                     diag::err_template_inside_local_class)
7606           << TemplateParams->getSourceRange();
7607       else
7608         return false;
7609     }
7610   }
7611
7612   return Diag(TemplateParams->getTemplateLoc(),
7613               diag::err_template_outside_namespace_or_class_scope)
7614     << TemplateParams->getSourceRange();
7615 }
7616
7617 /// Determine what kind of template specialization the given declaration
7618 /// is.
7619 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
7620   if (!D)
7621     return TSK_Undeclared;
7622
7623   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7624     return Record->getTemplateSpecializationKind();
7625   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7626     return Function->getTemplateSpecializationKind();
7627   if (VarDecl *Var = dyn_cast<VarDecl>(D))
7628     return Var->getTemplateSpecializationKind();
7629
7630   return TSK_Undeclared;
7631 }
7632
7633 /// Check whether a specialization is well-formed in the current
7634 /// context.
7635 ///
7636 /// This routine determines whether a template specialization can be declared
7637 /// in the current context (C++ [temp.expl.spec]p2).
7638 ///
7639 /// \param S the semantic analysis object for which this check is being
7640 /// performed.
7641 ///
7642 /// \param Specialized the entity being specialized or instantiated, which
7643 /// may be a kind of template (class template, function template, etc.) or
7644 /// a member of a class template (member function, static data member,
7645 /// member class).
7646 ///
7647 /// \param PrevDecl the previous declaration of this entity, if any.
7648 ///
7649 /// \param Loc the location of the explicit specialization or instantiation of
7650 /// this entity.
7651 ///
7652 /// \param IsPartialSpecialization whether this is a partial specialization of
7653 /// a class template.
7654 ///
7655 /// \returns true if there was an error that we cannot recover from, false
7656 /// otherwise.
7657 static bool CheckTemplateSpecializationScope(Sema &S,
7658                                              NamedDecl *Specialized,
7659                                              NamedDecl *PrevDecl,
7660                                              SourceLocation Loc,
7661                                              bool IsPartialSpecialization) {
7662   // Keep these "kind" numbers in sync with the %select statements in the
7663   // various diagnostics emitted by this routine.
7664   int EntityKind = 0;
7665   if (isa<ClassTemplateDecl>(Specialized))
7666     EntityKind = IsPartialSpecialization? 1 : 0;
7667   else if (isa<VarTemplateDecl>(Specialized))
7668     EntityKind = IsPartialSpecialization ? 3 : 2;
7669   else if (isa<FunctionTemplateDecl>(Specialized))
7670     EntityKind = 4;
7671   else if (isa<CXXMethodDecl>(Specialized))
7672     EntityKind = 5;
7673   else if (isa<VarDecl>(Specialized))
7674     EntityKind = 6;
7675   else if (isa<RecordDecl>(Specialized))
7676     EntityKind = 7;
7677   else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7678     EntityKind = 8;
7679   else {
7680     S.Diag(Loc, diag::err_template_spec_unknown_kind)
7681       << S.getLangOpts().CPlusPlus11;
7682     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7683     return true;
7684   }
7685
7686   // C++ [temp.expl.spec]p2:
7687   //   An explicit specialization may be declared in any scope in which
7688   //   the corresponding primary template may be defined.
7689   if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7690     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7691       << Specialized;
7692     return true;
7693   }
7694
7695   // C++ [temp.class.spec]p6:
7696   //   A class template partial specialization may be declared in any
7697   //   scope in which the primary template may be defined.
7698   DeclContext *SpecializedContext =
7699       Specialized->getDeclContext()->getRedeclContext();
7700   DeclContext *DC = S.CurContext->getRedeclContext();
7701
7702   // Make sure that this redeclaration (or definition) occurs in the same
7703   // scope or an enclosing namespace.
7704   if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7705                             : DC->Equals(SpecializedContext))) {
7706     if (isa<TranslationUnitDecl>(SpecializedContext))
7707       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7708         << EntityKind << Specialized;
7709     else {
7710       auto *ND = cast<NamedDecl>(SpecializedContext);
7711       int Diag = diag::err_template_spec_redecl_out_of_scope;
7712       if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
7713         Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7714       S.Diag(Loc, Diag) << EntityKind << Specialized
7715                         << ND << isa<CXXRecordDecl>(ND);
7716     }
7717
7718     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7719
7720     // Don't allow specializing in the wrong class during error recovery.
7721     // Otherwise, things can go horribly wrong.
7722     if (DC->isRecord())
7723       return true;
7724   }
7725
7726   return false;
7727 }
7728
7729 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7730   if (!E->isTypeDependent())
7731     return SourceLocation();
7732   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7733   Checker.TraverseStmt(E);
7734   if (Checker.MatchLoc.isInvalid())
7735     return E->getSourceRange();
7736   return Checker.MatchLoc;
7737 }
7738
7739 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7740   if (!TL.getType()->isDependentType())
7741     return SourceLocation();
7742   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7743   Checker.TraverseTypeLoc(TL);
7744   if (Checker.MatchLoc.isInvalid())
7745     return TL.getSourceRange();
7746   return Checker.MatchLoc;
7747 }
7748
7749 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7750 /// that checks non-type template partial specialization arguments.
7751 static bool CheckNonTypeTemplatePartialSpecializationArgs(
7752     Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7753     const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7754   for (unsigned I = 0; I != NumArgs; ++I) {
7755     if (Args[I].getKind() == TemplateArgument::Pack) {
7756       if (CheckNonTypeTemplatePartialSpecializationArgs(
7757               S, TemplateNameLoc, Param, Args[I].pack_begin(),
7758               Args[I].pack_size(), IsDefaultArgument))
7759         return true;
7760
7761       continue;
7762     }
7763
7764     if (Args[I].getKind() != TemplateArgument::Expression)
7765       continue;
7766
7767     Expr *ArgExpr = Args[I].getAsExpr();
7768
7769     // We can have a pack expansion of any of the bullets below.
7770     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7771       ArgExpr = Expansion->getPattern();
7772
7773     // Strip off any implicit casts we added as part of type checking.
7774     while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7775       ArgExpr = ICE->getSubExpr();
7776
7777     // C++ [temp.class.spec]p8:
7778     //   A non-type argument is non-specialized if it is the name of a
7779     //   non-type parameter. All other non-type arguments are
7780     //   specialized.
7781     //
7782     // Below, we check the two conditions that only apply to
7783     // specialized non-type arguments, so skip any non-specialized
7784     // arguments.
7785     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7786       if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7787         continue;
7788
7789     // C++ [temp.class.spec]p9:
7790     //   Within the argument list of a class template partial
7791     //   specialization, the following restrictions apply:
7792     //     -- A partially specialized non-type argument expression
7793     //        shall not involve a template parameter of the partial
7794     //        specialization except when the argument expression is a
7795     //        simple identifier.
7796     //     -- The type of a template parameter corresponding to a
7797     //        specialized non-type argument shall not be dependent on a
7798     //        parameter of the specialization.
7799     // DR1315 removes the first bullet, leaving an incoherent set of rules.
7800     // We implement a compromise between the original rules and DR1315:
7801     //     --  A specialized non-type template argument shall not be
7802     //         type-dependent and the corresponding template parameter
7803     //         shall have a non-dependent type.
7804     SourceRange ParamUseRange =
7805         findTemplateParameterInType(Param->getDepth(), ArgExpr);
7806     if (ParamUseRange.isValid()) {
7807       if (IsDefaultArgument) {
7808         S.Diag(TemplateNameLoc,
7809                diag::err_dependent_non_type_arg_in_partial_spec);
7810         S.Diag(ParamUseRange.getBegin(),
7811                diag::note_dependent_non_type_default_arg_in_partial_spec)
7812           << ParamUseRange;
7813       } else {
7814         S.Diag(ParamUseRange.getBegin(),
7815                diag::err_dependent_non_type_arg_in_partial_spec)
7816           << ParamUseRange;
7817       }
7818       return true;
7819     }
7820
7821     ParamUseRange = findTemplateParameter(
7822         Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7823     if (ParamUseRange.isValid()) {
7824       S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
7825              diag::err_dependent_typed_non_type_arg_in_partial_spec)
7826           << Param->getType();
7827       S.Diag(Param->getLocation(), diag::note_template_param_here)
7828         << (IsDefaultArgument ? ParamUseRange : SourceRange())
7829         << ParamUseRange;
7830       return true;
7831     }
7832   }
7833
7834   return false;
7835 }
7836
7837 /// Check the non-type template arguments of a class template
7838 /// partial specialization according to C++ [temp.class.spec]p9.
7839 ///
7840 /// \param TemplateNameLoc the location of the template name.
7841 /// \param PrimaryTemplate the template parameters of the primary class
7842 ///        template.
7843 /// \param NumExplicit the number of explicitly-specified template arguments.
7844 /// \param TemplateArgs the template arguments of the class template
7845 ///        partial specialization.
7846 ///
7847 /// \returns \c true if there was an error, \c false otherwise.
7848 bool Sema::CheckTemplatePartialSpecializationArgs(
7849     SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7850     unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7851   // We have to be conservative when checking a template in a dependent
7852   // context.
7853   if (PrimaryTemplate->getDeclContext()->isDependentContext())
7854     return false;
7855
7856   TemplateParameterList *TemplateParams =
7857       PrimaryTemplate->getTemplateParameters();
7858   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7859     NonTypeTemplateParmDecl *Param
7860       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7861     if (!Param)
7862       continue;
7863
7864     if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7865                                                       Param, &TemplateArgs[I],
7866                                                       1, I >= NumExplicit))
7867       return true;
7868   }
7869
7870   return false;
7871 }
7872
7873 DeclResult Sema::ActOnClassTemplateSpecialization(
7874     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7875     SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7876     const ParsedAttributesView &Attr,
7877     MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
7878   assert(TUK != TUK_Reference && "References are not specializations");
7879
7880   CXXScopeSpec &SS = TemplateId.SS;
7881
7882   // NOTE: KWLoc is the location of the tag keyword. This will instead
7883   // store the location of the outermost template keyword in the declaration.
7884   SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7885     ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7886   SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7887   SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7888   SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7889
7890   // Find the class template we're specializing
7891   TemplateName Name = TemplateId.Template.get();
7892   ClassTemplateDecl *ClassTemplate
7893     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7894
7895   if (!ClassTemplate) {
7896     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7897       << (Name.getAsTemplateDecl() &&
7898           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7899     return true;
7900   }
7901
7902   bool isMemberSpecialization = false;
7903   bool isPartialSpecialization = false;
7904
7905   // Check the validity of the template headers that introduce this
7906   // template.
7907   // FIXME: We probably shouldn't complain about these headers for
7908   // friend declarations.
7909   bool Invalid = false;
7910   TemplateParameterList *TemplateParams =
7911       MatchTemplateParametersToScopeSpecifier(
7912           KWLoc, TemplateNameLoc, SS, &TemplateId,
7913           TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7914           Invalid);
7915   if (Invalid)
7916     return true;
7917
7918   if (TemplateParams && TemplateParams->size() > 0) {
7919     isPartialSpecialization = true;
7920
7921     if (TUK == TUK_Friend) {
7922       Diag(KWLoc, diag::err_partial_specialization_friend)
7923         << SourceRange(LAngleLoc, RAngleLoc);
7924       return true;
7925     }
7926
7927     // C++ [temp.class.spec]p10:
7928     //   The template parameter list of a specialization shall not
7929     //   contain default template argument values.
7930     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7931       Decl *Param = TemplateParams->getParam(I);
7932       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7933         if (TTP->hasDefaultArgument()) {
7934           Diag(TTP->getDefaultArgumentLoc(),
7935                diag::err_default_arg_in_partial_spec);
7936           TTP->removeDefaultArgument();
7937         }
7938       } else if (NonTypeTemplateParmDecl *NTTP
7939                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7940         if (Expr *DefArg = NTTP->getDefaultArgument()) {
7941           Diag(NTTP->getDefaultArgumentLoc(),
7942                diag::err_default_arg_in_partial_spec)
7943             << DefArg->getSourceRange();
7944           NTTP->removeDefaultArgument();
7945         }
7946       } else {
7947         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7948         if (TTP->hasDefaultArgument()) {
7949           Diag(TTP->getDefaultArgument().getLocation(),
7950                diag::err_default_arg_in_partial_spec)
7951             << TTP->getDefaultArgument().getSourceRange();
7952           TTP->removeDefaultArgument();
7953         }
7954       }
7955     }
7956   } else if (TemplateParams) {
7957     if (TUK == TUK_Friend)
7958       Diag(KWLoc, diag::err_template_spec_friend)
7959         << FixItHint::CreateRemoval(
7960                                 SourceRange(TemplateParams->getTemplateLoc(),
7961                                             TemplateParams->getRAngleLoc()))
7962         << SourceRange(LAngleLoc, RAngleLoc);
7963   } else {
7964     assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
7965   }
7966
7967   // Check that the specialization uses the same tag kind as the
7968   // original template.
7969   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7970   assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
7971   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7972                                     Kind, TUK == TUK_Definition, KWLoc,
7973                                     ClassTemplate->getIdentifier())) {
7974     Diag(KWLoc, diag::err_use_with_wrong_tag)
7975       << ClassTemplate
7976       << FixItHint::CreateReplacement(KWLoc,
7977                             ClassTemplate->getTemplatedDecl()->getKindName());
7978     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7979          diag::note_previous_use);
7980     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7981   }
7982
7983   // Translate the parser's template argument list in our AST format.
7984   TemplateArgumentListInfo TemplateArgs =
7985       makeTemplateArgumentListInfo(*this, TemplateId);
7986
7987   // Check for unexpanded parameter packs in any of the template arguments.
7988   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7989     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7990                                         UPPC_PartialSpecialization))
7991       return true;
7992
7993   // Check that the template argument list is well-formed for this
7994   // template.
7995   SmallVector<TemplateArgument, 4> Converted;
7996   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7997                                 TemplateArgs, false, Converted,
7998                                 /*UpdateArgsWithConversion=*/true))
7999     return true;
8000
8001   // Find the class template (partial) specialization declaration that
8002   // corresponds to these arguments.
8003   if (isPartialSpecialization) {
8004     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8005                                                TemplateArgs.size(), Converted))
8006       return true;
8007
8008     // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8009     // also do it during instantiation.
8010     bool InstantiationDependent;
8011     if (!Name.isDependent() &&
8012         !TemplateSpecializationType::anyDependentTemplateArguments(
8013             TemplateArgs.arguments(), InstantiationDependent)) {
8014       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8015         << ClassTemplate->getDeclName();
8016       isPartialSpecialization = false;
8017     }
8018   }
8019
8020   void *InsertPos = nullptr;
8021   ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8022
8023   if (isPartialSpecialization)
8024     PrevDecl = ClassTemplate->findPartialSpecialization(Converted,
8025                                                         TemplateParams,
8026                                                         InsertPos);
8027   else
8028     PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
8029
8030   ClassTemplateSpecializationDecl *Specialization = nullptr;
8031
8032   // Check whether we can declare a class template specialization in
8033   // the current scope.
8034   if (TUK != TUK_Friend &&
8035       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
8036                                        TemplateNameLoc,
8037                                        isPartialSpecialization))
8038     return true;
8039
8040   // The canonical type
8041   QualType CanonType;
8042   if (isPartialSpecialization) {
8043     // Build the canonical type that describes the converted template
8044     // arguments of the class template partial specialization.
8045     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8046     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8047                                                       Converted);
8048
8049     if (Context.hasSameType(CanonType,
8050                         ClassTemplate->getInjectedClassNameSpecialization()) &&
8051         (!Context.getLangOpts().ConceptsTS ||
8052          !TemplateParams->hasAssociatedConstraints())) {
8053       // C++ [temp.class.spec]p9b3:
8054       //
8055       //   -- The argument list of the specialization shall not be identical
8056       //      to the implicit argument list of the primary template.
8057       //
8058       // This rule has since been removed, because it's redundant given DR1495,
8059       // but we keep it because it produces better diagnostics and recovery.
8060       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8061         << /*class template*/0 << (TUK == TUK_Definition)
8062         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8063       return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
8064                                 ClassTemplate->getIdentifier(),
8065                                 TemplateNameLoc,
8066                                 Attr,
8067                                 TemplateParams,
8068                                 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
8069                                 /*FriendLoc*/SourceLocation(),
8070                                 TemplateParameterLists.size() - 1,
8071                                 TemplateParameterLists.data());
8072     }
8073
8074     // Create a new class template partial specialization declaration node.
8075     ClassTemplatePartialSpecializationDecl *PrevPartial
8076       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8077     ClassTemplatePartialSpecializationDecl *Partial
8078       = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
8079                                              ClassTemplate->getDeclContext(),
8080                                                        KWLoc, TemplateNameLoc,
8081                                                        TemplateParams,
8082                                                        ClassTemplate,
8083                                                        Converted,
8084                                                        TemplateArgs,
8085                                                        CanonType,
8086                                                        PrevPartial);
8087     SetNestedNameSpecifier(*this, Partial, SS);
8088     if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8089       Partial->setTemplateParameterListsInfo(
8090           Context, TemplateParameterLists.drop_back(1));
8091     }
8092
8093     if (!PrevPartial)
8094       ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8095     Specialization = Partial;
8096
8097     // If we are providing an explicit specialization of a member class
8098     // template specialization, make a note of that.
8099     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8100       PrevPartial->setMemberSpecialization();
8101
8102     CheckTemplatePartialSpecialization(Partial);
8103   } else {
8104     // Create a new class template specialization declaration node for
8105     // this explicit specialization or friend declaration.
8106     Specialization
8107       = ClassTemplateSpecializationDecl::Create(Context, Kind,
8108                                              ClassTemplate->getDeclContext(),
8109                                                 KWLoc, TemplateNameLoc,
8110                                                 ClassTemplate,
8111                                                 Converted,
8112                                                 PrevDecl);
8113     SetNestedNameSpecifier(*this, Specialization, SS);
8114     if (TemplateParameterLists.size() > 0) {
8115       Specialization->setTemplateParameterListsInfo(Context,
8116                                                     TemplateParameterLists);
8117     }
8118
8119     if (!PrevDecl)
8120       ClassTemplate->AddSpecialization(Specialization, InsertPos);
8121
8122     if (CurContext->isDependentContext()) {
8123       TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8124       CanonType = Context.getTemplateSpecializationType(
8125           CanonTemplate, Converted);
8126     } else {
8127       CanonType = Context.getTypeDeclType(Specialization);
8128     }
8129   }
8130
8131   // C++ [temp.expl.spec]p6:
8132   //   If a template, a member template or the member of a class template is
8133   //   explicitly specialized then that specialization shall be declared
8134   //   before the first use of that specialization that would cause an implicit
8135   //   instantiation to take place, in every translation unit in which such a
8136   //   use occurs; no diagnostic is required.
8137   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8138     bool Okay = false;
8139     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8140       // Is there any previous explicit specialization declaration?
8141       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8142         Okay = true;
8143         break;
8144       }
8145     }
8146
8147     if (!Okay) {
8148       SourceRange Range(TemplateNameLoc, RAngleLoc);
8149       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8150         << Context.getTypeDeclType(Specialization) << Range;
8151
8152       Diag(PrevDecl->getPointOfInstantiation(),
8153            diag::note_instantiation_required_here)
8154         << (PrevDecl->getTemplateSpecializationKind()
8155                                                 != TSK_ImplicitInstantiation);
8156       return true;
8157     }
8158   }
8159
8160   // If this is not a friend, note that this is an explicit specialization.
8161   if (TUK != TUK_Friend)
8162     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8163
8164   // Check that this isn't a redefinition of this specialization.
8165   if (TUK == TUK_Definition) {
8166     RecordDecl *Def = Specialization->getDefinition();
8167     NamedDecl *Hidden = nullptr;
8168     if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8169       SkipBody->ShouldSkip = true;
8170       SkipBody->Previous = Def;
8171       makeMergedDefinitionVisible(Hidden);
8172     } else if (Def) {
8173       SourceRange Range(TemplateNameLoc, RAngleLoc);
8174       Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8175       Diag(Def->getLocation(), diag::note_previous_definition);
8176       Specialization->setInvalidDecl();
8177       return true;
8178     }
8179   }
8180
8181   ProcessDeclAttributeList(S, Specialization, Attr);
8182
8183   // Add alignment attributes if necessary; these attributes are checked when
8184   // the ASTContext lays out the structure.
8185   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8186     AddAlignmentAttributesForRecord(Specialization);
8187     AddMsStructLayoutForRecord(Specialization);
8188   }
8189
8190   if (ModulePrivateLoc.isValid())
8191     Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8192       << (isPartialSpecialization? 1 : 0)
8193       << FixItHint::CreateRemoval(ModulePrivateLoc);
8194
8195   // Build the fully-sugared type for this class template
8196   // specialization as the user wrote in the specialization
8197   // itself. This means that we'll pretty-print the type retrieved
8198   // from the specialization's declaration the way that the user
8199   // actually wrote the specialization, rather than formatting the
8200   // name based on the "canonical" representation used to store the
8201   // template arguments in the specialization.
8202   TypeSourceInfo *WrittenTy
8203     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8204                                                 TemplateArgs, CanonType);
8205   if (TUK != TUK_Friend) {
8206     Specialization->setTypeAsWritten(WrittenTy);
8207     Specialization->setTemplateKeywordLoc(TemplateKWLoc);
8208   }
8209
8210   // C++ [temp.expl.spec]p9:
8211   //   A template explicit specialization is in the scope of the
8212   //   namespace in which the template was defined.
8213   //
8214   // We actually implement this paragraph where we set the semantic
8215   // context (in the creation of the ClassTemplateSpecializationDecl),
8216   // but we also maintain the lexical context where the actual
8217   // definition occurs.
8218   Specialization->setLexicalDeclContext(CurContext);
8219
8220   // We may be starting the definition of this specialization.
8221   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
8222     Specialization->startDefinition();
8223
8224   if (TUK == TUK_Friend) {
8225     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8226                                             TemplateNameLoc,
8227                                             WrittenTy,
8228                                             /*FIXME:*/KWLoc);
8229     Friend->setAccess(AS_public);
8230     CurContext->addDecl(Friend);
8231   } else {
8232     // Add the specialization into its lexical context, so that it can
8233     // be seen when iterating through the list of declarations in that
8234     // context. However, specializations are not found by name lookup.
8235     CurContext->addDecl(Specialization);
8236   }
8237
8238   if (SkipBody && SkipBody->ShouldSkip)
8239     return SkipBody->Previous;
8240
8241   return Specialization;
8242 }
8243
8244 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8245                               MultiTemplateParamsArg TemplateParameterLists,
8246                                     Declarator &D) {
8247   Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8248   ActOnDocumentableDecl(NewDecl);
8249   return NewDecl;
8250 }
8251
8252 Decl *Sema::ActOnConceptDefinition(Scope *S,
8253                               MultiTemplateParamsArg TemplateParameterLists,
8254                                    IdentifierInfo *Name, SourceLocation NameLoc,
8255                                    Expr *ConstraintExpr) {
8256   DeclContext *DC = CurContext;
8257
8258   if (!DC->getRedeclContext()->isFileContext()) {
8259     Diag(NameLoc,
8260       diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8261     return nullptr;
8262   }
8263
8264   if (TemplateParameterLists.size() > 1) {
8265     Diag(NameLoc, diag::err_concept_extra_headers);
8266     return nullptr;
8267   }
8268
8269   if (TemplateParameterLists.front()->size() == 0) {
8270     Diag(NameLoc, diag::err_concept_no_parameters);
8271     return nullptr;
8272   }
8273
8274   ConceptDecl *NewDecl = ConceptDecl::Create(Context, DC, NameLoc, Name,
8275                                              TemplateParameterLists.front(),
8276                                              ConstraintExpr);
8277                                              
8278   if (NewDecl->hasAssociatedConstraints()) {
8279     // C++2a [temp.concept]p4:
8280     // A concept shall not have associated constraints.
8281     Diag(NameLoc, diag::err_concept_no_associated_constraints);
8282     NewDecl->setInvalidDecl();
8283   }
8284
8285   // Check for conflicting previous declaration.
8286   DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
8287   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8288                         ForVisibleRedeclaration);
8289   LookupName(Previous, S);
8290
8291   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
8292                        /*AllowInlineNamespace*/false);
8293   if (!Previous.empty()) {
8294     auto *Old = Previous.getRepresentativeDecl();
8295     Diag(NameLoc, isa<ConceptDecl>(Old) ? diag::err_redefinition :
8296          diag::err_redefinition_different_kind) << NewDecl->getDeclName();
8297     Diag(Old->getLocation(), diag::note_previous_definition);
8298   }
8299
8300   ActOnDocumentableDecl(NewDecl);
8301   PushOnScopeChains(NewDecl, S);
8302   return NewDecl;
8303 }
8304
8305 /// \brief Strips various properties off an implicit instantiation
8306 /// that has just been explicitly specialized.
8307 static void StripImplicitInstantiation(NamedDecl *D) {
8308   D->dropAttr<DLLImportAttr>();
8309   D->dropAttr<DLLExportAttr>();
8310
8311   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8312     FD->setInlineSpecified(false);
8313 }
8314
8315 /// Compute the diagnostic location for an explicit instantiation
8316 //  declaration or definition.
8317 static SourceLocation DiagLocForExplicitInstantiation(
8318     NamedDecl* D, SourceLocation PointOfInstantiation) {
8319   // Explicit instantiations following a specialization have no effect and
8320   // hence no PointOfInstantiation. In that case, walk decl backwards
8321   // until a valid name loc is found.
8322   SourceLocation PrevDiagLoc = PointOfInstantiation;
8323   for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8324        Prev = Prev->getPreviousDecl()) {
8325     PrevDiagLoc = Prev->getLocation();
8326   }
8327   assert(PrevDiagLoc.isValid() &&
8328          "Explicit instantiation without point of instantiation?");
8329   return PrevDiagLoc;
8330 }
8331
8332 /// Diagnose cases where we have an explicit template specialization
8333 /// before/after an explicit template instantiation, producing diagnostics
8334 /// for those cases where they are required and determining whether the
8335 /// new specialization/instantiation will have any effect.
8336 ///
8337 /// \param NewLoc the location of the new explicit specialization or
8338 /// instantiation.
8339 ///
8340 /// \param NewTSK the kind of the new explicit specialization or instantiation.
8341 ///
8342 /// \param PrevDecl the previous declaration of the entity.
8343 ///
8344 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
8345 ///
8346 /// \param PrevPointOfInstantiation if valid, indicates where the previus
8347 /// declaration was instantiated (either implicitly or explicitly).
8348 ///
8349 /// \param HasNoEffect will be set to true to indicate that the new
8350 /// specialization or instantiation has no effect and should be ignored.
8351 ///
8352 /// \returns true if there was an error that should prevent the introduction of
8353 /// the new declaration into the AST, false otherwise.
8354 bool
8355 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8356                                              TemplateSpecializationKind NewTSK,
8357                                              NamedDecl *PrevDecl,
8358                                              TemplateSpecializationKind PrevTSK,
8359                                         SourceLocation PrevPointOfInstantiation,
8360                                              bool &HasNoEffect) {
8361   HasNoEffect = false;
8362
8363   switch (NewTSK) {
8364   case TSK_Undeclared:
8365   case TSK_ImplicitInstantiation:
8366     assert(
8367         (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8368         "previous declaration must be implicit!");
8369     return false;
8370
8371   case TSK_ExplicitSpecialization:
8372     switch (PrevTSK) {
8373     case TSK_Undeclared:
8374     case TSK_ExplicitSpecialization:
8375       // Okay, we're just specializing something that is either already
8376       // explicitly specialized or has merely been mentioned without any
8377       // instantiation.
8378       return false;
8379
8380     case TSK_ImplicitInstantiation:
8381       if (PrevPointOfInstantiation.isInvalid()) {
8382         // The declaration itself has not actually been instantiated, so it is
8383         // still okay to specialize it.
8384         StripImplicitInstantiation(PrevDecl);
8385         return false;
8386       }
8387       // Fall through
8388       LLVM_FALLTHROUGH;
8389
8390     case TSK_ExplicitInstantiationDeclaration:
8391     case TSK_ExplicitInstantiationDefinition:
8392       assert((PrevTSK == TSK_ImplicitInstantiation ||
8393               PrevPointOfInstantiation.isValid()) &&
8394              "Explicit instantiation without point of instantiation?");
8395
8396       // C++ [temp.expl.spec]p6:
8397       //   If a template, a member template or the member of a class template
8398       //   is explicitly specialized then that specialization shall be declared
8399       //   before the first use of that specialization that would cause an
8400       //   implicit instantiation to take place, in every translation unit in
8401       //   which such a use occurs; no diagnostic is required.
8402       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8403         // Is there any previous explicit specialization declaration?
8404         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8405           return false;
8406       }
8407
8408       Diag(NewLoc, diag::err_specialization_after_instantiation)
8409         << PrevDecl;
8410       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8411         << (PrevTSK != TSK_ImplicitInstantiation);
8412
8413       return true;
8414     }
8415     llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8416
8417   case TSK_ExplicitInstantiationDeclaration:
8418     switch (PrevTSK) {
8419     case TSK_ExplicitInstantiationDeclaration:
8420       // This explicit instantiation declaration is redundant (that's okay).
8421       HasNoEffect = true;
8422       return false;
8423
8424     case TSK_Undeclared:
8425     case TSK_ImplicitInstantiation:
8426       // We're explicitly instantiating something that may have already been
8427       // implicitly instantiated; that's fine.
8428       return false;
8429
8430     case TSK_ExplicitSpecialization:
8431       // C++0x [temp.explicit]p4:
8432       //   For a given set of template parameters, if an explicit instantiation
8433       //   of a template appears after a declaration of an explicit
8434       //   specialization for that template, the explicit instantiation has no
8435       //   effect.
8436       HasNoEffect = true;
8437       return false;
8438
8439     case TSK_ExplicitInstantiationDefinition:
8440       // C++0x [temp.explicit]p10:
8441       //   If an entity is the subject of both an explicit instantiation
8442       //   declaration and an explicit instantiation definition in the same
8443       //   translation unit, the definition shall follow the declaration.
8444       Diag(NewLoc,
8445            diag::err_explicit_instantiation_declaration_after_definition);
8446
8447       // Explicit instantiations following a specialization have no effect and
8448       // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8449       // until a valid name loc is found.
8450       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8451            diag::note_explicit_instantiation_definition_here);
8452       HasNoEffect = true;
8453       return false;
8454     }
8455     llvm_unreachable("Unexpected TemplateSpecializationKind!");
8456
8457   case TSK_ExplicitInstantiationDefinition:
8458     switch (PrevTSK) {
8459     case TSK_Undeclared:
8460     case TSK_ImplicitInstantiation:
8461       // We're explicitly instantiating something that may have already been
8462       // implicitly instantiated; that's fine.
8463       return false;
8464
8465     case TSK_ExplicitSpecialization:
8466       // C++ DR 259, C++0x [temp.explicit]p4:
8467       //   For a given set of template parameters, if an explicit
8468       //   instantiation of a template appears after a declaration of
8469       //   an explicit specialization for that template, the explicit
8470       //   instantiation has no effect.
8471       Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8472         << PrevDecl;
8473       Diag(PrevDecl->getLocation(),
8474            diag::note_previous_template_specialization);
8475       HasNoEffect = true;
8476       return false;
8477
8478     case TSK_ExplicitInstantiationDeclaration:
8479       // We're explicitly instantiating a definition for something for which we
8480       // were previously asked to suppress instantiations. That's fine.
8481
8482       // C++0x [temp.explicit]p4:
8483       //   For a given set of template parameters, if an explicit instantiation
8484       //   of a template appears after a declaration of an explicit
8485       //   specialization for that template, the explicit instantiation has no
8486       //   effect.
8487       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8488         // Is there any previous explicit specialization declaration?
8489         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8490           HasNoEffect = true;
8491           break;
8492         }
8493       }
8494
8495       return false;
8496
8497     case TSK_ExplicitInstantiationDefinition:
8498       // C++0x [temp.spec]p5:
8499       //   For a given template and a given set of template-arguments,
8500       //     - an explicit instantiation definition shall appear at most once
8501       //       in a program,
8502
8503       // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8504       Diag(NewLoc, (getLangOpts().MSVCCompat)
8505                        ? diag::ext_explicit_instantiation_duplicate
8506                        : diag::err_explicit_instantiation_duplicate)
8507           << PrevDecl;
8508       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8509            diag::note_previous_explicit_instantiation);
8510       HasNoEffect = true;
8511       return false;
8512     }
8513   }
8514
8515   llvm_unreachable("Missing specialization/instantiation case?");
8516 }
8517
8518 /// Perform semantic analysis for the given dependent function
8519 /// template specialization.
8520 ///
8521 /// The only possible way to get a dependent function template specialization
8522 /// is with a friend declaration, like so:
8523 ///
8524 /// \code
8525 ///   template \<class T> void foo(T);
8526 ///   template \<class T> class A {
8527 ///     friend void foo<>(T);
8528 ///   };
8529 /// \endcode
8530 ///
8531 /// There really isn't any useful analysis we can do here, so we
8532 /// just store the information.
8533 bool
8534 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8535                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
8536                                                    LookupResult &Previous) {
8537   // Remove anything from Previous that isn't a function template in
8538   // the correct context.
8539   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8540   LookupResult::Filter F = Previous.makeFilter();
8541   enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8542   SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
8543   while (F.hasNext()) {
8544     NamedDecl *D = F.next()->getUnderlyingDecl();
8545     if (!isa<FunctionTemplateDecl>(D)) {
8546       F.erase();
8547       DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8548       continue;
8549     }
8550
8551     if (!FDLookupContext->InEnclosingNamespaceSetOf(
8552             D->getDeclContext()->getRedeclContext())) {
8553       F.erase();
8554       DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8555       continue;
8556     }
8557   }
8558   F.done();
8559
8560   if (Previous.empty()) {
8561     Diag(FD->getLocation(),
8562          diag::err_dependent_function_template_spec_no_match);
8563     for (auto &P : DiscardedCandidates)
8564       Diag(P.second->getLocation(),
8565            diag::note_dependent_function_template_spec_discard_reason)
8566           << P.first;
8567     return true;
8568   }
8569
8570   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8571                                          ExplicitTemplateArgs);
8572   return false;
8573 }
8574
8575 /// Perform semantic analysis for the given function template
8576 /// specialization.
8577 ///
8578 /// This routine performs all of the semantic analysis required for an
8579 /// explicit function template specialization. On successful completion,
8580 /// the function declaration \p FD will become a function template
8581 /// specialization.
8582 ///
8583 /// \param FD the function declaration, which will be updated to become a
8584 /// function template specialization.
8585 ///
8586 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8587 /// if any. Note that this may be valid info even when 0 arguments are
8588 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8589 /// as it anyway contains info on the angle brackets locations.
8590 ///
8591 /// \param Previous the set of declarations that may be specialized by
8592 /// this function specialization.
8593 ///
8594 /// \param QualifiedFriend whether this is a lookup for a qualified friend
8595 /// declaration with no explicit template argument list that might be
8596 /// befriending a function template specialization.
8597 bool Sema::CheckFunctionTemplateSpecialization(
8598     FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8599     LookupResult &Previous, bool QualifiedFriend) {
8600   // The set of function template specializations that could match this
8601   // explicit function template specialization.
8602   UnresolvedSet<8> Candidates;
8603   TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8604                                             /*ForTakingAddress=*/false);
8605
8606   llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8607       ConvertedTemplateArgs;
8608
8609   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8610   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8611          I != E; ++I) {
8612     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8613     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8614       // Only consider templates found within the same semantic lookup scope as
8615       // FD.
8616       if (!FDLookupContext->InEnclosingNamespaceSetOf(
8617                                 Ovl->getDeclContext()->getRedeclContext()))
8618         continue;
8619
8620       // When matching a constexpr member function template specialization
8621       // against the primary template, we don't yet know whether the
8622       // specialization has an implicit 'const' (because we don't know whether
8623       // it will be a static member function until we know which template it
8624       // specializes), so adjust it now assuming it specializes this template.
8625       QualType FT = FD->getType();
8626       if (FD->isConstexpr()) {
8627         CXXMethodDecl *OldMD =
8628           dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8629         if (OldMD && OldMD->isConst()) {
8630           const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8631           FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8632           EPI.TypeQuals.addConst();
8633           FT = Context.getFunctionType(FPT->getReturnType(),
8634                                        FPT->getParamTypes(), EPI);
8635         }
8636       }
8637
8638       TemplateArgumentListInfo Args;
8639       if (ExplicitTemplateArgs)
8640         Args = *ExplicitTemplateArgs;
8641
8642       // C++ [temp.expl.spec]p11:
8643       //   A trailing template-argument can be left unspecified in the
8644       //   template-id naming an explicit function template specialization
8645       //   provided it can be deduced from the function argument type.
8646       // Perform template argument deduction to determine whether we may be
8647       // specializing this template.
8648       // FIXME: It is somewhat wasteful to build
8649       TemplateDeductionInfo Info(FailedCandidates.getLocation());
8650       FunctionDecl *Specialization = nullptr;
8651       if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8652               cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8653               ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8654               Info)) {
8655         // Template argument deduction failed; record why it failed, so
8656         // that we can provide nifty diagnostics.
8657         FailedCandidates.addCandidate().set(
8658             I.getPair(), FunTmpl->getTemplatedDecl(),
8659             MakeDeductionFailureInfo(Context, TDK, Info));
8660         (void)TDK;
8661         continue;
8662       }
8663
8664       // Target attributes are part of the cuda function signature, so
8665       // the deduced template's cuda target must match that of the
8666       // specialization.  Given that C++ template deduction does not
8667       // take target attributes into account, we reject candidates
8668       // here that have a different target.
8669       if (LangOpts.CUDA &&
8670           IdentifyCUDATarget(Specialization,
8671                              /* IgnoreImplicitHDAttr = */ true) !=
8672               IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
8673         FailedCandidates.addCandidate().set(
8674             I.getPair(), FunTmpl->getTemplatedDecl(),
8675             MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8676         continue;
8677       }
8678
8679       // Record this candidate.
8680       if (ExplicitTemplateArgs)
8681         ConvertedTemplateArgs[Specialization] = std::move(Args);
8682       Candidates.addDecl(Specialization, I.getAccess());
8683     }
8684   }
8685
8686   // For a qualified friend declaration (with no explicit marker to indicate
8687   // that a template specialization was intended), note all (template and
8688   // non-template) candidates.
8689   if (QualifiedFriend && Candidates.empty()) {
8690     Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8691         << FD->getDeclName() << FDLookupContext;
8692     // FIXME: We should form a single candidate list and diagnose all
8693     // candidates at once, to get proper sorting and limiting.
8694     for (auto *OldND : Previous) {
8695       if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8696         NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
8697     }
8698     FailedCandidates.NoteCandidates(*this, FD->getLocation());
8699     return true;
8700   }
8701
8702   // Find the most specialized function template.
8703   UnresolvedSetIterator Result = getMostSpecialized(
8704       Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
8705       PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8706       PDiag(diag::err_function_template_spec_ambiguous)
8707           << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8708       PDiag(diag::note_function_template_spec_matched));
8709
8710   if (Result == Candidates.end())
8711     return true;
8712
8713   // Ignore access information;  it doesn't figure into redeclaration checking.
8714   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8715
8716   FunctionTemplateSpecializationInfo *SpecInfo
8717     = Specialization->getTemplateSpecializationInfo();
8718   assert(SpecInfo && "Function template specialization info missing?");
8719
8720   // Note: do not overwrite location info if previous template
8721   // specialization kind was explicit.
8722   TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
8723   if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8724     Specialization->setLocation(FD->getLocation());
8725     Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8726     // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8727     // function can differ from the template declaration with respect to
8728     // the constexpr specifier.
8729     // FIXME: We need an update record for this AST mutation.
8730     // FIXME: What if there are multiple such prior declarations (for instance,
8731     // from different modules)?
8732     Specialization->setConstexprKind(FD->getConstexprKind());
8733   }
8734
8735   // FIXME: Check if the prior specialization has a point of instantiation.
8736   // If so, we have run afoul of .
8737
8738   // If this is a friend declaration, then we're not really declaring
8739   // an explicit specialization.
8740   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8741
8742   // Check the scope of this explicit specialization.
8743   if (!isFriend &&
8744       CheckTemplateSpecializationScope(*this,
8745                                        Specialization->getPrimaryTemplate(),
8746                                        Specialization, FD->getLocation(),
8747                                        false))
8748     return true;
8749
8750   // C++ [temp.expl.spec]p6:
8751   //   If a template, a member template or the member of a class template is
8752   //   explicitly specialized then that specialization shall be declared
8753   //   before the first use of that specialization that would cause an implicit
8754   //   instantiation to take place, in every translation unit in which such a
8755   //   use occurs; no diagnostic is required.
8756   bool HasNoEffect = false;
8757   if (!isFriend &&
8758       CheckSpecializationInstantiationRedecl(FD->getLocation(),
8759                                              TSK_ExplicitSpecialization,
8760                                              Specialization,
8761                                    SpecInfo->getTemplateSpecializationKind(),
8762                                          SpecInfo->getPointOfInstantiation(),
8763                                              HasNoEffect))
8764     return true;
8765
8766   // Mark the prior declaration as an explicit specialization, so that later
8767   // clients know that this is an explicit specialization.
8768   if (!isFriend) {
8769     // Since explicit specializations do not inherit '=delete' from their
8770     // primary function template - check if the 'specialization' that was
8771     // implicitly generated (during template argument deduction for partial
8772     // ordering) from the most specialized of all the function templates that
8773     // 'FD' could have been specializing, has a 'deleted' definition.  If so,
8774     // first check that it was implicitly generated during template argument
8775     // deduction by making sure it wasn't referenced, and then reset the deleted
8776     // flag to not-deleted, so that we can inherit that information from 'FD'.
8777     if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8778         !Specialization->getCanonicalDecl()->isReferenced()) {
8779       // FIXME: This assert will not hold in the presence of modules.
8780       assert(
8781           Specialization->getCanonicalDecl() == Specialization &&
8782           "This must be the only existing declaration of this specialization");
8783       // FIXME: We need an update record for this AST mutation.
8784       Specialization->setDeletedAsWritten(false);
8785     }
8786     // FIXME: We need an update record for this AST mutation.
8787     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8788     MarkUnusedFileScopedDecl(Specialization);
8789   }
8790
8791   // Turn the given function declaration into a function template
8792   // specialization, with the template arguments from the previous
8793   // specialization.
8794   // Take copies of (semantic and syntactic) template argument lists.
8795   const TemplateArgumentList* TemplArgs = new (Context)
8796     TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8797   FD->setFunctionTemplateSpecialization(
8798       Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8799       SpecInfo->getTemplateSpecializationKind(),
8800       ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8801
8802   // A function template specialization inherits the target attributes
8803   // of its template.  (We require the attributes explicitly in the
8804   // code to match, but a template may have implicit attributes by
8805   // virtue e.g. of being constexpr, and it passes these implicit
8806   // attributes on to its specializations.)
8807   if (LangOpts.CUDA)
8808     inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8809
8810   // The "previous declaration" for this function template specialization is
8811   // the prior function template specialization.
8812   Previous.clear();
8813   Previous.addDecl(Specialization);
8814   return false;
8815 }
8816
8817 /// Perform semantic analysis for the given non-template member
8818 /// specialization.
8819 ///
8820 /// This routine performs all of the semantic analysis required for an
8821 /// explicit member function specialization. On successful completion,
8822 /// the function declaration \p FD will become a member function
8823 /// specialization.
8824 ///
8825 /// \param Member the member declaration, which will be updated to become a
8826 /// specialization.
8827 ///
8828 /// \param Previous the set of declarations, one of which may be specialized
8829 /// by this function specialization;  the set will be modified to contain the
8830 /// redeclared member.
8831 bool
8832 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
8833   assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
8834
8835   // Try to find the member we are instantiating.
8836   NamedDecl *FoundInstantiation = nullptr;
8837   NamedDecl *Instantiation = nullptr;
8838   NamedDecl *InstantiatedFrom = nullptr;
8839   MemberSpecializationInfo *MSInfo = nullptr;
8840
8841   if (Previous.empty()) {
8842     // Nowhere to look anyway.
8843   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8844     for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8845            I != E; ++I) {
8846       NamedDecl *D = (*I)->getUnderlyingDecl();
8847       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8848         QualType Adjusted = Function->getType();
8849         if (!hasExplicitCallingConv(Adjusted))
8850           Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8851         // This doesn't handle deduced return types, but both function
8852         // declarations should be undeduced at this point.
8853         if (Context.hasSameType(Adjusted, Method->getType())) {
8854           FoundInstantiation = *I;
8855           Instantiation = Method;
8856           InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8857           MSInfo = Method->getMemberSpecializationInfo();
8858           break;
8859         }
8860       }
8861     }
8862   } else if (isa<VarDecl>(Member)) {
8863     VarDecl *PrevVar;
8864     if (Previous.isSingleResult() &&
8865         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8866       if (PrevVar->isStaticDataMember()) {
8867         FoundInstantiation = Previous.getRepresentativeDecl();
8868         Instantiation = PrevVar;
8869         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8870         MSInfo = PrevVar->getMemberSpecializationInfo();
8871       }
8872   } else if (isa<RecordDecl>(Member)) {
8873     CXXRecordDecl *PrevRecord;
8874     if (Previous.isSingleResult() &&
8875         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8876       FoundInstantiation = Previous.getRepresentativeDecl();
8877       Instantiation = PrevRecord;
8878       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8879       MSInfo = PrevRecord->getMemberSpecializationInfo();
8880     }
8881   } else if (isa<EnumDecl>(Member)) {
8882     EnumDecl *PrevEnum;
8883     if (Previous.isSingleResult() &&
8884         (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8885       FoundInstantiation = Previous.getRepresentativeDecl();
8886       Instantiation = PrevEnum;
8887       InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8888       MSInfo = PrevEnum->getMemberSpecializationInfo();
8889     }
8890   }
8891
8892   if (!Instantiation) {
8893     // There is no previous declaration that matches. Since member
8894     // specializations are always out-of-line, the caller will complain about
8895     // this mismatch later.
8896     return false;
8897   }
8898
8899   // A member specialization in a friend declaration isn't really declaring
8900   // an explicit specialization, just identifying a specific (possibly implicit)
8901   // specialization. Don't change the template specialization kind.
8902   //
8903   // FIXME: Is this really valid? Other compilers reject.
8904   if (Member->getFriendObjectKind() != Decl::FOK_None) {
8905     // Preserve instantiation information.
8906     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8907       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8908                                       cast<CXXMethodDecl>(InstantiatedFrom),
8909         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8910     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8911       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8912                                       cast<CXXRecordDecl>(InstantiatedFrom),
8913         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8914     }
8915
8916     Previous.clear();
8917     Previous.addDecl(FoundInstantiation);
8918     return false;
8919   }
8920
8921   // Make sure that this is a specialization of a member.
8922   if (!InstantiatedFrom) {
8923     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8924       << Member;
8925     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8926     return true;
8927   }
8928
8929   // C++ [temp.expl.spec]p6:
8930   //   If a template, a member template or the member of a class template is
8931   //   explicitly specialized then that specialization shall be declared
8932   //   before the first use of that specialization that would cause an implicit
8933   //   instantiation to take place, in every translation unit in which such a
8934   //   use occurs; no diagnostic is required.
8935   assert(MSInfo && "Member specialization info missing?");
8936
8937   bool HasNoEffect = false;
8938   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8939                                              TSK_ExplicitSpecialization,
8940                                              Instantiation,
8941                                      MSInfo->getTemplateSpecializationKind(),
8942                                            MSInfo->getPointOfInstantiation(),
8943                                              HasNoEffect))
8944     return true;
8945
8946   // Check the scope of this explicit specialization.
8947   if (CheckTemplateSpecializationScope(*this,
8948                                        InstantiatedFrom,
8949                                        Instantiation, Member->getLocation(),
8950                                        false))
8951     return true;
8952
8953   // Note that this member specialization is an "instantiation of" the
8954   // corresponding member of the original template.
8955   if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8956     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8957     if (InstantiationFunction->getTemplateSpecializationKind() ==
8958           TSK_ImplicitInstantiation) {
8959       // Explicit specializations of member functions of class templates do not
8960       // inherit '=delete' from the member function they are specializing.
8961       if (InstantiationFunction->isDeleted()) {
8962         // FIXME: This assert will not hold in the presence of modules.
8963         assert(InstantiationFunction->getCanonicalDecl() ==
8964                InstantiationFunction);
8965         // FIXME: We need an update record for this AST mutation.
8966         InstantiationFunction->setDeletedAsWritten(false);
8967       }
8968     }
8969
8970     MemberFunction->setInstantiationOfMemberFunction(
8971         cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8972   } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8973     MemberVar->setInstantiationOfStaticDataMember(
8974         cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8975   } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8976     MemberClass->setInstantiationOfMemberClass(
8977         cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8978   } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8979     MemberEnum->setInstantiationOfMemberEnum(
8980         cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8981   } else {
8982     llvm_unreachable("unknown member specialization kind");
8983   }
8984
8985   // Save the caller the trouble of having to figure out which declaration
8986   // this specialization matches.
8987   Previous.clear();
8988   Previous.addDecl(FoundInstantiation);
8989   return false;
8990 }
8991
8992 /// Complete the explicit specialization of a member of a class template by
8993 /// updating the instantiated member to be marked as an explicit specialization.
8994 ///
8995 /// \param OrigD The member declaration instantiated from the template.
8996 /// \param Loc The location of the explicit specialization of the member.
8997 template<typename DeclT>
8998 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8999                                              SourceLocation Loc) {
9000   if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9001     return;
9002
9003   // FIXME: Inform AST mutation listeners of this AST mutation.
9004   // FIXME: If there are multiple in-class declarations of the member (from
9005   // multiple modules, or a declaration and later definition of a member type),
9006   // should we update all of them?
9007   OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9008   OrigD->setLocation(Loc);
9009 }
9010
9011 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
9012                                         LookupResult &Previous) {
9013   NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9014   if (Instantiation == Member)
9015     return;
9016
9017   if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9018     completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9019   else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9020     completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9021   else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9022     completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9023   else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9024     completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9025   else
9026     llvm_unreachable("unknown member specialization kind");
9027 }
9028
9029 /// Check the scope of an explicit instantiation.
9030 ///
9031 /// \returns true if a serious error occurs, false otherwise.
9032 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
9033                                             SourceLocation InstLoc,
9034                                             bool WasQualifiedName) {
9035   DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
9036   DeclContext *CurContext = S.CurContext->getRedeclContext();
9037
9038   if (CurContext->isRecord()) {
9039     S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9040       << D;
9041     return true;
9042   }
9043
9044   // C++11 [temp.explicit]p3:
9045   //   An explicit instantiation shall appear in an enclosing namespace of its
9046   //   template. If the name declared in the explicit instantiation is an
9047   //   unqualified name, the explicit instantiation shall appear in the
9048   //   namespace where its template is declared or, if that namespace is inline
9049   //   (7.3.1), any namespace from its enclosing namespace set.
9050   //
9051   // This is DR275, which we do not retroactively apply to C++98/03.
9052   if (WasQualifiedName) {
9053     if (CurContext->Encloses(OrigContext))
9054       return false;
9055   } else {
9056     if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9057       return false;
9058   }
9059
9060   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9061     if (WasQualifiedName)
9062       S.Diag(InstLoc,
9063              S.getLangOpts().CPlusPlus11?
9064                diag::err_explicit_instantiation_out_of_scope :
9065                diag::warn_explicit_instantiation_out_of_scope_0x)
9066         << D << NS;
9067     else
9068       S.Diag(InstLoc,
9069              S.getLangOpts().CPlusPlus11?
9070                diag::err_explicit_instantiation_unqualified_wrong_namespace :
9071                diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9072         << D << NS;
9073   } else
9074     S.Diag(InstLoc,
9075            S.getLangOpts().CPlusPlus11?
9076              diag::err_explicit_instantiation_must_be_global :
9077              diag::warn_explicit_instantiation_must_be_global_0x)
9078       << D;
9079   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9080   return false;
9081 }
9082
9083 /// Common checks for whether an explicit instantiation of \p D is valid.
9084 static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
9085                                        SourceLocation InstLoc,
9086                                        bool WasQualifiedName,
9087                                        TemplateSpecializationKind TSK) {
9088   // C++ [temp.explicit]p13:
9089   //   An explicit instantiation declaration shall not name a specialization of
9090   //   a template with internal linkage.
9091   if (TSK == TSK_ExplicitInstantiationDeclaration &&
9092       D->getFormalLinkage() == InternalLinkage) {
9093     S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9094     return true;
9095   }
9096
9097   // C++11 [temp.explicit]p3: [DR 275]
9098   //   An explicit instantiation shall appear in an enclosing namespace of its
9099   //   template.
9100   if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9101     return true;
9102
9103   return false;
9104 }
9105
9106 /// Determine whether the given scope specifier has a template-id in it.
9107 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
9108   if (!SS.isSet())
9109     return false;
9110
9111   // C++11 [temp.explicit]p3:
9112   //   If the explicit instantiation is for a member function, a member class
9113   //   or a static data member of a class template specialization, the name of
9114   //   the class template specialization in the qualified-id for the member
9115   //   name shall be a simple-template-id.
9116   //
9117   // C++98 has the same restriction, just worded differently.
9118   for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9119        NNS = NNS->getPrefix())
9120     if (const Type *T = NNS->getAsType())
9121       if (isa<TemplateSpecializationType>(T))
9122         return true;
9123
9124   return false;
9125 }
9126
9127 /// Make a dllexport or dllimport attr on a class template specialization take
9128 /// effect.
9129 static void dllExportImportClassTemplateSpecialization(
9130     Sema &S, ClassTemplateSpecializationDecl *Def) {
9131   auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9132   assert(A && "dllExportImportClassTemplateSpecialization called "
9133               "on Def without dllexport or dllimport");
9134
9135   // We reject explicit instantiations in class scope, so there should
9136   // never be any delayed exported classes to worry about.
9137   assert(S.DelayedDllExportClasses.empty() &&
9138          "delayed exports present at explicit instantiation");
9139   S.checkClassLevelDLLAttribute(Def);
9140
9141   // Propagate attribute to base class templates.
9142   for (auto &B : Def->bases()) {
9143     if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9144             B.getType()->getAsCXXRecordDecl()))
9145       S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
9146   }
9147
9148   S.referenceDLLExportedClassMethods();
9149 }
9150
9151 // Explicit instantiation of a class template specialization
9152 DeclResult Sema::ActOnExplicitInstantiation(
9153     Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9154     unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9155     TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9156     SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9157     SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9158   // Find the class template we're specializing
9159   TemplateName Name = TemplateD.get();
9160   TemplateDecl *TD = Name.getAsTemplateDecl();
9161   // Check that the specialization uses the same tag kind as the
9162   // original template.
9163   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9164   assert(Kind != TTK_Enum &&
9165          "Invalid enum tag in class template explicit instantiation!");
9166
9167   ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9168
9169   if (!ClassTemplate) {
9170     NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9171     Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
9172     Diag(TD->getLocation(), diag::note_previous_use);
9173     return true;
9174   }
9175
9176   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9177                                     Kind, /*isDefinition*/false, KWLoc,
9178                                     ClassTemplate->getIdentifier())) {
9179     Diag(KWLoc, diag::err_use_with_wrong_tag)
9180       << ClassTemplate
9181       << FixItHint::CreateReplacement(KWLoc,
9182                             ClassTemplate->getTemplatedDecl()->getKindName());
9183     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9184          diag::note_previous_use);
9185     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9186   }
9187
9188   // C++0x [temp.explicit]p2:
9189   //   There are two forms of explicit instantiation: an explicit instantiation
9190   //   definition and an explicit instantiation declaration. An explicit
9191   //   instantiation declaration begins with the extern keyword. [...]
9192   TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9193                                        ? TSK_ExplicitInstantiationDefinition
9194                                        : TSK_ExplicitInstantiationDeclaration;
9195
9196   if (TSK == TSK_ExplicitInstantiationDeclaration &&
9197       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9198     // Check for dllexport class template instantiation declarations,
9199     // except for MinGW mode.
9200     for (const ParsedAttr &AL : Attr) {
9201       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9202         Diag(ExternLoc,
9203              diag::warn_attribute_dllexport_explicit_instantiation_decl);
9204         Diag(AL.getLoc(), diag::note_attribute);
9205         break;
9206       }
9207     }
9208
9209     if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9210       Diag(ExternLoc,
9211            diag::warn_attribute_dllexport_explicit_instantiation_decl);
9212       Diag(A->getLocation(), diag::note_attribute);
9213     }
9214   }
9215
9216   // In MSVC mode, dllimported explicit instantiation definitions are treated as
9217   // instantiation declarations for most purposes.
9218   bool DLLImportExplicitInstantiationDef = false;
9219   if (TSK == TSK_ExplicitInstantiationDefinition &&
9220       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9221     // Check for dllimport class template instantiation definitions.
9222     bool DLLImport =
9223         ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9224     for (const ParsedAttr &AL : Attr) {
9225       if (AL.getKind() == ParsedAttr::AT_DLLImport)
9226         DLLImport = true;
9227       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9228         // dllexport trumps dllimport here.
9229         DLLImport = false;
9230         break;
9231       }
9232     }
9233     if (DLLImport) {
9234       TSK = TSK_ExplicitInstantiationDeclaration;
9235       DLLImportExplicitInstantiationDef = true;
9236     }
9237   }
9238
9239   // Translate the parser's template argument list in our AST format.
9240   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9241   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9242
9243   // Check that the template argument list is well-formed for this
9244   // template.
9245   SmallVector<TemplateArgument, 4> Converted;
9246   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
9247                                 TemplateArgs, false, Converted,
9248                                 /*UpdateArgsWithConversion=*/true))
9249     return true;
9250
9251   // Find the class template specialization declaration that
9252   // corresponds to these arguments.
9253   void *InsertPos = nullptr;
9254   ClassTemplateSpecializationDecl *PrevDecl
9255     = ClassTemplate->findSpecialization(Converted, InsertPos);
9256
9257   TemplateSpecializationKind PrevDecl_TSK
9258     = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9259
9260   if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9261       Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9262     // Check for dllexport class template instantiation definitions in MinGW
9263     // mode, if a previous declaration of the instantiation was seen.
9264     for (const ParsedAttr &AL : Attr) {
9265       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9266         Diag(AL.getLoc(),
9267              diag::warn_attribute_dllexport_explicit_instantiation_def);
9268         break;
9269       }
9270     }
9271   }
9272
9273   if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9274                                  SS.isSet(), TSK))
9275     return true;
9276
9277   ClassTemplateSpecializationDecl *Specialization = nullptr;
9278
9279   bool HasNoEffect = false;
9280   if (PrevDecl) {
9281     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9282                                                PrevDecl, PrevDecl_TSK,
9283                                             PrevDecl->getPointOfInstantiation(),
9284                                                HasNoEffect))
9285       return PrevDecl;
9286
9287     // Even though HasNoEffect == true means that this explicit instantiation
9288     // has no effect on semantics, we go on to put its syntax in the AST.
9289
9290     if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9291         PrevDecl_TSK == TSK_Undeclared) {
9292       // Since the only prior class template specialization with these
9293       // arguments was referenced but not declared, reuse that
9294       // declaration node as our own, updating the source location
9295       // for the template name to reflect our new declaration.
9296       // (Other source locations will be updated later.)
9297       Specialization = PrevDecl;
9298       Specialization->setLocation(TemplateNameLoc);
9299       PrevDecl = nullptr;
9300     }
9301
9302     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9303         DLLImportExplicitInstantiationDef) {
9304       // The new specialization might add a dllimport attribute.
9305       HasNoEffect = false;
9306     }
9307   }
9308
9309   if (!Specialization) {
9310     // Create a new class template specialization declaration node for
9311     // this explicit specialization.
9312     Specialization
9313       = ClassTemplateSpecializationDecl::Create(Context, Kind,
9314                                              ClassTemplate->getDeclContext(),
9315                                                 KWLoc, TemplateNameLoc,
9316                                                 ClassTemplate,
9317                                                 Converted,
9318                                                 PrevDecl);
9319     SetNestedNameSpecifier(*this, Specialization, SS);
9320
9321     if (!HasNoEffect && !PrevDecl) {
9322       // Insert the new specialization.
9323       ClassTemplate->AddSpecialization(Specialization, InsertPos);
9324     }
9325   }
9326
9327   // Build the fully-sugared type for this explicit instantiation as
9328   // the user wrote in the explicit instantiation itself. This means
9329   // that we'll pretty-print the type retrieved from the
9330   // specialization's declaration the way that the user actually wrote
9331   // the explicit instantiation, rather than formatting the name based
9332   // on the "canonical" representation used to store the template
9333   // arguments in the specialization.
9334   TypeSourceInfo *WrittenTy
9335     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
9336                                                 TemplateArgs,
9337                                   Context.getTypeDeclType(Specialization));
9338   Specialization->setTypeAsWritten(WrittenTy);
9339
9340   // Set source locations for keywords.
9341   Specialization->setExternLoc(ExternLoc);
9342   Specialization->setTemplateKeywordLoc(TemplateLoc);
9343   Specialization->setBraceRange(SourceRange());
9344
9345   bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9346   ProcessDeclAttributeList(S, Specialization, Attr);
9347
9348   // Add the explicit instantiation into its lexical context. However,
9349   // since explicit instantiations are never found by name lookup, we
9350   // just put it into the declaration context directly.
9351   Specialization->setLexicalDeclContext(CurContext);
9352   CurContext->addDecl(Specialization);
9353
9354   // Syntax is now OK, so return if it has no other effect on semantics.
9355   if (HasNoEffect) {
9356     // Set the template specialization kind.
9357     Specialization->setTemplateSpecializationKind(TSK);
9358     return Specialization;
9359   }
9360
9361   // C++ [temp.explicit]p3:
9362   //   A definition of a class template or class member template
9363   //   shall be in scope at the point of the explicit instantiation of
9364   //   the class template or class member template.
9365   //
9366   // This check comes when we actually try to perform the
9367   // instantiation.
9368   ClassTemplateSpecializationDecl *Def
9369     = cast_or_null<ClassTemplateSpecializationDecl>(
9370                                               Specialization->getDefinition());
9371   if (!Def)
9372     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
9373   else if (TSK == TSK_ExplicitInstantiationDefinition) {
9374     MarkVTableUsed(TemplateNameLoc, Specialization, true);
9375     Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9376   }
9377
9378   // Instantiate the members of this class template specialization.
9379   Def = cast_or_null<ClassTemplateSpecializationDecl>(
9380                                        Specialization->getDefinition());
9381   if (Def) {
9382     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
9383     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9384     // TSK_ExplicitInstantiationDefinition
9385     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9386         (TSK == TSK_ExplicitInstantiationDefinition ||
9387          DLLImportExplicitInstantiationDef)) {
9388       // FIXME: Need to notify the ASTMutationListener that we did this.
9389       Def->setTemplateSpecializationKind(TSK);
9390
9391       if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9392           (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9393            Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9394         // In the MS ABI, an explicit instantiation definition can add a dll
9395         // attribute to a template with a previous instantiation declaration.
9396         // MinGW doesn't allow this.
9397         auto *A = cast<InheritableAttr>(
9398             getDLLAttr(Specialization)->clone(getASTContext()));
9399         A->setInherited(true);
9400         Def->addAttr(A);
9401         dllExportImportClassTemplateSpecialization(*this, Def);
9402       }
9403     }
9404
9405     // Fix a TSK_ImplicitInstantiation followed by a
9406     // TSK_ExplicitInstantiationDefinition
9407     bool NewlyDLLExported =
9408         !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9409     if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9410         (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9411          Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9412       // In the MS ABI, an explicit instantiation definition can add a dll
9413       // attribute to a template with a previous implicit instantiation.
9414       // MinGW doesn't allow this. We limit clang to only adding dllexport, to
9415       // avoid potentially strange codegen behavior.  For example, if we extend
9416       // this conditional to dllimport, and we have a source file calling a
9417       // method on an implicitly instantiated template class instance and then
9418       // declaring a dllimport explicit instantiation definition for the same
9419       // template class, the codegen for the method call will not respect the
9420       // dllimport, while it will with cl. The Def will already have the DLL
9421       // attribute, since the Def and Specialization will be the same in the
9422       // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
9423       // attribute to the Specialization; we just need to make it take effect.
9424       assert(Def == Specialization &&
9425              "Def and Specialization should match for implicit instantiation");
9426       dllExportImportClassTemplateSpecialization(*this, Def);
9427     }
9428
9429     // In MinGW mode, export the template instantiation if the declaration
9430     // was marked dllexport.
9431     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9432         Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9433         PrevDecl->hasAttr<DLLExportAttr>()) {
9434       dllExportImportClassTemplateSpecialization(*this, Def);
9435     }
9436
9437     // Set the template specialization kind. Make sure it is set before
9438     // instantiating the members which will trigger ASTConsumer callbacks.
9439     Specialization->setTemplateSpecializationKind(TSK);
9440     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
9441   } else {
9442
9443     // Set the template specialization kind.
9444     Specialization->setTemplateSpecializationKind(TSK);
9445   }
9446
9447   return Specialization;
9448 }
9449
9450 // Explicit instantiation of a member class of a class template.
9451 DeclResult
9452 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
9453                                  SourceLocation TemplateLoc, unsigned TagSpec,
9454                                  SourceLocation KWLoc, CXXScopeSpec &SS,
9455                                  IdentifierInfo *Name, SourceLocation NameLoc,
9456                                  const ParsedAttributesView &Attr) {
9457
9458   bool Owned = false;
9459   bool IsDependent = false;
9460   Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
9461                         KWLoc, SS, Name, NameLoc, Attr, AS_none,
9462                         /*ModulePrivateLoc=*/SourceLocation(),
9463                         MultiTemplateParamsArg(), Owned, IsDependent,
9464                         SourceLocation(), false, TypeResult(),
9465                         /*IsTypeSpecifier*/false,
9466                         /*IsTemplateParamOrArg*/false);
9467   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
9468
9469   if (!TagD)
9470     return true;
9471
9472   TagDecl *Tag = cast<TagDecl>(TagD);
9473   assert(!Tag->isEnum() && "shouldn't see enumerations here");
9474
9475   if (Tag->isInvalidDecl())
9476     return true;
9477
9478   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9479   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9480   if (!Pattern) {
9481     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9482       << Context.getTypeDeclType(Record);
9483     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9484     return true;
9485   }
9486
9487   // C++0x [temp.explicit]p2:
9488   //   If the explicit instantiation is for a class or member class, the
9489   //   elaborated-type-specifier in the declaration shall include a
9490   //   simple-template-id.
9491   //
9492   // C++98 has the same restriction, just worded differently.
9493   if (!ScopeSpecifierHasTemplateId(SS))
9494     Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
9495       << Record << SS.getRange();
9496
9497   // C++0x [temp.explicit]p2:
9498   //   There are two forms of explicit instantiation: an explicit instantiation
9499   //   definition and an explicit instantiation declaration. An explicit
9500   //   instantiation declaration begins with the extern keyword. [...]
9501   TemplateSpecializationKind TSK
9502     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9503                            : TSK_ExplicitInstantiationDeclaration;
9504
9505   CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
9506
9507   // Verify that it is okay to explicitly instantiate here.
9508   CXXRecordDecl *PrevDecl
9509     = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
9510   if (!PrevDecl && Record->getDefinition())
9511     PrevDecl = Record;
9512   if (PrevDecl) {
9513     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
9514     bool HasNoEffect = false;
9515     assert(MSInfo && "No member specialization information?");
9516     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
9517                                                PrevDecl,
9518                                         MSInfo->getTemplateSpecializationKind(),
9519                                              MSInfo->getPointOfInstantiation(),
9520                                                HasNoEffect))
9521       return true;
9522     if (HasNoEffect)
9523       return TagD;
9524   }
9525
9526   CXXRecordDecl *RecordDef
9527     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9528   if (!RecordDef) {
9529     // C++ [temp.explicit]p3:
9530     //   A definition of a member class of a class template shall be in scope
9531     //   at the point of an explicit instantiation of the member class.
9532     CXXRecordDecl *Def
9533       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
9534     if (!Def) {
9535       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9536         << 0 << Record->getDeclName() << Record->getDeclContext();
9537       Diag(Pattern->getLocation(), diag::note_forward_declaration)
9538         << Pattern;
9539       return true;
9540     } else {
9541       if (InstantiateClass(NameLoc, Record, Def,
9542                            getTemplateInstantiationArgs(Record),
9543                            TSK))
9544         return true;
9545
9546       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9547       if (!RecordDef)
9548         return true;
9549     }
9550   }
9551
9552   // Instantiate all of the members of the class.
9553   InstantiateClassMembers(NameLoc, RecordDef,
9554                           getTemplateInstantiationArgs(Record), TSK);
9555
9556   if (TSK == TSK_ExplicitInstantiationDefinition)
9557     MarkVTableUsed(NameLoc, RecordDef, true);
9558
9559   // FIXME: We don't have any representation for explicit instantiations of
9560   // member classes. Such a representation is not needed for compilation, but it
9561   // should be available for clients that want to see all of the declarations in
9562   // the source code.
9563   return TagD;
9564 }
9565
9566 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9567                                             SourceLocation ExternLoc,
9568                                             SourceLocation TemplateLoc,
9569                                             Declarator &D) {
9570   // Explicit instantiations always require a name.
9571   // TODO: check if/when DNInfo should replace Name.
9572   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9573   DeclarationName Name = NameInfo.getName();
9574   if (!Name) {
9575     if (!D.isInvalidType())
9576       Diag(D.getDeclSpec().getBeginLoc(),
9577            diag::err_explicit_instantiation_requires_name)
9578           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
9579
9580     return true;
9581   }
9582
9583   // The scope passed in may not be a decl scope.  Zip up the scope tree until
9584   // we find one that is.
9585   while ((S->getFlags() & Scope::DeclScope) == 0 ||
9586          (S->getFlags() & Scope::TemplateParamScope) != 0)
9587     S = S->getParent();
9588
9589   // Determine the type of the declaration.
9590   TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9591   QualType R = T->getType();
9592   if (R.isNull())
9593     return true;
9594
9595   // C++ [dcl.stc]p1:
9596   //   A storage-class-specifier shall not be specified in [...] an explicit
9597   //   instantiation (14.7.2) directive.
9598   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
9599     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9600       << Name;
9601     return true;
9602   } else if (D.getDeclSpec().getStorageClassSpec()
9603                                                 != DeclSpec::SCS_unspecified) {
9604     // Complain about then remove the storage class specifier.
9605     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9606       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9607
9608     D.getMutableDeclSpec().ClearStorageClassSpecs();
9609   }
9610
9611   // C++0x [temp.explicit]p1:
9612   //   [...] An explicit instantiation of a function template shall not use the
9613   //   inline or constexpr specifiers.
9614   // Presumably, this also applies to member functions of class templates as
9615   // well.
9616   if (D.getDeclSpec().isInlineSpecified())
9617     Diag(D.getDeclSpec().getInlineSpecLoc(),
9618          getLangOpts().CPlusPlus11 ?
9619            diag::err_explicit_instantiation_inline :
9620            diag::warn_explicit_instantiation_inline_0x)
9621       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9622   if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
9623     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9624     // not already specified.
9625     Diag(D.getDeclSpec().getConstexprSpecLoc(),
9626          diag::err_explicit_instantiation_constexpr);
9627
9628   // A deduction guide is not on the list of entities that can be explicitly
9629   // instantiated.
9630   if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9631     Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9632         << /*explicit instantiation*/ 0;
9633     return true;
9634   }
9635
9636   // C++0x [temp.explicit]p2:
9637   //   There are two forms of explicit instantiation: an explicit instantiation
9638   //   definition and an explicit instantiation declaration. An explicit
9639   //   instantiation declaration begins with the extern keyword. [...]
9640   TemplateSpecializationKind TSK
9641     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9642                            : TSK_ExplicitInstantiationDeclaration;
9643
9644   LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
9645   LookupParsedName(Previous, S, &D.getCXXScopeSpec());
9646
9647   if (!R->isFunctionType()) {
9648     // C++ [temp.explicit]p1:
9649     //   A [...] static data member of a class template can be explicitly
9650     //   instantiated from the member definition associated with its class
9651     //   template.
9652     // C++1y [temp.explicit]p1:
9653     //   A [...] variable [...] template specialization can be explicitly
9654     //   instantiated from its template.
9655     if (Previous.isAmbiguous())
9656       return true;
9657
9658     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9659     VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9660
9661     if (!PrevTemplate) {
9662       if (!Prev || !Prev->isStaticDataMember()) {
9663         // We expect to see a static data member here.
9664         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9665             << Name;
9666         for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9667              P != PEnd; ++P)
9668           Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9669         return true;
9670       }
9671
9672       if (!Prev->getInstantiatedFromStaticDataMember()) {
9673         // FIXME: Check for explicit specialization?
9674         Diag(D.getIdentifierLoc(),
9675              diag::err_explicit_instantiation_data_member_not_instantiated)
9676             << Prev;
9677         Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9678         // FIXME: Can we provide a note showing where this was declared?
9679         return true;
9680       }
9681     } else {
9682       // Explicitly instantiate a variable template.
9683
9684       // C++1y [dcl.spec.auto]p6:
9685       //   ... A program that uses auto or decltype(auto) in a context not
9686       //   explicitly allowed in this section is ill-formed.
9687       //
9688       // This includes auto-typed variable template instantiations.
9689       if (R->isUndeducedType()) {
9690         Diag(T->getTypeLoc().getBeginLoc(),
9691              diag::err_auto_not_allowed_var_inst);
9692         return true;
9693       }
9694
9695       if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9696         // C++1y [temp.explicit]p3:
9697         //   If the explicit instantiation is for a variable, the unqualified-id
9698         //   in the declaration shall be a template-id.
9699         Diag(D.getIdentifierLoc(),
9700              diag::err_explicit_instantiation_without_template_id)
9701           << PrevTemplate;
9702         Diag(PrevTemplate->getLocation(),
9703              diag::note_explicit_instantiation_here);
9704         return true;
9705       }
9706
9707       // Translate the parser's template argument list into our AST format.
9708       TemplateArgumentListInfo TemplateArgs =
9709           makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9710
9711       DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9712                                           D.getIdentifierLoc(), TemplateArgs);
9713       if (Res.isInvalid())
9714         return true;
9715
9716       // Ignore access control bits, we don't need them for redeclaration
9717       // checking.
9718       Prev = cast<VarDecl>(Res.get());
9719     }
9720
9721     // C++0x [temp.explicit]p2:
9722     //   If the explicit instantiation is for a member function, a member class
9723     //   or a static data member of a class template specialization, the name of
9724     //   the class template specialization in the qualified-id for the member
9725     //   name shall be a simple-template-id.
9726     //
9727     // C++98 has the same restriction, just worded differently.
9728     //
9729     // This does not apply to variable template specializations, where the
9730     // template-id is in the unqualified-id instead.
9731     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9732       Diag(D.getIdentifierLoc(),
9733            diag::ext_explicit_instantiation_without_qualified_id)
9734         << Prev << D.getCXXScopeSpec().getRange();
9735
9736     CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
9737
9738     // Verify that it is okay to explicitly instantiate here.
9739     TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9740     SourceLocation POI = Prev->getPointOfInstantiation();
9741     bool HasNoEffect = false;
9742     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9743                                                PrevTSK, POI, HasNoEffect))
9744       return true;
9745
9746     if (!HasNoEffect) {
9747       // Instantiate static data member or variable template.
9748       Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9749       // Merge attributes.
9750       ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
9751       if (TSK == TSK_ExplicitInstantiationDefinition)
9752         InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9753     }
9754
9755     // Check the new variable specialization against the parsed input.
9756     if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9757       Diag(T->getTypeLoc().getBeginLoc(),
9758            diag::err_invalid_var_template_spec_type)
9759           << 0 << PrevTemplate << R << Prev->getType();
9760       Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9761           << 2 << PrevTemplate->getDeclName();
9762       return true;
9763     }
9764
9765     // FIXME: Create an ExplicitInstantiation node?
9766     return (Decl*) nullptr;
9767   }
9768
9769   // If the declarator is a template-id, translate the parser's template
9770   // argument list into our AST format.
9771   bool HasExplicitTemplateArgs = false;
9772   TemplateArgumentListInfo TemplateArgs;
9773   if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9774     TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9775     HasExplicitTemplateArgs = true;
9776   }
9777
9778   // C++ [temp.explicit]p1:
9779   //   A [...] function [...] can be explicitly instantiated from its template.
9780   //   A member function [...] of a class template can be explicitly
9781   //  instantiated from the member definition associated with its class
9782   //  template.
9783   UnresolvedSet<8> TemplateMatches;
9784   FunctionDecl *NonTemplateMatch = nullptr;
9785   TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9786   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9787        P != PEnd; ++P) {
9788     NamedDecl *Prev = *P;
9789     if (!HasExplicitTemplateArgs) {
9790       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9791         QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9792                                                 /*AdjustExceptionSpec*/true);
9793         if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9794           if (Method->getPrimaryTemplate()) {
9795             TemplateMatches.addDecl(Method, P.getAccess());
9796           } else {
9797             // FIXME: Can this assert ever happen?  Needs a test.
9798             assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9799             NonTemplateMatch = Method;
9800           }
9801         }
9802       }
9803     }
9804
9805     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9806     if (!FunTmpl)
9807       continue;
9808
9809     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9810     FunctionDecl *Specialization = nullptr;
9811     if (TemplateDeductionResult TDK
9812           = DeduceTemplateArguments(FunTmpl,
9813                                (HasExplicitTemplateArgs ? &TemplateArgs
9814                                                         : nullptr),
9815                                     R, Specialization, Info)) {
9816       // Keep track of almost-matches.
9817       FailedCandidates.addCandidate()
9818           .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9819                MakeDeductionFailureInfo(Context, TDK, Info));
9820       (void)TDK;
9821       continue;
9822     }
9823
9824     // Target attributes are part of the cuda function signature, so
9825     // the cuda target of the instantiated function must match that of its
9826     // template.  Given that C++ template deduction does not take
9827     // target attributes into account, we reject candidates here that
9828     // have a different target.
9829     if (LangOpts.CUDA &&
9830         IdentifyCUDATarget(Specialization,
9831                            /* IgnoreImplicitHDAttr = */ true) !=
9832             IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
9833       FailedCandidates.addCandidate().set(
9834           P.getPair(), FunTmpl->getTemplatedDecl(),
9835           MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9836       continue;
9837     }
9838
9839     TemplateMatches.addDecl(Specialization, P.getAccess());
9840   }
9841
9842   FunctionDecl *Specialization = NonTemplateMatch;
9843   if (!Specialization) {
9844     // Find the most specialized function template specialization.
9845     UnresolvedSetIterator Result = getMostSpecialized(
9846         TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9847         D.getIdentifierLoc(),
9848         PDiag(diag::err_explicit_instantiation_not_known) << Name,
9849         PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9850         PDiag(diag::note_explicit_instantiation_candidate));
9851
9852     if (Result == TemplateMatches.end())
9853       return true;
9854
9855     // Ignore access control bits, we don't need them for redeclaration checking.
9856     Specialization = cast<FunctionDecl>(*Result);
9857   }
9858
9859   // C++11 [except.spec]p4
9860   // In an explicit instantiation an exception-specification may be specified,
9861   // but is not required.
9862   // If an exception-specification is specified in an explicit instantiation
9863   // directive, it shall be compatible with the exception-specifications of
9864   // other declarations of that function.
9865   if (auto *FPT = R->getAs<FunctionProtoType>())
9866     if (FPT->hasExceptionSpec()) {
9867       unsigned DiagID =
9868           diag::err_mismatched_exception_spec_explicit_instantiation;
9869       if (getLangOpts().MicrosoftExt)
9870         DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9871       bool Result = CheckEquivalentExceptionSpec(
9872           PDiag(DiagID) << Specialization->getType(),
9873           PDiag(diag::note_explicit_instantiation_here),
9874           Specialization->getType()->getAs<FunctionProtoType>(),
9875           Specialization->getLocation(), FPT, D.getBeginLoc());
9876       // In Microsoft mode, mismatching exception specifications just cause a
9877       // warning.
9878       if (!getLangOpts().MicrosoftExt && Result)
9879         return true;
9880     }
9881
9882   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9883     Diag(D.getIdentifierLoc(),
9884          diag::err_explicit_instantiation_member_function_not_instantiated)
9885       << Specialization
9886       << (Specialization->getTemplateSpecializationKind() ==
9887           TSK_ExplicitSpecialization);
9888     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9889     return true;
9890   }
9891
9892   FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9893   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9894     PrevDecl = Specialization;
9895
9896   if (PrevDecl) {
9897     bool HasNoEffect = false;
9898     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9899                                                PrevDecl,
9900                                      PrevDecl->getTemplateSpecializationKind(),
9901                                           PrevDecl->getPointOfInstantiation(),
9902                                                HasNoEffect))
9903       return true;
9904
9905     // FIXME: We may still want to build some representation of this
9906     // explicit specialization.
9907     if (HasNoEffect)
9908       return (Decl*) nullptr;
9909   }
9910
9911   // HACK: libc++ has a bug where it attempts to explicitly instantiate the
9912   // functions
9913   //     valarray<size_t>::valarray(size_t) and
9914   //     valarray<size_t>::~valarray()
9915   // that it declared to have internal linkage with the internal_linkage
9916   // attribute. Ignore the explicit instantiation declaration in this case.
9917   if (Specialization->hasAttr<InternalLinkageAttr>() &&
9918       TSK == TSK_ExplicitInstantiationDeclaration) {
9919     if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
9920       if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
9921           RD->isInStdNamespace())
9922         return (Decl*) nullptr;
9923   }
9924
9925   ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
9926
9927   // In MSVC mode, dllimported explicit instantiation definitions are treated as
9928   // instantiation declarations.
9929   if (TSK == TSK_ExplicitInstantiationDefinition &&
9930       Specialization->hasAttr<DLLImportAttr>() &&
9931       Context.getTargetInfo().getCXXABI().isMicrosoft())
9932     TSK = TSK_ExplicitInstantiationDeclaration;
9933
9934   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9935
9936   if (Specialization->isDefined()) {
9937     // Let the ASTConsumer know that this function has been explicitly
9938     // instantiated now, and its linkage might have changed.
9939     Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9940   } else if (TSK == TSK_ExplicitInstantiationDefinition)
9941     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9942
9943   // C++0x [temp.explicit]p2:
9944   //   If the explicit instantiation is for a member function, a member class
9945   //   or a static data member of a class template specialization, the name of
9946   //   the class template specialization in the qualified-id for the member
9947   //   name shall be a simple-template-id.
9948   //
9949   // C++98 has the same restriction, just worded differently.
9950   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9951   if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
9952       D.getCXXScopeSpec().isSet() &&
9953       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
9954     Diag(D.getIdentifierLoc(),
9955          diag::ext_explicit_instantiation_without_qualified_id)
9956     << Specialization << D.getCXXScopeSpec().getRange();
9957
9958   CheckExplicitInstantiation(
9959       *this,
9960       FunTmpl ? (NamedDecl *)FunTmpl
9961               : Specialization->getInstantiatedFromMemberFunction(),
9962       D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
9963
9964   // FIXME: Create some kind of ExplicitInstantiationDecl here.
9965   return (Decl*) nullptr;
9966 }
9967
9968 TypeResult
9969 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9970                         const CXXScopeSpec &SS, IdentifierInfo *Name,
9971                         SourceLocation TagLoc, SourceLocation NameLoc) {
9972   // This has to hold, because SS is expected to be defined.
9973   assert(Name && "Expected a name in a dependent tag");
9974
9975   NestedNameSpecifier *NNS = SS.getScopeRep();
9976   if (!NNS)
9977     return true;
9978
9979   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9980
9981   if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9982     Diag(NameLoc, diag::err_dependent_tag_decl)
9983       << (TUK == TUK_Definition) << Kind << SS.getRange();
9984     return true;
9985   }
9986
9987   // Create the resulting type.
9988   ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9989   QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9990
9991   // Create type-source location information for this type.
9992   TypeLocBuilder TLB;
9993   DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9994   TL.setElaboratedKeywordLoc(TagLoc);
9995   TL.setQualifierLoc(SS.getWithLocInContext(Context));
9996   TL.setNameLoc(NameLoc);
9997   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9998 }
9999
10000 TypeResult
10001 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10002                         const CXXScopeSpec &SS, const IdentifierInfo &II,
10003                         SourceLocation IdLoc) {
10004   if (SS.isInvalid())
10005     return true;
10006
10007   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10008     Diag(TypenameLoc,
10009          getLangOpts().CPlusPlus11 ?
10010            diag::warn_cxx98_compat_typename_outside_of_template :
10011            diag::ext_typename_outside_of_template)
10012       << FixItHint::CreateRemoval(TypenameLoc);
10013
10014   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10015   QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
10016                                  TypenameLoc, QualifierLoc, II, IdLoc);
10017   if (T.isNull())
10018     return true;
10019
10020   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10021   if (isa<DependentNameType>(T)) {
10022     DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10023     TL.setElaboratedKeywordLoc(TypenameLoc);
10024     TL.setQualifierLoc(QualifierLoc);
10025     TL.setNameLoc(IdLoc);
10026   } else {
10027     ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
10028     TL.setElaboratedKeywordLoc(TypenameLoc);
10029     TL.setQualifierLoc(QualifierLoc);
10030     TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
10031   }
10032
10033   return CreateParsedType(T, TSI);
10034 }
10035
10036 TypeResult
10037 Sema::ActOnTypenameType(Scope *S,
10038                         SourceLocation TypenameLoc,
10039                         const CXXScopeSpec &SS,
10040                         SourceLocation TemplateKWLoc,
10041                         TemplateTy TemplateIn,
10042                         IdentifierInfo *TemplateII,
10043                         SourceLocation TemplateIILoc,
10044                         SourceLocation LAngleLoc,
10045                         ASTTemplateArgsPtr TemplateArgsIn,
10046                         SourceLocation RAngleLoc) {
10047   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10048     Diag(TypenameLoc,
10049          getLangOpts().CPlusPlus11 ?
10050            diag::warn_cxx98_compat_typename_outside_of_template :
10051            diag::ext_typename_outside_of_template)
10052       << FixItHint::CreateRemoval(TypenameLoc);
10053
10054   // Strangely, non-type results are not ignored by this lookup, so the
10055   // program is ill-formed if it finds an injected-class-name.
10056   if (TypenameLoc.isValid()) {
10057     auto *LookupRD =
10058         dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10059     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10060       Diag(TemplateIILoc,
10061            diag::ext_out_of_line_qualified_id_type_names_constructor)
10062         << TemplateII << 0 /*injected-class-name used as template name*/
10063         << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10064     }
10065   }
10066
10067   // Translate the parser's template argument list in our AST format.
10068   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10069   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10070
10071   TemplateName Template = TemplateIn.get();
10072   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10073     // Construct a dependent template specialization type.
10074     assert(DTN && "dependent template has non-dependent name?");
10075     assert(DTN->getQualifier() == SS.getScopeRep());
10076     QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
10077                                                           DTN->getQualifier(),
10078                                                           DTN->getIdentifier(),
10079                                                                 TemplateArgs);
10080
10081     // Create source-location information for this type.
10082     TypeLocBuilder Builder;
10083     DependentTemplateSpecializationTypeLoc SpecTL
10084     = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
10085     SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10086     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
10087     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10088     SpecTL.setTemplateNameLoc(TemplateIILoc);
10089     SpecTL.setLAngleLoc(LAngleLoc);
10090     SpecTL.setRAngleLoc(RAngleLoc);
10091     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10092       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10093     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10094   }
10095
10096   QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10097   if (T.isNull())
10098     return true;
10099
10100   // Provide source-location information for the template specialization type.
10101   TypeLocBuilder Builder;
10102   TemplateSpecializationTypeLoc SpecTL
10103     = Builder.push<TemplateSpecializationTypeLoc>(T);
10104   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10105   SpecTL.setTemplateNameLoc(TemplateIILoc);
10106   SpecTL.setLAngleLoc(LAngleLoc);
10107   SpecTL.setRAngleLoc(RAngleLoc);
10108   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10109     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10110
10111   T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
10112   ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10113   TL.setElaboratedKeywordLoc(TypenameLoc);
10114   TL.setQualifierLoc(SS.getWithLocInContext(Context));
10115
10116   TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10117   return CreateParsedType(T, TSI);
10118 }
10119
10120
10121 /// Determine whether this failed name lookup should be treated as being
10122 /// disabled by a usage of std::enable_if.
10123 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
10124                        SourceRange &CondRange, Expr *&Cond) {
10125   // We must be looking for a ::type...
10126   if (!II.isStr("type"))
10127     return false;
10128
10129   // ... within an explicitly-written template specialization...
10130   if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10131     return false;
10132   TypeLoc EnableIfTy = NNS.getTypeLoc();
10133   TemplateSpecializationTypeLoc EnableIfTSTLoc =
10134       EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
10135   if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10136     return false;
10137   const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10138
10139   // ... which names a complete class template declaration...
10140   const TemplateDecl *EnableIfDecl =
10141     EnableIfTST->getTemplateName().getAsTemplateDecl();
10142   if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10143     return false;
10144
10145   // ... called "enable_if".
10146   const IdentifierInfo *EnableIfII =
10147     EnableIfDecl->getDeclName().getAsIdentifierInfo();
10148   if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10149     return false;
10150
10151   // Assume the first template argument is the condition.
10152   CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10153
10154   // Dig out the condition.
10155   Cond = nullptr;
10156   if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10157         != TemplateArgument::Expression)
10158     return true;
10159
10160   Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10161
10162   // Ignore Boolean literals; they add no value.
10163   if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10164     Cond = nullptr;
10165
10166   return true;
10167 }
10168
10169 /// Build the type that describes a C++ typename specifier,
10170 /// e.g., "typename T::type".
10171 QualType
10172 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10173                         SourceLocation KeywordLoc,
10174                         NestedNameSpecifierLoc QualifierLoc,
10175                         const IdentifierInfo &II,
10176                         SourceLocation IILoc) {
10177   CXXScopeSpec SS;
10178   SS.Adopt(QualifierLoc);
10179
10180   DeclContext *Ctx = computeDeclContext(SS);
10181   if (!Ctx) {
10182     // If the nested-name-specifier is dependent and couldn't be
10183     // resolved to a type, build a typename type.
10184     assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10185     return Context.getDependentNameType(Keyword,
10186                                         QualifierLoc.getNestedNameSpecifier(),
10187                                         &II);
10188   }
10189
10190   // If the nested-name-specifier refers to the current instantiation,
10191   // the "typename" keyword itself is superfluous. In C++03, the
10192   // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10193   // allows such extraneous "typename" keywords, and we retroactively
10194   // apply this DR to C++03 code with only a warning. In any case we continue.
10195
10196   if (RequireCompleteDeclContext(SS, Ctx))
10197     return QualType();
10198
10199   DeclarationName Name(&II);
10200   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10201   LookupQualifiedName(Result, Ctx, SS);
10202   unsigned DiagID = 0;
10203   Decl *Referenced = nullptr;
10204   switch (Result.getResultKind()) {
10205   case LookupResult::NotFound: {
10206     // If we're looking up 'type' within a template named 'enable_if', produce
10207     // a more specific diagnostic.
10208     SourceRange CondRange;
10209     Expr *Cond = nullptr;
10210     if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10211       // If we have a condition, narrow it down to the specific failed
10212       // condition.
10213       if (Cond) {
10214         Expr *FailedCond;
10215         std::string FailedDescription;
10216         std::tie(FailedCond, FailedDescription) =
10217           findFailedBooleanCondition(Cond);
10218
10219         Diag(FailedCond->getExprLoc(),
10220              diag::err_typename_nested_not_found_requirement)
10221           << FailedDescription
10222           << FailedCond->getSourceRange();
10223         return QualType();
10224       }
10225
10226       Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
10227           << Ctx << CondRange;
10228       return QualType();
10229     }
10230
10231     DiagID = diag::err_typename_nested_not_found;
10232     break;
10233   }
10234
10235   case LookupResult::FoundUnresolvedValue: {
10236     // We found a using declaration that is a value. Most likely, the using
10237     // declaration itself is meant to have the 'typename' keyword.
10238     SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10239                           IILoc);
10240     Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10241       << Name << Ctx << FullRange;
10242     if (UnresolvedUsingValueDecl *Using
10243           = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10244       SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10245       Diag(Loc, diag::note_using_value_decl_missing_typename)
10246         << FixItHint::CreateInsertion(Loc, "typename ");
10247     }
10248   }
10249   // Fall through to create a dependent typename type, from which we can recover
10250   // better.
10251   LLVM_FALLTHROUGH;
10252
10253   case LookupResult::NotFoundInCurrentInstantiation:
10254     // Okay, it's a member of an unknown instantiation.
10255     return Context.getDependentNameType(Keyword,
10256                                         QualifierLoc.getNestedNameSpecifier(),
10257                                         &II);
10258
10259   case LookupResult::Found:
10260     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10261       // C++ [class.qual]p2:
10262       //   In a lookup in which function names are not ignored and the
10263       //   nested-name-specifier nominates a class C, if the name specified
10264       //   after the nested-name-specifier, when looked up in C, is the
10265       //   injected-class-name of C [...] then the name is instead considered
10266       //   to name the constructor of class C.
10267       //
10268       // Unlike in an elaborated-type-specifier, function names are not ignored
10269       // in typename-specifier lookup. However, they are ignored in all the
10270       // contexts where we form a typename type with no keyword (that is, in
10271       // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10272       //
10273       // FIXME: That's not strictly true: mem-initializer-id lookup does not
10274       // ignore functions, but that appears to be an oversight.
10275       auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10276       auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10277       if (Keyword == ETK_Typename && LookupRD && FoundRD &&
10278           FoundRD->isInjectedClassName() &&
10279           declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10280         Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10281             << &II << 1 << 0 /*'typename' keyword used*/;
10282
10283       // We found a type. Build an ElaboratedType, since the
10284       // typename-specifier was just sugar.
10285       MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10286       return Context.getElaboratedType(Keyword,
10287                                        QualifierLoc.getNestedNameSpecifier(),
10288                                        Context.getTypeDeclType(Type));
10289     }
10290
10291     // C++ [dcl.type.simple]p2:
10292     //   A type-specifier of the form
10293     //     typename[opt] nested-name-specifier[opt] template-name
10294     //   is a placeholder for a deduced class type [...].
10295     if (getLangOpts().CPlusPlus17) {
10296       if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10297         return Context.getElaboratedType(
10298             Keyword, QualifierLoc.getNestedNameSpecifier(),
10299             Context.getDeducedTemplateSpecializationType(TemplateName(TD),
10300                                                          QualType(), false));
10301       }
10302     }
10303
10304     DiagID = diag::err_typename_nested_not_type;
10305     Referenced = Result.getFoundDecl();
10306     break;
10307
10308   case LookupResult::FoundOverloaded:
10309     DiagID = diag::err_typename_nested_not_type;
10310     Referenced = *Result.begin();
10311     break;
10312
10313   case LookupResult::Ambiguous:
10314     return QualType();
10315   }
10316
10317   // If we get here, it's because name lookup did not find a
10318   // type. Emit an appropriate diagnostic and return an error.
10319   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10320                         IILoc);
10321   Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10322   if (Referenced)
10323     Diag(Referenced->getLocation(), diag::note_typename_refers_here)
10324       << Name;
10325   return QualType();
10326 }
10327
10328 namespace {
10329   // See Sema::RebuildTypeInCurrentInstantiation
10330   class CurrentInstantiationRebuilder
10331     : public TreeTransform<CurrentInstantiationRebuilder> {
10332     SourceLocation Loc;
10333     DeclarationName Entity;
10334
10335   public:
10336     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
10337
10338     CurrentInstantiationRebuilder(Sema &SemaRef,
10339                                   SourceLocation Loc,
10340                                   DeclarationName Entity)
10341     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
10342       Loc(Loc), Entity(Entity) { }
10343
10344     /// Determine whether the given type \p T has already been
10345     /// transformed.
10346     ///
10347     /// For the purposes of type reconstruction, a type has already been
10348     /// transformed if it is NULL or if it is not dependent.
10349     bool AlreadyTransformed(QualType T) {
10350       return T.isNull() || !T->isDependentType();
10351     }
10352
10353     /// Returns the location of the entity whose type is being
10354     /// rebuilt.
10355     SourceLocation getBaseLocation() { return Loc; }
10356
10357     /// Returns the name of the entity whose type is being rebuilt.
10358     DeclarationName getBaseEntity() { return Entity; }
10359
10360     /// Sets the "base" location and entity when that
10361     /// information is known based on another transformation.
10362     void setBase(SourceLocation Loc, DeclarationName Entity) {
10363       this->Loc = Loc;
10364       this->Entity = Entity;
10365     }
10366
10367     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10368       // Lambdas never need to be transformed.
10369       return E;
10370     }
10371   };
10372 } // end anonymous namespace
10373
10374 /// Rebuilds a type within the context of the current instantiation.
10375 ///
10376 /// The type \p T is part of the type of an out-of-line member definition of
10377 /// a class template (or class template partial specialization) that was parsed
10378 /// and constructed before we entered the scope of the class template (or
10379 /// partial specialization thereof). This routine will rebuild that type now
10380 /// that we have entered the declarator's scope, which may produce different
10381 /// canonical types, e.g.,
10382 ///
10383 /// \code
10384 /// template<typename T>
10385 /// struct X {
10386 ///   typedef T* pointer;
10387 ///   pointer data();
10388 /// };
10389 ///
10390 /// template<typename T>
10391 /// typename X<T>::pointer X<T>::data() { ... }
10392 /// \endcode
10393 ///
10394 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
10395 /// since we do not know that we can look into X<T> when we parsed the type.
10396 /// This function will rebuild the type, performing the lookup of "pointer"
10397 /// in X<T> and returning an ElaboratedType whose canonical type is the same
10398 /// as the canonical type of T*, allowing the return types of the out-of-line
10399 /// definition and the declaration to match.
10400 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
10401                                                         SourceLocation Loc,
10402                                                         DeclarationName Name) {
10403   if (!T || !T->getType()->isDependentType())
10404     return T;
10405
10406   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10407   return Rebuilder.TransformType(T);
10408 }
10409
10410 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
10411   CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10412                                           DeclarationName());
10413   return Rebuilder.TransformExpr(E);
10414 }
10415
10416 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
10417   if (SS.isInvalid())
10418     return true;
10419
10420   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10421   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10422                                           DeclarationName());
10423   NestedNameSpecifierLoc Rebuilt
10424     = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
10425   if (!Rebuilt)
10426     return true;
10427
10428   SS.Adopt(Rebuilt);
10429   return false;
10430 }
10431
10432 /// Rebuild the template parameters now that we know we're in a current
10433 /// instantiation.
10434 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
10435                                                TemplateParameterList *Params) {
10436   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10437     Decl *Param = Params->getParam(I);
10438
10439     // There is nothing to rebuild in a type parameter.
10440     if (isa<TemplateTypeParmDecl>(Param))
10441       continue;
10442
10443     // Rebuild the template parameter list of a template template parameter.
10444     if (TemplateTemplateParmDecl *TTP
10445         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10446       if (RebuildTemplateParamsInCurrentInstantiation(
10447             TTP->getTemplateParameters()))
10448         return true;
10449
10450       continue;
10451     }
10452
10453     // Rebuild the type of a non-type template parameter.
10454     NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
10455     TypeSourceInfo *NewTSI
10456       = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
10457                                           NTTP->getLocation(),
10458                                           NTTP->getDeclName());
10459     if (!NewTSI)
10460       return true;
10461
10462     if (NewTSI->getType()->isUndeducedType()) {
10463       // C++17 [temp.dep.expr]p3:
10464       //   An id-expression is type-dependent if it contains
10465       //    - an identifier associated by name lookup with a non-type
10466       //      template-parameter declared with a type that contains a
10467       //      placeholder type (7.1.7.4),
10468       NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
10469     }
10470
10471     if (NewTSI != NTTP->getTypeSourceInfo()) {
10472       NTTP->setTypeSourceInfo(NewTSI);
10473       NTTP->setType(NewTSI->getType());
10474     }
10475   }
10476
10477   return false;
10478 }
10479
10480 /// Produces a formatted string that describes the binding of
10481 /// template parameters to template arguments.
10482 std::string
10483 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10484                                       const TemplateArgumentList &Args) {
10485   return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
10486 }
10487
10488 std::string
10489 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10490                                       const TemplateArgument *Args,
10491                                       unsigned NumArgs) {
10492   SmallString<128> Str;
10493   llvm::raw_svector_ostream Out(Str);
10494
10495   if (!Params || Params->size() == 0 || NumArgs == 0)
10496     return std::string();
10497
10498   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10499     if (I >= NumArgs)
10500       break;
10501
10502     if (I == 0)
10503       Out << "[with ";
10504     else
10505       Out << ", ";
10506
10507     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
10508       Out << Id->getName();
10509     } else {
10510       Out << '$' << I;
10511     }
10512
10513     Out << " = ";
10514     Args[I].print(getPrintingPolicy(), Out);
10515   }
10516
10517   Out << ']';
10518   return Out.str();
10519 }
10520
10521 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10522                                     CachedTokens &Toks) {
10523   if (!FD)
10524     return;
10525
10526   auto LPT = std::make_unique<LateParsedTemplate>();
10527
10528   // Take tokens to avoid allocations
10529   LPT->Toks.swap(Toks);
10530   LPT->D = FnD;
10531   LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
10532
10533   FD->setLateTemplateParsed(true);
10534 }
10535
10536 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10537   if (!FD)
10538     return;
10539   FD->setLateTemplateParsed(false);
10540 }
10541
10542 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10543   DeclContext *DC = CurContext;
10544
10545   while (DC) {
10546     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10547       const FunctionDecl *FD = RD->isLocalClass();
10548       return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10549     } else if (DC->isTranslationUnit() || DC->isNamespace())
10550       return false;
10551
10552     DC = DC->getParent();
10553   }
10554   return false;
10555 }
10556
10557 namespace {
10558 /// Walk the path from which a declaration was instantiated, and check
10559 /// that every explicit specialization along that path is visible. This enforces
10560 /// C++ [temp.expl.spec]/6:
10561 ///
10562 ///   If a template, a member template or a member of a class template is
10563 ///   explicitly specialized then that specialization shall be declared before
10564 ///   the first use of that specialization that would cause an implicit
10565 ///   instantiation to take place, in every translation unit in which such a
10566 ///   use occurs; no diagnostic is required.
10567 ///
10568 /// and also C++ [temp.class.spec]/1:
10569 ///
10570 ///   A partial specialization shall be declared before the first use of a
10571 ///   class template specialization that would make use of the partial
10572 ///   specialization as the result of an implicit or explicit instantiation
10573 ///   in every translation unit in which such a use occurs; no diagnostic is
10574 ///   required.
10575 class ExplicitSpecializationVisibilityChecker {
10576   Sema &S;
10577   SourceLocation Loc;
10578   llvm::SmallVector<Module *, 8> Modules;
10579
10580 public:
10581   ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10582       : S(S), Loc(Loc) {}
10583
10584   void check(NamedDecl *ND) {
10585     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10586       return checkImpl(FD);
10587     if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10588       return checkImpl(RD);
10589     if (auto *VD = dyn_cast<VarDecl>(ND))
10590       return checkImpl(VD);
10591     if (auto *ED = dyn_cast<EnumDecl>(ND))
10592       return checkImpl(ED);
10593   }
10594
10595 private:
10596   void diagnose(NamedDecl *D, bool IsPartialSpec) {
10597     auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10598                               : Sema::MissingImportKind::ExplicitSpecialization;
10599     const bool Recover = true;
10600
10601     // If we got a custom set of modules (because only a subset of the
10602     // declarations are interesting), use them, otherwise let
10603     // diagnoseMissingImport intelligently pick some.
10604     if (Modules.empty())
10605       S.diagnoseMissingImport(Loc, D, Kind, Recover);
10606     else
10607       S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10608   }
10609
10610   // Check a specific declaration. There are three problematic cases:
10611   //
10612   //  1) The declaration is an explicit specialization of a template
10613   //     specialization.
10614   //  2) The declaration is an explicit specialization of a member of an
10615   //     templated class.
10616   //  3) The declaration is an instantiation of a template, and that template
10617   //     is an explicit specialization of a member of a templated class.
10618   //
10619   // We don't need to go any deeper than that, as the instantiation of the
10620   // surrounding class / etc is not triggered by whatever triggered this
10621   // instantiation, and thus should be checked elsewhere.
10622   template<typename SpecDecl>
10623   void checkImpl(SpecDecl *Spec) {
10624     bool IsHiddenExplicitSpecialization = false;
10625     if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10626       IsHiddenExplicitSpecialization =
10627           Spec->getMemberSpecializationInfo()
10628               ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
10629               : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
10630     } else {
10631       checkInstantiated(Spec);
10632     }
10633
10634     if (IsHiddenExplicitSpecialization)
10635       diagnose(Spec->getMostRecentDecl(), false);
10636   }
10637
10638   void checkInstantiated(FunctionDecl *FD) {
10639     if (auto *TD = FD->getPrimaryTemplate())
10640       checkTemplate(TD);
10641   }
10642
10643   void checkInstantiated(CXXRecordDecl *RD) {
10644     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10645     if (!SD)
10646       return;
10647
10648     auto From = SD->getSpecializedTemplateOrPartial();
10649     if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10650       checkTemplate(TD);
10651     else if (auto *TD =
10652                  From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10653       if (!S.hasVisibleDeclaration(TD))
10654         diagnose(TD, true);
10655       checkTemplate(TD);
10656     }
10657   }
10658
10659   void checkInstantiated(VarDecl *RD) {
10660     auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10661     if (!SD)
10662       return;
10663
10664     auto From = SD->getSpecializedTemplateOrPartial();
10665     if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10666       checkTemplate(TD);
10667     else if (auto *TD =
10668                  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10669       if (!S.hasVisibleDeclaration(TD))
10670         diagnose(TD, true);
10671       checkTemplate(TD);
10672     }
10673   }
10674
10675   void checkInstantiated(EnumDecl *FD) {}
10676
10677   template<typename TemplDecl>
10678   void checkTemplate(TemplDecl *TD) {
10679     if (TD->isMemberSpecialization()) {
10680       if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10681         diagnose(TD->getMostRecentDecl(), false);
10682     }
10683   }
10684 };
10685 } // end anonymous namespace
10686
10687 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10688   if (!getLangOpts().Modules)
10689     return;
10690
10691   ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10692 }
10693
10694 /// Check whether a template partial specialization that we've discovered
10695 /// is hidden, and produce suitable diagnostics if so.
10696 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10697                                                 NamedDecl *Spec) {
10698   llvm::SmallVector<Module *, 8> Modules;
10699   if (!hasVisibleDeclaration(Spec, &Modules))
10700     diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10701                           MissingImportKind::PartialSpecialization,
10702                           /*Recover*/true);
10703 }