Clang Project

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