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