Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Sema/SemaTemplate.cpp
Line
Count
Source (jump to first uncovered line)
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/Decl.h"
15
#include "clang/AST/DeclFriend.h"
16
#include "clang/AST/DeclTemplate.h"
17
#include "clang/AST/Expr.h"
18
#include "clang/AST/ExprCXX.h"
19
#include "clang/AST/RecursiveASTVisitor.h"
20
#include "clang/AST/TemplateName.h"
21
#include "clang/AST/TypeVisitor.h"
22
#include "clang/Basic/Builtins.h"
23
#include "clang/Basic/DiagnosticSema.h"
24
#include "clang/Basic/LangOptions.h"
25
#include "clang/Basic/PartialDiagnostic.h"
26
#include "clang/Basic/SourceLocation.h"
27
#include "clang/Basic/Stack.h"
28
#include "clang/Basic/TargetInfo.h"
29
#include "clang/Sema/DeclSpec.h"
30
#include "clang/Sema/EnterExpressionEvaluationContext.h"
31
#include "clang/Sema/Initialization.h"
32
#include "clang/Sema/Lookup.h"
33
#include "clang/Sema/Overload.h"
34
#include "clang/Sema/ParsedTemplate.h"
35
#include "clang/Sema/Scope.h"
36
#include "clang/Sema/SemaInternal.h"
37
#include "clang/Sema/Template.h"
38
#include "clang/Sema/TemplateDeduction.h"
39
#include "llvm/ADT/SmallBitVector.h"
40
#include "llvm/ADT/SmallString.h"
41
#include "llvm/ADT/StringExtras.h"
42
43
#include <iterator>
44
#include <optional>
45
using namespace clang;
46
using namespace sema;
47
48
// Exported for use by Parser.
49
SourceRange
50
clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
51
0
                              unsigned N) {
52
0
  if (!N) return SourceRange();
53
0
  return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
54
0
}
55
56
0
unsigned Sema::getTemplateDepth(Scope *S) const {
57
0
  unsigned Depth = 0;
58
59
  // Each template parameter scope represents one level of template parameter
60
  // depth.
61
0
  for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
62
0
       TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
63
0
    ++Depth;
64
0
  }
65
66
  // Note that there are template parameters with the given depth.
67
0
  auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
68
69
  // Look for parameters of an enclosing generic lambda. We don't create a
70
  // template parameter scope for these.
71
0
  for (FunctionScopeInfo *FSI : getFunctionScopes()) {
72
0
    if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
73
0
      if (!LSI->TemplateParams.empty()) {
74
0
        ParamsAtDepth(LSI->AutoTemplateParameterDepth);
75
0
        break;
76
0
      }
77
0
      if (LSI->GLTemplateParameterList) {
78
0
        ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
79
0
        break;
80
0
      }
81
0
    }
82
0
  }
83
84
  // Look for parameters of an enclosing terse function template. We don't
85
  // create a template parameter scope for these either.
86
0
  for (const InventedTemplateParameterInfo &Info :
87
0
       getInventedParameterInfos()) {
88
0
    if (!Info.TemplateParams.empty()) {
89
0
      ParamsAtDepth(Info.AutoTemplateParameterDepth);
90
0
      break;
91
0
    }
92
0
  }
93
94
0
  return Depth;
95
0
}
96
97
/// \brief Determine whether the declaration found is acceptable as the name
98
/// of a template and, if so, return that template declaration. Otherwise,
99
/// returns null.
100
///
101
/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
102
/// is true. In all other cases it will return a TemplateDecl (or null).
103
NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
104
                                       bool AllowFunctionTemplates,
105
2.43k
                                       bool AllowDependent) {
106
2.43k
  D = D->getUnderlyingDecl();
107
108
2.43k
  if (isa<TemplateDecl>(D)) {
109
0
    if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
110
0
      return nullptr;
111
112
0
    return D;
113
0
  }
114
115
2.43k
  if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
116
    // C++ [temp.local]p1:
117
    //   Like normal (non-template) classes, class templates have an
118
    //   injected-class-name (Clause 9). The injected-class-name
119
    //   can be used with or without a template-argument-list. When
120
    //   it is used without a template-argument-list, it is
121
    //   equivalent to the injected-class-name followed by the
122
    //   template-parameters of the class template enclosed in
123
    //   <>. When it is used with a template-argument-list, it
124
    //   refers to the specified class template specialization,
125
    //   which could be the current specialization or another
126
    //   specialization.
127
0
    if (Record->isInjectedClassName()) {
128
0
      Record = cast<CXXRecordDecl>(Record->getDeclContext());
129
0
      if (Record->getDescribedClassTemplate())
130
0
        return Record->getDescribedClassTemplate();
131
132
0
      if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
133
0
        return Spec->getSpecializedTemplate();
134
0
    }
135
136
0
    return nullptr;
137
0
  }
138
139
  // 'using Dependent::foo;' can resolve to a template name.
140
  // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
141
  // injected-class-name).
142
2.43k
  if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
143
0
    return D;
144
145
2.43k
  return nullptr;
146
2.43k
}
147
148
void Sema::FilterAcceptableTemplateNames(LookupResult &R,
149
                                         bool AllowFunctionTemplates,
150
2.76k
                                         bool AllowDependent) {
151
2.76k
  LookupResult::Filter filter = R.makeFilter();
152
5.19k
  while (filter.hasNext()) {
153
2.43k
    NamedDecl *Orig = filter.next();
154
2.43k
    if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
155
2.43k
      filter.erase();
156
2.43k
  }
157
2.76k
  filter.done();
158
2.76k
}
159
160
bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
161
                                         bool AllowFunctionTemplates,
162
                                         bool AllowDependent,
163
0
                                         bool AllowNonTemplateFunctions) {
164
0
  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
165
0
    if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
166
0
      return true;
167
0
    if (AllowNonTemplateFunctions &&
168
0
        isa<FunctionDecl>((*I)->getUnderlyingDecl()))
169
0
      return true;
170
0
  }
171
172
0
  return false;
173
0
}
174
175
TemplateNameKind Sema::isTemplateName(Scope *S,
176
                                      CXXScopeSpec &SS,
177
                                      bool hasTemplateKeyword,
178
                                      const UnqualifiedId &Name,
179
                                      ParsedType ObjectTypePtr,
180
                                      bool EnteringContext,
181
                                      TemplateTy &TemplateResult,
182
                                      bool &MemberOfUnknownSpecialization,
183
5.19k
                                      bool Disambiguation) {
184
5.19k
  assert(getLangOpts().CPlusPlus && "No template names in C!");
185
186
0
  DeclarationName TName;
187
5.19k
  MemberOfUnknownSpecialization = false;
188
189
5.19k
  switch (Name.getKind()) {
190
5.19k
  case UnqualifiedIdKind::IK_Identifier:
191
5.19k
    TName = DeclarationName(Name.Identifier);
192
5.19k
    break;
193
194
0
  case UnqualifiedIdKind::IK_OperatorFunctionId:
195
0
    TName = Context.DeclarationNames.getCXXOperatorName(
196
0
                                              Name.OperatorFunctionId.Operator);
197
0
    break;
198
199
0
  case UnqualifiedIdKind::IK_LiteralOperatorId:
200
0
    TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
201
0
    break;
202
203
0
  default:
204
0
    return TNK_Non_template;
205
5.19k
  }
206
207
5.19k
  QualType ObjectType = ObjectTypePtr.get();
208
209
5.19k
  AssumedTemplateKind AssumedTemplate;
210
5.19k
  LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
211
5.19k
  if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
212
5.19k
                         MemberOfUnknownSpecialization, SourceLocation(),
213
5.19k
                         &AssumedTemplate,
214
5.19k
                         /*AllowTypoCorrection=*/!Disambiguation))
215
0
    return TNK_Non_template;
216
217
5.19k
  if (AssumedTemplate != AssumedTemplateKind::None) {
218
3.06k
    TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
219
    // Let the parser know whether we found nothing or found functions; if we
220
    // found nothing, we want to more carefully check whether this is actually
221
    // a function template name versus some other kind of undeclared identifier.
222
3.06k
    return AssumedTemplate == AssumedTemplateKind::FoundNothing
223
3.06k
               ? TNK_Undeclared_template
224
3.06k
               : TNK_Function_template;
225
3.06k
  }
226
227
2.12k
  if (R.empty())
228
2.12k
    return TNK_Non_template;
229
230
0
  NamedDecl *D = nullptr;
231
0
  UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
232
0
  if (R.isAmbiguous()) {
233
    // If we got an ambiguity involving a non-function template, treat this
234
    // as a template name, and pick an arbitrary template for error recovery.
235
0
    bool AnyFunctionTemplates = false;
236
0
    for (NamedDecl *FoundD : R) {
237
0
      if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
238
0
        if (isa<FunctionTemplateDecl>(FoundTemplate))
239
0
          AnyFunctionTemplates = true;
240
0
        else {
241
0
          D = FoundTemplate;
242
0
          FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
243
0
          break;
244
0
        }
245
0
      }
246
0
    }
247
248
    // If we didn't find any templates at all, this isn't a template name.
249
    // Leave the ambiguity for a later lookup to diagnose.
250
0
    if (!D && !AnyFunctionTemplates) {
251
0
      R.suppressDiagnostics();
252
0
      return TNK_Non_template;
253
0
    }
254
255
    // If the only templates were function templates, filter out the rest.
256
    // We'll diagnose the ambiguity later.
257
0
    if (!D)
258
0
      FilterAcceptableTemplateNames(R);
259
0
  }
260
261
  // At this point, we have either picked a single template name declaration D
262
  // or we have a non-empty set of results R containing either one template name
263
  // declaration or a set of function templates.
264
265
0
  TemplateName Template;
266
0
  TemplateNameKind TemplateKind;
267
268
0
  unsigned ResultCount = R.end() - R.begin();
269
0
  if (!D && ResultCount > 1) {
270
    // We assume that we'll preserve the qualifier from a function
271
    // template name in other ways.
272
0
    Template = Context.getOverloadedTemplateName(R.begin(), R.end());
273
0
    TemplateKind = TNK_Function_template;
274
275
    // We'll do this lookup again later.
276
0
    R.suppressDiagnostics();
277
0
  } else {
278
0
    if (!D) {
279
0
      D = getAsTemplateNameDecl(*R.begin());
280
0
      assert(D && "unambiguous result is not a template name");
281
0
    }
282
283
0
    if (isa<UnresolvedUsingValueDecl>(D)) {
284
      // We don't yet know whether this is a template-name or not.
285
0
      MemberOfUnknownSpecialization = true;
286
0
      return TNK_Non_template;
287
0
    }
288
289
0
    TemplateDecl *TD = cast<TemplateDecl>(D);
290
0
    Template =
291
0
        FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
292
0
    assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
293
0
    if (SS.isSet() && !SS.isInvalid()) {
294
0
      NestedNameSpecifier *Qualifier = SS.getScopeRep();
295
0
      Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
296
0
                                                  Template);
297
0
    }
298
299
0
    if (isa<FunctionTemplateDecl>(TD)) {
300
0
      TemplateKind = TNK_Function_template;
301
302
      // We'll do this lookup again later.
303
0
      R.suppressDiagnostics();
304
0
    } else {
305
0
      assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
306
0
             isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
307
0
             isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
308
0
      TemplateKind =
309
0
          isa<VarTemplateDecl>(TD) ? TNK_Var_template :
310
0
          isa<ConceptDecl>(TD) ? TNK_Concept_template :
311
0
          TNK_Type_template;
312
0
    }
313
0
  }
314
315
0
  TemplateResult = TemplateTy::make(Template);
316
0
  return TemplateKind;
317
0
}
318
319
bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
320
                                SourceLocation NameLoc, CXXScopeSpec &SS,
321
640
                                ParsedTemplateTy *Template /*=nullptr*/) {
322
640
  bool MemberOfUnknownSpecialization = false;
323
324
  // We could use redeclaration lookup here, but we don't need to: the
325
  // syntactic form of a deduction guide is enough to identify it even
326
  // if we can't look up the template name at all.
327
640
  LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
328
640
  if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
329
640
                         /*EnteringContext*/ false,
330
640
                         MemberOfUnknownSpecialization))
331
0
    return false;
332
333
640
  if (R.empty()) return false;
334
0
  if (R.isAmbiguous()) {
335
    // FIXME: Diagnose an ambiguity if we find at least one template.
336
0
    R.suppressDiagnostics();
337
0
    return false;
338
0
  }
339
340
  // We only treat template-names that name type templates as valid deduction
341
  // guide names.
342
0
  TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
343
0
  if (!TD || !getAsTypeTemplateDecl(TD))
344
0
    return false;
345
346
0
  if (Template)
347
0
    *Template = TemplateTy::make(TemplateName(TD));
348
0
  return true;
349
0
}
350
351
bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
352
                                       SourceLocation IILoc,
353
                                       Scope *S,
354
                                       const CXXScopeSpec *SS,
355
                                       TemplateTy &SuggestedTemplate,
356
0
                                       TemplateNameKind &SuggestedKind) {
357
  // We can't recover unless there's a dependent scope specifier preceding the
358
  // template name.
359
  // FIXME: Typo correction?
360
0
  if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
361
0
      computeDeclContext(*SS))
362
0
    return false;
363
364
  // The code is missing a 'template' keyword prior to the dependent template
365
  // name.
366
0
  NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
367
0
  Diag(IILoc, diag::err_template_kw_missing)
368
0
    << Qualifier << II.getName()
369
0
    << FixItHint::CreateInsertion(IILoc, "template ");
370
0
  SuggestedTemplate
371
0
    = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
372
0
  SuggestedKind = TNK_Dependent_template_name;
373
0
  return true;
374
0
}
375
376
bool Sema::LookupTemplateName(LookupResult &Found,
377
                              Scope *S, CXXScopeSpec &SS,
378
                              QualType ObjectType,
379
                              bool EnteringContext,
380
                              bool &MemberOfUnknownSpecialization,
381
                              RequiredTemplateKind RequiredTemplate,
382
                              AssumedTemplateKind *ATK,
383
5.83k
                              bool AllowTypoCorrection) {
384
5.83k
  if (ATK)
385
5.19k
    *ATK = AssumedTemplateKind::None;
386
387
5.83k
  if (SS.isInvalid())
388
0
    return true;
389
390
5.83k
  Found.setTemplateNameLookup(true);
391
392
  // Determine where to perform name lookup
393
5.83k
  MemberOfUnknownSpecialization = false;
394
5.83k
  DeclContext *LookupCtx = nullptr;
395
5.83k
  bool IsDependent = false;
396
5.83k
  if (!ObjectType.isNull()) {
397
    // This nested-name-specifier occurs in a member access expression, e.g.,
398
    // x->B::f, and we are looking into the type of the object.
399
0
    assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
400
0
    LookupCtx = computeDeclContext(ObjectType);
401
0
    IsDependent = !LookupCtx && ObjectType->isDependentType();
402
0
    assert((IsDependent || !ObjectType->isIncompleteType() ||
403
0
            !ObjectType->getAs<TagType>() ||
404
0
            ObjectType->castAs<TagType>()->isBeingDefined()) &&
405
0
           "Caller should have completed object type");
406
407
    // Template names cannot appear inside an Objective-C class or object type
408
    // or a vector type.
409
    //
410
    // FIXME: This is wrong. For example:
411
    //
412
    //   template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
413
    //   Vec<int> vi;
414
    //   vi.Vec<int>::~Vec<int>();
415
    //
416
    // ... should be accepted but we will not treat 'Vec' as a template name
417
    // here. The right thing to do would be to check if the name is a valid
418
    // vector component name, and look up a template name if not. And similarly
419
    // for lookups into Objective-C class and object types, where the same
420
    // problem can arise.
421
0
    if (ObjectType->isObjCObjectOrInterfaceType() ||
422
0
        ObjectType->isVectorType()) {
423
0
      Found.clear();
424
0
      return false;
425
0
    }
426
5.83k
  } else if (SS.isNotEmpty()) {
427
    // This nested-name-specifier occurs after another nested-name-specifier,
428
    // so long into the context associated with the prior nested-name-specifier.
429
0
    LookupCtx = computeDeclContext(SS, EnteringContext);
430
0
    IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
431
432
    // The declaration context must be complete.
433
0
    if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
434
0
      return true;
435
0
  }
436
437
5.83k
  bool ObjectTypeSearchedInScope = false;
438
5.83k
  bool AllowFunctionTemplatesInLookup = true;
439
5.83k
  if (LookupCtx) {
440
    // Perform "qualified" name lookup into the declaration context we
441
    // computed, which is either the type of the base of a member access
442
    // expression or the declaration context associated with a prior
443
    // nested-name-specifier.
444
0
    LookupQualifiedName(Found, LookupCtx);
445
446
    // FIXME: The C++ standard does not clearly specify what happens in the
447
    // case where the object type is dependent, and implementations vary. In
448
    // Clang, we treat a name after a . or -> as a template-name if lookup
449
    // finds a non-dependent member or member of the current instantiation that
450
    // is a type template, or finds no such members and lookup in the context
451
    // of the postfix-expression finds a type template. In the latter case, the
452
    // name is nonetheless dependent, and we may resolve it to a member of an
453
    // unknown specialization when we come to instantiate the template.
454
0
    IsDependent |= Found.wasNotFoundInCurrentInstantiation();
455
0
  }
456
457
5.83k
  if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
458
    // C++ [basic.lookup.classref]p1:
459
    //   In a class member access expression (5.2.5), if the . or -> token is
460
    //   immediately followed by an identifier followed by a <, the
461
    //   identifier must be looked up to determine whether the < is the
462
    //   beginning of a template argument list (14.2) or a less-than operator.
463
    //   The identifier is first looked up in the class of the object
464
    //   expression. If the identifier is not found, it is then looked up in
465
    //   the context of the entire postfix-expression and shall name a class
466
    //   template.
467
5.83k
    if (S)
468
5.83k
      LookupName(Found, S);
469
470
5.83k
    if (!ObjectType.isNull()) {
471
      //  FIXME: We should filter out all non-type templates here, particularly
472
      //  variable templates and concepts. But the exclusion of alias templates
473
      //  and template template parameters is a wording defect.
474
0
      AllowFunctionTemplatesInLookup = false;
475
0
      ObjectTypeSearchedInScope = true;
476
0
    }
477
478
5.83k
    IsDependent |= Found.wasNotFoundInCurrentInstantiation();
479
5.83k
  }
480
481
5.83k
  if (Found.isAmbiguous())
482
0
    return false;
483
484
5.83k
  if (ATK && SS.isEmpty() && ObjectType.isNull() &&
485
5.83k
      !RequiredTemplate.hasTemplateKeyword()) {
486
    // C++2a [temp.names]p2:
487
    //   A name is also considered to refer to a template if it is an
488
    //   unqualified-id followed by a < and name lookup finds either one or more
489
    //   functions or finds nothing.
490
    //
491
    // To keep our behavior consistent, we apply the "finds nothing" part in
492
    // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
493
    // successfully form a call to an undeclared template-id.
494
5.19k
    bool AllFunctions =
495
5.19k
        getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
496
0
          return isa<FunctionDecl>(ND->getUnderlyingDecl());
497
0
        });
498
5.19k
    if (AllFunctions || (Found.empty() && !IsDependent)) {
499
      // If lookup found any functions, or if this is a name that can only be
500
      // used for a function, then strongly assume this is a function
501
      // template-id.
502
3.06k
      *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
503
3.06k
                 ? AssumedTemplateKind::FoundNothing
504
3.06k
                 : AssumedTemplateKind::FoundFunctions;
505
3.06k
      Found.clear();
506
3.06k
      return false;
507
3.06k
    }
508
5.19k
  }
509
510
2.76k
  if (Found.empty() && !IsDependent && AllowTypoCorrection) {
511
    // If we did not find any names, and this is not a disambiguation, attempt
512
    // to correct any typos.
513
337
    DeclarationName Name = Found.getLookupName();
514
337
    Found.clear();
515
    // Simple filter callback that, for keywords, only accepts the C++ *_cast
516
337
    DefaultFilterCCC FilterCCC{};
517
337
    FilterCCC.WantTypeSpecifiers = false;
518
337
    FilterCCC.WantExpressionKeywords = false;
519
337
    FilterCCC.WantRemainingKeywords = false;
520
337
    FilterCCC.WantCXXNamedCasts = true;
521
337
    if (TypoCorrection Corrected =
522
337
            CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
523
337
                        &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
524
0
      if (auto *ND = Corrected.getFoundDecl())
525
0
        Found.addDecl(ND);
526
0
      FilterAcceptableTemplateNames(Found);
527
0
      if (Found.isAmbiguous()) {
528
0
        Found.clear();
529
0
      } else if (!Found.empty()) {
530
0
        Found.setLookupName(Corrected.getCorrection());
531
0
        if (LookupCtx) {
532
0
          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
533
0
          bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
534
0
                                  Name.getAsString() == CorrectedStr;
535
0
          diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
536
0
                                    << Name << LookupCtx << DroppedSpecifier
537
0
                                    << SS.getRange());
538
0
        } else {
539
0
          diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
540
0
        }
541
0
      }
542
0
    }
543
337
  }
544
545
2.76k
  NamedDecl *ExampleLookupResult =
546
2.76k
      Found.empty() ? nullptr : Found.getRepresentativeDecl();
547
2.76k
  FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
548
2.76k
  if (Found.empty()) {
549
2.76k
    if (IsDependent) {
550
0
      MemberOfUnknownSpecialization = true;
551
0
      return false;
552
0
    }
553
554
    // If a 'template' keyword was used, a lookup that finds only non-template
555
    // names is an error.
556
2.76k
    if (ExampleLookupResult && RequiredTemplate) {
557
0
      Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
558
0
          << Found.getLookupName() << SS.getRange()
559
0
          << RequiredTemplate.hasTemplateKeyword()
560
0
          << RequiredTemplate.getTemplateKeywordLoc();
561
0
      Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
562
0
           diag::note_template_kw_refers_to_non_template)
563
0
          << Found.getLookupName();
564
0
      return true;
565
0
    }
566
567
2.76k
    return false;
568
2.76k
  }
569
570
0
  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
571
0
      !getLangOpts().CPlusPlus11) {
572
    // C++03 [basic.lookup.classref]p1:
573
    //   [...] If the lookup in the class of the object expression finds a
574
    //   template, the name is also looked up in the context of the entire
575
    //   postfix-expression and [...]
576
    //
577
    // Note: C++11 does not perform this second lookup.
578
0
    LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
579
0
                            LookupOrdinaryName);
580
0
    FoundOuter.setTemplateNameLookup(true);
581
0
    LookupName(FoundOuter, S);
582
    // FIXME: We silently accept an ambiguous lookup here, in violation of
583
    // [basic.lookup]/1.
584
0
    FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
585
586
0
    NamedDecl *OuterTemplate;
587
0
    if (FoundOuter.empty()) {
588
      //   - if the name is not found, the name found in the class of the
589
      //     object expression is used, otherwise
590
0
    } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
591
0
               !(OuterTemplate =
592
0
                     getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
593
      //   - if the name is found in the context of the entire
594
      //     postfix-expression and does not name a class template, the name
595
      //     found in the class of the object expression is used, otherwise
596
0
      FoundOuter.clear();
597
0
    } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
598
      //   - if the name found is a class template, it must refer to the same
599
      //     entity as the one found in the class of the object expression,
600
      //     otherwise the program is ill-formed.
601
0
      if (!Found.isSingleResult() ||
602
0
          getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
603
0
              OuterTemplate->getCanonicalDecl()) {
604
0
        Diag(Found.getNameLoc(),
605
0
             diag::ext_nested_name_member_ref_lookup_ambiguous)
606
0
          << Found.getLookupName()
607
0
          << ObjectType;
608
0
        Diag(Found.getRepresentativeDecl()->getLocation(),
609
0
             diag::note_ambig_member_ref_object_type)
610
0
          << ObjectType;
611
0
        Diag(FoundOuter.getFoundDecl()->getLocation(),
612
0
             diag::note_ambig_member_ref_scope);
613
614
        // Recover by taking the template that we found in the object
615
        // expression's type.
616
0
      }
617
0
    }
618
0
  }
619
620
0
  return false;
621
2.76k
}
622
623
void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
624
                                              SourceLocation Less,
625
0
                                              SourceLocation Greater) {
626
0
  if (TemplateName.isInvalid())
627
0
    return;
628
629
0
  DeclarationNameInfo NameInfo;
630
0
  CXXScopeSpec SS;
631
0
  LookupNameKind LookupKind;
632
633
0
  DeclContext *LookupCtx = nullptr;
634
0
  NamedDecl *Found = nullptr;
635
0
  bool MissingTemplateKeyword = false;
636
637
  // Figure out what name we looked up.
638
0
  if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
639
0
    NameInfo = DRE->getNameInfo();
640
0
    SS.Adopt(DRE->getQualifierLoc());
641
0
    LookupKind = LookupOrdinaryName;
642
0
    Found = DRE->getFoundDecl();
643
0
  } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
644
0
    NameInfo = ME->getMemberNameInfo();
645
0
    SS.Adopt(ME->getQualifierLoc());
646
0
    LookupKind = LookupMemberName;
647
0
    LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
648
0
    Found = ME->getMemberDecl();
649
0
  } else if (auto *DSDRE =
650
0
                 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
651
0
    NameInfo = DSDRE->getNameInfo();
652
0
    SS.Adopt(DSDRE->getQualifierLoc());
653
0
    MissingTemplateKeyword = true;
654
0
  } else if (auto *DSME =
655
0
                 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
656
0
    NameInfo = DSME->getMemberNameInfo();
657
0
    SS.Adopt(DSME->getQualifierLoc());
658
0
    MissingTemplateKeyword = true;
659
0
  } else {
660
0
    llvm_unreachable("unexpected kind of potential template name");
661
0
  }
662
663
  // If this is a dependent-scope lookup, diagnose that the 'template' keyword
664
  // was missing.
665
0
  if (MissingTemplateKeyword) {
666
0
    Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
667
0
        << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
668
0
    return;
669
0
  }
670
671
  // Try to correct the name by looking for templates and C++ named casts.
672
0
  struct TemplateCandidateFilter : CorrectionCandidateCallback {
673
0
    Sema &S;
674
0
    TemplateCandidateFilter(Sema &S) : S(S) {
675
0
      WantTypeSpecifiers = false;
676
0
      WantExpressionKeywords = false;
677
0
      WantRemainingKeywords = false;
678
0
      WantCXXNamedCasts = true;
679
0
    };
680
0
    bool ValidateCandidate(const TypoCorrection &Candidate) override {
681
0
      if (auto *ND = Candidate.getCorrectionDecl())
682
0
        return S.getAsTemplateNameDecl(ND);
683
0
      return Candidate.isKeyword();
684
0
    }
685
686
0
    std::unique_ptr<CorrectionCandidateCallback> clone() override {
687
0
      return std::make_unique<TemplateCandidateFilter>(*this);
688
0
    }
689
0
  };
690
691
0
  DeclarationName Name = NameInfo.getName();
692
0
  TemplateCandidateFilter CCC(*this);
693
0
  if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
694
0
                                             CTK_ErrorRecovery, LookupCtx)) {
695
0
    auto *ND = Corrected.getFoundDecl();
696
0
    if (ND)
697
0
      ND = getAsTemplateNameDecl(ND);
698
0
    if (ND || Corrected.isKeyword()) {
699
0
      if (LookupCtx) {
700
0
        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
701
0
        bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
702
0
                                Name.getAsString() == CorrectedStr;
703
0
        diagnoseTypo(Corrected,
704
0
                     PDiag(diag::err_non_template_in_member_template_id_suggest)
705
0
                         << Name << LookupCtx << DroppedSpecifier
706
0
                         << SS.getRange(), false);
707
0
      } else {
708
0
        diagnoseTypo(Corrected,
709
0
                     PDiag(diag::err_non_template_in_template_id_suggest)
710
0
                         << Name, false);
711
0
      }
712
0
      if (Found)
713
0
        Diag(Found->getLocation(),
714
0
             diag::note_non_template_in_template_id_found);
715
0
      return;
716
0
    }
717
0
  }
718
719
0
  Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
720
0
    << Name << SourceRange(Less, Greater);
721
0
  if (Found)
722
0
    Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
723
0
}
724
725
/// ActOnDependentIdExpression - Handle a dependent id-expression that
726
/// was just parsed.  This is only possible with an explicit scope
727
/// specifier naming a dependent type.
728
ExprResult
729
Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
730
                                 SourceLocation TemplateKWLoc,
731
                                 const DeclarationNameInfo &NameInfo,
732
                                 bool isAddressOfOperand,
733
0
                           const TemplateArgumentListInfo *TemplateArgs) {
734
0
  DeclContext *DC = getFunctionLevelDeclContext();
735
736
  // C++11 [expr.prim.general]p12:
737
  //   An id-expression that denotes a non-static data member or non-static
738
  //   member function of a class can only be used:
739
  //   (...)
740
  //   - if that id-expression denotes a non-static data member and it
741
  //     appears in an unevaluated operand.
742
  //
743
  // If this might be the case, form a DependentScopeDeclRefExpr instead of a
744
  // CXXDependentScopeMemberExpr. The former can instantiate to either
745
  // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
746
  // always a MemberExpr.
747
0
  bool MightBeCxx11UnevalField =
748
0
      getLangOpts().CPlusPlus11 && isUnevaluatedContext();
749
750
  // Check if the nested name specifier is an enum type.
751
0
  bool IsEnum = false;
752
0
  if (NestedNameSpecifier *NNS = SS.getScopeRep())
753
0
    IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
754
755
0
  if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
756
0
      isa<CXXMethodDecl>(DC) &&
757
0
      cast<CXXMethodDecl>(DC)->isImplicitObjectMemberFunction()) {
758
0
    QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType().getNonReferenceType();
759
760
    // Since the 'this' expression is synthesized, we don't need to
761
    // perform the double-lookup check.
762
0
    NamedDecl *FirstQualifierInScope = nullptr;
763
764
0
    return CXXDependentScopeMemberExpr::Create(
765
0
        Context, /*This=*/nullptr, ThisType,
766
0
        /*IsArrow=*/!Context.getLangOpts().HLSL,
767
0
        /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
768
0
        FirstQualifierInScope, NameInfo, TemplateArgs);
769
0
  }
770
771
0
  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
772
0
}
773
774
ExprResult
775
Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
776
                                SourceLocation TemplateKWLoc,
777
                                const DeclarationNameInfo &NameInfo,
778
0
                                const TemplateArgumentListInfo *TemplateArgs) {
779
  // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
780
0
  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
781
0
  if (!QualifierLoc)
782
0
    return ExprError();
783
784
0
  return DependentScopeDeclRefExpr::Create(
785
0
      Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
786
0
}
787
788
789
/// Determine whether we would be unable to instantiate this template (because
790
/// it either has no definition, or is in the process of being instantiated).
791
bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
792
                                          NamedDecl *Instantiation,
793
                                          bool InstantiatedFromMember,
794
                                          const NamedDecl *Pattern,
795
                                          const NamedDecl *PatternDef,
796
                                          TemplateSpecializationKind TSK,
797
0
                                          bool Complain /*= true*/) {
798
0
  assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
799
0
         isa<VarDecl>(Instantiation));
800
801
0
  bool IsEntityBeingDefined = false;
802
0
  if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
803
0
    IsEntityBeingDefined = TD->isBeingDefined();
804
805
0
  if (PatternDef && !IsEntityBeingDefined) {
806
0
    NamedDecl *SuggestedDef = nullptr;
807
0
    if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
808
0
                                &SuggestedDef,
809
0
                                /*OnlyNeedComplete*/ false)) {
810
      // If we're allowed to diagnose this and recover, do so.
811
0
      bool Recover = Complain && !isSFINAEContext();
812
0
      if (Complain)
813
0
        diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
814
0
                              Sema::MissingImportKind::Definition, Recover);
815
0
      return !Recover;
816
0
    }
817
0
    return false;
818
0
  }
819
820
0
  if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
821
0
    return true;
822
823
0
  QualType InstantiationTy;
824
0
  if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
825
0
    InstantiationTy = Context.getTypeDeclType(TD);
826
0
  if (PatternDef) {
827
0
    Diag(PointOfInstantiation,
828
0
         diag::err_template_instantiate_within_definition)
829
0
      << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
830
0
      << InstantiationTy;
831
    // Not much point in noting the template declaration here, since
832
    // we're lexically inside it.
833
0
    Instantiation->setInvalidDecl();
834
0
  } else if (InstantiatedFromMember) {
835
0
    if (isa<FunctionDecl>(Instantiation)) {
836
0
      Diag(PointOfInstantiation,
837
0
           diag::err_explicit_instantiation_undefined_member)
838
0
        << /*member function*/ 1 << Instantiation->getDeclName()
839
0
        << Instantiation->getDeclContext();
840
0
      Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
841
0
    } else {
842
0
      assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
843
0
      Diag(PointOfInstantiation,
844
0
           diag::err_implicit_instantiate_member_undefined)
845
0
        << InstantiationTy;
846
0
      Diag(Pattern->getLocation(), diag::note_member_declared_at);
847
0
    }
848
0
  } else {
849
0
    if (isa<FunctionDecl>(Instantiation)) {
850
0
      Diag(PointOfInstantiation,
851
0
           diag::err_explicit_instantiation_undefined_func_template)
852
0
        << Pattern;
853
0
      Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
854
0
    } else if (isa<TagDecl>(Instantiation)) {
855
0
      Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
856
0
        << (TSK != TSK_ImplicitInstantiation)
857
0
        << InstantiationTy;
858
0
      NoteTemplateLocation(*Pattern);
859
0
    } else {
860
0
      assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
861
0
      if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
862
0
        Diag(PointOfInstantiation,
863
0
             diag::err_explicit_instantiation_undefined_var_template)
864
0
          << Instantiation;
865
0
        Instantiation->setInvalidDecl();
866
0
      } else
867
0
        Diag(PointOfInstantiation,
868
0
             diag::err_explicit_instantiation_undefined_member)
869
0
          << /*static data member*/ 2 << Instantiation->getDeclName()
870
0
          << Instantiation->getDeclContext();
871
0
      Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
872
0
    }
873
0
  }
874
875
  // In general, Instantiation isn't marked invalid to get more than one
876
  // error for multiple undefined instantiations. But the code that does
877
  // explicit declaration -> explicit definition conversion can't handle
878
  // invalid declarations, so mark as invalid in that case.
879
0
  if (TSK == TSK_ExplicitInstantiationDeclaration)
880
0
    Instantiation->setInvalidDecl();
881
0
  return true;
882
0
}
883
884
/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
885
/// that the template parameter 'PrevDecl' is being shadowed by a new
886
/// declaration at location Loc. Returns true to indicate that this is
887
/// an error, and false otherwise.
888
0
void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
889
0
  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
890
891
  // C++ [temp.local]p4:
892
  //   A template-parameter shall not be redeclared within its
893
  //   scope (including nested scopes).
894
  //
895
  // Make this a warning when MSVC compatibility is requested.
896
0
  unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
897
0
                                             : diag::err_template_param_shadow;
898
0
  const auto *ND = cast<NamedDecl>(PrevDecl);
899
0
  Diag(Loc, DiagId) << ND->getDeclName();
900
0
  NoteTemplateParameterLocation(*ND);
901
0
}
902
903
/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
904
/// the parameter D to reference the templated declaration and return a pointer
905
/// to the template declaration. Otherwise, do nothing to D and return null.
906
0
TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
907
0
  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
908
0
    D = Temp->getTemplatedDecl();
909
0
    return Temp;
910
0
  }
911
0
  return nullptr;
912
0
}
913
914
ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
915
0
                                             SourceLocation EllipsisLoc) const {
916
0
  assert(Kind == Template &&
917
0
         "Only template template arguments can be pack expansions here");
918
0
  assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
919
0
         "Template template argument pack expansion without packs");
920
0
  ParsedTemplateArgument Result(*this);
921
0
  Result.EllipsisLoc = EllipsisLoc;
922
0
  return Result;
923
0
}
924
925
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
926
0
                                            const ParsedTemplateArgument &Arg) {
927
928
0
  switch (Arg.getKind()) {
929
0
  case ParsedTemplateArgument::Type: {
930
0
    TypeSourceInfo *DI;
931
0
    QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
932
0
    if (!DI)
933
0
      DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
934
0
    return TemplateArgumentLoc(TemplateArgument(T), DI);
935
0
  }
936
937
0
  case ParsedTemplateArgument::NonType: {
938
0
    Expr *E = static_cast<Expr *>(Arg.getAsExpr());
939
0
    return TemplateArgumentLoc(TemplateArgument(E), E);
940
0
  }
941
942
0
  case ParsedTemplateArgument::Template: {
943
0
    TemplateName Template = Arg.getAsTemplate().get();
944
0
    TemplateArgument TArg;
945
0
    if (Arg.getEllipsisLoc().isValid())
946
0
      TArg = TemplateArgument(Template, std::optional<unsigned int>());
947
0
    else
948
0
      TArg = Template;
949
0
    return TemplateArgumentLoc(
950
0
        SemaRef.Context, TArg,
951
0
        Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
952
0
        Arg.getLocation(), Arg.getEllipsisLoc());
953
0
  }
954
0
  }
955
956
0
  llvm_unreachable("Unhandled parsed template argument");
957
0
}
958
959
/// Translates template arguments as provided by the parser
960
/// into template arguments used by semantic analysis.
961
void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
962
0
                                      TemplateArgumentListInfo &TemplateArgs) {
963
0
 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
964
0
   TemplateArgs.addArgument(translateTemplateArgument(*this,
965
0
                                                      TemplateArgsIn[I]));
966
0
}
967
968
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
969
                                                 SourceLocation Loc,
970
0
                                                 IdentifierInfo *Name) {
971
0
  NamedDecl *PrevDecl = SemaRef.LookupSingleName(
972
0
      S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
973
0
  if (PrevDecl && PrevDecl->isTemplateParameter())
974
0
    SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
975
0
}
976
977
/// Convert a parsed type into a parsed template argument. This is mostly
978
/// trivial, except that we may have parsed a C++17 deduced class template
979
/// specialization type, in which case we should form a template template
980
/// argument instead of a type template argument.
981
18
ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
982
18
  TypeSourceInfo *TInfo;
983
18
  QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
984
18
  if (T.isNull())
985
18
    return ParsedTemplateArgument();
986
0
  assert(TInfo && "template argument with no location");
987
988
  // If we might have formed a deduced template specialization type, convert
989
  // it to a template template argument.
990
0
  if (getLangOpts().CPlusPlus17) {
991
0
    TypeLoc TL = TInfo->getTypeLoc();
992
0
    SourceLocation EllipsisLoc;
993
0
    if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
994
0
      EllipsisLoc = PET.getEllipsisLoc();
995
0
      TL = PET.getPatternLoc();
996
0
    }
997
998
0
    CXXScopeSpec SS;
999
0
    if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
1000
0
      SS.Adopt(ET.getQualifierLoc());
1001
0
      TL = ET.getNamedTypeLoc();
1002
0
    }
1003
1004
0
    if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1005
0
      TemplateName Name = DTST.getTypePtr()->getTemplateName();
1006
0
      if (SS.isSet())
1007
0
        Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
1008
0
                                                /*HasTemplateKeyword=*/false,
1009
0
                                                Name);
1010
0
      ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
1011
0
                                    DTST.getTemplateNameLoc());
1012
0
      if (EllipsisLoc.isValid())
1013
0
        Result = Result.getTemplatePackExpansion(EllipsisLoc);
1014
0
      return Result;
1015
0
    }
1016
0
  }
1017
1018
  // This is a normal type template argument. Note, if the type template
1019
  // argument is an injected-class-name for a template, it has a dual nature
1020
  // and can be used as either a type or a template. We handle that in
1021
  // convertTypeTemplateArgumentToTemplate.
1022
0
  return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1023
0
                                ParsedType.get().getAsOpaquePtr(),
1024
0
                                TInfo->getTypeLoc().getBeginLoc());
1025
0
}
1026
1027
/// ActOnTypeParameter - Called when a C++ template type parameter
1028
/// (e.g., "typename T") has been parsed. Typename specifies whether
1029
/// the keyword "typename" was used to declare the type parameter
1030
/// (otherwise, "class" was used), and KeyLoc is the location of the
1031
/// "class" or "typename" keyword. ParamName is the name of the
1032
/// parameter (NULL indicates an unnamed template parameter) and
1033
/// ParamNameLoc is the location of the parameter name (if any).
1034
/// If the type parameter has a default argument, it will be added
1035
/// later via ActOnTypeParameterDefault.
1036
NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1037
                                    SourceLocation EllipsisLoc,
1038
                                    SourceLocation KeyLoc,
1039
                                    IdentifierInfo *ParamName,
1040
                                    SourceLocation ParamNameLoc,
1041
                                    unsigned Depth, unsigned Position,
1042
                                    SourceLocation EqualLoc,
1043
                                    ParsedType DefaultArg,
1044
0
                                    bool HasTypeConstraint) {
1045
0
  assert(S->isTemplateParamScope() &&
1046
0
         "Template type parameter not in template parameter scope!");
1047
1048
0
  bool IsParameterPack = EllipsisLoc.isValid();
1049
0
  TemplateTypeParmDecl *Param
1050
0
    = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1051
0
                                   KeyLoc, ParamNameLoc, Depth, Position,
1052
0
                                   ParamName, Typename, IsParameterPack,
1053
0
                                   HasTypeConstraint);
1054
0
  Param->setAccess(AS_public);
1055
1056
0
  if (Param->isParameterPack())
1057
0
    if (auto *LSI = getEnclosingLambda())
1058
0
      LSI->LocalPacks.push_back(Param);
1059
1060
0
  if (ParamName) {
1061
0
    maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1062
1063
    // Add the template parameter into the current scope.
1064
0
    S->AddDecl(Param);
1065
0
    IdResolver.AddDecl(Param);
1066
0
  }
1067
1068
  // C++0x [temp.param]p9:
1069
  //   A default template-argument may be specified for any kind of
1070
  //   template-parameter that is not a template parameter pack.
1071
0
  if (DefaultArg && IsParameterPack) {
1072
0
    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1073
0
    DefaultArg = nullptr;
1074
0
  }
1075
1076
  // Handle the default argument, if provided.
1077
0
  if (DefaultArg) {
1078
0
    TypeSourceInfo *DefaultTInfo;
1079
0
    GetTypeFromParser(DefaultArg, &DefaultTInfo);
1080
1081
0
    assert(DefaultTInfo && "expected source information for type");
1082
1083
    // Check for unexpanded parameter packs.
1084
0
    if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1085
0
                                        UPPC_DefaultArgument))
1086
0
      return Param;
1087
1088
    // Check the template argument itself.
1089
0
    if (CheckTemplateArgument(DefaultTInfo)) {
1090
0
      Param->setInvalidDecl();
1091
0
      return Param;
1092
0
    }
1093
1094
0
    Param->setDefaultArgument(DefaultTInfo);
1095
0
  }
1096
1097
0
  return Param;
1098
0
}
1099
1100
/// Convert the parser's template argument list representation into our form.
1101
static TemplateArgumentListInfo
1102
0
makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1103
0
  TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1104
0
                                        TemplateId.RAngleLoc);
1105
0
  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1106
0
                                     TemplateId.NumArgs);
1107
0
  S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1108
0
  return TemplateArgs;
1109
0
}
1110
1111
0
bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1112
1113
0
  TemplateName TN = TypeConstr->Template.get();
1114
0
  ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1115
1116
  // C++2a [temp.param]p4:
1117
  //     [...] The concept designated by a type-constraint shall be a type
1118
  //     concept ([temp.concept]).
1119
0
  if (!CD->isTypeConcept()) {
1120
0
    Diag(TypeConstr->TemplateNameLoc,
1121
0
         diag::err_type_constraint_non_type_concept);
1122
0
    return true;
1123
0
  }
1124
1125
0
  bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1126
1127
0
  if (!WereArgsSpecified &&
1128
0
      CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1129
0
    Diag(TypeConstr->TemplateNameLoc,
1130
0
         diag::err_type_constraint_missing_arguments)
1131
0
        << CD;
1132
0
    return true;
1133
0
  }
1134
0
  return false;
1135
0
}
1136
1137
bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1138
                               TemplateIdAnnotation *TypeConstr,
1139
                               TemplateTypeParmDecl *ConstrainedParameter,
1140
0
                               SourceLocation EllipsisLoc) {
1141
0
  return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1142
0
                             false);
1143
0
}
1144
1145
bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1146
                               TemplateIdAnnotation *TypeConstr,
1147
                               TemplateTypeParmDecl *ConstrainedParameter,
1148
                               SourceLocation EllipsisLoc,
1149
0
                               bool AllowUnexpandedPack) {
1150
1151
0
  if (CheckTypeConstraint(TypeConstr))
1152
0
    return true;
1153
1154
0
  TemplateName TN = TypeConstr->Template.get();
1155
0
  ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1156
1157
0
  DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1158
0
                                  TypeConstr->TemplateNameLoc);
1159
1160
0
  TemplateArgumentListInfo TemplateArgs;
1161
0
  if (TypeConstr->LAngleLoc.isValid()) {
1162
0
    TemplateArgs =
1163
0
        makeTemplateArgumentListInfo(*this, *TypeConstr);
1164
1165
0
    if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1166
0
      for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1167
0
        if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
1168
0
          return true;
1169
0
      }
1170
0
    }
1171
0
  }
1172
0
  return AttachTypeConstraint(
1173
0
      SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1174
0
      ConceptName, CD,
1175
0
      TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1176
0
      ConstrainedParameter, EllipsisLoc);
1177
0
}
1178
1179
template<typename ArgumentLocAppender>
1180
static ExprResult formImmediatelyDeclaredConstraint(
1181
    Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1182
    ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
1183
    SourceLocation RAngleLoc, QualType ConstrainedType,
1184
    SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1185
0
    SourceLocation EllipsisLoc) {
1186
1187
0
  TemplateArgumentListInfo ConstraintArgs;
1188
0
  ConstraintArgs.addArgument(
1189
0
    S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1190
0
                                    /*NTTPType=*/QualType(), ParamNameLoc));
1191
1192
0
  ConstraintArgs.setRAngleLoc(RAngleLoc);
1193
0
  ConstraintArgs.setLAngleLoc(LAngleLoc);
1194
0
  Appender(ConstraintArgs);
1195
1196
  // C++2a [temp.param]p4:
1197
  //     [...] This constraint-expression E is called the immediately-declared
1198
  //     constraint of T. [...]
1199
0
  CXXScopeSpec SS;
1200
0
  SS.Adopt(NS);
1201
0
  ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1202
0
      SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1203
0
      /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1204
0
  if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1205
0
    return ImmediatelyDeclaredConstraint;
1206
1207
  // C++2a [temp.param]p4:
1208
  //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1209
  //
1210
  // We have the following case:
1211
  //
1212
  // template<typename T> concept C1 = true;
1213
  // template<C1... T> struct s1;
1214
  //
1215
  // The constraint: (C1<T> && ...)
1216
  //
1217
  // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1218
  // any unqualified lookups for 'operator&&' here.
1219
0
  return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1220
0
                            /*LParenLoc=*/SourceLocation(),
1221
0
                            ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1222
0
                            EllipsisLoc, /*RHS=*/nullptr,
1223
0
                            /*RParenLoc=*/SourceLocation(),
1224
0
                            /*NumExpansions=*/std::nullopt);
1225
0
}
Unexecuted instantiation: SemaTemplate.cpp:clang::ActionResult<clang::Expr*, true> formImmediatelyDeclaredConstraint<clang::Sema::AttachTypeConstraint(clang::NestedNameSpecifierLoc, clang::DeclarationNameInfo, clang::ConceptDecl*, clang::TemplateArgumentListInfo const*, clang::TemplateTypeParmDecl*, clang::SourceLocation)::$_2>(clang::Sema&, clang::NestedNameSpecifierLoc, clang::DeclarationNameInfo, clang::ConceptDecl*, clang::SourceLocation, clang::SourceLocation, clang::QualType, clang::SourceLocation, clang::Sema::AttachTypeConstraint(clang::NestedNameSpecifierLoc, clang::DeclarationNameInfo, clang::ConceptDecl*, clang::TemplateArgumentListInfo const*, clang::TemplateTypeParmDecl*, clang::SourceLocation)::$_2, clang::SourceLocation)
Unexecuted instantiation: SemaTemplate.cpp:clang::ActionResult<clang::Expr*, true> formImmediatelyDeclaredConstraint<clang::Sema::AttachTypeConstraint(clang::AutoTypeLoc, clang::NonTypeTemplateParmDecl*, clang::NonTypeTemplateParmDecl*, clang::SourceLocation)::$_3>(clang::Sema&, clang::NestedNameSpecifierLoc, clang::DeclarationNameInfo, clang::ConceptDecl*, clang::SourceLocation, clang::SourceLocation, clang::QualType, clang::SourceLocation, clang::Sema::AttachTypeConstraint(clang::AutoTypeLoc, clang::NonTypeTemplateParmDecl*, clang::NonTypeTemplateParmDecl*, clang::SourceLocation)::$_3, clang::SourceLocation)
1226
1227
/// Attach a type-constraint to a template parameter.
1228
/// \returns true if an error occurred. This can happen if the
1229
/// immediately-declared constraint could not be formed (e.g. incorrect number
1230
/// of arguments for the named concept).
1231
bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1232
                                DeclarationNameInfo NameInfo,
1233
                                ConceptDecl *NamedConcept,
1234
                                const TemplateArgumentListInfo *TemplateArgs,
1235
                                TemplateTypeParmDecl *ConstrainedParameter,
1236
0
                                SourceLocation EllipsisLoc) {
1237
  // C++2a [temp.param]p4:
1238
  //     [...] If Q is of the form C<A1, ..., An>, then let E' be
1239
  //     C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1240
0
  const ASTTemplateArgumentListInfo *ArgsAsWritten =
1241
0
    TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1242
0
                                                       *TemplateArgs) : nullptr;
1243
1244
0
  QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1245
1246
0
  ExprResult ImmediatelyDeclaredConstraint =
1247
0
      formImmediatelyDeclaredConstraint(
1248
0
          *this, NS, NameInfo, NamedConcept,
1249
0
          TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1250
0
          TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1251
0
          ParamAsArgument, ConstrainedParameter->getLocation(),
1252
0
          [&] (TemplateArgumentListInfo &ConstraintArgs) {
1253
0
            if (TemplateArgs)
1254
0
              for (const auto &ArgLoc : TemplateArgs->arguments())
1255
0
                ConstraintArgs.addArgument(ArgLoc);
1256
0
          }, EllipsisLoc);
1257
0
  if (ImmediatelyDeclaredConstraint.isInvalid())
1258
0
    return true;
1259
1260
0
  auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1261
0
                                      /*TemplateKWLoc=*/SourceLocation{},
1262
0
                                      /*ConceptNameInfo=*/NameInfo,
1263
0
                                      /*FoundDecl=*/NamedConcept,
1264
0
                                      /*NamedConcept=*/NamedConcept,
1265
0
                                      /*ArgsWritten=*/ArgsAsWritten);
1266
0
  ConstrainedParameter->setTypeConstraint(CL,
1267
0
                                          ImmediatelyDeclaredConstraint.get());
1268
0
  return false;
1269
0
}
1270
1271
bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1272
                                NonTypeTemplateParmDecl *NewConstrainedParm,
1273
                                NonTypeTemplateParmDecl *OrigConstrainedParm,
1274
0
                                SourceLocation EllipsisLoc) {
1275
0
  if (NewConstrainedParm->getType() != TL.getType() ||
1276
0
      TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1277
0
    Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1278
0
         diag::err_unsupported_placeholder_constraint)
1279
0
        << NewConstrainedParm->getTypeSourceInfo()
1280
0
               ->getTypeLoc()
1281
0
               .getSourceRange();
1282
0
    return true;
1283
0
  }
1284
  // FIXME: Concepts: This should be the type of the placeholder, but this is
1285
  // unclear in the wording right now.
1286
0
  DeclRefExpr *Ref =
1287
0
      BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1288
0
                       VK_PRValue, OrigConstrainedParm->getLocation());
1289
0
  if (!Ref)
1290
0
    return true;
1291
0
  ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1292
0
      *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1293
0
      TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1294
0
      BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(),
1295
0
      [&](TemplateArgumentListInfo &ConstraintArgs) {
1296
0
        for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1297
0
          ConstraintArgs.addArgument(TL.getArgLoc(I));
1298
0
      },
1299
0
      EllipsisLoc);
1300
0
  if (ImmediatelyDeclaredConstraint.isInvalid() ||
1301
0
      !ImmediatelyDeclaredConstraint.isUsable())
1302
0
    return true;
1303
1304
0
  NewConstrainedParm->setPlaceholderTypeConstraint(
1305
0
      ImmediatelyDeclaredConstraint.get());
1306
0
  return false;
1307
0
}
1308
1309
/// Check that the type of a non-type template parameter is
1310
/// well-formed.
1311
///
1312
/// \returns the (possibly-promoted) parameter type if valid;
1313
/// otherwise, produces a diagnostic and returns a NULL type.
1314
QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1315
0
                                                 SourceLocation Loc) {
1316
0
  if (TSI->getType()->isUndeducedType()) {
1317
    // C++17 [temp.dep.expr]p3:
1318
    //   An id-expression is type-dependent if it contains
1319
    //    - an identifier associated by name lookup with a non-type
1320
    //      template-parameter declared with a type that contains a
1321
    //      placeholder type (7.1.7.4),
1322
0
    TSI = SubstAutoTypeSourceInfoDependent(TSI);
1323
0
  }
1324
1325
0
  return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1326
0
}
1327
1328
/// Require the given type to be a structural type, and diagnose if it is not.
1329
///
1330
/// \return \c true if an error was produced.
1331
0
bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1332
0
  if (T->isDependentType())
1333
0
    return false;
1334
1335
0
  if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1336
0
    return true;
1337
1338
0
  if (T->isStructuralType())
1339
0
    return false;
1340
1341
  // Structural types are required to be object types or lvalue references.
1342
0
  if (T->isRValueReferenceType()) {
1343
0
    Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1344
0
    return true;
1345
0
  }
1346
1347
  // Don't mention structural types in our diagnostic prior to C++20. Also,
1348
  // there's not much more we can say about non-scalar non-class types --
1349
  // because we can't see functions or arrays here, those can only be language
1350
  // extensions.
1351
0
  if (!getLangOpts().CPlusPlus20 ||
1352
0
      (!T->isScalarType() && !T->isRecordType())) {
1353
0
    Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1354
0
    return true;
1355
0
  }
1356
1357
  // Structural types are required to be literal types.
1358
0
  if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1359
0
    return true;
1360
1361
0
  Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1362
1363
  // Drill down into the reason why the class is non-structural.
1364
0
  while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1365
    // All members are required to be public and non-mutable, and can't be of
1366
    // rvalue reference type. Check these conditions first to prefer a "local"
1367
    // reason over a more distant one.
1368
0
    for (const FieldDecl *FD : RD->fields()) {
1369
0
      if (FD->getAccess() != AS_public) {
1370
0
        Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1371
0
        return true;
1372
0
      }
1373
0
      if (FD->isMutable()) {
1374
0
        Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1375
0
        return true;
1376
0
      }
1377
0
      if (FD->getType()->isRValueReferenceType()) {
1378
0
        Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1379
0
            << T;
1380
0
        return true;
1381
0
      }
1382
0
    }
1383
1384
    // All bases are required to be public.
1385
0
    for (const auto &BaseSpec : RD->bases()) {
1386
0
      if (BaseSpec.getAccessSpecifier() != AS_public) {
1387
0
        Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1388
0
            << T << 1;
1389
0
        return true;
1390
0
      }
1391
0
    }
1392
1393
    // All subobjects are required to be of structural types.
1394
0
    SourceLocation SubLoc;
1395
0
    QualType SubType;
1396
0
    int Kind = -1;
1397
1398
0
    for (const FieldDecl *FD : RD->fields()) {
1399
0
      QualType T = Context.getBaseElementType(FD->getType());
1400
0
      if (!T->isStructuralType()) {
1401
0
        SubLoc = FD->getLocation();
1402
0
        SubType = T;
1403
0
        Kind = 0;
1404
0
        break;
1405
0
      }
1406
0
    }
1407
1408
0
    if (Kind == -1) {
1409
0
      for (const auto &BaseSpec : RD->bases()) {
1410
0
        QualType T = BaseSpec.getType();
1411
0
        if (!T->isStructuralType()) {
1412
0
          SubLoc = BaseSpec.getBaseTypeLoc();
1413
0
          SubType = T;
1414
0
          Kind = 1;
1415
0
          break;
1416
0
        }
1417
0
      }
1418
0
    }
1419
1420
0
    assert(Kind != -1 && "couldn't find reason why type is not structural");
1421
0
    Diag(SubLoc, diag::note_not_structural_subobject)
1422
0
        << T << Kind << SubType;
1423
0
    T = SubType;
1424
0
    RD = T->getAsCXXRecordDecl();
1425
0
  }
1426
1427
0
  return true;
1428
0
}
1429
1430
QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1431
0
                                                 SourceLocation Loc) {
1432
  // We don't allow variably-modified types as the type of non-type template
1433
  // parameters.
1434
0
  if (T->isVariablyModifiedType()) {
1435
0
    Diag(Loc, diag::err_variably_modified_nontype_template_param)
1436
0
      << T;
1437
0
    return QualType();
1438
0
  }
1439
1440
  // C++ [temp.param]p4:
1441
  //
1442
  // A non-type template-parameter shall have one of the following
1443
  // (optionally cv-qualified) types:
1444
  //
1445
  //       -- integral or enumeration type,
1446
0
  if (T->isIntegralOrEnumerationType() ||
1447
      //   -- pointer to object or pointer to function,
1448
0
      T->isPointerType() ||
1449
      //   -- lvalue reference to object or lvalue reference to function,
1450
0
      T->isLValueReferenceType() ||
1451
      //   -- pointer to member,
1452
0
      T->isMemberPointerType() ||
1453
      //   -- std::nullptr_t, or
1454
0
      T->isNullPtrType() ||
1455
      //   -- a type that contains a placeholder type.
1456
0
      T->isUndeducedType()) {
1457
    // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1458
    // are ignored when determining its type.
1459
0
    return T.getUnqualifiedType();
1460
0
  }
1461
1462
  // C++ [temp.param]p8:
1463
  //
1464
  //   A non-type template-parameter of type "array of T" or
1465
  //   "function returning T" is adjusted to be of type "pointer to
1466
  //   T" or "pointer to function returning T", respectively.
1467
0
  if (T->isArrayType() || T->isFunctionType())
1468
0
    return Context.getDecayedType(T);
1469
1470
  // If T is a dependent type, we can't do the check now, so we
1471
  // assume that it is well-formed. Note that stripping off the
1472
  // qualifiers here is not really correct if T turns out to be
1473
  // an array type, but we'll recompute the type everywhere it's
1474
  // used during instantiation, so that should be OK. (Using the
1475
  // qualified type is equally wrong.)
1476
0
  if (T->isDependentType())
1477
0
    return T.getUnqualifiedType();
1478
1479
  // C++20 [temp.param]p6:
1480
  //   -- a structural type
1481
0
  if (RequireStructuralType(T, Loc))
1482
0
    return QualType();
1483
1484
0
  if (!getLangOpts().CPlusPlus20) {
1485
    // FIXME: Consider allowing structural types as an extension in C++17. (In
1486
    // earlier language modes, the template argument evaluation rules are too
1487
    // inflexible.)
1488
0
    Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1489
0
    return QualType();
1490
0
  }
1491
1492
0
  Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1493
0
  return T.getUnqualifiedType();
1494
0
}
1495
1496
NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1497
                                          unsigned Depth,
1498
                                          unsigned Position,
1499
                                          SourceLocation EqualLoc,
1500
0
                                          Expr *Default) {
1501
0
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1502
1503
  // Check that we have valid decl-specifiers specified.
1504
0
  auto CheckValidDeclSpecifiers = [this, &D] {
1505
    // C++ [temp.param]
1506
    // p1
1507
    //   template-parameter:
1508
    //     ...
1509
    //     parameter-declaration
1510
    // p2
1511
    //   ... A storage class shall not be specified in a template-parameter
1512
    //   declaration.
1513
    // [dcl.typedef]p1:
1514
    //   The typedef specifier [...] shall not be used in the decl-specifier-seq
1515
    //   of a parameter-declaration
1516
0
    const DeclSpec &DS = D.getDeclSpec();
1517
0
    auto EmitDiag = [this](SourceLocation Loc) {
1518
0
      Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1519
0
          << FixItHint::CreateRemoval(Loc);
1520
0
    };
1521
0
    if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1522
0
      EmitDiag(DS.getStorageClassSpecLoc());
1523
1524
0
    if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1525
0
      EmitDiag(DS.getThreadStorageClassSpecLoc());
1526
1527
    // [dcl.inline]p1:
1528
    //   The inline specifier can be applied only to the declaration or
1529
    //   definition of a variable or function.
1530
1531
0
    if (DS.isInlineSpecified())
1532
0
      EmitDiag(DS.getInlineSpecLoc());
1533
1534
    // [dcl.constexpr]p1:
1535
    //   The constexpr specifier shall be applied only to the definition of a
1536
    //   variable or variable template or the declaration of a function or
1537
    //   function template.
1538
1539
0
    if (DS.hasConstexprSpecifier())
1540
0
      EmitDiag(DS.getConstexprSpecLoc());
1541
1542
    // [dcl.fct.spec]p1:
1543
    //   Function-specifiers can be used only in function declarations.
1544
1545
0
    if (DS.isVirtualSpecified())
1546
0
      EmitDiag(DS.getVirtualSpecLoc());
1547
1548
0
    if (DS.hasExplicitSpecifier())
1549
0
      EmitDiag(DS.getExplicitSpecLoc());
1550
1551
0
    if (DS.isNoreturnSpecified())
1552
0
      EmitDiag(DS.getNoreturnSpecLoc());
1553
0
  };
1554
1555
0
  CheckValidDeclSpecifiers();
1556
1557
0
  if (const auto *T = TInfo->getType()->getContainedDeducedType())
1558
0
    if (isa<AutoType>(T))
1559
0
      Diag(D.getIdentifierLoc(),
1560
0
           diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1561
0
          << QualType(TInfo->getType()->getContainedAutoType(), 0);
1562
1563
0
  assert(S->isTemplateParamScope() &&
1564
0
         "Non-type template parameter not in template parameter scope!");
1565
0
  bool Invalid = false;
1566
1567
0
  QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1568
0
  if (T.isNull()) {
1569
0
    T = Context.IntTy; // Recover with an 'int' type.
1570
0
    Invalid = true;
1571
0
  }
1572
1573
0
  CheckFunctionOrTemplateParamDeclarator(S, D);
1574
1575
0
  IdentifierInfo *ParamName = D.getIdentifier();
1576
0
  bool IsParameterPack = D.hasEllipsis();
1577
0
  NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1578
0
      Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1579
0
      D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1580
0
      TInfo);
1581
0
  Param->setAccess(AS_public);
1582
1583
0
  if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1584
0
    if (TL.isConstrained())
1585
0
      if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1586
0
        Invalid = true;
1587
1588
0
  if (Invalid)
1589
0
    Param->setInvalidDecl();
1590
1591
0
  if (Param->isParameterPack())
1592
0
    if (auto *LSI = getEnclosingLambda())
1593
0
      LSI->LocalPacks.push_back(Param);
1594
1595
0
  if (ParamName) {
1596
0
    maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1597
0
                                         ParamName);
1598
1599
    // Add the template parameter into the current scope.
1600
0
    S->AddDecl(Param);
1601
0
    IdResolver.AddDecl(Param);
1602
0
  }
1603
1604
  // C++0x [temp.param]p9:
1605
  //   A default template-argument may be specified for any kind of
1606
  //   template-parameter that is not a template parameter pack.
1607
0
  if (Default && IsParameterPack) {
1608
0
    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1609
0
    Default = nullptr;
1610
0
  }
1611
1612
  // Check the well-formedness of the default template argument, if provided.
1613
0
  if (Default) {
1614
    // Check for unexpanded parameter packs.
1615
0
    if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1616
0
      return Param;
1617
1618
0
    Param->setDefaultArgument(Default);
1619
0
  }
1620
1621
0
  return Param;
1622
0
}
1623
1624
/// ActOnTemplateTemplateParameter - Called when a C++ template template
1625
/// parameter (e.g. T in template <template \<typename> class T> class array)
1626
/// has been parsed. S is the current scope.
1627
NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1628
                                           SourceLocation TmpLoc,
1629
                                           TemplateParameterList *Params,
1630
                                           SourceLocation EllipsisLoc,
1631
                                           IdentifierInfo *Name,
1632
                                           SourceLocation NameLoc,
1633
                                           unsigned Depth,
1634
                                           unsigned Position,
1635
                                           SourceLocation EqualLoc,
1636
0
                                           ParsedTemplateArgument Default) {
1637
0
  assert(S->isTemplateParamScope() &&
1638
0
         "Template template parameter not in template parameter scope!");
1639
1640
  // Construct the parameter object.
1641
0
  bool IsParameterPack = EllipsisLoc.isValid();
1642
0
  TemplateTemplateParmDecl *Param =
1643
0
    TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1644
0
                                     NameLoc.isInvalid()? TmpLoc : NameLoc,
1645
0
                                     Depth, Position, IsParameterPack,
1646
0
                                     Name, Params);
1647
0
  Param->setAccess(AS_public);
1648
1649
0
  if (Param->isParameterPack())
1650
0
    if (auto *LSI = getEnclosingLambda())
1651
0
      LSI->LocalPacks.push_back(Param);
1652
1653
  // If the template template parameter has a name, then link the identifier
1654
  // into the scope and lookup mechanisms.
1655
0
  if (Name) {
1656
0
    maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1657
1658
0
    S->AddDecl(Param);
1659
0
    IdResolver.AddDecl(Param);
1660
0
  }
1661
1662
0
  if (Params->size() == 0) {
1663
0
    Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1664
0
    << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1665
0
    Param->setInvalidDecl();
1666
0
  }
1667
1668
  // C++0x [temp.param]p9:
1669
  //   A default template-argument may be specified for any kind of
1670
  //   template-parameter that is not a template parameter pack.
1671
0
  if (IsParameterPack && !Default.isInvalid()) {
1672
0
    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1673
0
    Default = ParsedTemplateArgument();
1674
0
  }
1675
1676
0
  if (!Default.isInvalid()) {
1677
    // Check only that we have a template template argument. We don't want to
1678
    // try to check well-formedness now, because our template template parameter
1679
    // might have dependent types in its template parameters, which we wouldn't
1680
    // be able to match now.
1681
    //
1682
    // If none of the template template parameter's template arguments mention
1683
    // other template parameters, we could actually perform more checking here.
1684
    // However, it isn't worth doing.
1685
0
    TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1686
0
    if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1687
0
      Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1688
0
        << DefaultArg.getSourceRange();
1689
0
      return Param;
1690
0
    }
1691
1692
    // Check for unexpanded parameter packs.
1693
0
    if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1694
0
                                        DefaultArg.getArgument().getAsTemplate(),
1695
0
                                        UPPC_DefaultArgument))
1696
0
      return Param;
1697
1698
0
    Param->setDefaultArgument(Context, DefaultArg);
1699
0
  }
1700
1701
0
  return Param;
1702
0
}
1703
1704
namespace {
1705
class ConstraintRefersToContainingTemplateChecker
1706
    : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1707
  bool Result = false;
1708
  const FunctionDecl *Friend = nullptr;
1709
  unsigned TemplateDepth = 0;
1710
1711
  // Check a record-decl that we've seen to see if it is a lexical parent of the
1712
  // Friend, likely because it was referred to without its template arguments.
1713
0
  void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1714
0
    CheckingRD = CheckingRD->getMostRecentDecl();
1715
0
    if (!CheckingRD->isTemplated())
1716
0
      return;
1717
1718
0
    for (const DeclContext *DC = Friend->getLexicalDeclContext();
1719
0
         DC && !DC->isFileContext(); DC = DC->getParent())
1720
0
      if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1721
0
        if (CheckingRD == RD->getMostRecentDecl())
1722
0
          Result = true;
1723
0
  }
1724
1725
0
  void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1726
0
    assert(D->getDepth() <= TemplateDepth &&
1727
0
           "Nothing should reference a value below the actual template depth, "
1728
0
           "depth is likely wrong");
1729
0
    if (D->getDepth() != TemplateDepth)
1730
0
      Result = true;
1731
1732
    // Necessary because the type of the NTTP might be what refers to the parent
1733
    // constriant.
1734
0
    TransformType(D->getType());
1735
0
  }
1736
1737
public:
1738
  using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>;
1739
1740
  ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1741
                                              const FunctionDecl *Friend,
1742
                                              unsigned TemplateDepth)
1743
0
      : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1744
0
  bool getResult() const { return Result; }
1745
1746
  // This should be the only template parm type that we have to deal with.
1747
  // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1748
  // FunctionParmPackExpr are all partially substituted, which cannot happen
1749
  // with concepts at this point in translation.
1750
  using inherited::TransformTemplateTypeParmType;
1751
  QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1752
0
                                         TemplateTypeParmTypeLoc TL, bool) {
1753
0
    assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1754
0
           "Nothing should reference a value below the actual template depth, "
1755
0
           "depth is likely wrong");
1756
0
    if (TL.getDecl()->getDepth() != TemplateDepth)
1757
0
      Result = true;
1758
0
    return inherited::TransformTemplateTypeParmType(
1759
0
        TLB, TL,
1760
0
        /*SuppressObjCLifetime=*/false);
1761
0
  }
1762
1763
0
  Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1764
0
    if (!D)
1765
0
      return D;
1766
    // FIXME : This is possibly an incomplete list, but it is unclear what other
1767
    // Decl kinds could be used to refer to the template parameters.  This is a
1768
    // best guess so far based on examples currently available, but the
1769
    // unreachable should catch future instances/cases.
1770
0
    if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1771
0
      TransformType(TD->getUnderlyingType());
1772
0
    else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1773
0
      CheckNonTypeTemplateParmDecl(NTTPD);
1774
0
    else if (auto *VD = dyn_cast<ValueDecl>(D))
1775
0
      TransformType(VD->getType());
1776
0
    else if (auto *TD = dyn_cast<TemplateDecl>(D))
1777
0
      TransformTemplateParameterList(TD->getTemplateParameters());
1778
0
    else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1779
0
      CheckIfContainingRecord(RD);
1780
0
    else if (isa<NamedDecl>(D)) {
1781
      // No direct types to visit here I believe.
1782
0
    } else
1783
0
      llvm_unreachable("Don't know how to handle this declaration type yet");
1784
0
    return D;
1785
0
  }
1786
};
1787
} // namespace
1788
1789
bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1790
    const FunctionDecl *Friend, unsigned TemplateDepth,
1791
0
    const Expr *Constraint) {
1792
0
  assert(Friend->getFriendObjectKind() && "Only works on a friend");
1793
0
  ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1794
0
                                                      TemplateDepth);
1795
0
  Checker.TransformExpr(const_cast<Expr *>(Constraint));
1796
0
  return Checker.getResult();
1797
0
}
1798
1799
/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1800
/// constrained by RequiresClause, that contains the template parameters in
1801
/// Params.
1802
TemplateParameterList *
1803
Sema::ActOnTemplateParameterList(unsigned Depth,
1804
                                 SourceLocation ExportLoc,
1805
                                 SourceLocation TemplateLoc,
1806
                                 SourceLocation LAngleLoc,
1807
                                 ArrayRef<NamedDecl *> Params,
1808
                                 SourceLocation RAngleLoc,
1809
0
                                 Expr *RequiresClause) {
1810
0
  if (ExportLoc.isValid())
1811
0
    Diag(ExportLoc, diag::warn_template_export_unsupported);
1812
1813
0
  for (NamedDecl *P : Params)
1814
0
    warnOnReservedIdentifier(P);
1815
1816
0
  return TemplateParameterList::Create(
1817
0
      Context, TemplateLoc, LAngleLoc,
1818
0
      llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1819
0
}
1820
1821
static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1822
0
                                   const CXXScopeSpec &SS) {
1823
0
  if (SS.isSet())
1824
0
    T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1825
0
}
1826
1827
// Returns the template parameter list with all default template argument
1828
// information.
1829
0
static TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD) {
1830
  // Make sure we get the template parameter list from the most
1831
  // recent declaration, since that is the only one that is guaranteed to
1832
  // have all the default template argument information.
1833
0
  return cast<TemplateDecl>(TD->getMostRecentDecl())->getTemplateParameters();
1834
0
}
1835
1836
DeclResult Sema::CheckClassTemplate(
1837
    Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1838
    CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1839
    const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1840
    AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1841
    SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1842
0
    TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1843
0
  assert(TemplateParams && TemplateParams->size() > 0 &&
1844
0
         "No template parameters");
1845
0
  assert(TUK != TUK_Reference && "Can only declare or define class templates");
1846
0
  bool Invalid = false;
1847
1848
  // Check that we can declare a template here.
1849
0
  if (CheckTemplateDeclScope(S, TemplateParams))
1850
0
    return true;
1851
1852
0
  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1853
0
  assert(Kind != TagTypeKind::Enum &&
1854
0
         "can't build template of enumerated type");
1855
1856
  // There is no such thing as an unnamed class template.
1857
0
  if (!Name) {
1858
0
    Diag(KWLoc, diag::err_template_unnamed_class);
1859
0
    return true;
1860
0
  }
1861
1862
  // Find any previous declaration with this name. For a friend with no
1863
  // scope explicitly specified, we only look for tag declarations (per
1864
  // C++11 [basic.lookup.elab]p2).
1865
0
  DeclContext *SemanticContext;
1866
0
  LookupResult Previous(*this, Name, NameLoc,
1867
0
                        (SS.isEmpty() && TUK == TUK_Friend)
1868
0
                          ? LookupTagName : LookupOrdinaryName,
1869
0
                        forRedeclarationInCurContext());
1870
0
  if (SS.isNotEmpty() && !SS.isInvalid()) {
1871
0
    SemanticContext = computeDeclContext(SS, true);
1872
0
    if (!SemanticContext) {
1873
      // FIXME: Horrible, horrible hack! We can't currently represent this
1874
      // in the AST, and historically we have just ignored such friend
1875
      // class templates, so don't complain here.
1876
0
      Diag(NameLoc, TUK == TUK_Friend
1877
0
                        ? diag::warn_template_qualified_friend_ignored
1878
0
                        : diag::err_template_qualified_declarator_no_match)
1879
0
          << SS.getScopeRep() << SS.getRange();
1880
0
      return TUK != TUK_Friend;
1881
0
    }
1882
1883
0
    if (RequireCompleteDeclContext(SS, SemanticContext))
1884
0
      return true;
1885
1886
    // If we're adding a template to a dependent context, we may need to
1887
    // rebuilding some of the types used within the template parameter list,
1888
    // now that we know what the current instantiation is.
1889
0
    if (SemanticContext->isDependentContext()) {
1890
0
      ContextRAII SavedContext(*this, SemanticContext);
1891
0
      if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1892
0
        Invalid = true;
1893
0
    } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1894
0
      diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1895
1896
0
    LookupQualifiedName(Previous, SemanticContext);
1897
0
  } else {
1898
0
    SemanticContext = CurContext;
1899
1900
    // C++14 [class.mem]p14:
1901
    //   If T is the name of a class, then each of the following shall have a
1902
    //   name different from T:
1903
    //    -- every member template of class T
1904
0
    if (TUK != TUK_Friend &&
1905
0
        DiagnoseClassNameShadow(SemanticContext,
1906
0
                                DeclarationNameInfo(Name, NameLoc)))
1907
0
      return true;
1908
1909
0
    LookupName(Previous, S);
1910
0
  }
1911
1912
0
  if (Previous.isAmbiguous())
1913
0
    return true;
1914
1915
0
  NamedDecl *PrevDecl = nullptr;
1916
0
  if (Previous.begin() != Previous.end())
1917
0
    PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1918
1919
0
  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1920
    // Maybe we will complain about the shadowed template parameter.
1921
0
    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1922
    // Just pretend that we didn't see the previous declaration.
1923
0
    PrevDecl = nullptr;
1924
0
  }
1925
1926
  // If there is a previous declaration with the same name, check
1927
  // whether this is a valid redeclaration.
1928
0
  ClassTemplateDecl *PrevClassTemplate =
1929
0
      dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1930
1931
  // We may have found the injected-class-name of a class template,
1932
  // class template partial specialization, or class template specialization.
1933
  // In these cases, grab the template that is being defined or specialized.
1934
0
  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1935
0
      cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1936
0
    PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1937
0
    PrevClassTemplate
1938
0
      = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1939
0
    if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1940
0
      PrevClassTemplate
1941
0
        = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1942
0
            ->getSpecializedTemplate();
1943
0
    }
1944
0
  }
1945
1946
0
  if (TUK == TUK_Friend) {
1947
    // C++ [namespace.memdef]p3:
1948
    //   [...] When looking for a prior declaration of a class or a function
1949
    //   declared as a friend, and when the name of the friend class or
1950
    //   function is neither a qualified name nor a template-id, scopes outside
1951
    //   the innermost enclosing namespace scope are not considered.
1952
0
    if (!SS.isSet()) {
1953
0
      DeclContext *OutermostContext = CurContext;
1954
0
      while (!OutermostContext->isFileContext())
1955
0
        OutermostContext = OutermostContext->getLookupParent();
1956
1957
0
      if (PrevDecl &&
1958
0
          (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1959
0
           OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1960
0
        SemanticContext = PrevDecl->getDeclContext();
1961
0
      } else {
1962
        // Declarations in outer scopes don't matter. However, the outermost
1963
        // context we computed is the semantic context for our new
1964
        // declaration.
1965
0
        PrevDecl = PrevClassTemplate = nullptr;
1966
0
        SemanticContext = OutermostContext;
1967
1968
        // Check that the chosen semantic context doesn't already contain a
1969
        // declaration of this name as a non-tag type.
1970
0
        Previous.clear(LookupOrdinaryName);
1971
0
        DeclContext *LookupContext = SemanticContext;
1972
0
        while (LookupContext->isTransparentContext())
1973
0
          LookupContext = LookupContext->getLookupParent();
1974
0
        LookupQualifiedName(Previous, LookupContext);
1975
1976
0
        if (Previous.isAmbiguous())
1977
0
          return true;
1978
1979
0
        if (Previous.begin() != Previous.end())
1980
0
          PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1981
0
      }
1982
0
    }
1983
0
  } else if (PrevDecl &&
1984
0
             !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1985
0
                            S, SS.isValid()))
1986
0
    PrevDecl = PrevClassTemplate = nullptr;
1987
1988
0
  if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1989
0
          PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1990
0
    if (SS.isEmpty() &&
1991
0
        !(PrevClassTemplate &&
1992
0
          PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1993
0
              SemanticContext->getRedeclContext()))) {
1994
0
      Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1995
0
      Diag(Shadow->getTargetDecl()->getLocation(),
1996
0
           diag::note_using_decl_target);
1997
0
      Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1998
      // Recover by ignoring the old declaration.
1999
0
      PrevDecl = PrevClassTemplate = nullptr;
2000
0
    }
2001
0
  }
2002
2003
0
  if (PrevClassTemplate) {
2004
    // Ensure that the template parameter lists are compatible. Skip this check
2005
    // for a friend in a dependent context: the template parameter list itself
2006
    // could be dependent.
2007
0
    if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2008
0
        !TemplateParameterListsAreEqual(
2009
0
            TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2010
0
                                                       : CurContext,
2011
0
                                       CurContext, KWLoc),
2012
0
            TemplateParams, PrevClassTemplate,
2013
0
            PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2014
0
            TPL_TemplateMatch))
2015
0
      return true;
2016
2017
    // C++ [temp.class]p4:
2018
    //   In a redeclaration, partial specialization, explicit
2019
    //   specialization or explicit instantiation of a class template,
2020
    //   the class-key shall agree in kind with the original class
2021
    //   template declaration (7.1.5.3).
2022
0
    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2023
0
    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
2024
0
                                      TUK == TUK_Definition,  KWLoc, Name)) {
2025
0
      Diag(KWLoc, diag::err_use_with_wrong_tag)
2026
0
        << Name
2027
0
        << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2028
0
      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2029
0
      Kind = PrevRecordDecl->getTagKind();
2030
0
    }
2031
2032
    // Check for redefinition of this class template.
2033
0
    if (TUK == TUK_Definition) {
2034
0
      if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2035
        // If we have a prior definition that is not visible, treat this as
2036
        // simply making that previous definition visible.
2037
0
        NamedDecl *Hidden = nullptr;
2038
0
        if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2039
0
          SkipBody->ShouldSkip = true;
2040
0
          SkipBody->Previous = Def;
2041
0
          auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2042
0
          assert(Tmpl && "original definition of a class template is not a "
2043
0
                         "class template?");
2044
0
          makeMergedDefinitionVisible(Hidden);
2045
0
          makeMergedDefinitionVisible(Tmpl);
2046
0
        } else {
2047
0
          Diag(NameLoc, diag::err_redefinition) << Name;
2048
0
          Diag(Def->getLocation(), diag::note_previous_definition);
2049
          // FIXME: Would it make sense to try to "forget" the previous
2050
          // definition, as part of error recovery?
2051
0
          return true;
2052
0
        }
2053
0
      }
2054
0
    }
2055
0
  } else if (PrevDecl) {
2056
    // C++ [temp]p5:
2057
    //   A class template shall not have the same name as any other
2058
    //   template, class, function, object, enumeration, enumerator,
2059
    //   namespace, or type in the same scope (3.3), except as specified
2060
    //   in (14.5.4).
2061
0
    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2062
0
    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2063
0
    return true;
2064
0
  }
2065
2066
  // Check the template parameter list of this declaration, possibly
2067
  // merging in the template parameter list from the previous class
2068
  // template declaration. Skip this check for a friend in a dependent
2069
  // context, because the template parameter list might be dependent.
2070
0
  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2071
0
      CheckTemplateParameterList(
2072
0
          TemplateParams,
2073
0
          PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2074
0
                            : nullptr,
2075
0
          (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2076
0
           SemanticContext->isDependentContext())
2077
0
              ? TPC_ClassTemplateMember
2078
0
          : TUK == TUK_Friend ? TPC_FriendClassTemplate
2079
0
                              : TPC_ClassTemplate,
2080
0
          SkipBody))
2081
0
    Invalid = true;
2082
2083
0
  if (SS.isSet()) {
2084
    // If the name of the template was qualified, we must be defining the
2085
    // template out-of-line.
2086
0
    if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2087
0
      Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
2088
0
                                      : diag::err_member_decl_does_not_match)
2089
0
        << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
2090
0
      Invalid = true;
2091
0
    }
2092
0
  }
2093
2094
  // If this is a templated friend in a dependent context we should not put it
2095
  // on the redecl chain. In some cases, the templated friend can be the most
2096
  // recent declaration tricking the template instantiator to make substitutions
2097
  // there.
2098
  // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2099
0
  bool ShouldAddRedecl
2100
0
    = !(TUK == TUK_Friend && CurContext->isDependentContext());
2101
2102
0
  CXXRecordDecl *NewClass =
2103
0
    CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2104
0
                          PrevClassTemplate && ShouldAddRedecl ?
2105
0
                            PrevClassTemplate->getTemplatedDecl() : nullptr,
2106
0
                          /*DelayTypeCreation=*/true);
2107
0
  SetNestedNameSpecifier(*this, NewClass, SS);
2108
0
  if (NumOuterTemplateParamLists > 0)
2109
0
    NewClass->setTemplateParameterListsInfo(
2110
0
        Context,
2111
0
        llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2112
2113
  // Add alignment attributes if necessary; these attributes are checked when
2114
  // the ASTContext lays out the structure.
2115
0
  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2116
0
    AddAlignmentAttributesForRecord(NewClass);
2117
0
    AddMsStructLayoutForRecord(NewClass);
2118
0
  }
2119
2120
0
  ClassTemplateDecl *NewTemplate
2121
0
    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2122
0
                                DeclarationName(Name), TemplateParams,
2123
0
                                NewClass);
2124
2125
0
  if (ShouldAddRedecl)
2126
0
    NewTemplate->setPreviousDecl(PrevClassTemplate);
2127
2128
0
  NewClass->setDescribedClassTemplate(NewTemplate);
2129
2130
0
  if (ModulePrivateLoc.isValid())
2131
0
    NewTemplate->setModulePrivate();
2132
2133
  // Build the type for the class template declaration now.
2134
0
  QualType T = NewTemplate->getInjectedClassNameSpecialization();
2135
0
  T = Context.getInjectedClassNameType(NewClass, T);
2136
0
  assert(T->isDependentType() && "Class template type is not dependent?");
2137
0
  (void)T;
2138
2139
  // If we are providing an explicit specialization of a member that is a
2140
  // class template, make a note of that.
2141
0
  if (PrevClassTemplate &&
2142
0
      PrevClassTemplate->getInstantiatedFromMemberTemplate())
2143
0
    PrevClassTemplate->setMemberSpecialization();
2144
2145
  // Set the access specifier.
2146
0
  if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
2147
0
    SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2148
2149
  // Set the lexical context of these templates
2150
0
  NewClass->setLexicalDeclContext(CurContext);
2151
0
  NewTemplate->setLexicalDeclContext(CurContext);
2152
2153
0
  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2154
0
    NewClass->startDefinition();
2155
2156
0
  ProcessDeclAttributeList(S, NewClass, Attr);
2157
2158
0
  if (PrevClassTemplate)
2159
0
    mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2160
2161
0
  AddPushedVisibilityAttribute(NewClass);
2162
0
  inferGslOwnerPointerAttribute(NewClass);
2163
2164
0
  if (TUK != TUK_Friend) {
2165
    // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2166
0
    Scope *Outer = S;
2167
0
    while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2168
0
      Outer = Outer->getParent();
2169
0
    PushOnScopeChains(NewTemplate, Outer);
2170
0
  } else {
2171
0
    if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2172
0
      NewTemplate->setAccess(PrevClassTemplate->getAccess());
2173
0
      NewClass->setAccess(PrevClassTemplate->getAccess());
2174
0
    }
2175
2176
0
    NewTemplate->setObjectOfFriendDecl();
2177
2178
    // Friend templates are visible in fairly strange ways.
2179
0
    if (!CurContext->isDependentContext()) {
2180
0
      DeclContext *DC = SemanticContext->getRedeclContext();
2181
0
      DC->makeDeclVisibleInContext(NewTemplate);
2182
0
      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2183
0
        PushOnScopeChains(NewTemplate, EnclosingScope,
2184
0
                          /* AddToContext = */ false);
2185
0
    }
2186
2187
0
    FriendDecl *Friend = FriendDecl::Create(
2188
0
        Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2189
0
    Friend->setAccess(AS_public);
2190
0
    CurContext->addDecl(Friend);
2191
0
  }
2192
2193
0
  if (PrevClassTemplate)
2194
0
    CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2195
2196
0
  if (Invalid) {
2197
0
    NewTemplate->setInvalidDecl();
2198
0
    NewClass->setInvalidDecl();
2199
0
  }
2200
2201
0
  ActOnDocumentableDecl(NewTemplate);
2202
2203
0
  if (SkipBody && SkipBody->ShouldSkip)
2204
0
    return SkipBody->Previous;
2205
2206
0
  return NewTemplate;
2207
0
}
2208
2209
namespace {
2210
/// Tree transform to "extract" a transformed type from a class template's
2211
/// constructor to a deduction guide.
2212
class ExtractTypeForDeductionGuide
2213
  : public TreeTransform<ExtractTypeForDeductionGuide> {
2214
  llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2215
2216
public:
2217
  typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
2218
  ExtractTypeForDeductionGuide(
2219
      Sema &SemaRef,
2220
      llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2221
0
      : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2222
2223
0
  TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2224
2225
0
  QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2226
0
    ASTContext &Context = SemaRef.getASTContext();
2227
0
    TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2228
0
    TypedefNameDecl *Decl = OrigDecl;
2229
    // Transform the underlying type of the typedef and clone the Decl only if
2230
    // the typedef has a dependent context.
2231
0
    if (OrigDecl->getDeclContext()->isDependentContext()) {
2232
0
      TypeLocBuilder InnerTLB;
2233
0
      QualType Transformed =
2234
0
          TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2235
0
      TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
2236
0
      if (isa<TypeAliasDecl>(OrigDecl))
2237
0
        Decl = TypeAliasDecl::Create(
2238
0
            Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2239
0
            OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2240
0
      else {
2241
0
        assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2242
0
        Decl = TypedefDecl::Create(
2243
0
            Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2244
0
            OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2245
0
      }
2246
0
      MaterializedTypedefs.push_back(Decl);
2247
0
    }
2248
2249
0
    QualType TDTy = Context.getTypedefType(Decl);
2250
0
    TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2251
0
    TypedefTL.setNameLoc(TL.getNameLoc());
2252
2253
0
    return TDTy;
2254
0
  }
2255
};
2256
2257
/// Transform to convert portions of a constructor declaration into the
2258
/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2259
struct ConvertConstructorToDeductionGuideTransform {
2260
  ConvertConstructorToDeductionGuideTransform(Sema &S,
2261
                                              ClassTemplateDecl *Template)
2262
0
      : SemaRef(S), Template(Template) {
2263
    // If the template is nested, then we need to use the original
2264
    // pattern to iterate over the constructors.
2265
0
    ClassTemplateDecl *Pattern = Template;
2266
0
    while (Pattern->getInstantiatedFromMemberTemplate()) {
2267
0
      if (Pattern->isMemberSpecialization())
2268
0
        break;
2269
0
      Pattern = Pattern->getInstantiatedFromMemberTemplate();
2270
0
      NestedPattern = Pattern;
2271
0
    }
2272
2273
0
    if (NestedPattern)
2274
0
      OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template);
2275
0
  }
2276
2277
  Sema &SemaRef;
2278
  ClassTemplateDecl *Template;
2279
  ClassTemplateDecl *NestedPattern = nullptr;
2280
2281
  DeclContext *DC = Template->getDeclContext();
2282
  CXXRecordDecl *Primary = Template->getTemplatedDecl();
2283
  DeclarationName DeductionGuideName =
2284
      SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
2285
2286
  QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2287
2288
  // Index adjustment to apply to convert depth-1 template parameters into
2289
  // depth-0 template parameters.
2290
  unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2291
2292
  // Instantiation arguments for the outermost depth-1 templates
2293
  // when the template is nested
2294
  MultiLevelTemplateArgumentList OuterInstantiationArgs;
2295
2296
  /// Transform a constructor declaration into a deduction guide.
2297
  NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2298
0
                                  CXXConstructorDecl *CD) {
2299
0
    SmallVector<TemplateArgument, 16> SubstArgs;
2300
2301
0
    LocalInstantiationScope Scope(SemaRef);
2302
2303
    // C++ [over.match.class.deduct]p1:
2304
    // -- For each constructor of the class template designated by the
2305
    //    template-name, a function template with the following properties:
2306
2307
    //    -- The template parameters are the template parameters of the class
2308
    //       template followed by the template parameters (including default
2309
    //       template arguments) of the constructor, if any.
2310
0
    TemplateParameterList *TemplateParams = GetTemplateParameterList(Template);
2311
0
    if (FTD) {
2312
0
      TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2313
0
      SmallVector<NamedDecl *, 16> AllParams;
2314
0
      SmallVector<TemplateArgument, 16> Depth1Args;
2315
0
      AllParams.reserve(TemplateParams->size() + InnerParams->size());
2316
0
      AllParams.insert(AllParams.begin(),
2317
0
                       TemplateParams->begin(), TemplateParams->end());
2318
0
      SubstArgs.reserve(InnerParams->size());
2319
0
      Depth1Args.reserve(InnerParams->size());
2320
2321
      // Later template parameters could refer to earlier ones, so build up
2322
      // a list of substituted template arguments as we go.
2323
0
      for (NamedDecl *Param : *InnerParams) {
2324
0
        MultiLevelTemplateArgumentList Args;
2325
0
        Args.setKind(TemplateSubstitutionKind::Rewrite);
2326
0
        Args.addOuterTemplateArguments(Depth1Args);
2327
0
        Args.addOuterRetainedLevel();
2328
0
        if (NestedPattern)
2329
0
          Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2330
0
        NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2331
0
        if (!NewParam)
2332
0
          return nullptr;
2333
2334
        // Constraints require that we substitute depth-1 arguments
2335
        // to match depths when substituted for evaluation later
2336
0
        Depth1Args.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2337
0
            SemaRef.Context.getInjectedTemplateArg(NewParam)));
2338
2339
0
        if (NestedPattern) {
2340
0
          TemplateDeclInstantiator Instantiator(SemaRef, DC,
2341
0
                                                OuterInstantiationArgs);
2342
0
          Instantiator.setEvaluateConstraints(false);
2343
0
          SemaRef.runWithSufficientStackSpace(NewParam->getLocation(), [&] {
2344
0
            NewParam = cast<NamedDecl>(Instantiator.Visit(NewParam));
2345
0
          });
2346
0
        }
2347
2348
0
        assert(NewParam->getTemplateDepth() == 0 &&
2349
0
               "Unexpected template parameter depth");
2350
2351
0
        AllParams.push_back(NewParam);
2352
0
        SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2353
0
            SemaRef.Context.getInjectedTemplateArg(NewParam)));
2354
0
      }
2355
2356
      // Substitute new template parameters into requires-clause if present.
2357
0
      Expr *RequiresClause = nullptr;
2358
0
      if (Expr *InnerRC = InnerParams->getRequiresClause()) {
2359
0
        MultiLevelTemplateArgumentList Args;
2360
0
        Args.setKind(TemplateSubstitutionKind::Rewrite);
2361
0
        Args.addOuterTemplateArguments(Depth1Args);
2362
0
        Args.addOuterRetainedLevel();
2363
0
        if (NestedPattern)
2364
0
          Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2365
0
        ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
2366
0
        if (E.isInvalid())
2367
0
          return nullptr;
2368
0
        RequiresClause = E.getAs<Expr>();
2369
0
      }
2370
2371
0
      TemplateParams = TemplateParameterList::Create(
2372
0
          SemaRef.Context, InnerParams->getTemplateLoc(),
2373
0
          InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2374
0
          RequiresClause);
2375
0
    }
2376
2377
    // If we built a new template-parameter-list, track that we need to
2378
    // substitute references to the old parameters into references to the
2379
    // new ones.
2380
0
    MultiLevelTemplateArgumentList Args;
2381
0
    Args.setKind(TemplateSubstitutionKind::Rewrite);
2382
0
    if (FTD) {
2383
0
      Args.addOuterTemplateArguments(SubstArgs);
2384
0
      Args.addOuterRetainedLevel();
2385
0
    }
2386
2387
0
    if (NestedPattern)
2388
0
      Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2389
2390
0
    FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
2391
0
                                   .getAsAdjusted<FunctionProtoTypeLoc>();
2392
0
    assert(FPTL && "no prototype for constructor declaration");
2393
2394
    // Transform the type of the function, adjusting the return type and
2395
    // replacing references to the old parameters with references to the
2396
    // new ones.
2397
0
    TypeLocBuilder TLB;
2398
0
    SmallVector<ParmVarDecl*, 8> Params;
2399
0
    SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2400
0
    QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2401
0
                                                  MaterializedTypedefs);
2402
0
    if (NewType.isNull())
2403
0
      return nullptr;
2404
0
    TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2405
2406
0
    return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(),
2407
0
                               NewTInfo, CD->getBeginLoc(), CD->getLocation(),
2408
0
                               CD->getEndLoc(), MaterializedTypedefs);
2409
0
  }
2410
2411
  /// Build a deduction guide with the specified parameter types.
2412
0
  NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2413
0
    SourceLocation Loc = Template->getLocation();
2414
2415
    // Build the requested type.
2416
0
    FunctionProtoType::ExtProtoInfo EPI;
2417
0
    EPI.HasTrailingReturn = true;
2418
0
    QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2419
0
                                                DeductionGuideName, EPI);
2420
0
    TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2421
2422
0
    FunctionProtoTypeLoc FPTL =
2423
0
        TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
2424
2425
    // Build the parameters, needed during deduction / substitution.
2426
0
    SmallVector<ParmVarDecl*, 4> Params;
2427
0
    for (auto T : ParamTypes) {
2428
0
      ParmVarDecl *NewParam = ParmVarDecl::Create(
2429
0
          SemaRef.Context, DC, Loc, Loc, nullptr, T,
2430
0
          SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
2431
0
      NewParam->setScopeInfo(0, Params.size());
2432
0
      FPTL.setParam(Params.size(), NewParam);
2433
0
      Params.push_back(NewParam);
2434
0
    }
2435
2436
0
    return buildDeductionGuide(GetTemplateParameterList(Template), nullptr,
2437
0
                               ExplicitSpecifier(), TSI, Loc, Loc, Loc);
2438
0
  }
2439
2440
private:
2441
  /// Transform a constructor template parameter into a deduction guide template
2442
  /// parameter, rebuilding any internal references to earlier parameters and
2443
  /// renumbering as we go.
2444
  NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2445
0
                                        MultiLevelTemplateArgumentList &Args) {
2446
0
    if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
2447
      // TemplateTypeParmDecl's index cannot be changed after creation, so
2448
      // substitute it directly.
2449
0
      auto *NewTTP = TemplateTypeParmDecl::Create(
2450
0
          SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
2451
0
          TTP->getDepth() - 1, Depth1IndexAdjustment + TTP->getIndex(),
2452
0
          TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2453
0
          TTP->isParameterPack(), TTP->hasTypeConstraint(),
2454
0
          TTP->isExpandedParameterPack()
2455
0
              ? std::optional<unsigned>(TTP->getNumExpansionParameters())
2456
0
              : std::nullopt);
2457
0
      if (const auto *TC = TTP->getTypeConstraint())
2458
0
        SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
2459
0
                                    /*EvaluateConstraint*/ true);
2460
0
      if (TTP->hasDefaultArgument()) {
2461
0
        TypeSourceInfo *InstantiatedDefaultArg =
2462
0
            SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2463
0
                              TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2464
0
        if (InstantiatedDefaultArg)
2465
0
          NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2466
0
      }
2467
0
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2468
0
                                                           NewTTP);
2469
0
      return NewTTP;
2470
0
    }
2471
2472
0
    if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2473
0
      return transformTemplateParameterImpl(TTP, Args);
2474
2475
0
    return transformTemplateParameterImpl(
2476
0
        cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2477
0
  }
2478
  template<typename TemplateParmDecl>
2479
  TemplateParmDecl *
2480
  transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2481
0
                                 MultiLevelTemplateArgumentList &Args) {
2482
    // Ask the template instantiator to do the heavy lifting for us, then adjust
2483
    // the index of the parameter once it's done.
2484
0
    auto *NewParam =
2485
0
        cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2486
0
    assert(NewParam->getDepth() == OldParam->getDepth() - 1 &&
2487
0
           "unexpected template param depth");
2488
0
    NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2489
0
    return NewParam;
2490
0
  }
Unexecuted instantiation: SemaTemplate.cpp:clang::TemplateTemplateParmDecl* (anonymous namespace)::ConvertConstructorToDeductionGuideTransform::transformTemplateParameterImpl<clang::TemplateTemplateParmDecl>(clang::TemplateTemplateParmDecl*, clang::MultiLevelTemplateArgumentList&)
Unexecuted instantiation: SemaTemplate.cpp:clang::NonTypeTemplateParmDecl* (anonymous namespace)::ConvertConstructorToDeductionGuideTransform::transformTemplateParameterImpl<clang::NonTypeTemplateParmDecl>(clang::NonTypeTemplateParmDecl*, clang::MultiLevelTemplateArgumentList&)
2491
2492
  QualType transformFunctionProtoType(
2493
      TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
2494
      SmallVectorImpl<ParmVarDecl *> &Params,
2495
      MultiLevelTemplateArgumentList &Args,
2496
0
      SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2497
0
    SmallVector<QualType, 4> ParamTypes;
2498
0
    const FunctionProtoType *T = TL.getTypePtr();
2499
2500
    //    -- The types of the function parameters are those of the constructor.
2501
0
    for (auto *OldParam : TL.getParams()) {
2502
0
      ParmVarDecl *NewParam =
2503
0
          transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2504
0
      if (NestedPattern && NewParam)
2505
0
        NewParam = transformFunctionTypeParam(NewParam, OuterInstantiationArgs,
2506
0
                                              MaterializedTypedefs);
2507
0
      if (!NewParam)
2508
0
        return QualType();
2509
0
      ParamTypes.push_back(NewParam->getType());
2510
0
      Params.push_back(NewParam);
2511
0
    }
2512
2513
    //    -- The return type is the class template specialization designated by
2514
    //       the template-name and template arguments corresponding to the
2515
    //       template parameters obtained from the class template.
2516
    //
2517
    // We use the injected-class-name type of the primary template instead.
2518
    // This has the convenient property that it is different from any type that
2519
    // the user can write in a deduction-guide (because they cannot enter the
2520
    // context of the template), so implicit deduction guides can never collide
2521
    // with explicit ones.
2522
0
    QualType ReturnType = DeducedType;
2523
0
    TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2524
2525
    // Resolving a wording defect, we also inherit the variadicness of the
2526
    // constructor.
2527
0
    FunctionProtoType::ExtProtoInfo EPI;
2528
0
    EPI.Variadic = T->isVariadic();
2529
0
    EPI.HasTrailingReturn = true;
2530
2531
0
    QualType Result = SemaRef.BuildFunctionType(
2532
0
        ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2533
0
    if (Result.isNull())
2534
0
      return QualType();
2535
2536
0
    FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2537
0
    NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2538
0
    NewTL.setLParenLoc(TL.getLParenLoc());
2539
0
    NewTL.setRParenLoc(TL.getRParenLoc());
2540
0
    NewTL.setExceptionSpecRange(SourceRange());
2541
0
    NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2542
0
    for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2543
0
      NewTL.setParam(I, Params[I]);
2544
2545
0
    return Result;
2546
0
  }
2547
2548
  ParmVarDecl *transformFunctionTypeParam(
2549
      ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
2550
0
      llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2551
0
    TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2552
0
    TypeSourceInfo *NewDI;
2553
0
    if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2554
      // Expand out the one and only element in each inner pack.
2555
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2556
0
      NewDI =
2557
0
          SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2558
0
                            OldParam->getLocation(), OldParam->getDeclName());
2559
0
      if (!NewDI) return nullptr;
2560
0
      NewDI =
2561
0
          SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2562
0
                                     PackTL.getTypePtr()->getNumExpansions());
2563
0
    } else
2564
0
      NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2565
0
                                OldParam->getDeclName());
2566
0
    if (!NewDI)
2567
0
      return nullptr;
2568
2569
    // Extract the type. This (for instance) replaces references to typedef
2570
    // members of the current instantiations with the definitions of those
2571
    // typedefs, avoiding triggering instantiation of the deduced type during
2572
    // deduction.
2573
0
    NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2574
0
                .transform(NewDI);
2575
2576
    // Resolving a wording defect, we also inherit default arguments from the
2577
    // constructor.
2578
0
    ExprResult NewDefArg;
2579
0
    if (OldParam->hasDefaultArg()) {
2580
      // We don't care what the value is (we won't use it); just create a
2581
      // placeholder to indicate there is a default argument.
2582
0
      QualType ParamTy = NewDI->getType();
2583
0
      NewDefArg = new (SemaRef.Context)
2584
0
          OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
2585
0
                          ParamTy.getNonLValueExprType(SemaRef.Context),
2586
0
                          ParamTy->isLValueReferenceType()   ? VK_LValue
2587
0
                          : ParamTy->isRValueReferenceType() ? VK_XValue
2588
0
                                                             : VK_PRValue);
2589
0
    }
2590
    // Handle arrays and functions decay.
2591
0
    auto NewType = NewDI->getType();
2592
0
    if (NewType->isArrayType() || NewType->isFunctionType())
2593
0
      NewType = SemaRef.Context.getDecayedType(NewType);
2594
2595
0
    ParmVarDecl *NewParam = ParmVarDecl::Create(
2596
0
        SemaRef.Context, DC, OldParam->getInnerLocStart(),
2597
0
        OldParam->getLocation(), OldParam->getIdentifier(), NewType, NewDI,
2598
0
        OldParam->getStorageClass(), NewDefArg.get());
2599
0
    NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2600
0
                           OldParam->getFunctionScopeIndex());
2601
0
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2602
0
    return NewParam;
2603
0
  }
2604
2605
  FunctionTemplateDecl *buildDeductionGuide(
2606
      TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2607
      ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2608
      SourceLocation Loc, SourceLocation LocEnd,
2609
0
      llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2610
0
    DeclarationNameInfo Name(DeductionGuideName, Loc);
2611
0
    ArrayRef<ParmVarDecl *> Params =
2612
0
        TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2613
2614
    // Build the implicit deduction guide template.
2615
0
    auto *Guide =
2616
0
        CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2617
0
                                      TInfo->getType(), TInfo, LocEnd, Ctor);
2618
0
    Guide->setImplicit();
2619
0
    Guide->setParams(Params);
2620
2621
0
    for (auto *Param : Params)
2622
0
      Param->setDeclContext(Guide);
2623
0
    for (auto *TD : MaterializedTypedefs)
2624
0
      TD->setDeclContext(Guide);
2625
2626
0
    auto *GuideTemplate = FunctionTemplateDecl::Create(
2627
0
        SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2628
0
    GuideTemplate->setImplicit();
2629
0
    Guide->setDescribedFunctionTemplate(GuideTemplate);
2630
2631
0
    if (isa<CXXRecordDecl>(DC)) {
2632
0
      Guide->setAccess(AS_public);
2633
0
      GuideTemplate->setAccess(AS_public);
2634
0
    }
2635
2636
0
    DC->addDecl(GuideTemplate);
2637
0
    return GuideTemplate;
2638
0
  }
2639
};
2640
}
2641
2642
FunctionTemplateDecl *Sema::DeclareImplicitDeductionGuideFromInitList(
2643
    TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
2644
0
    SourceLocation Loc) {
2645
0
  if (CXXRecordDecl *DefRecord =
2646
0
          cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2647
0
    if (TemplateDecl *DescribedTemplate =
2648
0
            DefRecord->getDescribedClassTemplate())
2649
0
      Template = DescribedTemplate;
2650
0
  }
2651
2652
0
  DeclContext *DC = Template->getDeclContext();
2653
0
  if (DC->isDependentContext())
2654
0
    return nullptr;
2655
2656
0
  ConvertConstructorToDeductionGuideTransform Transform(
2657
0
      *this, cast<ClassTemplateDecl>(Template));
2658
0
  if (!isCompleteType(Loc, Transform.DeducedType))
2659
0
    return nullptr;
2660
2661
  // In case we were expanding a pack when we attempted to declare deduction
2662
  // guides, turn off pack expansion for everything we're about to do.
2663
0
  ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
2664
0
                                               /*NewSubstitutionIndex=*/-1);
2665
  // Create a template instantiation record to track the "instantiation" of
2666
  // constructors into deduction guides.
2667
0
  InstantiatingTemplate BuildingDeductionGuides(
2668
0
      *this, Loc, Template,
2669
0
      Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{});
2670
0
  if (BuildingDeductionGuides.isInvalid())
2671
0
    return nullptr;
2672
2673
0
  return cast<FunctionTemplateDecl>(
2674
0
      Transform.buildSimpleDeductionGuide(ParamTypes));
2675
0
}
2676
2677
void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2678
0
                                          SourceLocation Loc) {
2679
0
  if (CXXRecordDecl *DefRecord =
2680
0
          cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2681
0
    if (TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate())
2682
0
      Template = DescribedTemplate;
2683
0
  }
2684
2685
0
  DeclContext *DC = Template->getDeclContext();
2686
0
  if (DC->isDependentContext())
2687
0
    return;
2688
2689
0
  ConvertConstructorToDeductionGuideTransform Transform(
2690
0
      *this, cast<ClassTemplateDecl>(Template));
2691
0
  if (!isCompleteType(Loc, Transform.DeducedType))
2692
0
    return;
2693
2694
  // Check whether we've already declared deduction guides for this template.
2695
  // FIXME: Consider storing a flag on the template to indicate this.
2696
0
  auto Existing = DC->lookup(Transform.DeductionGuideName);
2697
0
  for (auto *D : Existing)
2698
0
    if (D->isImplicit())
2699
0
      return;
2700
2701
  // In case we were expanding a pack when we attempted to declare deduction
2702
  // guides, turn off pack expansion for everything we're about to do.
2703
0
  ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2704
  // Create a template instantiation record to track the "instantiation" of
2705
  // constructors into deduction guides.
2706
0
  InstantiatingTemplate BuildingDeductionGuides(
2707
0
      *this, Loc, Template,
2708
0
      Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{});
2709
0
  if (BuildingDeductionGuides.isInvalid())
2710
0
    return;
2711
2712
  // Convert declared constructors into deduction guide templates.
2713
  // FIXME: Skip constructors for which deduction must necessarily fail (those
2714
  // for which some class template parameter without a default argument never
2715
  // appears in a deduced context).
2716
0
  ClassTemplateDecl *Pattern =
2717
0
      Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
2718
0
  ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
2719
0
  llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors;
2720
0
  bool AddedAny = false;
2721
0
  for (NamedDecl *D : LookupConstructors(Pattern->getTemplatedDecl())) {
2722
0
    D = D->getUnderlyingDecl();
2723
0
    if (D->isInvalidDecl() || D->isImplicit())
2724
0
      continue;
2725
2726
0
    D = cast<NamedDecl>(D->getCanonicalDecl());
2727
2728
    // Within C++20 modules, we may have multiple same constructors in
2729
    // multiple same RecordDecls. And it doesn't make sense to create
2730
    // duplicated deduction guides for the duplicated constructors.
2731
0
    if (ProcessedCtors.count(D))
2732
0
      continue;
2733
2734
0
    auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2735
0
    auto *CD =
2736
0
        dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2737
    // Class-scope explicit specializations (MS extension) do not result in
2738
    // deduction guides.
2739
0
    if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2740
0
      continue;
2741
2742
    // Cannot make a deduction guide when unparsed arguments are present.
2743
0
    if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
2744
0
          return !P || P->hasUnparsedDefaultArg();
2745
0
        }))
2746
0
      continue;
2747
2748
0
    ProcessedCtors.insert(D);
2749
0
    Transform.transformConstructor(FTD, CD);
2750
0
    AddedAny = true;
2751
0
  }
2752
2753
  // C++17 [over.match.class.deduct]
2754
  //    --  If C is not defined or does not declare any constructors, an
2755
  //    additional function template derived as above from a hypothetical
2756
  //    constructor C().
2757
0
  if (!AddedAny)
2758
0
    Transform.buildSimpleDeductionGuide(std::nullopt);
2759
2760
  //    -- An additional function template derived as above from a hypothetical
2761
  //    constructor C(C), called the copy deduction candidate.
2762
0
  cast<CXXDeductionGuideDecl>(
2763
0
      cast<FunctionTemplateDecl>(
2764
0
          Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2765
0
          ->getTemplatedDecl())
2766
0
      ->setDeductionCandidateKind(DeductionCandidate::Copy);
2767
2768
0
  SavedContext.pop();
2769
0
}
2770
2771
/// Diagnose the presence of a default template argument on a
2772
/// template parameter, which is ill-formed in certain contexts.
2773
///
2774
/// \returns true if the default template argument should be dropped.
2775
static bool DiagnoseDefaultTemplateArgument(Sema &S,
2776
                                            Sema::TemplateParamListContext TPC,
2777
                                            SourceLocation ParamLoc,
2778
0
                                            SourceRange DefArgRange) {
2779
0
  switch (TPC) {
2780
0
  case Sema::TPC_ClassTemplate:
2781
0
  case Sema::TPC_VarTemplate:
2782
0
  case Sema::TPC_TypeAliasTemplate:
2783
0
    return false;
2784
2785
0
  case Sema::TPC_FunctionTemplate:
2786
0
  case Sema::TPC_FriendFunctionTemplateDefinition:
2787
    // C++ [temp.param]p9:
2788
    //   A default template-argument shall not be specified in a
2789
    //   function template declaration or a function template
2790
    //   definition [...]
2791
    //   If a friend function template declaration specifies a default
2792
    //   template-argument, that declaration shall be a definition and shall be
2793
    //   the only declaration of the function template in the translation unit.
2794
    // (C++98/03 doesn't have this wording; see DR226).
2795
0
    S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2796
0
         diag::warn_cxx98_compat_template_parameter_default_in_function_template
2797
0
           : diag::ext_template_parameter_default_in_function_template)
2798
0
      << DefArgRange;
2799
0
    return false;
2800
2801
0
  case Sema::TPC_ClassTemplateMember:
2802
    // C++0x [temp.param]p9:
2803
    //   A default template-argument shall not be specified in the
2804
    //   template-parameter-lists of the definition of a member of a
2805
    //   class template that appears outside of the member's class.
2806
0
    S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2807
0
      << DefArgRange;
2808
0
    return true;
2809
2810
0
  case Sema::TPC_FriendClassTemplate:
2811
0
  case Sema::TPC_FriendFunctionTemplate:
2812
    // C++ [temp.param]p9:
2813
    //   A default template-argument shall not be specified in a
2814
    //   friend template declaration.
2815
0
    S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2816
0
      << DefArgRange;
2817
0
    return true;
2818
2819
    // FIXME: C++0x [temp.param]p9 allows default template-arguments
2820
    // for friend function templates if there is only a single
2821
    // declaration (and it is a definition). Strange!
2822
0
  }
2823
2824
0
  llvm_unreachable("Invalid TemplateParamListContext!");
2825
0
}
2826
2827
/// Check for unexpanded parameter packs within the template parameters
2828
/// of a template template parameter, recursively.
2829
static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2830
0
                                             TemplateTemplateParmDecl *TTP) {
2831
  // A template template parameter which is a parameter pack is also a pack
2832
  // expansion.
2833
0
  if (TTP->isParameterPack())
2834
0
    return false;
2835
2836
0
  TemplateParameterList *Params = TTP->getTemplateParameters();
2837
0
  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2838
0
    NamedDecl *P = Params->getParam(I);
2839
0
    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2840
0
      if (!TTP->isParameterPack())
2841
0
        if (const TypeConstraint *TC = TTP->getTypeConstraint())
2842
0
          if (TC->hasExplicitTemplateArgs())
2843
0
            for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2844
0
              if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2845
0
                                                    Sema::UPPC_TypeConstraint))
2846
0
                return true;
2847
0
      continue;
2848
0
    }
2849
2850
0
    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2851
0
      if (!NTTP->isParameterPack() &&
2852
0
          S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2853
0
                                            NTTP->getTypeSourceInfo(),
2854
0
                                      Sema::UPPC_NonTypeTemplateParameterType))
2855
0
        return true;
2856
2857
0
      continue;
2858
0
    }
2859
2860
0
    if (TemplateTemplateParmDecl *InnerTTP
2861
0
                                        = dyn_cast<TemplateTemplateParmDecl>(P))
2862
0
      if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2863
0
        return true;
2864
0
  }
2865
2866
0
  return false;
2867
0
}
2868
2869
/// Checks the validity of a template parameter list, possibly
2870
/// considering the template parameter list from a previous
2871
/// declaration.
2872
///
2873
/// If an "old" template parameter list is provided, it must be
2874
/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2875
/// template parameter list.
2876
///
2877
/// \param NewParams Template parameter list for a new template
2878
/// declaration. This template parameter list will be updated with any
2879
/// default arguments that are carried through from the previous
2880
/// template parameter list.
2881
///
2882
/// \param OldParams If provided, template parameter list from a
2883
/// previous declaration of the same template. Default template
2884
/// arguments will be merged from the old template parameter list to
2885
/// the new template parameter list.
2886
///
2887
/// \param TPC Describes the context in which we are checking the given
2888
/// template parameter list.
2889
///
2890
/// \param SkipBody If we might have already made a prior merged definition
2891
/// of this template visible, the corresponding body-skipping information.
2892
/// Default argument redefinition is not an error when skipping such a body,
2893
/// because (under the ODR) we can assume the default arguments are the same
2894
/// as the prior merged definition.
2895
///
2896
/// \returns true if an error occurred, false otherwise.
2897
bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2898
                                      TemplateParameterList *OldParams,
2899
                                      TemplateParamListContext TPC,
2900
0
                                      SkipBodyInfo *SkipBody) {
2901
0
  bool Invalid = false;
2902
2903
  // C++ [temp.param]p10:
2904
  //   The set of default template-arguments available for use with a
2905
  //   template declaration or definition is obtained by merging the
2906
  //   default arguments from the definition (if in scope) and all
2907
  //   declarations in scope in the same way default function
2908
  //   arguments are (8.3.6).
2909
0
  bool SawDefaultArgument = false;
2910
0
  SourceLocation PreviousDefaultArgLoc;
2911
2912
  // Dummy initialization to avoid warnings.
2913
0
  TemplateParameterList::iterator OldParam = NewParams->end();
2914
0
  if (OldParams)
2915
0
    OldParam = OldParams->begin();
2916
2917
0
  bool RemoveDefaultArguments = false;
2918
0
  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2919
0
                                    NewParamEnd = NewParams->end();
2920
0
       NewParam != NewParamEnd; ++NewParam) {
2921
    // Whether we've seen a duplicate default argument in the same translation
2922
    // unit.
2923
0
    bool RedundantDefaultArg = false;
2924
    // Whether we've found inconsis inconsitent default arguments in different
2925
    // translation unit.
2926
0
    bool InconsistentDefaultArg = false;
2927
    // The name of the module which contains the inconsistent default argument.
2928
0
    std::string PrevModuleName;
2929
2930
0
    SourceLocation OldDefaultLoc;
2931
0
    SourceLocation NewDefaultLoc;
2932
2933
    // Variable used to diagnose missing default arguments
2934
0
    bool MissingDefaultArg = false;
2935
2936
    // Variable used to diagnose non-final parameter packs
2937
0
    bool SawParameterPack = false;
2938
2939
0
    if (TemplateTypeParmDecl *NewTypeParm
2940
0
          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2941
      // Check the presence of a default argument here.
2942
0
      if (NewTypeParm->hasDefaultArgument() &&
2943
0
          DiagnoseDefaultTemplateArgument(*this, TPC,
2944
0
                                          NewTypeParm->getLocation(),
2945
0
               NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2946
0
                                                       .getSourceRange()))
2947
0
        NewTypeParm->removeDefaultArgument();
2948
2949
      // Merge default arguments for template type parameters.
2950
0
      TemplateTypeParmDecl *OldTypeParm
2951
0
          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2952
0
      if (NewTypeParm->isParameterPack()) {
2953
0
        assert(!NewTypeParm->hasDefaultArgument() &&
2954
0
               "Parameter packs can't have a default argument!");
2955
0
        SawParameterPack = true;
2956
0
      } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2957
0
                 NewTypeParm->hasDefaultArgument() &&
2958
0
                 (!SkipBody || !SkipBody->ShouldSkip)) {
2959
0
        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2960
0
        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2961
0
        SawDefaultArgument = true;
2962
2963
0
        if (!OldTypeParm->getOwningModule())
2964
0
          RedundantDefaultArg = true;
2965
0
        else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2966
0
                                                                NewTypeParm)) {
2967
0
          InconsistentDefaultArg = true;
2968
0
          PrevModuleName =
2969
0
              OldTypeParm->getImportedOwningModule()->getFullModuleName();
2970
0
        }
2971
0
        PreviousDefaultArgLoc = NewDefaultLoc;
2972
0
      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2973
        // Merge the default argument from the old declaration to the
2974
        // new declaration.
2975
0
        NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2976
0
        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2977
0
      } else if (NewTypeParm->hasDefaultArgument()) {
2978
0
        SawDefaultArgument = true;
2979
0
        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2980
0
      } else if (SawDefaultArgument)
2981
0
        MissingDefaultArg = true;
2982
0
    } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2983
0
               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2984
      // Check for unexpanded parameter packs.
2985
0
      if (!NewNonTypeParm->isParameterPack() &&
2986
0
          DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2987
0
                                          NewNonTypeParm->getTypeSourceInfo(),
2988
0
                                          UPPC_NonTypeTemplateParameterType)) {
2989
0
        Invalid = true;
2990
0
        continue;
2991
0
      }
2992
2993
      // Check the presence of a default argument here.
2994
0
      if (NewNonTypeParm->hasDefaultArgument() &&
2995
0
          DiagnoseDefaultTemplateArgument(*this, TPC,
2996
0
                                          NewNonTypeParm->getLocation(),
2997
0
                    NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2998
0
        NewNonTypeParm->removeDefaultArgument();
2999
0
      }
3000
3001
      // Merge default arguments for non-type template parameters
3002
0
      NonTypeTemplateParmDecl *OldNonTypeParm
3003
0
        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
3004
0
      if (NewNonTypeParm->isParameterPack()) {
3005
0
        assert(!NewNonTypeParm->hasDefaultArgument() &&
3006
0
               "Parameter packs can't have a default argument!");
3007
0
        if (!NewNonTypeParm->isPackExpansion())
3008
0
          SawParameterPack = true;
3009
0
      } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
3010
0
                 NewNonTypeParm->hasDefaultArgument() &&
3011
0
                 (!SkipBody || !SkipBody->ShouldSkip)) {
3012
0
        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
3013
0
        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
3014
0
        SawDefaultArgument = true;
3015
0
        if (!OldNonTypeParm->getOwningModule())
3016
0
          RedundantDefaultArg = true;
3017
0
        else if (!getASTContext().isSameDefaultTemplateArgument(
3018
0
                     OldNonTypeParm, NewNonTypeParm)) {
3019
0
          InconsistentDefaultArg = true;
3020
0
          PrevModuleName =
3021
0
              OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
3022
0
        }
3023
0
        PreviousDefaultArgLoc = NewDefaultLoc;
3024
0
      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
3025
        // Merge the default argument from the old declaration to the
3026
        // new declaration.
3027
0
        NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
3028
0
        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
3029
0
      } else if (NewNonTypeParm->hasDefaultArgument()) {
3030
0
        SawDefaultArgument = true;
3031
0
        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
3032
0
      } else if (SawDefaultArgument)
3033
0
        MissingDefaultArg = true;
3034
0
    } else {
3035
0
      TemplateTemplateParmDecl *NewTemplateParm
3036
0
        = cast<TemplateTemplateParmDecl>(*NewParam);
3037
3038
      // Check for unexpanded parameter packs, recursively.
3039
0
      if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
3040
0
        Invalid = true;
3041
0
        continue;
3042
0
      }
3043
3044
      // Check the presence of a default argument here.
3045
0
      if (NewTemplateParm->hasDefaultArgument() &&
3046
0
          DiagnoseDefaultTemplateArgument(*this, TPC,
3047
0
                                          NewTemplateParm->getLocation(),
3048
0
                     NewTemplateParm->getDefaultArgument().getSourceRange()))
3049
0
        NewTemplateParm->removeDefaultArgument();
3050
3051
      // Merge default arguments for template template parameters
3052
0
      TemplateTemplateParmDecl *OldTemplateParm
3053
0
        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
3054
0
      if (NewTemplateParm->isParameterPack()) {
3055
0
        assert(!NewTemplateParm->hasDefaultArgument() &&
3056
0
               "Parameter packs can't have a default argument!");
3057
0
        if (!NewTemplateParm->isPackExpansion())
3058
0
          SawParameterPack = true;
3059
0
      } else if (OldTemplateParm &&
3060
0
                 hasVisibleDefaultArgument(OldTemplateParm) &&
3061
0
                 NewTemplateParm->hasDefaultArgument() &&
3062
0
                 (!SkipBody || !SkipBody->ShouldSkip)) {
3063
0
        OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
3064
0
        NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
3065
0
        SawDefaultArgument = true;
3066
0
        if (!OldTemplateParm->getOwningModule())
3067
0
          RedundantDefaultArg = true;
3068
0
        else if (!getASTContext().isSameDefaultTemplateArgument(
3069
0
                     OldTemplateParm, NewTemplateParm)) {
3070
0
          InconsistentDefaultArg = true;
3071
0
          PrevModuleName =
3072
0
              OldTemplateParm->getImportedOwningModule()->getFullModuleName();
3073
0
        }
3074
0
        PreviousDefaultArgLoc = NewDefaultLoc;
3075
0
      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
3076
        // Merge the default argument from the old declaration to the
3077
        // new declaration.
3078
0
        NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
3079
0
        PreviousDefaultArgLoc
3080
0
          = OldTemplateParm->getDefaultArgument().getLocation();
3081
0
      } else if (NewTemplateParm->hasDefaultArgument()) {
3082
0
        SawDefaultArgument = true;
3083
0
        PreviousDefaultArgLoc
3084
0
          = NewTemplateParm->getDefaultArgument().getLocation();
3085
0
      } else if (SawDefaultArgument)
3086
0
        MissingDefaultArg = true;
3087
0
    }
3088
3089
    // C++11 [temp.param]p11:
3090
    //   If a template parameter of a primary class template or alias template
3091
    //   is a template parameter pack, it shall be the last template parameter.
3092
0
    if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
3093
0
        (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
3094
0
         TPC == TPC_TypeAliasTemplate)) {
3095
0
      Diag((*NewParam)->getLocation(),
3096
0
           diag::err_template_param_pack_must_be_last_template_parameter);
3097
0
      Invalid = true;
3098
0
    }
3099
3100
    // [basic.def.odr]/13:
3101
    //     There can be more than one definition of a
3102
    //     ...
3103
    //     default template argument
3104
    //     ...
3105
    //     in a program provided that each definition appears in a different
3106
    //     translation unit and the definitions satisfy the [same-meaning
3107
    //     criteria of the ODR].
3108
    //
3109
    // Simply, the design of modules allows the definition of template default
3110
    // argument to be repeated across translation unit. Note that the ODR is
3111
    // checked elsewhere. But it is still not allowed to repeat template default
3112
    // argument in the same translation unit.
3113
0
    if (RedundantDefaultArg) {
3114
0
      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
3115
0
      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
3116
0
      Invalid = true;
3117
0
    } else if (InconsistentDefaultArg) {
3118
      // We could only diagnose about the case that the OldParam is imported.
3119
      // The case NewParam is imported should be handled in ASTReader.
3120
0
      Diag(NewDefaultLoc,
3121
0
           diag::err_template_param_default_arg_inconsistent_redefinition);
3122
0
      Diag(OldDefaultLoc,
3123
0
           diag::note_template_param_prev_default_arg_in_other_module)
3124
0
          << PrevModuleName;
3125
0
      Invalid = true;
3126
0
    } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
3127
      // C++ [temp.param]p11:
3128
      //   If a template-parameter of a class template has a default
3129
      //   template-argument, each subsequent template-parameter shall either
3130
      //   have a default template-argument supplied or be a template parameter
3131
      //   pack.
3132
0
      Diag((*NewParam)->getLocation(),
3133
0
           diag::err_template_param_default_arg_missing);
3134
0
      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
3135
0
      Invalid = true;
3136
0
      RemoveDefaultArguments = true;
3137
0
    }
3138
3139
    // If we have an old template parameter list that we're merging
3140
    // in, move on to the next parameter.
3141
0
    if (OldParams)
3142
0
      ++OldParam;
3143
0
  }
3144
3145
  // We were missing some default arguments at the end of the list, so remove
3146
  // all of the default arguments.
3147
0
  if (RemoveDefaultArguments) {
3148
0
    for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3149
0
                                      NewParamEnd = NewParams->end();
3150
0
         NewParam != NewParamEnd; ++NewParam) {
3151
0
      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
3152
0
        TTP->removeDefaultArgument();
3153
0
      else if (NonTypeTemplateParmDecl *NTTP
3154
0
                                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
3155
0
        NTTP->removeDefaultArgument();
3156
0
      else
3157
0
        cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
3158
0
    }
3159
0
  }
3160
3161
0
  return Invalid;
3162
0
}
3163
3164
namespace {
3165
3166
/// A class which looks for a use of a certain level of template
3167
/// parameter.
3168
struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
3169
  typedef RecursiveASTVisitor<DependencyChecker> super;
3170
3171
  unsigned Depth;
3172
3173
  // Whether we're looking for a use of a template parameter that makes the
3174
  // overall construct type-dependent / a dependent type. This is strictly
3175
  // best-effort for now; we may fail to match at all for a dependent type
3176
  // in some cases if this is set.
3177
  bool IgnoreNonTypeDependent;
3178
3179
  bool Match;
3180
  SourceLocation MatchLoc;
3181
3182
  DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
3183
      : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
3184
0
        Match(false) {}
3185
3186
  DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
3187
0
      : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
3188
0
    NamedDecl *ND = Params->getParam(0);
3189
0
    if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
3190
0
      Depth = PD->getDepth();
3191
0
    } else if (NonTypeTemplateParmDecl *PD =
3192
0
                 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
3193
0
      Depth = PD->getDepth();
3194
0
    } else {
3195
0
      Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
3196
0
    }
3197
0
  }
3198
3199
0
  bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
3200
0
    if (ParmDepth >= Depth) {
3201
0
      Match = true;
3202
0
      MatchLoc = Loc;
3203
0
      return true;
3204
0
    }
3205
0
    return false;
3206
0
  }
3207
3208
0
  bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
3209
    // Prune out non-type-dependent expressions if requested. This can
3210
    // sometimes result in us failing to find a template parameter reference
3211
    // (if a value-dependent expression creates a dependent type), but this
3212
    // mode is best-effort only.
3213
0
    if (auto *E = dyn_cast_or_null<Expr>(S))
3214
0
      if (IgnoreNonTypeDependent && !E->isTypeDependent())
3215
0
        return true;
3216
0
    return super::TraverseStmt(S, Q);
3217
0
  }
3218
3219
0
  bool TraverseTypeLoc(TypeLoc TL) {
3220
0
    if (IgnoreNonTypeDependent && !TL.isNull() &&
3221
0
        !TL.getType()->isDependentType())
3222
0
      return true;
3223
0
    return super::TraverseTypeLoc(TL);
3224
0
  }
3225
3226
0
  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3227
0
    return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
3228
0
  }
3229
3230
0
  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
3231
    // For a best-effort search, keep looking until we find a location.
3232
0
    return IgnoreNonTypeDependent || !Matches(T->getDepth());
3233
0
  }
3234
3235
0
  bool TraverseTemplateName(TemplateName N) {
3236
0
    if (TemplateTemplateParmDecl *PD =
3237
0
          dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
3238
0
      if (Matches(PD->getDepth()))
3239
0
        return false;
3240
0
    return super::TraverseTemplateName(N);
3241
0
  }
3242
3243
0
  bool VisitDeclRefExpr(DeclRefExpr *E) {
3244
0
    if (NonTypeTemplateParmDecl *PD =
3245
0
          dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
3246
0
      if (Matches(PD->getDepth(), E->getExprLoc()))
3247
0
        return false;
3248
0
    return super::VisitDeclRefExpr(E);
3249
0
  }
3250
3251
0
  bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3252
0
    return TraverseType(T->getReplacementType());
3253
0
  }
3254
3255
  bool
3256
0
  VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
3257
0
    return TraverseTemplateArgument(T->getArgumentPack());
3258
0
  }
3259
3260
0
  bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
3261
0
    return TraverseType(T->getInjectedSpecializationType());
3262
0
  }
3263
};
3264
} // end anonymous namespace
3265
3266
/// Determines whether a given type depends on the given parameter
3267
/// list.
3268
static bool
3269
0
DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
3270
0
  if (!Params->size())
3271
0
    return false;
3272
3273
0
  DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
3274
0
  Checker.TraverseType(T);
3275
0
  return Checker.Match;
3276
0
}
3277
3278
// Find the source range corresponding to the named type in the given
3279
// nested-name-specifier, if any.
3280
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
3281
                                                       QualType T,
3282
0
                                                       const CXXScopeSpec &SS) {
3283
0
  NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
3284
0
  while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3285
0
    if (const Type *CurType = NNS->getAsType()) {
3286
0
      if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
3287
0
        return NNSLoc.getTypeLoc().getSourceRange();
3288
0
    } else
3289
0
      break;
3290
3291
0
    NNSLoc = NNSLoc.getPrefix();
3292
0
  }
3293
3294
0
  return SourceRange();
3295
0
}
3296
3297
/// Match the given template parameter lists to the given scope
3298
/// specifier, returning the template parameter list that applies to the
3299
/// name.
3300
///
3301
/// \param DeclStartLoc the start of the declaration that has a scope
3302
/// specifier or a template parameter list.
3303
///
3304
/// \param DeclLoc The location of the declaration itself.
3305
///
3306
/// \param SS the scope specifier that will be matched to the given template
3307
/// parameter lists. This scope specifier precedes a qualified name that is
3308
/// being declared.
3309
///
3310
/// \param TemplateId The template-id following the scope specifier, if there
3311
/// is one. Used to check for a missing 'template<>'.
3312
///
3313
/// \param ParamLists the template parameter lists, from the outermost to the
3314
/// innermost template parameter lists.
3315
///
3316
/// \param IsFriend Whether to apply the slightly different rules for
3317
/// matching template parameters to scope specifiers in friend
3318
/// declarations.
3319
///
3320
/// \param IsMemberSpecialization will be set true if the scope specifier
3321
/// denotes a fully-specialized type, and therefore this is a declaration of
3322
/// a member specialization.
3323
///
3324
/// \returns the template parameter list, if any, that corresponds to the
3325
/// name that is preceded by the scope specifier @p SS. This template
3326
/// parameter list may have template parameters (if we're declaring a
3327
/// template) or may have no template parameters (if we're declaring a
3328
/// template specialization), or may be NULL (if what we're declaring isn't
3329
/// itself a template).
3330
TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
3331
    SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3332
    TemplateIdAnnotation *TemplateId,
3333
    ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3334
2.58k
    bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3335
2.58k
  IsMemberSpecialization = false;
3336
2.58k
  Invalid = false;
3337
3338
  // The sequence of nested types to which we will match up the template
3339
  // parameter lists. We first build this list by starting with the type named
3340
  // by the nested-name-specifier and walking out until we run out of types.
3341
2.58k
  SmallVector<QualType, 4> NestedTypes;
3342
2.58k
  QualType T;
3343
2.58k
  if (SS.getScopeRep()) {
3344
0
    if (CXXRecordDecl *Record
3345
0
              = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3346
0
      T = Context.getTypeDeclType(Record);
3347
0
    else
3348
0
      T = QualType(SS.getScopeRep()->getAsType(), 0);
3349
0
  }
3350
3351
  // If we found an explicit specialization that prevents us from needing
3352
  // 'template<>' headers, this will be set to the location of that
3353
  // explicit specialization.
3354
2.58k
  SourceLocation ExplicitSpecLoc;
3355
3356
2.58k
  while (!T.isNull()) {
3357
0
    NestedTypes.push_back(T);
3358
3359
    // Retrieve the parent of a record type.
3360
0
    if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3361
      // If this type is an explicit specialization, we're done.
3362
0
      if (ClassTemplateSpecializationDecl *Spec
3363
0
          = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3364
0
        if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3365
0
            Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3366
0
          ExplicitSpecLoc = Spec->getLocation();
3367
0
          break;
3368
0
        }
3369
0
      } else if (Record->getTemplateSpecializationKind()
3370
0
                                                == TSK_ExplicitSpecialization) {
3371
0
        ExplicitSpecLoc = Record->getLocation();
3372
0
        break;
3373
0
      }
3374
3375
0
      if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3376
0
        T = Context.getTypeDeclType(Parent);
3377
0
      else
3378
0
        T = QualType();
3379
0
      continue;
3380
0
    }
3381
3382
0
    if (const TemplateSpecializationType *TST
3383
0
                                     = T->getAs<TemplateSpecializationType>()) {
3384
0
      if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3385
0
        if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3386
0
          T = Context.getTypeDeclType(Parent);
3387
0
        else
3388
0
          T = QualType();
3389
0
        continue;
3390
0
      }
3391
0
    }
3392
3393
    // Look one step prior in a dependent template specialization type.
3394
0
    if (const DependentTemplateSpecializationType *DependentTST
3395
0
                          = T->getAs<DependentTemplateSpecializationType>()) {
3396
0
      if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3397
0
        T = QualType(NNS->getAsType(), 0);
3398
0
      else
3399
0
        T = QualType();
3400
0
      continue;
3401
0
    }
3402
3403
    // Look one step prior in a dependent name type.
3404
0
    if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3405
0
      if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3406
0
        T = QualType(NNS->getAsType(), 0);
3407
0
      else
3408
0
        T = QualType();
3409
0
      continue;
3410
0
    }
3411
3412
    // Retrieve the parent of an enumeration type.
3413
0
    if (const EnumType *EnumT = T->getAs<EnumType>()) {
3414
      // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3415
      // check here.
3416
0
      EnumDecl *Enum = EnumT->getDecl();
3417
3418
      // Get to the parent type.
3419
0
      if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3420
0
        T = Context.getTypeDeclType(Parent);
3421
0
      else
3422
0
        T = QualType();
3423
0
      continue;
3424
0
    }
3425
3426
0
    T = QualType();
3427
0
  }
3428
  // Reverse the nested types list, since we want to traverse from the outermost
3429
  // to the innermost while checking template-parameter-lists.
3430
2.58k
  std::reverse(NestedTypes.begin(), NestedTypes.end());
3431
3432
  // C++0x [temp.expl.spec]p17:
3433
  //   A member or a member template may be nested within many
3434
  //   enclosing class templates. In an explicit specialization for
3435
  //   such a member, the member declaration shall be preceded by a
3436
  //   template<> for each enclosing class template that is
3437
  //   explicitly specialized.
3438
2.58k
  bool SawNonEmptyTemplateParameterList = false;
3439
3440
2.58k
  auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3441
0
    if (SawNonEmptyTemplateParameterList) {
3442
0
      if (!SuppressDiagnostic)
3443
0
        Diag(DeclLoc, diag::err_specialize_member_of_template)
3444
0
          << !Recovery << Range;
3445
0
      Invalid = true;
3446
0
      IsMemberSpecialization = false;
3447
0
      return true;
3448
0
    }
3449
3450
0
    return false;
3451
0
  };
3452
3453
2.58k
  auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3454
    // Check that we can have an explicit specialization here.
3455
0
    if (CheckExplicitSpecialization(Range, true))
3456
0
      return true;
3457
3458
    // We don't have a template header, but we should.
3459
0
    SourceLocation ExpectedTemplateLoc;
3460
0
    if (!ParamLists.empty())
3461
0
      ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3462
0
    else
3463
0
      ExpectedTemplateLoc = DeclStartLoc;
3464
3465
0
    if (!SuppressDiagnostic)
3466
0
      Diag(DeclLoc, diag::err_template_spec_needs_header)
3467
0
        << Range
3468
0
        << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3469
0
    return false;
3470
0
  };
3471
3472
2.58k
  unsigned ParamIdx = 0;
3473
2.58k
  for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3474
2.58k
       ++TypeIdx) {
3475
0
    T = NestedTypes[TypeIdx];
3476
3477
    // Whether we expect a 'template<>' header.
3478
0
    bool NeedEmptyTemplateHeader = false;
3479
3480
    // Whether we expect a template header with parameters.
3481
0
    bool NeedNonemptyTemplateHeader = false;
3482
3483
    // For a dependent type, the set of template parameters that we
3484
    // expect to see.
3485
0
    TemplateParameterList *ExpectedTemplateParams = nullptr;
3486
3487
    // C++0x [temp.expl.spec]p15:
3488
    //   A member or a member template may be nested within many enclosing
3489
    //   class templates. In an explicit specialization for such a member, the
3490
    //   member declaration shall be preceded by a template<> for each
3491
    //   enclosing class template that is explicitly specialized.
3492
0
    if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3493
0
      if (ClassTemplatePartialSpecializationDecl *Partial
3494
0
            = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3495
0
        ExpectedTemplateParams = Partial->getTemplateParameters();
3496
0
        NeedNonemptyTemplateHeader = true;
3497
0
      } else if (Record->isDependentType()) {
3498
0
        if (Record->getDescribedClassTemplate()) {
3499
0
          ExpectedTemplateParams = Record->getDescribedClassTemplate()
3500
0
                                                      ->getTemplateParameters();
3501
0
          NeedNonemptyTemplateHeader = true;
3502
0
        }
3503
0
      } else if (ClassTemplateSpecializationDecl *Spec
3504
0
                     = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3505
        // C++0x [temp.expl.spec]p4:
3506
        //   Members of an explicitly specialized class template are defined
3507
        //   in the same manner as members of normal classes, and not using
3508
        //   the template<> syntax.
3509
0
        if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3510
0
          NeedEmptyTemplateHeader = true;
3511
0
        else
3512
0
          continue;
3513
0
      } else if (Record->getTemplateSpecializationKind()) {
3514
0
        if (Record->getTemplateSpecializationKind()
3515
0
                                                != TSK_ExplicitSpecialization &&
3516
0
            TypeIdx == NumTypes - 1)
3517
0
          IsMemberSpecialization = true;
3518
3519
0
        continue;
3520
0
      }
3521
0
    } else if (const TemplateSpecializationType *TST
3522
0
                                     = T->getAs<TemplateSpecializationType>()) {
3523
0
      if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3524
0
        ExpectedTemplateParams = Template->getTemplateParameters();
3525
0
        NeedNonemptyTemplateHeader = true;
3526
0
      }
3527
0
    } else if (T->getAs<DependentTemplateSpecializationType>()) {
3528
      // FIXME:  We actually could/should check the template arguments here
3529
      // against the corresponding template parameter list.
3530
0
      NeedNonemptyTemplateHeader = false;
3531
0
    }
3532
3533
    // C++ [temp.expl.spec]p16:
3534
    //   In an explicit specialization declaration for a member of a class
3535
    //   template or a member template that ap- pears in namespace scope, the
3536
    //   member template and some of its enclosing class templates may remain
3537
    //   unspecialized, except that the declaration shall not explicitly
3538
    //   specialize a class member template if its en- closing class templates
3539
    //   are not explicitly specialized as well.
3540
0
    if (ParamIdx < ParamLists.size()) {
3541
0
      if (ParamLists[ParamIdx]->size() == 0) {
3542
0
        if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3543
0
                                        false))
3544
0
          return nullptr;
3545
0
      } else
3546
0
        SawNonEmptyTemplateParameterList = true;
3547
0
    }
3548
3549
0
    if (NeedEmptyTemplateHeader) {
3550
      // If we're on the last of the types, and we need a 'template<>' header
3551
      // here, then it's a member specialization.
3552
0
      if (TypeIdx == NumTypes - 1)
3553
0
        IsMemberSpecialization = true;
3554
3555
0
      if (ParamIdx < ParamLists.size()) {
3556
0
        if (ParamLists[ParamIdx]->size() > 0) {
3557
          // The header has template parameters when it shouldn't. Complain.
3558
0
          if (!SuppressDiagnostic)
3559
0
            Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3560
0
                 diag::err_template_param_list_matches_nontemplate)
3561
0
              << T
3562
0
              << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3563
0
                             ParamLists[ParamIdx]->getRAngleLoc())
3564
0
              << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3565
0
          Invalid = true;
3566
0
          return nullptr;
3567
0
        }
3568
3569
        // Consume this template header.
3570
0
        ++ParamIdx;
3571
0
        continue;
3572
0
      }
3573
3574
0
      if (!IsFriend)
3575
0
        if (DiagnoseMissingExplicitSpecialization(
3576
0
                getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3577
0
          return nullptr;
3578
3579
0
      continue;
3580
0
    }
3581
3582
0
    if (NeedNonemptyTemplateHeader) {
3583
      // In friend declarations we can have template-ids which don't
3584
      // depend on the corresponding template parameter lists.  But
3585
      // assume that empty parameter lists are supposed to match this
3586
      // template-id.
3587
0
      if (IsFriend && T->isDependentType()) {
3588
0
        if (ParamIdx < ParamLists.size() &&
3589
0
            DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3590
0
          ExpectedTemplateParams = nullptr;
3591
0
        else
3592
0
          continue;
3593
0
      }
3594
3595
0
      if (ParamIdx < ParamLists.size()) {
3596
        // Check the template parameter list, if we can.
3597
0
        if (ExpectedTemplateParams &&
3598
0
            !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3599
0
                                            ExpectedTemplateParams,
3600
0
                                            !SuppressDiagnostic, TPL_TemplateMatch))
3601
0
          Invalid = true;
3602
3603
0
        if (!Invalid &&
3604
0
            CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3605
0
                                       TPC_ClassTemplateMember))
3606
0
          Invalid = true;
3607
3608
0
        ++ParamIdx;
3609
0
        continue;
3610
0
      }
3611
3612
0
      if (!SuppressDiagnostic)
3613
0
        Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3614
0
          << T
3615
0
          << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3616
0
      Invalid = true;
3617
0
      continue;
3618
0
    }
3619
0
  }
3620
3621
  // If there were at least as many template-ids as there were template
3622
  // parameter lists, then there are no template parameter lists remaining for
3623
  // the declaration itself.
3624
2.58k
  if (ParamIdx >= ParamLists.size()) {
3625
2.58k
    if (TemplateId && !IsFriend) {
3626
      // We don't have a template header for the declaration itself, but we
3627
      // should.
3628
0
      DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3629
0
                                                        TemplateId->RAngleLoc));
3630
3631
      // Fabricate an empty template parameter list for the invented header.
3632
0
      return TemplateParameterList::Create(Context, SourceLocation(),
3633
0
                                           SourceLocation(), std::nullopt,
3634
0
                                           SourceLocation(), nullptr);
3635
0
    }
3636
3637
2.58k
    return nullptr;
3638
2.58k
  }
3639
3640
  // If there were too many template parameter lists, complain about that now.
3641
0
  if (ParamIdx < ParamLists.size() - 1) {
3642
0
    bool HasAnyExplicitSpecHeader = false;
3643
0
    bool AllExplicitSpecHeaders = true;
3644
0
    for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3645
0
      if (ParamLists[I]->size() == 0)
3646
0
        HasAnyExplicitSpecHeader = true;
3647
0
      else
3648
0
        AllExplicitSpecHeaders = false;
3649
0
    }
3650
3651
0
    if (!SuppressDiagnostic)
3652
0
      Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3653
0
           AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
3654
0
                                  : diag::err_template_spec_extra_headers)
3655
0
          << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3656
0
                         ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3657
3658
    // If there was a specialization somewhere, such that 'template<>' is
3659
    // not required, and there were any 'template<>' headers, note where the
3660
    // specialization occurred.
3661
0
    if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3662
0
        !SuppressDiagnostic)
3663
0
      Diag(ExplicitSpecLoc,
3664
0
           diag::note_explicit_template_spec_does_not_need_header)
3665
0
        << NestedTypes.back();
3666
3667
    // We have a template parameter list with no corresponding scope, which
3668
    // means that the resulting template declaration can't be instantiated
3669
    // properly (we'll end up with dependent nodes when we shouldn't).
3670
0
    if (!AllExplicitSpecHeaders)
3671
0
      Invalid = true;
3672
0
  }
3673
3674
  // C++ [temp.expl.spec]p16:
3675
  //   In an explicit specialization declaration for a member of a class
3676
  //   template or a member template that ap- pears in namespace scope, the
3677
  //   member template and some of its enclosing class templates may remain
3678
  //   unspecialized, except that the declaration shall not explicitly
3679
  //   specialize a class member template if its en- closing class templates
3680
  //   are not explicitly specialized as well.
3681
0
  if (ParamLists.back()->size() == 0 &&
3682
0
      CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3683
0
                                  false))
3684
0
    return nullptr;
3685
3686
  // Return the last template parameter list, which corresponds to the
3687
  // entity being declared.
3688
0
  return ParamLists.back();
3689
0
}
3690
3691
0
void Sema::NoteAllFoundTemplates(TemplateName Name) {
3692
0
  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3693
0
    Diag(Template->getLocation(), diag::note_template_declared_here)
3694
0
        << (isa<FunctionTemplateDecl>(Template)
3695
0
                ? 0
3696
0
                : isa<ClassTemplateDecl>(Template)
3697
0
                      ? 1
3698
0
                      : isa<VarTemplateDecl>(Template)
3699
0
                            ? 2
3700
0
                            : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3701
0
        << Template->getDeclName();
3702
0
    return;
3703
0
  }
3704
3705
0
  if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3706
0
    for (OverloadedTemplateStorage::iterator I = OST->begin(),
3707
0
                                          IEnd = OST->end();
3708
0
         I != IEnd; ++I)
3709
0
      Diag((*I)->getLocation(), diag::note_template_declared_here)
3710
0
        << 0 << (*I)->getDeclName();
3711
3712
0
    return;
3713
0
  }
3714
0
}
3715
3716
static QualType
3717
checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3718
                           ArrayRef<TemplateArgument> Converted,
3719
                           SourceLocation TemplateLoc,
3720
0
                           TemplateArgumentListInfo &TemplateArgs) {
3721
0
  ASTContext &Context = SemaRef.getASTContext();
3722
3723
0
  switch (BTD->getBuiltinTemplateKind()) {
3724
0
  case BTK__make_integer_seq: {
3725
    // Specializations of __make_integer_seq<S, T, N> are treated like
3726
    // S<T, 0, ..., N-1>.
3727
3728
0
    QualType OrigType = Converted[1].getAsType();
3729
    // C++14 [inteseq.intseq]p1:
3730
    //   T shall be an integer type.
3731
0
    if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3732
0
      SemaRef.Diag(TemplateArgs[1].getLocation(),
3733
0
                   diag::err_integer_sequence_integral_element_type);
3734
0
      return QualType();
3735
0
    }
3736
3737
0
    TemplateArgument NumArgsArg = Converted[2];
3738
0
    if (NumArgsArg.isDependent())
3739
0
      return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3740
0
                                                            Converted);
3741
3742
0
    TemplateArgumentListInfo SyntheticTemplateArgs;
3743
    // The type argument, wrapped in substitution sugar, gets reused as the
3744
    // first template argument in the synthetic template argument list.
3745
0
    SyntheticTemplateArgs.addArgument(
3746
0
        TemplateArgumentLoc(TemplateArgument(OrigType),
3747
0
                            SemaRef.Context.getTrivialTypeSourceInfo(
3748
0
                                OrigType, TemplateArgs[1].getLocation())));
3749
3750
0
    if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3751
      // Expand N into 0 ... N-1.
3752
0
      for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3753
0
           I < NumArgs; ++I) {
3754
0
        TemplateArgument TA(Context, I, OrigType);
3755
0
        SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3756
0
            TA, OrigType, TemplateArgs[2].getLocation()));
3757
0
      }
3758
0
    } else {
3759
      // C++14 [inteseq.make]p1:
3760
      //   If N is negative the program is ill-formed.
3761
0
      SemaRef.Diag(TemplateArgs[2].getLocation(),
3762
0
                   diag::err_integer_sequence_negative_length);
3763
0
      return QualType();
3764
0
    }
3765
3766
    // The first template argument will be reused as the template decl that
3767
    // our synthetic template arguments will be applied to.
3768
0
    return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3769
0
                                       TemplateLoc, SyntheticTemplateArgs);
3770
0
  }
3771
3772
0
  case BTK__type_pack_element:
3773
    // Specializations of
3774
    //    __type_pack_element<Index, T_1, ..., T_N>
3775
    // are treated like T_Index.
3776
0
    assert(Converted.size() == 2 &&
3777
0
      "__type_pack_element should be given an index and a parameter pack");
3778
3779
0
    TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3780
0
    if (IndexArg.isDependent() || Ts.isDependent())
3781
0
      return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3782
0
                                                            Converted);
3783
3784
0
    llvm::APSInt Index = IndexArg.getAsIntegral();
3785
0
    assert(Index >= 0 && "the index used with __type_pack_element should be of "
3786
0
                         "type std::size_t, and hence be non-negative");
3787
    // If the Index is out of bounds, the program is ill-formed.
3788
0
    if (Index >= Ts.pack_size()) {
3789
0
      SemaRef.Diag(TemplateArgs[0].getLocation(),
3790
0
                   diag::err_type_pack_element_out_of_bounds);
3791
0
      return QualType();
3792
0
    }
3793
3794
    // We simply return the type at index `Index`.
3795
0
    int64_t N = Index.getExtValue();
3796
0
    return Ts.getPackAsArray()[N].getAsType();
3797
0
  }
3798
0
  llvm_unreachable("unexpected BuiltinTemplateDecl!");
3799
0
}
3800
3801
/// Determine whether this alias template is "enable_if_t".
3802
/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3803
0
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3804
0
  return AliasTemplate->getName().equals("enable_if_t") ||
3805
0
         AliasTemplate->getName().equals("__enable_if_t");
3806
0
}
3807
3808
/// Collect all of the separable terms in the given condition, which
3809
/// might be a conjunction.
3810
///
3811
/// FIXME: The right answer is to convert the logical expression into
3812
/// disjunctive normal form, so we can find the first failed term
3813
/// within each possible clause.
3814
static void collectConjunctionTerms(Expr *Clause,
3815
0
                                    SmallVectorImpl<Expr *> &Terms) {
3816
0
  if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3817
0
    if (BinOp->getOpcode() == BO_LAnd) {
3818
0
      collectConjunctionTerms(BinOp->getLHS(), Terms);
3819
0
      collectConjunctionTerms(BinOp->getRHS(), Terms);
3820
0
      return;
3821
0
    }
3822
0
  }
3823
3824
0
  Terms.push_back(Clause);
3825
0
}
3826
3827
// The ranges-v3 library uses an odd pattern of a top-level "||" with
3828
// a left-hand side that is value-dependent but never true. Identify
3829
// the idiom and ignore that term.
3830
0
static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3831
  // Top-level '||'.
3832
0
  auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3833
0
  if (!BinOp) return Cond;
3834
3835
0
  if (BinOp->getOpcode() != BO_LOr) return Cond;
3836
3837
  // With an inner '==' that has a literal on the right-hand side.
3838
0
  Expr *LHS = BinOp->getLHS();
3839
0
  auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3840
0
  if (!InnerBinOp) return Cond;
3841
3842
0
  if (InnerBinOp->getOpcode() != BO_EQ ||
3843
0
      !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3844
0
    return Cond;
3845
3846
  // If the inner binary operation came from a macro expansion named
3847
  // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3848
  // of the '||', which is the real, user-provided condition.
3849
0
  SourceLocation Loc = InnerBinOp->getExprLoc();
3850
0
  if (!Loc.isMacroID()) return Cond;
3851
3852
0
  StringRef MacroName = PP.getImmediateMacroName(Loc);
3853
0
  if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3854
0
    return BinOp->getRHS();
3855
3856
0
  return Cond;
3857
0
}
3858
3859
namespace {
3860
3861
// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3862
// within failing boolean expression, such as substituting template parameters
3863
// for actual types.
3864
class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3865
public:
3866
  explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3867
0
      : Policy(P) {}
3868
3869
0
  bool handledStmt(Stmt *E, raw_ostream &OS) override {
3870
0
    const auto *DR = dyn_cast<DeclRefExpr>(E);
3871
0
    if (DR && DR->getQualifier()) {
3872
      // If this is a qualified name, expand the template arguments in nested
3873
      // qualifiers.
3874
0
      DR->getQualifier()->print(OS, Policy, true);
3875
      // Then print the decl itself.
3876
0
      const ValueDecl *VD = DR->getDecl();
3877
0
      OS << VD->getName();
3878
0
      if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3879
        // This is a template variable, print the expanded template arguments.
3880
0
        printTemplateArgumentList(
3881
0
            OS, IV->getTemplateArgs().asArray(), Policy,
3882
0
            IV->getSpecializedTemplate()->getTemplateParameters());
3883
0
      }
3884
0
      return true;
3885
0
    }
3886
0
    return false;
3887
0
  }
3888
3889
private:
3890
  const PrintingPolicy Policy;
3891
};
3892
3893
} // end anonymous namespace
3894
3895
std::pair<Expr *, std::string>
3896
0
Sema::findFailedBooleanCondition(Expr *Cond) {
3897
0
  Cond = lookThroughRangesV3Condition(PP, Cond);
3898
3899
  // Separate out all of the terms in a conjunction.
3900
0
  SmallVector<Expr *, 4> Terms;
3901
0
  collectConjunctionTerms(Cond, Terms);
3902
3903
  // Determine which term failed.
3904
0
  Expr *FailedCond = nullptr;
3905
0
  for (Expr *Term : Terms) {
3906
0
    Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3907
3908
    // Literals are uninteresting.
3909
0
    if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3910
0
        isa<IntegerLiteral>(TermAsWritten))
3911
0
      continue;
3912
3913
    // The initialization of the parameter from the argument is
3914
    // a constant-evaluated context.
3915
0
    EnterExpressionEvaluationContext ConstantEvaluated(
3916
0
      *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3917
3918
0
    bool Succeeded;
3919
0
    if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3920
0
        !Succeeded) {
3921
0
      FailedCond = TermAsWritten;
3922
0
      break;
3923
0
    }
3924
0
  }
3925
0
  if (!FailedCond)
3926
0
    FailedCond = Cond->IgnoreParenImpCasts();
3927
3928
0
  std::string Description;
3929
0
  {
3930
0
    llvm::raw_string_ostream Out(Description);
3931
0
    PrintingPolicy Policy = getPrintingPolicy();
3932
0
    Policy.PrintCanonicalTypes = true;
3933
0
    FailedBooleanConditionPrinterHelper Helper(Policy);
3934
0
    FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3935
0
  }
3936
0
  return { FailedCond, Description };
3937
0
}
3938
3939
QualType Sema::CheckTemplateIdType(TemplateName Name,
3940
                                   SourceLocation TemplateLoc,
3941
0
                                   TemplateArgumentListInfo &TemplateArgs) {
3942
0
  DependentTemplateName *DTN
3943
0
    = Name.getUnderlying().getAsDependentTemplateName();
3944
0
  if (DTN && DTN->isIdentifier())
3945
    // When building a template-id where the template-name is dependent,
3946
    // assume the template is a type template. Either our assumption is
3947
    // correct, or the code is ill-formed and will be diagnosed when the
3948
    // dependent name is substituted.
3949
0
    return Context.getDependentTemplateSpecializationType(
3950
0
        ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3951
0
        TemplateArgs.arguments());
3952
3953
0
  if (Name.getAsAssumedTemplateName() &&
3954
0
      resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3955
0
    return QualType();
3956
3957
0
  TemplateDecl *Template = Name.getAsTemplateDecl();
3958
0
  if (!Template || isa<FunctionTemplateDecl>(Template) ||
3959
0
      isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3960
    // We might have a substituted template template parameter pack. If so,
3961
    // build a template specialization type for it.
3962
0
    if (Name.getAsSubstTemplateTemplateParmPack())
3963
0
      return Context.getTemplateSpecializationType(Name,
3964
0
                                                   TemplateArgs.arguments());
3965
3966
0
    Diag(TemplateLoc, diag::err_template_id_not_a_type)
3967
0
      << Name;
3968
0
    NoteAllFoundTemplates(Name);
3969
0
    return QualType();
3970
0
  }
3971
3972
  // Check that the template argument list is well-formed for this
3973
  // template.
3974
0
  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3975
0
  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
3976
0
                                SugaredConverted, CanonicalConverted,
3977
0
                                /*UpdateArgsWithConversions=*/true))
3978
0
    return QualType();
3979
3980
0
  QualType CanonType;
3981
3982
0
  if (TypeAliasTemplateDecl *AliasTemplate =
3983
0
          dyn_cast<TypeAliasTemplateDecl>(Template)) {
3984
3985
    // Find the canonical type for this type alias template specialization.
3986
0
    TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3987
0
    if (Pattern->isInvalidDecl())
3988
0
      return QualType();
3989
3990
    // Only substitute for the innermost template argument list.
3991
0
    MultiLevelTemplateArgumentList TemplateArgLists;
3992
0
    TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
3993
0
                                               /*Final=*/false);
3994
0
    TemplateArgLists.addOuterRetainedLevels(
3995
0
        AliasTemplate->getTemplateParameters()->getDepth());
3996
3997
0
    LocalInstantiationScope Scope(*this);
3998
0
    InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3999
0
    if (Inst.isInvalid())
4000
0
      return QualType();
4001
4002
0
    CanonType = SubstType(Pattern->getUnderlyingType(),
4003
0
                          TemplateArgLists, AliasTemplate->getLocation(),
4004
0
                          AliasTemplate->getDeclName());
4005
0
    if (CanonType.isNull()) {
4006
      // If this was enable_if and we failed to find the nested type
4007
      // within enable_if in a SFINAE context, dig out the specific
4008
      // enable_if condition that failed and present that instead.
4009
0
      if (isEnableIfAliasTemplate(AliasTemplate)) {
4010
0
        if (auto DeductionInfo = isSFINAEContext()) {
4011
0
          if (*DeductionInfo &&
4012
0
              (*DeductionInfo)->hasSFINAEDiagnostic() &&
4013
0
              (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
4014
0
                diag::err_typename_nested_not_found_enable_if &&
4015
0
              TemplateArgs[0].getArgument().getKind()
4016
0
                == TemplateArgument::Expression) {
4017
0
            Expr *FailedCond;
4018
0
            std::string FailedDescription;
4019
0
            std::tie(FailedCond, FailedDescription) =
4020
0
              findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
4021
4022
            // Remove the old SFINAE diagnostic.
4023
0
            PartialDiagnosticAt OldDiag =
4024
0
              {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
4025
0
            (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
4026
4027
            // Add a new SFINAE diagnostic specifying which condition
4028
            // failed.
4029
0
            (*DeductionInfo)->addSFINAEDiagnostic(
4030
0
              OldDiag.first,
4031
0
              PDiag(diag::err_typename_nested_not_found_requirement)
4032
0
                << FailedDescription
4033
0
                << FailedCond->getSourceRange());
4034
0
          }
4035
0
        }
4036
0
      }
4037
4038
0
      return QualType();
4039
0
    }
4040
0
  } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
4041
0
    CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
4042
0
                                           TemplateLoc, TemplateArgs);
4043
0
  } else if (Name.isDependent() ||
4044
0
             TemplateSpecializationType::anyDependentTemplateArguments(
4045
0
                 TemplateArgs, CanonicalConverted)) {
4046
    // This class template specialization is a dependent
4047
    // type. Therefore, its canonical type is another class template
4048
    // specialization type that contains all of the converted
4049
    // arguments in canonical form. This ensures that, e.g., A<T> and
4050
    // A<T, T> have identical types when A is declared as:
4051
    //
4052
    //   template<typename T, typename U = T> struct A;
4053
0
    CanonType = Context.getCanonicalTemplateSpecializationType(
4054
0
        Name, CanonicalConverted);
4055
4056
    // This might work out to be a current instantiation, in which
4057
    // case the canonical type needs to be the InjectedClassNameType.
4058
    //
4059
    // TODO: in theory this could be a simple hashtable lookup; most
4060
    // changes to CurContext don't change the set of current
4061
    // instantiations.
4062
0
    if (isa<ClassTemplateDecl>(Template)) {
4063
0
      for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
4064
        // If we get out to a namespace, we're done.
4065
0
        if (Ctx->isFileContext()) break;
4066
4067
        // If this isn't a record, keep looking.
4068
0
        CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
4069
0
        if (!Record) continue;
4070
4071
        // Look for one of the two cases with InjectedClassNameTypes
4072
        // and check whether it's the same template.
4073
0
        if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
4074
0
            !Record->getDescribedClassTemplate())
4075
0
          continue;
4076
4077
        // Fetch the injected class name type and check whether its
4078
        // injected type is equal to the type we just built.
4079
0
        QualType ICNT = Context.getTypeDeclType(Record);
4080
0
        QualType Injected = cast<InjectedClassNameType>(ICNT)
4081
0
          ->getInjectedSpecializationType();
4082
4083
0
        if (CanonType != Injected->getCanonicalTypeInternal())
4084
0
          continue;
4085
4086
        // If so, the canonical type of this TST is the injected
4087
        // class name type of the record we just found.
4088
0
        assert(ICNT.isCanonical());
4089
0
        CanonType = ICNT;
4090
0
        break;
4091
0
      }
4092
0
    }
4093
0
  } else if (ClassTemplateDecl *ClassTemplate =
4094
0
                 dyn_cast<ClassTemplateDecl>(Template)) {
4095
    // Find the class template specialization declaration that
4096
    // corresponds to these arguments.
4097
0
    void *InsertPos = nullptr;
4098
0
    ClassTemplateSpecializationDecl *Decl =
4099
0
        ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
4100
0
    if (!Decl) {
4101
      // This is the first time we have referenced this class template
4102
      // specialization. Create the canonical declaration and add it to
4103
      // the set of specializations.
4104
0
      Decl = ClassTemplateSpecializationDecl::Create(
4105
0
          Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
4106
0
          ClassTemplate->getDeclContext(),
4107
0
          ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4108
0
          ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
4109
0
          nullptr);
4110
0
      ClassTemplate->AddSpecialization(Decl, InsertPos);
4111
0
      if (ClassTemplate->isOutOfLine())
4112
0
        Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4113
0
    }
4114
4115
0
    if (Decl->getSpecializationKind() == TSK_Undeclared &&
4116
0
        ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4117
0
      InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4118
0
      if (!Inst.isInvalid()) {
4119
0
        MultiLevelTemplateArgumentList TemplateArgLists(Template,
4120
0
                                                        CanonicalConverted,
4121
0
                                                        /*Final=*/false);
4122
0
        InstantiateAttrsForDecl(TemplateArgLists,
4123
0
                                ClassTemplate->getTemplatedDecl(), Decl);
4124
0
      }
4125
0
    }
4126
4127
    // Diagnose uses of this specialization.
4128
0
    (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4129
4130
0
    CanonType = Context.getTypeDeclType(Decl);
4131
0
    assert(isa<RecordType>(CanonType) &&
4132
0
           "type of non-dependent specialization is not a RecordType");
4133
0
  } else {
4134
0
    llvm_unreachable("Unhandled template kind");
4135
0
  }
4136
4137
  // Build the fully-sugared type for this class template
4138
  // specialization, which refers back to the class template
4139
  // specialization we created or found.
4140
0
  return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
4141
0
                                               CanonType);
4142
0
}
4143
4144
void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
4145
                                           TemplateNameKind &TNK,
4146
                                           SourceLocation NameLoc,
4147
0
                                           IdentifierInfo *&II) {
4148
0
  assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4149
4150
0
  TemplateName Name = ParsedName.get();
4151
0
  auto *ATN = Name.getAsAssumedTemplateName();
4152
0
  assert(ATN && "not an assumed template name");
4153
0
  II = ATN->getDeclName().getAsIdentifierInfo();
4154
4155
0
  if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
4156
    // Resolved to a type template name.
4157
0
    ParsedName = TemplateTy::make(Name);
4158
0
    TNK = TNK_Type_template;
4159
0
  }
4160
0
}
4161
4162
bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
4163
                                            SourceLocation NameLoc,
4164
1
                                            bool Diagnose) {
4165
  // We assumed this undeclared identifier to be an (ADL-only) function
4166
  // template name, but it was used in a context where a type was required.
4167
  // Try to typo-correct it now.
4168
1
  AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
4169
1
  assert(ATN && "not an assumed template name");
4170
4171
0
  LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
4172
1
  struct CandidateCallback : CorrectionCandidateCallback {
4173
1
    bool ValidateCandidate(const TypoCorrection &TC) override {
4174
0
      return TC.getCorrectionDecl() &&
4175
0
             getAsTypeTemplateDecl(TC.getCorrectionDecl());
4176
0
    }
4177
1
    std::unique_ptr<CorrectionCandidateCallback> clone() override {
4178
0
      return std::make_unique<CandidateCallback>(*this);
4179
0
    }
4180
1
  } FilterCCC;
4181
4182
1
  TypoCorrection Corrected =
4183
1
      CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
4184
1
                  FilterCCC, CTK_ErrorRecovery);
4185
1
  if (Corrected && Corrected.getFoundDecl()) {
4186
0
    diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
4187
0
                                << ATN->getDeclName());
4188
0
    Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
4189
0
    return false;
4190
0
  }
4191
4192
1
  if (Diagnose)
4193
1
    Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
4194
1
  return true;
4195
1
}
4196
4197
TypeResult Sema::ActOnTemplateIdType(
4198
    Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4199
    TemplateTy TemplateD, IdentifierInfo *TemplateII,
4200
    SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
4201
    ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
4202
    bool IsCtorOrDtorName, bool IsClassName,
4203
1
    ImplicitTypenameContext AllowImplicitTypename) {
4204
1
  if (SS.isInvalid())
4205
0
    return true;
4206
4207
1
  if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4208
0
    DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4209
4210
    // C++ [temp.res]p3:
4211
    //   A qualified-id that refers to a type and in which the
4212
    //   nested-name-specifier depends on a template-parameter (14.6.2)
4213
    //   shall be prefixed by the keyword typename to indicate that the
4214
    //   qualified-id denotes a type, forming an
4215
    //   elaborated-type-specifier (7.1.5.3).
4216
0
    if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4217
      // C++2a relaxes some of those restrictions in [temp.res]p5.
4218
0
      if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4219
0
        if (getLangOpts().CPlusPlus20)
4220
0
          Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
4221
0
        else
4222
0
          Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
4223
0
              << SS.getScopeRep() << TemplateII->getName()
4224
0
              << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4225
0
      } else
4226
0
        Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
4227
0
            << SS.getScopeRep() << TemplateII->getName();
4228
4229
      // FIXME: This is not quite correct recovery as we don't transform SS
4230
      // into the corresponding dependent form (and we don't diagnose missing
4231
      // 'template' keywords within SS as a result).
4232
0
      return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4233
0
                               TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4234
0
                               TemplateArgsIn, RAngleLoc);
4235
0
    }
4236
4237
    // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4238
    // it's not actually allowed to be used as a type in most cases. Because
4239
    // we annotate it before we know whether it's valid, we have to check for
4240
    // this case here.
4241
0
    auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4242
0
    if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4243
0
      Diag(TemplateIILoc,
4244
0
           TemplateKWLoc.isInvalid()
4245
0
               ? diag::err_out_of_line_qualified_id_type_names_constructor
4246
0
               : diag::ext_out_of_line_qualified_id_type_names_constructor)
4247
0
        << TemplateII << 0 /*injected-class-name used as template name*/
4248
0
        << 1 /*if any keyword was present, it was 'template'*/;
4249
0
    }
4250
0
  }
4251
4252
1
  TemplateName Template = TemplateD.get();
4253
1
  if (Template.getAsAssumedTemplateName() &&
4254
1
      resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4255
1
    return true;
4256
4257
  // Translate the parser's template argument list in our AST format.
4258
0
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4259
0
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4260
4261
0
  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4262
0
    assert(SS.getScopeRep() == DTN->getQualifier());
4263
0
    QualType T = Context.getDependentTemplateSpecializationType(
4264
0
        ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
4265
0
        TemplateArgs.arguments());
4266
    // Build type-source information.
4267
0
    TypeLocBuilder TLB;
4268
0
    DependentTemplateSpecializationTypeLoc SpecTL
4269
0
      = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4270
0
    SpecTL.setElaboratedKeywordLoc(SourceLocation());
4271
0
    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4272
0
    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4273
0
    SpecTL.setTemplateNameLoc(TemplateIILoc);
4274
0
    SpecTL.setLAngleLoc(LAngleLoc);
4275
0
    SpecTL.setRAngleLoc(RAngleLoc);
4276
0
    for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4277
0
      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4278
0
    return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4279
0
  }
4280
4281
0
  QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
4282
0
  if (SpecTy.isNull())
4283
0
    return true;
4284
4285
  // Build type-source information.
4286
0
  TypeLocBuilder TLB;
4287
0
  TemplateSpecializationTypeLoc SpecTL =
4288
0
      TLB.push<TemplateSpecializationTypeLoc>(SpecTy);
4289
0
  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4290
0
  SpecTL.setTemplateNameLoc(TemplateIILoc);
4291
0
  SpecTL.setLAngleLoc(LAngleLoc);
4292
0
  SpecTL.setRAngleLoc(RAngleLoc);
4293
0
  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4294
0
    SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4295
4296
  // Create an elaborated-type-specifier containing the nested-name-specifier.
4297
0
  QualType ElTy =
4298
0
      getElaboratedType(ElaboratedTypeKeyword::None,
4299
0
                        !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
4300
0
  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
4301
0
  ElabTL.setElaboratedKeywordLoc(SourceLocation());
4302
0
  if (!ElabTL.isEmpty())
4303
0
    ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4304
0
  return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
4305
0
}
4306
4307
TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4308
                                        TypeSpecifierType TagSpec,
4309
                                        SourceLocation TagLoc,
4310
                                        CXXScopeSpec &SS,
4311
                                        SourceLocation TemplateKWLoc,
4312
                                        TemplateTy TemplateD,
4313
                                        SourceLocation TemplateLoc,
4314
                                        SourceLocation LAngleLoc,
4315
                                        ASTTemplateArgsPtr TemplateArgsIn,
4316
0
                                        SourceLocation RAngleLoc) {
4317
0
  if (SS.isInvalid())
4318
0
    return TypeResult(true);
4319
4320
0
  TemplateName Template = TemplateD.get();
4321
4322
  // Translate the parser's template argument list in our AST format.
4323
0
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4324
0
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4325
4326
  // Determine the tag kind
4327
0
  TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4328
0
  ElaboratedTypeKeyword Keyword
4329
0
    = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
4330
4331
0
  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4332
0
    assert(SS.getScopeRep() == DTN->getQualifier());
4333
0
    QualType T = Context.getDependentTemplateSpecializationType(
4334
0
        Keyword, DTN->getQualifier(), DTN->getIdentifier(),
4335
0
        TemplateArgs.arguments());
4336
4337
    // Build type-source information.
4338
0
    TypeLocBuilder TLB;
4339
0
    DependentTemplateSpecializationTypeLoc SpecTL
4340
0
      = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4341
0
    SpecTL.setElaboratedKeywordLoc(TagLoc);
4342
0
    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4343
0
    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4344
0
    SpecTL.setTemplateNameLoc(TemplateLoc);
4345
0
    SpecTL.setLAngleLoc(LAngleLoc);
4346
0
    SpecTL.setRAngleLoc(RAngleLoc);
4347
0
    for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4348
0
      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4349
0
    return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4350
0
  }
4351
4352
0
  if (TypeAliasTemplateDecl *TAT =
4353
0
        dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4354
    // C++0x [dcl.type.elab]p2:
4355
    //   If the identifier resolves to a typedef-name or the simple-template-id
4356
    //   resolves to an alias template specialization, the
4357
    //   elaborated-type-specifier is ill-formed.
4358
0
    Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4359
0
        << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
4360
0
    Diag(TAT->getLocation(), diag::note_declared_at);
4361
0
  }
4362
4363
0
  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4364
0
  if (Result.isNull())
4365
0
    return TypeResult(true);
4366
4367
  // Check the tag kind
4368
0
  if (const RecordType *RT = Result->getAs<RecordType>()) {
4369
0
    RecordDecl *D = RT->getDecl();
4370
4371
0
    IdentifierInfo *Id = D->getIdentifier();
4372
0
    assert(Id && "templated class must have an identifier");
4373
4374
0
    if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4375
0
                                      TagLoc, Id)) {
4376
0
      Diag(TagLoc, diag::err_use_with_wrong_tag)
4377
0
        << Result
4378
0
        << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
4379
0
      Diag(D->getLocation(), diag::note_previous_use);
4380
0
    }
4381
0
  }
4382
4383
  // Provide source-location information for the template specialization.
4384
0
  TypeLocBuilder TLB;
4385
0
  TemplateSpecializationTypeLoc SpecTL
4386
0
    = TLB.push<TemplateSpecializationTypeLoc>(Result);
4387
0
  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4388
0
  SpecTL.setTemplateNameLoc(TemplateLoc);
4389
0
  SpecTL.setLAngleLoc(LAngleLoc);
4390
0
  SpecTL.setRAngleLoc(RAngleLoc);
4391
0
  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4392
0
    SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4393
4394
  // Construct an elaborated type containing the nested-name-specifier (if any)
4395
  // and tag keyword.
4396
0
  Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
4397
0
  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
4398
0
  ElabTL.setElaboratedKeywordLoc(TagLoc);
4399
0
  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4400
0
  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
4401
0
}
4402
4403
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4404
                                             NamedDecl *PrevDecl,
4405
                                             SourceLocation Loc,
4406
                                             bool IsPartialSpecialization);
4407
4408
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4409
4410
static bool isTemplateArgumentTemplateParameter(
4411
0
    const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4412
0
  switch (Arg.getKind()) {
4413
0
  case TemplateArgument::Null:
4414
0
  case TemplateArgument::NullPtr:
4415
0
  case TemplateArgument::Integral:
4416
0
  case TemplateArgument::Declaration:
4417
0
  case TemplateArgument::Pack:
4418
0
  case TemplateArgument::TemplateExpansion:
4419
0
    return false;
4420
4421
0
  case TemplateArgument::Type: {
4422
0
    QualType Type = Arg.getAsType();
4423
0
    const TemplateTypeParmType *TPT =
4424
0
        Arg.getAsType()->getAs<TemplateTypeParmType>();
4425
0
    return TPT && !Type.hasQualifiers() &&
4426
0
           TPT->getDepth() == Depth && TPT->getIndex() == Index;
4427
0
  }
4428
4429
0
  case TemplateArgument::Expression: {
4430
0
    DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4431
0
    if (!DRE || !DRE->getDecl())
4432
0
      return false;
4433
0
    const NonTypeTemplateParmDecl *NTTP =
4434
0
        dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4435
0
    return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4436
0
  }
4437
4438
0
  case TemplateArgument::Template:
4439
0
    const TemplateTemplateParmDecl *TTP =
4440
0
        dyn_cast_or_null<TemplateTemplateParmDecl>(
4441
0
            Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4442
0
    return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4443
0
  }
4444
0
  llvm_unreachable("unexpected kind of template argument");
4445
0
}
4446
4447
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4448
0
                                    ArrayRef<TemplateArgument> Args) {
4449
0
  if (Params->size() != Args.size())
4450
0
    return false;
4451
4452
0
  unsigned Depth = Params->getDepth();
4453
4454
0
  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4455
0
    TemplateArgument Arg = Args[I];
4456
4457
    // If the parameter is a pack expansion, the argument must be a pack
4458
    // whose only element is a pack expansion.
4459
0
    if (Params->getParam(I)->isParameterPack()) {
4460
0
      if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4461
0
          !Arg.pack_begin()->isPackExpansion())
4462
0
        return false;
4463
0
      Arg = Arg.pack_begin()->getPackExpansionPattern();
4464
0
    }
4465
4466
0
    if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4467
0
      return false;
4468
0
  }
4469
4470
0
  return true;
4471
0
}
4472
4473
template<typename PartialSpecDecl>
4474
0
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4475
0
  if (Partial->getDeclContext()->isDependentContext())
4476
0
    return;
4477
4478
  // FIXME: Get the TDK from deduction in order to provide better diagnostics
4479
  // for non-substitution-failure issues?
4480
0
  TemplateDeductionInfo Info(Partial->getLocation());
4481
0
  if (S.isMoreSpecializedThanPrimary(Partial, Info))
4482
0
    return;
4483
4484
0
  auto *Template = Partial->getSpecializedTemplate();
4485
0
  S.Diag(Partial->getLocation(),
4486
0
         diag::ext_partial_spec_not_more_specialized_than_primary)
4487
0
      << isa<VarTemplateDecl>(Template);
4488
4489
0
  if (Info.hasSFINAEDiagnostic()) {
4490
0
    PartialDiagnosticAt Diag = {SourceLocation(),
4491
0
                                PartialDiagnostic::NullDiagnostic()};
4492
0
    Info.takeSFINAEDiagnostic(Diag);
4493
0
    SmallString<128> SFINAEArgString;
4494
0
    Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4495
0
    S.Diag(Diag.first,
4496
0
           diag::note_partial_spec_not_more_specialized_than_primary)
4497
0
      << SFINAEArgString;
4498
0
  }
4499
4500
0
  S.NoteTemplateLocation(*Template);
4501
0
  SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4502
0
  Template->getAssociatedConstraints(TemplateAC);
4503
0
  Partial->getAssociatedConstraints(PartialAC);
4504
0
  S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4505
0
                                                  TemplateAC);
4506
0
}
Unexecuted instantiation: SemaTemplate.cpp:void checkMoreSpecializedThanPrimary<clang::ClassTemplatePartialSpecializationDecl>(clang::Sema&, clang::ClassTemplatePartialSpecializationDecl*)
Unexecuted instantiation: SemaTemplate.cpp:void checkMoreSpecializedThanPrimary<clang::VarTemplatePartialSpecializationDecl>(clang::Sema&, clang::VarTemplatePartialSpecializationDecl*)
4507
4508
static void
4509
noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4510
0
                           const llvm::SmallBitVector &DeducibleParams) {
4511
0
  for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4512
0
    if (!DeducibleParams[I]) {
4513
0
      NamedDecl *Param = TemplateParams->getParam(I);
4514
0
      if (Param->getDeclName())
4515
0
        S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4516
0
            << Param->getDeclName();
4517
0
      else
4518
0
        S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4519
0
            << "(anonymous)";
4520
0
    }
4521
0
  }
4522
0
}
4523
4524
4525
template<typename PartialSpecDecl>
4526
static void checkTemplatePartialSpecialization(Sema &S,
4527
0
                                               PartialSpecDecl *Partial) {
4528
  // C++1z [temp.class.spec]p8: (DR1495)
4529
  //   - The specialization shall be more specialized than the primary
4530
  //     template (14.5.5.2).
4531
0
  checkMoreSpecializedThanPrimary(S, Partial);
4532
4533
  // C++ [temp.class.spec]p8: (DR1315)
4534
  //   - Each template-parameter shall appear at least once in the
4535
  //     template-id outside a non-deduced context.
4536
  // C++1z [temp.class.spec.match]p3 (P0127R2)
4537
  //   If the template arguments of a partial specialization cannot be
4538
  //   deduced because of the structure of its template-parameter-list
4539
  //   and the template-id, the program is ill-formed.
4540
0
  auto *TemplateParams = Partial->getTemplateParameters();
4541
0
  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4542
0
  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4543
0
                               TemplateParams->getDepth(), DeducibleParams);
4544
4545
0
  if (!DeducibleParams.all()) {
4546
0
    unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4547
0
    S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4548
0
      << isa<VarTemplatePartialSpecializationDecl>(Partial)
4549
0
      << (NumNonDeducible > 1)
4550
0
      << SourceRange(Partial->getLocation(),
4551
0
                     Partial->getTemplateArgsAsWritten()->RAngleLoc);
4552
0
    noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4553
0
  }
4554
0
}
Unexecuted instantiation: SemaTemplate.cpp:void checkTemplatePartialSpecialization<clang::ClassTemplatePartialSpecializationDecl>(clang::Sema&, clang::ClassTemplatePartialSpecializationDecl*)
Unexecuted instantiation: SemaTemplate.cpp:void checkTemplatePartialSpecialization<clang::VarTemplatePartialSpecializationDecl>(clang::Sema&, clang::VarTemplatePartialSpecializationDecl*)
4555
4556
void Sema::CheckTemplatePartialSpecialization(
4557
0
    ClassTemplatePartialSpecializationDecl *Partial) {
4558
0
  checkTemplatePartialSpecialization(*this, Partial);
4559
0
}
4560
4561
void Sema::CheckTemplatePartialSpecialization(
4562
0
    VarTemplatePartialSpecializationDecl *Partial) {
4563
0
  checkTemplatePartialSpecialization(*this, Partial);
4564
0
}
4565
4566
0
void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4567
  // C++1z [temp.param]p11:
4568
  //   A template parameter of a deduction guide template that does not have a
4569
  //   default-argument shall be deducible from the parameter-type-list of the
4570
  //   deduction guide template.
4571
0
  auto *TemplateParams = TD->getTemplateParameters();
4572
0
  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4573
0
  MarkDeducedTemplateParameters(TD, DeducibleParams);
4574
0
  for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4575
    // A parameter pack is deducible (to an empty pack).
4576
0
    auto *Param = TemplateParams->getParam(I);
4577
0
    if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4578
0
      DeducibleParams[I] = true;
4579
0
  }
4580
4581
0
  if (!DeducibleParams.all()) {
4582
0
    unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4583
0
    Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4584
0
      << (NumNonDeducible > 1);
4585
0
    noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4586
0
  }
4587
0
}
4588
4589
DeclResult Sema::ActOnVarTemplateSpecialization(
4590
    Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
4591
    TemplateParameterList *TemplateParams, StorageClass SC,
4592
0
    bool IsPartialSpecialization) {
4593
  // D must be variable template id.
4594
0
  assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4595
0
         "Variable template specialization is declared with a template id.");
4596
4597
0
  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4598
0
  TemplateArgumentListInfo TemplateArgs =
4599
0
      makeTemplateArgumentListInfo(*this, *TemplateId);
4600
0
  SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4601
0
  SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4602
0
  SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4603
4604
0
  TemplateName Name = TemplateId->Template.get();
4605
4606
  // The template-id must name a variable template.
4607
0
  VarTemplateDecl *VarTemplate =
4608
0
      dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4609
0
  if (!VarTemplate) {
4610
0
    NamedDecl *FnTemplate;
4611
0
    if (auto *OTS = Name.getAsOverloadedTemplate())
4612
0
      FnTemplate = *OTS->begin();
4613
0
    else
4614
0
      FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4615
0
    if (FnTemplate)
4616
0
      return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4617
0
               << FnTemplate->getDeclName();
4618
0
    return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4619
0
             << IsPartialSpecialization;
4620
0
  }
4621
4622
  // Check for unexpanded parameter packs in any of the template arguments.
4623
0
  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4624
0
    if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4625
0
                                        IsPartialSpecialization
4626
0
                                            ? UPPC_PartialSpecialization
4627
0
                                            : UPPC_ExplicitSpecialization))
4628
0
      return true;
4629
4630
  // Check that the template argument list is well-formed for this
4631
  // template.
4632
0
  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4633
0
  if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4634
0
                                false, SugaredConverted, CanonicalConverted,
4635
0
                                /*UpdateArgsWithConversions=*/true))
4636
0
    return true;
4637
4638
  // Find the variable template (partial) specialization declaration that
4639
  // corresponds to these arguments.
4640
0
  if (IsPartialSpecialization) {
4641
0
    if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4642
0
                                               TemplateArgs.size(),
4643
0
                                               CanonicalConverted))
4644
0
      return true;
4645
4646
    // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4647
    // also do them during instantiation.
4648
0
    if (!Name.isDependent() &&
4649
0
        !TemplateSpecializationType::anyDependentTemplateArguments(
4650
0
            TemplateArgs, CanonicalConverted)) {
4651
0
      Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4652
0
          << VarTemplate->getDeclName();
4653
0
      IsPartialSpecialization = false;
4654
0
    }
4655
4656
0
    if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4657
0
                                CanonicalConverted) &&
4658
0
        (!Context.getLangOpts().CPlusPlus20 ||
4659
0
         !TemplateParams->hasAssociatedConstraints())) {
4660
      // C++ [temp.class.spec]p9b3:
4661
      //
4662
      //   -- The argument list of the specialization shall not be identical
4663
      //      to the implicit argument list of the primary template.
4664
0
      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4665
0
        << /*variable template*/ 1
4666
0
        << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4667
0
        << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4668
      // FIXME: Recover from this by treating the declaration as a redeclaration
4669
      // of the primary template.
4670
0
      return true;
4671
0
    }
4672
0
  }
4673
4674
0
  void *InsertPos = nullptr;
4675
0
  VarTemplateSpecializationDecl *PrevDecl = nullptr;
4676
4677
0
  if (IsPartialSpecialization)
4678
0
    PrevDecl = VarTemplate->findPartialSpecialization(
4679
0
        CanonicalConverted, TemplateParams, InsertPos);
4680
0
  else
4681
0
    PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4682
4683
0
  VarTemplateSpecializationDecl *Specialization = nullptr;
4684
4685
  // Check whether we can declare a variable template specialization in
4686
  // the current scope.
4687
0
  if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4688
0
                                       TemplateNameLoc,
4689
0
                                       IsPartialSpecialization))
4690
0
    return true;
4691
4692
0
  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4693
    // Since the only prior variable template specialization with these
4694
    // arguments was referenced but not declared,  reuse that
4695
    // declaration node as our own, updating its source location and
4696
    // the list of outer template parameters to reflect our new declaration.
4697
0
    Specialization = PrevDecl;
4698
0
    Specialization->setLocation(TemplateNameLoc);
4699
0
    PrevDecl = nullptr;
4700
0
  } else if (IsPartialSpecialization) {
4701
    // Create a new class template partial specialization declaration node.
4702
0
    VarTemplatePartialSpecializationDecl *PrevPartial =
4703
0
        cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4704
0
    VarTemplatePartialSpecializationDecl *Partial =
4705
0
        VarTemplatePartialSpecializationDecl::Create(
4706
0
            Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4707
0
            TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4708
0
            CanonicalConverted, TemplateArgs);
4709
4710
0
    if (!PrevPartial)
4711
0
      VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4712
0
    Specialization = Partial;
4713
4714
    // If we are providing an explicit specialization of a member variable
4715
    // template specialization, make a note of that.
4716
0
    if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4717
0
      PrevPartial->setMemberSpecialization();
4718
4719
0
    CheckTemplatePartialSpecialization(Partial);
4720
0
  } else {
4721
    // Create a new class template specialization declaration node for
4722
    // this explicit specialization or friend declaration.
4723
0
    Specialization = VarTemplateSpecializationDecl::Create(
4724
0
        Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4725
0
        VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4726
0
    Specialization->setTemplateArgsInfo(TemplateArgs);
4727
4728
0
    if (!PrevDecl)
4729
0
      VarTemplate->AddSpecialization(Specialization, InsertPos);
4730
0
  }
4731
4732
  // C++ [temp.expl.spec]p6:
4733
  //   If a template, a member template or the member of a class template is
4734
  //   explicitly specialized then that specialization shall be declared
4735
  //   before the first use of that specialization that would cause an implicit
4736
  //   instantiation to take place, in every translation unit in which such a
4737
  //   use occurs; no diagnostic is required.
4738
0
  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4739
0
    bool Okay = false;
4740
0
    for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4741
      // Is there any previous explicit specialization declaration?
4742
0
      if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4743
0
        Okay = true;
4744
0
        break;
4745
0
      }
4746
0
    }
4747
4748
0
    if (!Okay) {
4749
0
      SourceRange Range(TemplateNameLoc, RAngleLoc);
4750
0
      Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4751
0
          << Name << Range;
4752
4753
0
      Diag(PrevDecl->getPointOfInstantiation(),
4754
0
           diag::note_instantiation_required_here)
4755
0
          << (PrevDecl->getTemplateSpecializationKind() !=
4756
0
              TSK_ImplicitInstantiation);
4757
0
      return true;
4758
0
    }
4759
0
  }
4760
4761
0
  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4762
0
  Specialization->setLexicalDeclContext(CurContext);
4763
4764
  // Add the specialization into its lexical context, so that it can
4765
  // be seen when iterating through the list of declarations in that
4766
  // context. However, specializations are not found by name lookup.
4767
0
  CurContext->addDecl(Specialization);
4768
4769
  // Note that this is an explicit specialization.
4770
0
  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4771
4772
0
  if (PrevDecl) {
4773
    // Check that this isn't a redefinition of this specialization,
4774
    // merging with previous declarations.
4775
0
    LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4776
0
                          forRedeclarationInCurContext());
4777
0
    PrevSpec.addDecl(PrevDecl);
4778
0
    D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4779
0
  } else if (Specialization->isStaticDataMember() &&
4780
0
             Specialization->isOutOfLine()) {
4781
0
    Specialization->setAccess(VarTemplate->getAccess());
4782
0
  }
4783
4784
0
  return Specialization;
4785
0
}
4786
4787
namespace {
4788
/// A partial specialization whose template arguments have matched
4789
/// a given template-id.
4790
struct PartialSpecMatchResult {
4791
  VarTemplatePartialSpecializationDecl *Partial;
4792
  TemplateArgumentList *Args;
4793
};
4794
} // end anonymous namespace
4795
4796
DeclResult
4797
Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4798
                         SourceLocation TemplateNameLoc,
4799
0
                         const TemplateArgumentListInfo &TemplateArgs) {
4800
0
  assert(Template && "A variable template id without template?");
4801
4802
  // Check that the template argument list is well-formed for this template.
4803
0
  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4804
0
  if (CheckTemplateArgumentList(
4805
0
          Template, TemplateNameLoc,
4806
0
          const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4807
0
          SugaredConverted, CanonicalConverted,
4808
0
          /*UpdateArgsWithConversions=*/true))
4809
0
    return true;
4810
4811
  // Produce a placeholder value if the specialization is dependent.
4812
0
  if (Template->getDeclContext()->isDependentContext() ||
4813
0
      TemplateSpecializationType::anyDependentTemplateArguments(
4814
0
          TemplateArgs, CanonicalConverted))
4815
0
    return DeclResult();
4816
4817
  // Find the variable template specialization declaration that
4818
  // corresponds to these arguments.
4819
0
  void *InsertPos = nullptr;
4820
0
  if (VarTemplateSpecializationDecl *Spec =
4821
0
          Template->findSpecialization(CanonicalConverted, InsertPos)) {
4822
0
    checkSpecializationReachability(TemplateNameLoc, Spec);
4823
    // If we already have a variable template specialization, return it.
4824
0
    return Spec;
4825
0
  }
4826
4827
  // This is the first time we have referenced this variable template
4828
  // specialization. Create the canonical declaration and add it to
4829
  // the set of specializations, based on the closest partial specialization
4830
  // that it represents. That is,
4831
0
  VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4832
0
  TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4833
0
                                       CanonicalConverted);
4834
0
  TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4835
0
  bool AmbiguousPartialSpec = false;
4836
0
  typedef PartialSpecMatchResult MatchResult;
4837
0
  SmallVector<MatchResult, 4> Matched;
4838
0
  SourceLocation PointOfInstantiation = TemplateNameLoc;
4839
0
  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4840
0
                                            /*ForTakingAddress=*/false);
4841
4842
  // 1. Attempt to find the closest partial specialization that this
4843
  // specializes, if any.
4844
  // TODO: Unify with InstantiateClassTemplateSpecialization()?
4845
  //       Perhaps better after unification of DeduceTemplateArguments() and
4846
  //       getMoreSpecializedPartialSpecialization().
4847
0
  SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4848
0
  Template->getPartialSpecializations(PartialSpecs);
4849
4850
0
  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4851
0
    VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4852
0
    TemplateDeductionInfo Info(FailedCandidates.getLocation());
4853
4854
0
    if (TemplateDeductionResult Result =
4855
0
            DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4856
      // Store the failed-deduction information for use in diagnostics, later.
4857
      // TODO: Actually use the failed-deduction info?
4858
0
      FailedCandidates.addCandidate().set(
4859
0
          DeclAccessPair::make(Template, AS_public), Partial,
4860
0
          MakeDeductionFailureInfo(Context, Result, Info));
4861
0
      (void)Result;
4862
0
    } else {
4863
0
      Matched.push_back(PartialSpecMatchResult());
4864
0
      Matched.back().Partial = Partial;
4865
0
      Matched.back().Args = Info.takeCanonical();
4866
0
    }
4867
0
  }
4868
4869
0
  if (Matched.size() >= 1) {
4870
0
    SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4871
0
    if (Matched.size() == 1) {
4872
      //   -- If exactly one matching specialization is found, the
4873
      //      instantiation is generated from that specialization.
4874
      // We don't need to do anything for this.
4875
0
    } else {
4876
      //   -- If more than one matching specialization is found, the
4877
      //      partial order rules (14.5.4.2) are used to determine
4878
      //      whether one of the specializations is more specialized
4879
      //      than the others. If none of the specializations is more
4880
      //      specialized than all of the other matching
4881
      //      specializations, then the use of the variable template is
4882
      //      ambiguous and the program is ill-formed.
4883
0
      for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4884
0
                                                 PEnd = Matched.end();
4885
0
           P != PEnd; ++P) {
4886
0
        if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4887
0
                                                    PointOfInstantiation) ==
4888
0
            P->Partial)
4889
0
          Best = P;
4890
0
      }
4891
4892
      // Determine if the best partial specialization is more specialized than
4893
      // the others.
4894
0
      for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4895
0
                                                 PEnd = Matched.end();
4896
0
           P != PEnd; ++P) {
4897
0
        if (P != Best && getMoreSpecializedPartialSpecialization(
4898
0
                             P->Partial, Best->Partial,
4899
0
                             PointOfInstantiation) != Best->Partial) {
4900
0
          AmbiguousPartialSpec = true;
4901
0
          break;
4902
0
        }
4903
0
      }
4904
0
    }
4905
4906
    // Instantiate using the best variable template partial specialization.
4907
0
    InstantiationPattern = Best->Partial;
4908
0
    InstantiationArgs = Best->Args;
4909
0
  } else {
4910
    //   -- If no match is found, the instantiation is generated
4911
    //      from the primary template.
4912
    // InstantiationPattern = Template->getTemplatedDecl();
4913
0
  }
4914
4915
  // 2. Create the canonical declaration.
4916
  // Note that we do not instantiate a definition until we see an odr-use
4917
  // in DoMarkVarDeclReferenced().
4918
  // FIXME: LateAttrs et al.?
4919
0
  VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4920
0
      Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4921
0
      CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4922
0
  if (!Decl)
4923
0
    return true;
4924
4925
0
  if (AmbiguousPartialSpec) {
4926
    // Partial ordering did not produce a clear winner. Complain.
4927
0
    Decl->setInvalidDecl();
4928
0
    Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4929
0
        << Decl;
4930
4931
    // Print the matching partial specializations.
4932
0
    for (MatchResult P : Matched)
4933
0
      Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4934
0
          << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4935
0
                                             *P.Args);
4936
0
    return true;
4937
0
  }
4938
4939
0
  if (VarTemplatePartialSpecializationDecl *D =
4940
0
          dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4941
0
    Decl->setInstantiationOf(D, InstantiationArgs);
4942
4943
0
  checkSpecializationReachability(TemplateNameLoc, Decl);
4944
4945
0
  assert(Decl && "No variable template specialization?");
4946
0
  return Decl;
4947
0
}
4948
4949
ExprResult
4950
Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4951
                         const DeclarationNameInfo &NameInfo,
4952
                         VarTemplateDecl *Template, SourceLocation TemplateLoc,
4953
0
                         const TemplateArgumentListInfo *TemplateArgs) {
4954
4955
0
  DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4956
0
                                       *TemplateArgs);
4957
0
  if (Decl.isInvalid())
4958
0
    return ExprError();
4959
4960
0
  if (!Decl.get())
4961
0
    return ExprResult();
4962
4963
0
  VarDecl *Var = cast<VarDecl>(Decl.get());
4964
0
  if (!Var->getTemplateSpecializationKind())
4965
0
    Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4966
0
                                       NameInfo.getLoc());
4967
4968
  // Build an ordinary singleton decl ref.
4969
0
  return BuildDeclarationNameExpr(SS, NameInfo, Var,
4970
0
                                  /*FoundD=*/nullptr, TemplateArgs);
4971
0
}
4972
4973
void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4974
0
                                            SourceLocation Loc) {
4975
0
  Diag(Loc, diag::err_template_missing_args)
4976
0
    << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4977
0
  if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4978
0
    NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4979
0
  }
4980
0
}
4981
4982
ExprResult
4983
Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4984
                             SourceLocation TemplateKWLoc,
4985
                             const DeclarationNameInfo &ConceptNameInfo,
4986
                             NamedDecl *FoundDecl,
4987
                             ConceptDecl *NamedConcept,
4988
0
                             const TemplateArgumentListInfo *TemplateArgs) {
4989
0
  assert(NamedConcept && "A concept template id without a template?");
4990
4991
0
  llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4992
0
  if (CheckTemplateArgumentList(
4993
0
          NamedConcept, ConceptNameInfo.getLoc(),
4994
0
          const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4995
0
          /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4996
0
          /*UpdateArgsWithConversions=*/false))
4997
0
    return ExprError();
4998
4999
0
  auto *CSD = ImplicitConceptSpecializationDecl::Create(
5000
0
      Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
5001
0
      CanonicalConverted);
5002
0
  ConstraintSatisfaction Satisfaction;
5003
0
  bool AreArgsDependent =
5004
0
      TemplateSpecializationType::anyDependentTemplateArguments(
5005
0
          *TemplateArgs, CanonicalConverted);
5006
0
  MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
5007
0
                                       /*Final=*/false);
5008
0
  LocalInstantiationScope Scope(*this);
5009
5010
0
  EnterExpressionEvaluationContext EECtx{
5011
0
      *this, ExpressionEvaluationContext::ConstantEvaluated, CSD};
5012
5013
0
  if (!AreArgsDependent &&
5014
0
      CheckConstraintSatisfaction(
5015
0
          NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
5016
0
          SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
5017
0
                      TemplateArgs->getRAngleLoc()),
5018
0
          Satisfaction))
5019
0
    return ExprError();
5020
0
  auto *CL = ConceptReference::Create(
5021
0
      Context,
5022
0
      SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
5023
0
      TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
5024
0
      ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs));
5025
0
  return ConceptSpecializationExpr::Create(
5026
0
      Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
5027
0
}
5028
5029
ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
5030
                                     SourceLocation TemplateKWLoc,
5031
                                     LookupResult &R,
5032
                                     bool RequiresADL,
5033
0
                                 const TemplateArgumentListInfo *TemplateArgs) {
5034
  // FIXME: Can we do any checking at this point? I guess we could check the
5035
  // template arguments that we have against the template name, if the template
5036
  // name refers to a single template. That's not a terribly common case,
5037
  // though.
5038
  // foo<int> could identify a single function unambiguously
5039
  // This approach does NOT work, since f<int>(1);
5040
  // gets resolved prior to resorting to overload resolution
5041
  // i.e., template<class T> void f(double);
5042
  //       vs template<class T, class U> void f(U);
5043
5044
  // These should be filtered out by our callers.
5045
0
  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5046
5047
  // Non-function templates require a template argument list.
5048
0
  if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5049
0
    if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
5050
0
      diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
5051
0
      return ExprError();
5052
0
    }
5053
0
  }
5054
0
  bool KnownDependent = false;
5055
  // In C++1y, check variable template ids.
5056
0
  if (R.getAsSingle<VarTemplateDecl>()) {
5057
0
    ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
5058
0
                                        R.getAsSingle<VarTemplateDecl>(),
5059
0
                                        TemplateKWLoc, TemplateArgs);
5060
0
    if (Res.isInvalid() || Res.isUsable())
5061
0
      return Res;
5062
    // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
5063
0
    KnownDependent = true;
5064
0
  }
5065
5066
0
  if (R.getAsSingle<ConceptDecl>()) {
5067
0
    return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5068
0
                                  R.getFoundDecl(),
5069
0
                                  R.getAsSingle<ConceptDecl>(), TemplateArgs);
5070
0
  }
5071
5072
  // We don't want lookup warnings at this point.
5073
0
  R.suppressDiagnostics();
5074
5075
0
  UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
5076
0
      Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5077
0
      TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5078
0
      R.begin(), R.end(), KnownDependent);
5079
5080
0
  return ULE;
5081
0
}
5082
5083
// We actually only call this from template instantiation.
5084
ExprResult
5085
Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5086
                                   SourceLocation TemplateKWLoc,
5087
                                   const DeclarationNameInfo &NameInfo,
5088
0
                             const TemplateArgumentListInfo *TemplateArgs) {
5089
5090
0
  assert(TemplateArgs || TemplateKWLoc.isValid());
5091
0
  DeclContext *DC;
5092
0
  if (!(DC = computeDeclContext(SS, false)) ||
5093
0
      DC->isDependentContext() ||
5094
0
      RequireCompleteDeclContext(SS, DC))
5095
0
    return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5096
5097
0
  bool MemberOfUnknownSpecialization;
5098
0
  LookupResult R(*this, NameInfo, LookupOrdinaryName);
5099
0
  if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
5100
0
                         /*Entering*/false, MemberOfUnknownSpecialization,
5101
0
                         TemplateKWLoc))
5102
0
    return ExprError();
5103
5104
0
  if (R.isAmbiguous())
5105
0
    return ExprError();
5106
5107
0
  if (R.empty()) {
5108
0
    Diag(NameInfo.getLoc(), diag::err_no_member)
5109
0
      << NameInfo.getName() << DC << SS.getRange();
5110
0
    return ExprError();
5111
0
  }
5112
5113
0
  auto DiagnoseTypeTemplateDecl = [&](TemplateDecl *Temp,
5114
0
                                      bool isTypeAliasTemplateDecl) {
5115
0
    Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
5116
0
        << SS.getScopeRep() << NameInfo.getName().getAsString() << SS.getRange()
5117
0
        << isTypeAliasTemplateDecl;
5118
0
    Diag(Temp->getLocation(), diag::note_referenced_type_template) << 0;
5119
0
    return ExprError();
5120
0
  };
5121
5122
0
  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>())
5123
0
    return DiagnoseTypeTemplateDecl(Temp, false);
5124
5125
0
  if (TypeAliasTemplateDecl *Temp = R.getAsSingle<TypeAliasTemplateDecl>())
5126
0
    return DiagnoseTypeTemplateDecl(Temp, true);
5127
5128
0
  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
5129
0
}
5130
5131
/// Form a template name from a name that is syntactically required to name a
5132
/// template, either due to use of the 'template' keyword or because a name in
5133
/// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
5134
///
5135
/// This action forms a template name given the name of the template and its
5136
/// optional scope specifier. This is used when the 'template' keyword is used
5137
/// or when the parsing context unambiguously treats a following '<' as
5138
/// introducing a template argument list. Note that this may produce a
5139
/// non-dependent template name if we can perform the lookup now and identify
5140
/// the named template.
5141
///
5142
/// For example, given "x.MetaFun::template apply", the scope specifier
5143
/// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
5144
/// of the "template" keyword, and "apply" is the \p Name.
5145
TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5146
                                         CXXScopeSpec &SS,
5147
                                         SourceLocation TemplateKWLoc,
5148
                                         const UnqualifiedId &Name,
5149
                                         ParsedType ObjectType,
5150
                                         bool EnteringContext,
5151
                                         TemplateTy &Result,
5152
0
                                         bool AllowInjectedClassName) {
5153
0
  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5154
0
    Diag(TemplateKWLoc,
5155
0
         getLangOpts().CPlusPlus11 ?
5156
0
           diag::warn_cxx98_compat_template_outside_of_template :
5157
0
           diag::ext_template_outside_of_template)
5158
0
      << FixItHint::CreateRemoval(TemplateKWLoc);
5159
5160
0
  if (SS.isInvalid())
5161
0
    return TNK_Non_template;
5162
5163
  // Figure out where isTemplateName is going to look.
5164
0
  DeclContext *LookupCtx = nullptr;
5165
0
  if (SS.isNotEmpty())
5166
0
    LookupCtx = computeDeclContext(SS, EnteringContext);
5167
0
  else if (ObjectType)
5168
0
    LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5169
5170
  // C++0x [temp.names]p5:
5171
  //   If a name prefixed by the keyword template is not the name of
5172
  //   a template, the program is ill-formed. [Note: the keyword
5173
  //   template may not be applied to non-template members of class
5174
  //   templates. -end note ] [ Note: as is the case with the
5175
  //   typename prefix, the template prefix is allowed in cases
5176
  //   where it is not strictly necessary; i.e., when the
5177
  //   nested-name-specifier or the expression on the left of the ->
5178
  //   or . is not dependent on a template-parameter, or the use
5179
  //   does not appear in the scope of a template. -end note]
5180
  //
5181
  // Note: C++03 was more strict here, because it banned the use of
5182
  // the "template" keyword prior to a template-name that was not a
5183
  // dependent name. C++ DR468 relaxed this requirement (the
5184
  // "template" keyword is now permitted). We follow the C++0x
5185
  // rules, even in C++03 mode with a warning, retroactively applying the DR.
5186
0
  bool MemberOfUnknownSpecialization;
5187
0
  TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5188
0
                                        ObjectType, EnteringContext, Result,
5189
0
                                        MemberOfUnknownSpecialization);
5190
0
  if (TNK != TNK_Non_template) {
5191
    // We resolved this to a (non-dependent) template name. Return it.
5192
0
    auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5193
0
    if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5194
0
        Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5195
0
        Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5196
      // C++14 [class.qual]p2:
5197
      //   In a lookup in which function names are not ignored and the
5198
      //   nested-name-specifier nominates a class C, if the name specified
5199
      //   [...] is the injected-class-name of C, [...] the name is instead
5200
      //   considered to name the constructor
5201
      //
5202
      // We don't get here if naming the constructor would be valid, so we
5203
      // just reject immediately and recover by treating the
5204
      // injected-class-name as naming the template.
5205
0
      Diag(Name.getBeginLoc(),
5206
0
           diag::ext_out_of_line_qualified_id_type_names_constructor)
5207
0
          << Name.Identifier
5208
0
          << 0 /*injected-class-name used as template name*/
5209
0
          << TemplateKWLoc.isValid();
5210
0
    }
5211
0
    return TNK;
5212
0
  }
5213
5214
0
  if (!MemberOfUnknownSpecialization) {
5215
    // Didn't find a template name, and the lookup wasn't dependent.
5216
    // Do the lookup again to determine if this is a "nothing found" case or
5217
    // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5218
    // need to do this.
5219
0
    DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5220
0
    LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5221
0
                   LookupOrdinaryName);
5222
0
    bool MOUS;
5223
    // Tell LookupTemplateName that we require a template so that it diagnoses
5224
    // cases where it finds a non-template.
5225
0
    RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5226
0
                                   ? RequiredTemplateKind(TemplateKWLoc)
5227
0
                                   : TemplateNameIsRequired;
5228
0
    if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
5229
0
                            RTK, nullptr, /*AllowTypoCorrection=*/false) &&
5230
0
        !R.isAmbiguous()) {
5231
0
      if (LookupCtx)
5232
0
        Diag(Name.getBeginLoc(), diag::err_no_member)
5233
0
            << DNI.getName() << LookupCtx << SS.getRange();
5234
0
      else
5235
0
        Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5236
0
            << DNI.getName() << SS.getRange();
5237
0
    }
5238
0
    return TNK_Non_template;
5239
0
  }
5240
5241
0
  NestedNameSpecifier *Qualifier = SS.getScopeRep();
5242
5243
0
  switch (Name.getKind()) {
5244
0
  case UnqualifiedIdKind::IK_Identifier:
5245
0
    Result = TemplateTy::make(
5246
0
        Context.getDependentTemplateName(Qualifier, Name.Identifier));
5247
0
    return TNK_Dependent_template_name;
5248
5249
0
  case UnqualifiedIdKind::IK_OperatorFunctionId:
5250
0
    Result = TemplateTy::make(Context.getDependentTemplateName(
5251
0
        Qualifier, Name.OperatorFunctionId.Operator));
5252
0
    return TNK_Function_template;
5253
5254
0
  case UnqualifiedIdKind::IK_LiteralOperatorId:
5255
    // This is a kind of template name, but can never occur in a dependent
5256
    // scope (literal operators can only be declared at namespace scope).
5257
0
    break;
5258
5259
0
  default:
5260
0
    break;
5261
0
  }
5262
5263
  // This name cannot possibly name a dependent template. Diagnose this now
5264
  // rather than building a dependent template name that can never be valid.
5265
0
  Diag(Name.getBeginLoc(),
5266
0
       diag::err_template_kw_refers_to_dependent_non_template)
5267
0
      << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5268
0
      << TemplateKWLoc.isValid() << TemplateKWLoc;
5269
0
  return TNK_Non_template;
5270
0
}
5271
5272
bool Sema::CheckTemplateTypeArgument(
5273
    TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5274
    SmallVectorImpl<TemplateArgument> &SugaredConverted,
5275
0
    SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5276
0
  const TemplateArgument &Arg = AL.getArgument();
5277
0
  QualType ArgType;
5278
0
  TypeSourceInfo *TSI = nullptr;
5279
5280
  // Check template type parameter.
5281
0
  switch(Arg.getKind()) {
5282
0
  case TemplateArgument::Type:
5283
    // C++ [temp.arg.type]p1:
5284
    //   A template-argument for a template-parameter which is a
5285
    //   type shall be a type-id.
5286
0
    ArgType = Arg.getAsType();
5287
0
    TSI = AL.getTypeSourceInfo();
5288
0
    break;
5289
0
  case TemplateArgument::Template:
5290
0
  case TemplateArgument::TemplateExpansion: {
5291
    // We have a template type parameter but the template argument
5292
    // is a template without any arguments.
5293
0
    SourceRange SR = AL.getSourceRange();
5294
0
    TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5295
0
    diagnoseMissingTemplateArguments(Name, SR.getEnd());
5296
0
    return true;
5297
0
  }
5298
0
  case TemplateArgument::Expression: {
5299
    // We have a template type parameter but the template argument is an
5300
    // expression; see if maybe it is missing the "typename" keyword.
5301
0
    CXXScopeSpec SS;
5302
0
    DeclarationNameInfo NameInfo;
5303
5304
0
   if (DependentScopeDeclRefExpr *ArgExpr =
5305
0
               dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5306
0
      SS.Adopt(ArgExpr->getQualifierLoc());
5307
0
      NameInfo = ArgExpr->getNameInfo();
5308
0
    } else if (CXXDependentScopeMemberExpr *ArgExpr =
5309
0
               dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5310
0
      if (ArgExpr->isImplicitAccess()) {
5311
0
        SS.Adopt(ArgExpr->getQualifierLoc());
5312
0
        NameInfo = ArgExpr->getMemberNameInfo();
5313
0
      }
5314
0
    }
5315
5316
0
    if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5317
0
      LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5318
0
      LookupParsedName(Result, CurScope, &SS);
5319
5320
0
      if (Result.getAsSingle<TypeDecl>() ||
5321
0
          Result.getResultKind() ==
5322
0
              LookupResult::NotFoundInCurrentInstantiation) {
5323
0
        assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5324
        // Suggest that the user add 'typename' before the NNS.
5325
0
        SourceLocation Loc = AL.getSourceRange().getBegin();
5326
0
        Diag(Loc, getLangOpts().MSVCCompat
5327
0
                      ? diag::ext_ms_template_type_arg_missing_typename
5328
0
                      : diag::err_template_arg_must_be_type_suggest)
5329
0
            << FixItHint::CreateInsertion(Loc, "typename ");
5330
0
        NoteTemplateParameterLocation(*Param);
5331
5332
        // Recover by synthesizing a type using the location information that we
5333
        // already have.
5334
0
        ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::Typename,
5335
0
                                               SS.getScopeRep(), II);
5336
0
        TypeLocBuilder TLB;
5337
0
        DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
5338
0
        TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5339
0
        TL.setQualifierLoc(SS.getWithLocInContext(Context));
5340
0
        TL.setNameLoc(NameInfo.getLoc());
5341
0
        TSI = TLB.getTypeSourceInfo(Context, ArgType);
5342
5343
        // Overwrite our input TemplateArgumentLoc so that we can recover
5344
        // properly.
5345
0
        AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5346
0
                                 TemplateArgumentLocInfo(TSI));
5347
5348
0
        break;
5349
0
      }
5350
0
    }
5351
    // fallthrough
5352
0
    [[fallthrough]];
5353
0
  }
5354
0
  default: {
5355
    // We have a template type parameter but the template argument
5356
    // is not a type.
5357
0
    SourceRange SR = AL.getSourceRange();
5358
0
    Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5359
0
    NoteTemplateParameterLocation(*Param);
5360
5361
0
    return true;
5362
0
  }
5363
0
  }
5364
5365
0
  if (CheckTemplateArgument(TSI))
5366
0
    return true;
5367
5368
  // Objective-C ARC:
5369
  //   If an explicitly-specified template argument type is a lifetime type
5370
  //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5371
0
  if (getLangOpts().ObjCAutoRefCount &&
5372
0
      ArgType->isObjCLifetimeType() &&
5373
0
      !ArgType.getObjCLifetime()) {
5374
0
    Qualifiers Qs;
5375
0
    Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5376
0
    ArgType = Context.getQualifiedType(ArgType, Qs);
5377
0
  }
5378
5379
0
  SugaredConverted.push_back(TemplateArgument(ArgType));
5380
0
  CanonicalConverted.push_back(
5381
0
      TemplateArgument(Context.getCanonicalType(ArgType)));
5382
0
  return false;
5383
0
}
5384
5385
/// Substitute template arguments into the default template argument for
5386
/// the given template type parameter.
5387
///
5388
/// \param SemaRef the semantic analysis object for which we are performing
5389
/// the substitution.
5390
///
5391
/// \param Template the template that we are synthesizing template arguments
5392
/// for.
5393
///
5394
/// \param TemplateLoc the location of the template name that started the
5395
/// template-id we are checking.
5396
///
5397
/// \param RAngleLoc the location of the right angle bracket ('>') that
5398
/// terminates the template-id.
5399
///
5400
/// \param Param the template template parameter whose default we are
5401
/// substituting into.
5402
///
5403
/// \param Converted the list of template arguments provided for template
5404
/// parameters that precede \p Param in the template parameter list.
5405
/// \returns the substituted template argument, or NULL if an error occurred.
5406
static TypeSourceInfo *SubstDefaultTemplateArgument(
5407
    Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5408
    SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5409
    ArrayRef<TemplateArgument> SugaredConverted,
5410
0
    ArrayRef<TemplateArgument> CanonicalConverted) {
5411
0
  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
5412
5413
  // If the argument type is dependent, instantiate it now based
5414
  // on the previously-computed template arguments.
5415
0
  if (ArgType->getType()->isInstantiationDependentType()) {
5416
0
    Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5417
0
                                     SugaredConverted,
5418
0
                                     SourceRange(TemplateLoc, RAngleLoc));
5419
0
    if (Inst.isInvalid())
5420
0
      return nullptr;
5421
5422
    // Only substitute for the innermost template argument list.
5423
0
    MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5424
0
                                                    /*Final=*/true);
5425
0
    for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5426
0
      TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5427
5428
0
    bool ForLambdaCallOperator = false;
5429
0
    if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5430
0
      ForLambdaCallOperator = Rec->isLambda();
5431
0
    Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5432
0
                                   !ForLambdaCallOperator);
5433
0
    ArgType =
5434
0
        SemaRef.SubstType(ArgType, TemplateArgLists,
5435
0
                          Param->getDefaultArgumentLoc(), Param->getDeclName());
5436
0
  }
5437
5438
0
  return ArgType;
5439
0
}
5440
5441
/// Substitute template arguments into the default template argument for
5442
/// the given non-type template parameter.
5443
///
5444
/// \param SemaRef the semantic analysis object for which we are performing
5445
/// the substitution.
5446
///
5447
/// \param Template the template that we are synthesizing template arguments
5448
/// for.
5449
///
5450
/// \param TemplateLoc the location of the template name that started the
5451
/// template-id we are checking.
5452
///
5453
/// \param RAngleLoc the location of the right angle bracket ('>') that
5454
/// terminates the template-id.
5455
///
5456
/// \param Param the non-type template parameter whose default we are
5457
/// substituting into.
5458
///
5459
/// \param Converted the list of template arguments provided for template
5460
/// parameters that precede \p Param in the template parameter list.
5461
///
5462
/// \returns the substituted template argument, or NULL if an error occurred.
5463
static ExprResult SubstDefaultTemplateArgument(
5464
    Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5465
    SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5466
    ArrayRef<TemplateArgument> SugaredConverted,
5467
0
    ArrayRef<TemplateArgument> CanonicalConverted) {
5468
0
  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5469
0
                                   SugaredConverted,
5470
0
                                   SourceRange(TemplateLoc, RAngleLoc));
5471
0
  if (Inst.isInvalid())
5472
0
    return ExprError();
5473
5474
  // Only substitute for the innermost template argument list.
5475
0
  MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5476
0
                                                  /*Final=*/true);
5477
0
  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5478
0
    TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5479
5480
0
  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5481
0
  EnterExpressionEvaluationContext ConstantEvaluated(
5482
0
      SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5483
0
  return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
5484
0
}
5485
5486
/// Substitute template arguments into the default template argument for
5487
/// the given template template parameter.
5488
///
5489
/// \param SemaRef the semantic analysis object for which we are performing
5490
/// the substitution.
5491
///
5492
/// \param Template the template that we are synthesizing template arguments
5493
/// for.
5494
///
5495
/// \param TemplateLoc the location of the template name that started the
5496
/// template-id we are checking.
5497
///
5498
/// \param RAngleLoc the location of the right angle bracket ('>') that
5499
/// terminates the template-id.
5500
///
5501
/// \param Param the template template parameter whose default we are
5502
/// substituting into.
5503
///
5504
/// \param Converted the list of template arguments provided for template
5505
/// parameters that precede \p Param in the template parameter list.
5506
///
5507
/// \param QualifierLoc Will be set to the nested-name-specifier (with
5508
/// source-location information) that precedes the template name.
5509
///
5510
/// \returns the substituted template argument, or NULL if an error occurred.
5511
static TemplateName SubstDefaultTemplateArgument(
5512
    Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5513
    SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5514
    ArrayRef<TemplateArgument> SugaredConverted,
5515
    ArrayRef<TemplateArgument> CanonicalConverted,
5516
0
    NestedNameSpecifierLoc &QualifierLoc) {
5517
0
  Sema::InstantiatingTemplate Inst(
5518
0
      SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5519
0
      SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5520
0
  if (Inst.isInvalid())
5521
0
    return TemplateName();
5522
5523
  // Only substitute for the innermost template argument list.
5524
0
  MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5525
0
                                                  /*Final=*/true);
5526
0
  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5527
0
    TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5528
5529
0
  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5530
  // Substitute into the nested-name-specifier first,
5531
0
  QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5532
0
  if (QualifierLoc) {
5533
0
    QualifierLoc =
5534
0
        SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5535
0
    if (!QualifierLoc)
5536
0
      return TemplateName();
5537
0
  }
5538
5539
0
  return SemaRef.SubstTemplateName(
5540
0
             QualifierLoc,
5541
0
             Param->getDefaultArgument().getArgument().getAsTemplate(),
5542
0
             Param->getDefaultArgument().getTemplateNameLoc(),
5543
0
             TemplateArgLists);
5544
0
}
5545
5546
/// If the given template parameter has a default template
5547
/// argument, substitute into that default template argument and
5548
/// return the corresponding template argument.
5549
TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5550
    TemplateDecl *Template, SourceLocation TemplateLoc,
5551
    SourceLocation RAngleLoc, Decl *Param,
5552
    ArrayRef<TemplateArgument> SugaredConverted,
5553
0
    ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5554
0
  HasDefaultArg = false;
5555
5556
0
  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5557
0
    if (!hasReachableDefaultArgument(TypeParm))
5558
0
      return TemplateArgumentLoc();
5559
5560
0
    HasDefaultArg = true;
5561
0
    TypeSourceInfo *DI = SubstDefaultTemplateArgument(
5562
0
        *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted,
5563
0
        CanonicalConverted);
5564
0
    if (DI)
5565
0
      return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
5566
5567
0
    return TemplateArgumentLoc();
5568
0
  }
5569
5570
0
  if (NonTypeTemplateParmDecl *NonTypeParm
5571
0
        = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5572
0
    if (!hasReachableDefaultArgument(NonTypeParm))
5573
0
      return TemplateArgumentLoc();
5574
5575
0
    HasDefaultArg = true;
5576
0
    ExprResult Arg = SubstDefaultTemplateArgument(
5577
0
        *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted,
5578
0
        CanonicalConverted);
5579
0
    if (Arg.isInvalid())
5580
0
      return TemplateArgumentLoc();
5581
5582
0
    Expr *ArgE = Arg.getAs<Expr>();
5583
0
    return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
5584
0
  }
5585
5586
0
  TemplateTemplateParmDecl *TempTempParm
5587
0
    = cast<TemplateTemplateParmDecl>(Param);
5588
0
  if (!hasReachableDefaultArgument(TempTempParm))
5589
0
    return TemplateArgumentLoc();
5590
5591
0
  HasDefaultArg = true;
5592
0
  NestedNameSpecifierLoc QualifierLoc;
5593
0
  TemplateName TName = SubstDefaultTemplateArgument(
5594
0
      *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5595
0
      CanonicalConverted, QualifierLoc);
5596
0
  if (TName.isNull())
5597
0
    return TemplateArgumentLoc();
5598
5599
0
  return TemplateArgumentLoc(
5600
0
      Context, TemplateArgument(TName),
5601
0
      TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5602
0
      TempTempParm->getDefaultArgument().getTemplateNameLoc());
5603
0
}
5604
5605
/// Convert a template-argument that we parsed as a type into a template, if
5606
/// possible. C++ permits injected-class-names to perform dual service as
5607
/// template template arguments and as template type arguments.
5608
static TemplateArgumentLoc
5609
0
convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5610
  // Extract and step over any surrounding nested-name-specifier.
5611
0
  NestedNameSpecifierLoc QualLoc;
5612
0
  if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5613
0
    if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5614
0
      return TemplateArgumentLoc();
5615
5616
0
    QualLoc = ETLoc.getQualifierLoc();
5617
0
    TLoc = ETLoc.getNamedTypeLoc();
5618
0
  }
5619
  // If this type was written as an injected-class-name, it can be used as a
5620
  // template template argument.
5621
0
  if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5622
0
    return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5623
0
                               QualLoc, InjLoc.getNameLoc());
5624
5625
  // If this type was written as an injected-class-name, it may have been
5626
  // converted to a RecordType during instantiation. If the RecordType is
5627
  // *not* wrapped in a TemplateSpecializationType and denotes a class
5628
  // template specialization, it must have come from an injected-class-name.
5629
0
  if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5630
0
    if (auto *CTSD =
5631
0
            dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5632
0
      return TemplateArgumentLoc(Context,
5633
0
                                 TemplateName(CTSD->getSpecializedTemplate()),
5634
0
                                 QualLoc, RecLoc.getNameLoc());
5635
5636
0
  return TemplateArgumentLoc();
5637
0
}
5638
5639
/// Check that the given template argument corresponds to the given
5640
/// template parameter.
5641
///
5642
/// \param Param The template parameter against which the argument will be
5643
/// checked.
5644
///
5645
/// \param Arg The template argument, which may be updated due to conversions.
5646
///
5647
/// \param Template The template in which the template argument resides.
5648
///
5649
/// \param TemplateLoc The location of the template name for the template
5650
/// whose argument list we're matching.
5651
///
5652
/// \param RAngleLoc The location of the right angle bracket ('>') that closes
5653
/// the template argument list.
5654
///
5655
/// \param ArgumentPackIndex The index into the argument pack where this
5656
/// argument will be placed. Only valid if the parameter is a parameter pack.
5657
///
5658
/// \param Converted The checked, converted argument will be added to the
5659
/// end of this small vector.
5660
///
5661
/// \param CTAK Describes how we arrived at this particular template argument:
5662
/// explicitly written, deduced, etc.
5663
///
5664
/// \returns true on error, false otherwise.
5665
bool Sema::CheckTemplateArgument(
5666
    NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
5667
    SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5668
    unsigned ArgumentPackIndex,
5669
    SmallVectorImpl<TemplateArgument> &SugaredConverted,
5670
    SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5671
0
    CheckTemplateArgumentKind CTAK) {
5672
  // Check template type parameters.
5673
0
  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5674
0
    return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5675
0
                                     CanonicalConverted);
5676
5677
  // Check non-type template parameters.
5678
0
  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5679
    // Do substitution on the type of the non-type template parameter
5680
    // with the template arguments we've seen thus far.  But if the
5681
    // template has a dependent context then we cannot substitute yet.
5682
0
    QualType NTTPType = NTTP->getType();
5683
0
    if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5684
0
      NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5685
5686
0
    if (NTTPType->isInstantiationDependentType() &&
5687
0
        !isa<TemplateTemplateParmDecl>(Template) &&
5688
0
        !Template->getDeclContext()->isDependentContext()) {
5689
      // Do substitution on the type of the non-type template parameter.
5690
0
      InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5691
0
                                 SugaredConverted,
5692
0
                                 SourceRange(TemplateLoc, RAngleLoc));
5693
0
      if (Inst.isInvalid())
5694
0
        return true;
5695
5696
0
      MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5697
0
                                           /*Final=*/true);
5698
      // If the parameter is a pack expansion, expand this slice of the pack.
5699
0
      if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5700
0
        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5701
0
                                                           ArgumentPackIndex);
5702
0
        NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5703
0
                             NTTP->getDeclName());
5704
0
      } else {
5705
0
        NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5706
0
                             NTTP->getDeclName());
5707
0
      }
5708
5709
      // If that worked, check the non-type template parameter type
5710
      // for validity.
5711
0
      if (!NTTPType.isNull())
5712
0
        NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5713
0
                                                     NTTP->getLocation());
5714
0
      if (NTTPType.isNull())
5715
0
        return true;
5716
0
    }
5717
5718
0
    switch (Arg.getArgument().getKind()) {
5719
0
    case TemplateArgument::Null:
5720
0
      llvm_unreachable("Should never see a NULL template argument here");
5721
5722
0
    case TemplateArgument::Expression: {
5723
0
      Expr *E = Arg.getArgument().getAsExpr();
5724
0
      TemplateArgument SugaredResult, CanonicalResult;
5725
0
      unsigned CurSFINAEErrors = NumSFINAEErrors;
5726
0
      ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5727
0
                                             CanonicalResult, CTAK);
5728
0
      if (Res.isInvalid())
5729
0
        return true;
5730
      // If the current template argument causes an error, give up now.
5731
0
      if (CurSFINAEErrors < NumSFINAEErrors)
5732
0
        return true;
5733
5734
      // If the resulting expression is new, then use it in place of the
5735
      // old expression in the template argument.
5736
0
      if (Res.get() != E) {
5737
0
        TemplateArgument TA(Res.get());
5738
0
        Arg = TemplateArgumentLoc(TA, Res.get());
5739
0
      }
5740
5741
0
      SugaredConverted.push_back(SugaredResult);
5742
0
      CanonicalConverted.push_back(CanonicalResult);
5743
0
      break;
5744
0
    }
5745
5746
0
    case TemplateArgument::Declaration:
5747
0
    case TemplateArgument::Integral:
5748
0
    case TemplateArgument::NullPtr:
5749
      // We've already checked this template argument, so just copy
5750
      // it to the list of converted arguments.
5751
0
      SugaredConverted.push_back(Arg.getArgument());
5752
0
      CanonicalConverted.push_back(
5753
0
          Context.getCanonicalTemplateArgument(Arg.getArgument()));
5754
0
      break;
5755
5756
0
    case TemplateArgument::Template:
5757
0
    case TemplateArgument::TemplateExpansion:
5758
      // We were given a template template argument. It may not be ill-formed;
5759
      // see below.
5760
0
      if (DependentTemplateName *DTN
5761
0
            = Arg.getArgument().getAsTemplateOrTemplatePattern()
5762
0
                                              .getAsDependentTemplateName()) {
5763
        // We have a template argument such as \c T::template X, which we
5764
        // parsed as a template template argument. However, since we now
5765
        // know that we need a non-type template argument, convert this
5766
        // template name into an expression.
5767
5768
0
        DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5769
0
                                     Arg.getTemplateNameLoc());
5770
5771
0
        CXXScopeSpec SS;
5772
0
        SS.Adopt(Arg.getTemplateQualifierLoc());
5773
        // FIXME: the template-template arg was a DependentTemplateName,
5774
        // so it was provided with a template keyword. However, its source
5775
        // location is not stored in the template argument structure.
5776
0
        SourceLocation TemplateKWLoc;
5777
0
        ExprResult E = DependentScopeDeclRefExpr::Create(
5778
0
            Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5779
0
            nullptr);
5780
5781
        // If we parsed the template argument as a pack expansion, create a
5782
        // pack expansion expression.
5783
0
        if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5784
0
          E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5785
0
          if (E.isInvalid())
5786
0
            return true;
5787
0
        }
5788
5789
0
        TemplateArgument SugaredResult, CanonicalResult;
5790
0
        E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5791
0
                                  CanonicalResult, CTAK_Specified);
5792
0
        if (E.isInvalid())
5793
0
          return true;
5794
5795
0
        SugaredConverted.push_back(SugaredResult);
5796
0
        CanonicalConverted.push_back(CanonicalResult);
5797
0
        break;
5798
0
      }
5799
5800
      // We have a template argument that actually does refer to a class
5801
      // template, alias template, or template template parameter, and
5802
      // therefore cannot be a non-type template argument.
5803
0
      Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5804
0
        << Arg.getSourceRange();
5805
0
      NoteTemplateParameterLocation(*Param);
5806
5807
0
      return true;
5808
5809
0
    case TemplateArgument::Type: {
5810
      // We have a non-type template parameter but the template
5811
      // argument is a type.
5812
5813
      // C++ [temp.arg]p2:
5814
      //   In a template-argument, an ambiguity between a type-id and
5815
      //   an expression is resolved to a type-id, regardless of the
5816
      //   form of the corresponding template-parameter.
5817
      //
5818
      // We warn specifically about this case, since it can be rather
5819
      // confusing for users.
5820
0
      QualType T = Arg.getArgument().getAsType();
5821
0
      SourceRange SR = Arg.getSourceRange();
5822
0
      if (T->isFunctionType())
5823
0
        Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5824
0
      else
5825
0
        Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5826
0
      NoteTemplateParameterLocation(*Param);
5827
0
      return true;
5828
0
    }
5829
5830
0
    case TemplateArgument::Pack:
5831
0
      llvm_unreachable("Caller must expand template argument packs");
5832
0
    }
5833
5834
0
    return false;
5835
0
  }
5836
5837
5838
  // Check template template parameters.
5839
0
  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5840
5841
0
  TemplateParameterList *Params = TempParm->getTemplateParameters();
5842
0
  if (TempParm->isExpandedParameterPack())
5843
0
    Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5844
5845
  // Substitute into the template parameter list of the template
5846
  // template parameter, since previously-supplied template arguments
5847
  // may appear within the template template parameter.
5848
  //
5849
  // FIXME: Skip this if the parameters aren't instantiation-dependent.
5850
0
  {
5851
    // Set up a template instantiation context.
5852
0
    LocalInstantiationScope Scope(*this);
5853
0
    InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5854
0
                               SugaredConverted,
5855
0
                               SourceRange(TemplateLoc, RAngleLoc));
5856
0
    if (Inst.isInvalid())
5857
0
      return true;
5858
5859
0
    Params =
5860
0
        SubstTemplateParams(Params, CurContext,
5861
0
                            MultiLevelTemplateArgumentList(
5862
0
                                Template, SugaredConverted, /*Final=*/true),
5863
0
                            /*EvaluateConstraints=*/false);
5864
0
    if (!Params)
5865
0
      return true;
5866
0
  }
5867
5868
  // C++1z [temp.local]p1: (DR1004)
5869
  //   When [the injected-class-name] is used [...] as a template-argument for
5870
  //   a template template-parameter [...] it refers to the class template
5871
  //   itself.
5872
0
  if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5873
0
    TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5874
0
        Context, Arg.getTypeSourceInfo()->getTypeLoc());
5875
0
    if (!ConvertedArg.getArgument().isNull())
5876
0
      Arg = ConvertedArg;
5877
0
  }
5878
5879
0
  switch (Arg.getArgument().getKind()) {
5880
0
  case TemplateArgument::Null:
5881
0
    llvm_unreachable("Should never see a NULL template argument here");
5882
5883
0
  case TemplateArgument::Template:
5884
0
  case TemplateArgument::TemplateExpansion:
5885
0
    if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
5886
0
      return true;
5887
5888
0
    SugaredConverted.push_back(Arg.getArgument());
5889
0
    CanonicalConverted.push_back(
5890
0
        Context.getCanonicalTemplateArgument(Arg.getArgument()));
5891
0
    break;
5892
5893
0
  case TemplateArgument::Expression:
5894
0
  case TemplateArgument::Type:
5895
    // We have a template template parameter but the template
5896
    // argument does not refer to a template.
5897
0
    Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5898
0
      << getLangOpts().CPlusPlus11;
5899
0
    return true;
5900
5901
0
  case TemplateArgument::Declaration:
5902
0
    llvm_unreachable("Declaration argument with template template parameter");
5903
0
  case TemplateArgument::Integral:
5904
0
    llvm_unreachable("Integral argument with template template parameter");
5905
0
  case TemplateArgument::NullPtr:
5906
0
    llvm_unreachable("Null pointer argument with template template parameter");
5907
5908
0
  case TemplateArgument::Pack:
5909
0
    llvm_unreachable("Caller must expand template argument packs");
5910
0
  }
5911
5912
0
  return false;
5913
0
}
5914
5915
/// Diagnose a missing template argument.
5916
template<typename TemplateParmDecl>
5917
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5918
                                    TemplateDecl *TD,
5919
                                    const TemplateParmDecl *D,
5920
0
                                    TemplateArgumentListInfo &Args) {
5921
  // Dig out the most recent declaration of the template parameter; there may be
5922
  // declarations of the template that are more recent than TD.
5923
0
  D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5924
0
                                 ->getTemplateParameters()
5925
0
                                 ->getParam(D->getIndex()));
5926
5927
  // If there's a default argument that's not reachable, diagnose that we're
5928
  // missing a module import.
5929
0
  llvm::SmallVector<Module*, 8> Modules;
5930
0
  if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5931
0
    S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5932
0
                            D->getDefaultArgumentLoc(), Modules,
5933
0
                            Sema::MissingImportKind::DefaultArgument,
5934
0
                            /*Recover*/true);
5935
0
    return true;
5936
0
  }
5937
5938
  // FIXME: If there's a more recent default argument that *is* visible,
5939
  // diagnose that it was declared too late.
5940
5941
0
  TemplateParameterList *Params = TD->getTemplateParameters();
5942
5943
0
  S.Diag(Loc, diag::err_template_arg_list_different_arity)
5944
0
    << /*not enough args*/0
5945
0
    << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5946
0
    << TD;
5947
0
  S.NoteTemplateLocation(*TD, Params->getSourceRange());
5948
0
  return true;
5949
0
}
Unexecuted instantiation: SemaTemplate.cpp:bool diagnoseMissingArgument<clang::TemplateTypeParmDecl>(clang::Sema&, clang::SourceLocation, clang::TemplateDecl*, clang::TemplateTypeParmDecl const*, clang::TemplateArgumentListInfo&)
Unexecuted instantiation: SemaTemplate.cpp:bool diagnoseMissingArgument<clang::NonTypeTemplateParmDecl>(clang::Sema&, clang::SourceLocation, clang::TemplateDecl*, clang::NonTypeTemplateParmDecl const*, clang::TemplateArgumentListInfo&)
Unexecuted instantiation: SemaTemplate.cpp:bool diagnoseMissingArgument<clang::TemplateTemplateParmDecl>(clang::Sema&, clang::SourceLocation, clang::TemplateDecl*, clang::TemplateTemplateParmDecl const*, clang::TemplateArgumentListInfo&)
5950
5951
/// Check that the given template argument list is well-formed
5952
/// for specializing the given template.
5953
bool Sema::CheckTemplateArgumentList(
5954
    TemplateDecl *Template, SourceLocation TemplateLoc,
5955
    TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5956
    SmallVectorImpl<TemplateArgument> &SugaredConverted,
5957
    SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5958
0
    bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5959
5960
0
  if (ConstraintsNotSatisfied)
5961
0
    *ConstraintsNotSatisfied = false;
5962
5963
  // Make a copy of the template arguments for processing.  Only make the
5964
  // changes at the end when successful in matching the arguments to the
5965
  // template.
5966
0
  TemplateArgumentListInfo NewArgs = TemplateArgs;
5967
5968
0
  TemplateParameterList *Params = GetTemplateParameterList(Template);
5969
5970
0
  SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5971
5972
  // C++ [temp.arg]p1:
5973
  //   [...] The type and form of each template-argument specified in
5974
  //   a template-id shall match the type and form specified for the
5975
  //   corresponding parameter declared by the template in its
5976
  //   template-parameter-list.
5977
0
  bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5978
0
  SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5979
0
  SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5980
0
  unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5981
0
  LocalInstantiationScope InstScope(*this, true);
5982
0
  for (TemplateParameterList::iterator Param = Params->begin(),
5983
0
                                       ParamEnd = Params->end();
5984
0
       Param != ParamEnd; /* increment in loop */) {
5985
    // If we have an expanded parameter pack, make sure we don't have too
5986
    // many arguments.
5987
0
    if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5988
0
      if (*Expansions == SugaredArgumentPack.size()) {
5989
        // We're done with this parameter pack. Pack up its arguments and add
5990
        // them to the list.
5991
0
        SugaredConverted.push_back(
5992
0
            TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5993
0
        SugaredArgumentPack.clear();
5994
5995
0
        CanonicalConverted.push_back(
5996
0
            TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5997
0
        CanonicalArgumentPack.clear();
5998
5999
        // This argument is assigned to the next parameter.
6000
0
        ++Param;
6001
0
        continue;
6002
0
      } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
6003
        // Not enough arguments for this parameter pack.
6004
0
        Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6005
0
          << /*not enough args*/0
6006
0
          << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
6007
0
          << Template;
6008
0
        NoteTemplateLocation(*Template, Params->getSourceRange());
6009
0
        return true;
6010
0
      }
6011
0
    }
6012
6013
0
    if (ArgIdx < NumArgs) {
6014
      // Check the template argument we were given.
6015
0
      if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
6016
0
                                RAngleLoc, SugaredArgumentPack.size(),
6017
0
                                SugaredConverted, CanonicalConverted,
6018
0
                                CTAK_Specified))
6019
0
        return true;
6020
6021
0
      CanonicalConverted.back().setIsDefaulted(
6022
0
          clang::isSubstitutedDefaultArgument(
6023
0
              Context, NewArgs[ArgIdx].getArgument(), *Param,
6024
0
              CanonicalConverted, Params->getDepth()));
6025
6026
0
      bool PackExpansionIntoNonPack =
6027
0
          NewArgs[ArgIdx].getArgument().isPackExpansion() &&
6028
0
          (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
6029
0
      if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
6030
0
                                       isa<ConceptDecl>(Template))) {
6031
        // Core issue 1430: we have a pack expansion as an argument to an
6032
        // alias template, and it's not part of a parameter pack. This
6033
        // can't be canonicalized, so reject it now.
6034
        // As for concepts - we cannot normalize constraints where this
6035
        // situation exists.
6036
0
        Diag(NewArgs[ArgIdx].getLocation(),
6037
0
             diag::err_template_expansion_into_fixed_list)
6038
0
          << (isa<ConceptDecl>(Template) ? 1 : 0)
6039
0
          << NewArgs[ArgIdx].getSourceRange();
6040
0
        NoteTemplateParameterLocation(**Param);
6041
0
        return true;
6042
0
      }
6043
6044
      // We're now done with this argument.
6045
0
      ++ArgIdx;
6046
6047
0
      if ((*Param)->isTemplateParameterPack()) {
6048
        // The template parameter was a template parameter pack, so take the
6049
        // deduced argument and place it on the argument pack. Note that we
6050
        // stay on the same template parameter so that we can deduce more
6051
        // arguments.
6052
0
        SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
6053
0
        CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
6054
0
      } else {
6055
        // Move to the next template parameter.
6056
0
        ++Param;
6057
0
      }
6058
6059
      // If we just saw a pack expansion into a non-pack, then directly convert
6060
      // the remaining arguments, because we don't know what parameters they'll
6061
      // match up with.
6062
0
      if (PackExpansionIntoNonPack) {
6063
0
        if (!SugaredArgumentPack.empty()) {
6064
          // If we were part way through filling in an expanded parameter pack,
6065
          // fall back to just producing individual arguments.
6066
0
          SugaredConverted.insert(SugaredConverted.end(),
6067
0
                                  SugaredArgumentPack.begin(),
6068
0
                                  SugaredArgumentPack.end());
6069
0
          SugaredArgumentPack.clear();
6070
6071
0
          CanonicalConverted.insert(CanonicalConverted.end(),
6072
0
                                    CanonicalArgumentPack.begin(),
6073
0
                                    CanonicalArgumentPack.end());
6074
0
          CanonicalArgumentPack.clear();
6075
0
        }
6076
6077
0
        while (ArgIdx < NumArgs) {
6078
0
          const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6079
0
          SugaredConverted.push_back(Arg);
6080
0
          CanonicalConverted.push_back(
6081
0
              Context.getCanonicalTemplateArgument(Arg));
6082
0
          ++ArgIdx;
6083
0
        }
6084
6085
0
        return false;
6086
0
      }
6087
6088
0
      continue;
6089
0
    }
6090
6091
    // If we're checking a partial template argument list, we're done.
6092
0
    if (PartialTemplateArgs) {
6093
0
      if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6094
0
        SugaredConverted.push_back(
6095
0
            TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6096
0
        CanonicalConverted.push_back(
6097
0
            TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6098
0
      }
6099
0
      return false;
6100
0
    }
6101
6102
    // If we have a template parameter pack with no more corresponding
6103
    // arguments, just break out now and we'll fill in the argument pack below.
6104
0
    if ((*Param)->isTemplateParameterPack()) {
6105
0
      assert(!getExpandedPackSize(*Param) &&
6106
0
             "Should have dealt with this already");
6107
6108
      // A non-expanded parameter pack before the end of the parameter list
6109
      // only occurs for an ill-formed template parameter list, unless we've
6110
      // got a partial argument list for a function template, so just bail out.
6111
0
      if (Param + 1 != ParamEnd) {
6112
0
        assert(
6113
0
            (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6114
0
            "Concept templates must have parameter packs at the end.");
6115
0
        return true;
6116
0
      }
6117
6118
0
      SugaredConverted.push_back(
6119
0
          TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6120
0
      SugaredArgumentPack.clear();
6121
6122
0
      CanonicalConverted.push_back(
6123
0
          TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6124
0
      CanonicalArgumentPack.clear();
6125
6126
0
      ++Param;
6127
0
      continue;
6128
0
    }
6129
6130
    // Check whether we have a default argument.
6131
0
    TemplateArgumentLoc Arg;
6132
6133
    // Retrieve the default template argument from the template
6134
    // parameter. For each kind of template parameter, we substitute the
6135
    // template arguments provided thus far and any "outer" template arguments
6136
    // (when the template parameter was part of a nested template) into
6137
    // the default argument.
6138
0
    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
6139
0
      if (!hasReachableDefaultArgument(TTP))
6140
0
        return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6141
0
                                       NewArgs);
6142
6143
0
      TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(
6144
0
          *this, Template, TemplateLoc, RAngleLoc, TTP, SugaredConverted,
6145
0
          CanonicalConverted);
6146
0
      if (!ArgType)
6147
0
        return true;
6148
6149
0
      Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
6150
0
                                ArgType);
6151
0
    } else if (NonTypeTemplateParmDecl *NTTP
6152
0
                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
6153
0
      if (!hasReachableDefaultArgument(NTTP))
6154
0
        return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6155
0
                                       NewArgs);
6156
6157
0
      ExprResult E = SubstDefaultTemplateArgument(
6158
0
          *this, Template, TemplateLoc, RAngleLoc, NTTP, SugaredConverted,
6159
0
          CanonicalConverted);
6160
0
      if (E.isInvalid())
6161
0
        return true;
6162
6163
0
      Expr *Ex = E.getAs<Expr>();
6164
0
      Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
6165
0
    } else {
6166
0
      TemplateTemplateParmDecl *TempParm
6167
0
        = cast<TemplateTemplateParmDecl>(*Param);
6168
6169
0
      if (!hasReachableDefaultArgument(TempParm))
6170
0
        return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
6171
0
                                       NewArgs);
6172
6173
0
      NestedNameSpecifierLoc QualifierLoc;
6174
0
      TemplateName Name = SubstDefaultTemplateArgument(
6175
0
          *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted,
6176
0
          CanonicalConverted, QualifierLoc);
6177
0
      if (Name.isNull())
6178
0
        return true;
6179
6180
0
      Arg = TemplateArgumentLoc(
6181
0
          Context, TemplateArgument(Name), QualifierLoc,
6182
0
          TempParm->getDefaultArgument().getTemplateNameLoc());
6183
0
    }
6184
6185
    // Introduce an instantiation record that describes where we are using
6186
    // the default template argument. We're not actually instantiating a
6187
    // template here, we just create this object to put a note into the
6188
    // context stack.
6189
0
    InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6190
0
                               SugaredConverted,
6191
0
                               SourceRange(TemplateLoc, RAngleLoc));
6192
0
    if (Inst.isInvalid())
6193
0
      return true;
6194
6195
    // Check the default template argument.
6196
0
    if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6197
0
                              SugaredConverted, CanonicalConverted,
6198
0
                              CTAK_Specified))
6199
0
      return true;
6200
6201
0
    CanonicalConverted.back().setIsDefaulted(true);
6202
6203
    // Core issue 150 (assumed resolution): if this is a template template
6204
    // parameter, keep track of the default template arguments from the
6205
    // template definition.
6206
0
    if (isTemplateTemplateParameter)
6207
0
      NewArgs.addArgument(Arg);
6208
6209
    // Move to the next template parameter and argument.
6210
0
    ++Param;
6211
0
    ++ArgIdx;
6212
0
  }
6213
6214
  // If we're performing a partial argument substitution, allow any trailing
6215
  // pack expansions; they might be empty. This can happen even if
6216
  // PartialTemplateArgs is false (the list of arguments is complete but
6217
  // still dependent).
6218
0
  if (ArgIdx < NumArgs && CurrentInstantiationScope &&
6219
0
      CurrentInstantiationScope->getPartiallySubstitutedPack()) {
6220
0
    while (ArgIdx < NumArgs &&
6221
0
           NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6222
0
      const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6223
0
      SugaredConverted.push_back(Arg);
6224
0
      CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
6225
0
    }
6226
0
  }
6227
6228
  // If we have any leftover arguments, then there were too many arguments.
6229
  // Complain and fail.
6230
0
  if (ArgIdx < NumArgs) {
6231
0
    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6232
0
        << /*too many args*/1
6233
0
        << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
6234
0
        << Template
6235
0
        << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6236
0
    NoteTemplateLocation(*Template, Params->getSourceRange());
6237
0
    return true;
6238
0
  }
6239
6240
  // No problems found with the new argument list, propagate changes back
6241
  // to caller.
6242
0
  if (UpdateArgsWithConversions)
6243
0
    TemplateArgs = std::move(NewArgs);
6244
6245
0
  if (!PartialTemplateArgs) {
6246
0
    TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
6247
0
                                           CanonicalConverted);
6248
    // Setup the context/ThisScope for the case where we are needing to
6249
    // re-instantiate constraints outside of normal instantiation.
6250
0
    DeclContext *NewContext = Template->getDeclContext();
6251
6252
    // If this template is in a template, make sure we extract the templated
6253
    // decl.
6254
0
    if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6255
0
      NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6256
0
    auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6257
6258
0
    Qualifiers ThisQuals;
6259
0
    if (const auto *Method =
6260
0
            dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6261
0
      ThisQuals = Method->getMethodQualifiers();
6262
6263
0
    ContextRAII Context(*this, NewContext);
6264
0
    CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
6265
6266
0
    MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6267
0
        Template, NewContext, /*Final=*/false, &StackTemplateArgs,
6268
0
        /*RelativeToPrimary=*/true,
6269
0
        /*Pattern=*/nullptr,
6270
0
        /*ForConceptInstantiation=*/true);
6271
0
    if (EnsureTemplateArgumentListConstraints(
6272
0
            Template, MLTAL,
6273
0
            SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6274
0
      if (ConstraintsNotSatisfied)
6275
0
        *ConstraintsNotSatisfied = true;
6276
0
      return true;
6277
0
    }
6278
0
  }
6279
6280
0
  return false;
6281
0
}
6282
6283
namespace {
6284
  class UnnamedLocalNoLinkageFinder
6285
    : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6286
  {
6287
    Sema &S;
6288
    SourceRange SR;
6289
6290
    typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6291
6292
  public:
6293
0
    UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6294
6295
0
    bool Visit(QualType T) {
6296
0
      return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6297
0
    }
6298
6299
#define TYPE(Class, Parent) \
6300
    bool Visit##Class##Type(const Class##Type *);
6301
#define ABSTRACT_TYPE(Class, Parent) \
6302
0
    bool Visit##Class##Type(const Class##Type *) { return false; }
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitArrayType(clang::ArrayType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitDeducedType(clang::DeducedType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitFunctionType(clang::FunctionType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitMatrixType(clang::MatrixType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitReferenceType(clang::ReferenceType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitTagType(clang::TagType const*)
6303
#define NON_CANONICAL_TYPE(Class, Parent) \
6304
0
    bool Visit##Class##Type(const Class##Type *) { return false; }
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitAdjustedType(clang::AdjustedType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitDecayedType(clang::DecayedType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitAttributedType(clang::AttributedType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitBTFTagAttributedType(clang::BTFTagAttributedType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitElaboratedType(clang::ElaboratedType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitMacroQualifiedType(clang::MacroQualifiedType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitObjCTypeParamType(clang::ObjCTypeParamType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitParenType(clang::ParenType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmType(clang::SubstTemplateTypeParmType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitTypedefType(clang::TypedefType const*)
Unexecuted instantiation: SemaTemplate.cpp:(anonymous namespace)::UnnamedLocalNoLinkageFinder::VisitUsingType(clang::UsingType const*)
6305
#include "clang/AST/TypeNodes.inc"
6306
6307
    bool VisitTagDecl(const TagDecl *Tag);
6308
    bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
6309
  };
6310
} // end anonymous namespace
6311
6312
0
bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6313
0
  return false;
6314
0
}
6315
6316
0
bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6317
0
  return Visit(T->getElementType());
6318
0
}
6319
6320
0
bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6321
0
  return Visit(T->getPointeeType());
6322
0
}
6323
6324
bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6325
0
                                                    const BlockPointerType* T) {
6326
0
  return Visit(T->getPointeeType());
6327
0
}
6328
6329
bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6330
0
                                                const LValueReferenceType* T) {
6331
0
  return Visit(T->getPointeeType());
6332
0
}
6333
6334
bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6335
0
                                                const RValueReferenceType* T) {
6336
0
  return Visit(T->getPointeeType());
6337
0
}
6338
6339
bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6340
0
                                                  const MemberPointerType* T) {
6341
0
  return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
6342
0
}
6343
6344
bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6345
0
                                                  const ConstantArrayType* T) {
6346
0
  return Visit(T->getElementType());
6347
0
}
6348
6349
bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6350
0
                                                 const IncompleteArrayType* T) {
6351
0
  return Visit(T->getElementType());
6352
0
}
6353
6354
bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6355
0
                                                   const VariableArrayType* T) {
6356
0
  return Visit(T->getElementType());
6357
0
}
6358
6359
bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6360
0
                                            const DependentSizedArrayType* T) {
6361
0
  return Visit(T->getElementType());
6362
0
}
6363
6364
bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6365
0
                                         const DependentSizedExtVectorType* T) {
6366
0
  return Visit(T->getElementType());
6367
0
}
6368
6369
bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6370
0
    const DependentSizedMatrixType *T) {
6371
0
  return Visit(T->getElementType());
6372
0
}
6373
6374
bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6375
0
    const DependentAddressSpaceType *T) {
6376
0
  return Visit(T->getPointeeType());
6377
0
}
6378
6379
0
bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6380
0
  return Visit(T->getElementType());
6381
0
}
6382
6383
bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6384
0
    const DependentVectorType *T) {
6385
0
  return Visit(T->getElementType());
6386
0
}
6387
6388
0
bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6389
0
  return Visit(T->getElementType());
6390
0
}
6391
6392
bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6393
0
    const ConstantMatrixType *T) {
6394
0
  return Visit(T->getElementType());
6395
0
}
6396
6397
bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6398
0
                                                  const FunctionProtoType* T) {
6399
0
  for (const auto &A : T->param_types()) {
6400
0
    if (Visit(A))
6401
0
      return true;
6402
0
  }
6403
6404
0
  return Visit(T->getReturnType());
6405
0
}
6406
6407
bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6408
0
                                               const FunctionNoProtoType* T) {
6409
0
  return Visit(T->getReturnType());
6410
0
}
6411
6412
bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6413
0
                                                  const UnresolvedUsingType*) {
6414
0
  return false;
6415
0
}
6416
6417
0
bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6418
0
  return false;
6419
0
}
6420
6421
0
bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6422
0
  return Visit(T->getUnmodifiedType());
6423
0
}
6424
6425
0
bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6426
0
  return false;
6427
0
}
6428
6429
bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6430
0
                                                    const UnaryTransformType*) {
6431
0
  return false;
6432
0
}
6433
6434
0
bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6435
0
  return Visit(T->getDeducedType());
6436
0
}
6437
6438
bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6439
0
    const DeducedTemplateSpecializationType *T) {
6440
0
  return Visit(T->getDeducedType());
6441
0
}
6442
6443
0
bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6444
0
  return VisitTagDecl(T->getDecl());
6445
0
}
6446
6447
0
bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6448
0
  return VisitTagDecl(T->getDecl());
6449
0
}
6450
6451
bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6452
0
                                                 const TemplateTypeParmType*) {
6453
0
  return false;
6454
0
}
6455
6456
bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6457
0
                                        const SubstTemplateTypeParmPackType *) {
6458
0
  return false;
6459
0
}
6460
6461
bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6462
0
                                            const TemplateSpecializationType*) {
6463
0
  return false;
6464
0
}
6465
6466
bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6467
0
                                              const InjectedClassNameType* T) {
6468
0
  return VisitTagDecl(T->getDecl());
6469
0
}
6470
6471
bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6472
0
                                                   const DependentNameType* T) {
6473
0
  return VisitNestedNameSpecifier(T->getQualifier());
6474
0
}
6475
6476
bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6477
0
                                 const DependentTemplateSpecializationType* T) {
6478
0
  if (auto *Q = T->getQualifier())
6479
0
    return VisitNestedNameSpecifier(Q);
6480
0
  return false;
6481
0
}
6482
6483
bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6484
0
                                                   const PackExpansionType* T) {
6485
0
  return Visit(T->getPattern());
6486
0
}
6487
6488
0
bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6489
0
  return false;
6490
0
}
6491
6492
bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6493
0
                                                   const ObjCInterfaceType *) {
6494
0
  return false;
6495
0
}
6496
6497
bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6498
0
                                                const ObjCObjectPointerType *) {
6499
0
  return false;
6500
0
}
6501
6502
0
bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6503
0
  return Visit(T->getValueType());
6504
0
}
6505
6506
0
bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6507
0
  return false;
6508
0
}
6509
6510
0
bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6511
0
  return false;
6512
0
}
6513
6514
bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6515
0
    const DependentBitIntType *T) {
6516
0
  return false;
6517
0
}
6518
6519
0
bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6520
0
  if (Tag->getDeclContext()->isFunctionOrMethod()) {
6521
0
    S.Diag(SR.getBegin(),
6522
0
           S.getLangOpts().CPlusPlus11 ?
6523
0
             diag::warn_cxx98_compat_template_arg_local_type :
6524
0
             diag::ext_template_arg_local_type)
6525
0
      << S.Context.getTypeDeclType(Tag) << SR;
6526
0
    return true;
6527
0
  }
6528
6529
0
  if (!Tag->hasNameForLinkage()) {
6530
0
    S.Diag(SR.getBegin(),
6531
0
           S.getLangOpts().CPlusPlus11 ?
6532
0
             diag::warn_cxx98_compat_template_arg_unnamed_type :
6533
0
             diag::ext_template_arg_unnamed_type) << SR;
6534
0
    S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6535
0
    return true;
6536
0
  }
6537
6538
0
  return false;
6539
0
}
6540
6541
bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6542
0
                                                    NestedNameSpecifier *NNS) {
6543
0
  assert(NNS);
6544
0
  if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6545
0
    return true;
6546
6547
0
  switch (NNS->getKind()) {
6548
0
  case NestedNameSpecifier::Identifier:
6549
0
  case NestedNameSpecifier::Namespace:
6550
0
  case NestedNameSpecifier::NamespaceAlias:
6551
0
  case NestedNameSpecifier::Global:
6552
0
  case NestedNameSpecifier::Super:
6553
0
    return false;
6554
6555
0
  case NestedNameSpecifier::TypeSpec:
6556
0
  case NestedNameSpecifier::TypeSpecWithTemplate:
6557
0
    return Visit(QualType(NNS->getAsType(), 0));
6558
0
  }
6559
0
  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6560
0
}
6561
6562
/// Check a template argument against its corresponding
6563
/// template type parameter.
6564
///
6565
/// This routine implements the semantics of C++ [temp.arg.type]. It
6566
/// returns true if an error occurred, and false otherwise.
6567
0
bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6568
0
  assert(ArgInfo && "invalid TypeSourceInfo");
6569
0
  QualType Arg = ArgInfo->getType();
6570
0
  SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6571
0
  QualType CanonArg = Context.getCanonicalType(Arg);
6572
6573
0
  if (CanonArg->isVariablyModifiedType()) {
6574
0
    return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6575
0
  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6576
0
    return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6577
0
  }
6578
6579
  // C++03 [temp.arg.type]p2:
6580
  //   A local type, a type with no linkage, an unnamed type or a type
6581
  //   compounded from any of these types shall not be used as a
6582
  //   template-argument for a template type-parameter.
6583
  //
6584
  // C++11 allows these, and even in C++03 we allow them as an extension with
6585
  // a warning.
6586
0
  if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6587
0
    UnnamedLocalNoLinkageFinder Finder(*this, SR);
6588
0
    (void)Finder.Visit(CanonArg);
6589
0
  }
6590
6591
0
  return false;
6592
0
}
6593
6594
enum NullPointerValueKind {
6595
  NPV_NotNullPointer,
6596
  NPV_NullPointer,
6597
  NPV_Error
6598
};
6599
6600
/// Determine whether the given template argument is a null pointer
6601
/// value of the appropriate type.
6602
static NullPointerValueKind
6603
isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
6604
                                   QualType ParamType, Expr *Arg,
6605
0
                                   Decl *Entity = nullptr) {
6606
0
  if (Arg->isValueDependent() || Arg->isTypeDependent())
6607
0
    return NPV_NotNullPointer;
6608
6609
  // dllimport'd entities aren't constant but are available inside of template
6610
  // arguments.
6611
0
  if (Entity && Entity->hasAttr<DLLImportAttr>())
6612
0
    return NPV_NotNullPointer;
6613
6614
0
  if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6615
0
    llvm_unreachable(
6616
0
        "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6617
6618
0
  if (!S.getLangOpts().CPlusPlus11)
6619
0
    return NPV_NotNullPointer;
6620
6621
  // Determine whether we have a constant expression.
6622
0
  ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
6623
0
  if (ArgRV.isInvalid())
6624
0
    return NPV_Error;
6625
0
  Arg = ArgRV.get();
6626
6627
0
  Expr::EvalResult EvalResult;
6628
0
  SmallVector<PartialDiagnosticAt, 8> Notes;
6629
0
  EvalResult.Diag = &Notes;
6630
0
  if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6631
0
      EvalResult.HasSideEffects) {
6632
0
    SourceLocation DiagLoc = Arg->getExprLoc();
6633
6634
    // If our only note is the usual "invalid subexpression" note, just point
6635
    // the caret at its location rather than producing an essentially
6636
    // redundant note.
6637
0
    if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6638
0
        diag::note_invalid_subexpr_in_const_expr) {
6639
0
      DiagLoc = Notes[0].first;
6640
0
      Notes.clear();
6641
0
    }
6642
6643
0
    S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6644
0
      << Arg->getType() << Arg->getSourceRange();
6645
0
    for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6646
0
      S.Diag(Notes[I].first, Notes[I].second);
6647
6648
0
    S.NoteTemplateParameterLocation(*Param);
6649
0
    return NPV_Error;
6650
0
  }
6651
6652
  // C++11 [temp.arg.nontype]p1:
6653
  //   - an address constant expression of type std::nullptr_t
6654
0
  if (Arg->getType()->isNullPtrType())
6655
0
    return NPV_NullPointer;
6656
6657
  //   - a constant expression that evaluates to a null pointer value (4.10); or
6658
  //   - a constant expression that evaluates to a null member pointer value
6659
  //     (4.11); or
6660
0
  if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6661
0
      (EvalResult.Val.isMemberPointer() &&
6662
0
       !EvalResult.Val.getMemberPointerDecl())) {
6663
    // If our expression has an appropriate type, we've succeeded.
6664
0
    bool ObjCLifetimeConversion;
6665
0
    if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6666
0
        S.IsQualificationConversion(Arg->getType(), ParamType, false,
6667
0
                                     ObjCLifetimeConversion))
6668
0
      return NPV_NullPointer;
6669
6670
    // The types didn't match, but we know we got a null pointer; complain,
6671
    // then recover as if the types were correct.
6672
0
    S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6673
0
      << Arg->getType() << ParamType << Arg->getSourceRange();
6674
0
    S.NoteTemplateParameterLocation(*Param);
6675
0
    return NPV_NullPointer;
6676
0
  }
6677
6678
0
  if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6679
    // We found a pointer that isn't null, but doesn't refer to an object.
6680
    // We could just return NPV_NotNullPointer, but we can print a better
6681
    // message with the information we have here.
6682
0
    S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6683
0
      << EvalResult.Val.getAsString(S.Context, ParamType);
6684
0
    S.NoteTemplateParameterLocation(*Param);
6685
0
    return NPV_Error;
6686
0
  }
6687
6688
  // If we don't have a null pointer value, but we do have a NULL pointer
6689
  // constant, suggest a cast to the appropriate type.
6690
0
  if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
6691
0
    std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6692
0
    S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6693
0
        << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6694
0
        << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
6695
0
                                      ")");
6696
0
    S.NoteTemplateParameterLocation(*Param);
6697
0
    return NPV_NullPointer;
6698
0
  }
6699
6700
  // FIXME: If we ever want to support general, address-constant expressions
6701
  // as non-type template arguments, we should return the ExprResult here to
6702
  // be interpreted by the caller.
6703
0
  return NPV_NotNullPointer;
6704
0
}
6705
6706
/// Checks whether the given template argument is compatible with its
6707
/// template parameter.
6708
static bool CheckTemplateArgumentIsCompatibleWithParameter(
6709
    Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6710
0
    Expr *Arg, QualType ArgType) {
6711
0
  bool ObjCLifetimeConversion;
6712
0
  if (ParamType->isPointerType() &&
6713
0
      !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6714
0
      S.IsQualificationConversion(ArgType, ParamType, false,
6715
0
                                  ObjCLifetimeConversion)) {
6716
    // For pointer-to-object types, qualification conversions are
6717
    // permitted.
6718
0
  } else {
6719
0
    if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6720
0
      if (!ParamRef->getPointeeType()->isFunctionType()) {
6721
        // C++ [temp.arg.nontype]p5b3:
6722
        //   For a non-type template-parameter of type reference to
6723
        //   object, no conversions apply. The type referred to by the
6724
        //   reference may be more cv-qualified than the (otherwise
6725
        //   identical) type of the template- argument. The
6726
        //   template-parameter is bound directly to the
6727
        //   template-argument, which shall be an lvalue.
6728
6729
        // FIXME: Other qualifiers?
6730
0
        unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6731
0
        unsigned ArgQuals = ArgType.getCVRQualifiers();
6732
6733
0
        if ((ParamQuals | ArgQuals) != ParamQuals) {
6734
0
          S.Diag(Arg->getBeginLoc(),
6735
0
                 diag::err_template_arg_ref_bind_ignores_quals)
6736
0
              << ParamType << Arg->getType() << Arg->getSourceRange();
6737
0
          S.NoteTemplateParameterLocation(*Param);
6738
0
          return true;
6739
0
        }
6740
0
      }
6741
0
    }
6742
6743
    // At this point, the template argument refers to an object or
6744
    // function with external linkage. We now need to check whether the
6745
    // argument and parameter types are compatible.
6746
0
    if (!S.Context.hasSameUnqualifiedType(ArgType,
6747
0
                                          ParamType.getNonReferenceType())) {
6748
      // We can't perform this conversion or binding.
6749
0
      if (ParamType->isReferenceType())
6750
0
        S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6751
0
            << ParamType << ArgIn->getType() << Arg->getSourceRange();
6752
0
      else
6753
0
        S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6754
0
            << ArgIn->getType() << ParamType << Arg->getSourceRange();
6755
0
      S.NoteTemplateParameterLocation(*Param);
6756
0
      return true;
6757
0
    }
6758
0
  }
6759
6760
0
  return false;
6761
0
}
6762
6763
/// Checks whether the given template argument is the address
6764
/// of an object or function according to C++ [temp.arg.nontype]p1.
6765
static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6766
    Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6767
0
    TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6768
0
  bool Invalid = false;
6769
0
  Expr *Arg = ArgIn;
6770
0
  QualType ArgType = Arg->getType();
6771
6772
0
  bool AddressTaken = false;
6773
0
  SourceLocation AddrOpLoc;
6774
0
  if (S.getLangOpts().MicrosoftExt) {
6775
    // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6776
    // dereference and address-of operators.
6777
0
    Arg = Arg->IgnoreParenCasts();
6778
6779
0
    bool ExtWarnMSTemplateArg = false;
6780
0
    UnaryOperatorKind FirstOpKind;
6781
0
    SourceLocation FirstOpLoc;
6782
0
    while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6783
0
      UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6784
0
      if (UnOpKind == UO_Deref)
6785
0
        ExtWarnMSTemplateArg = true;
6786
0
      if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6787
0
        Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6788
0
        if (!AddrOpLoc.isValid()) {
6789
0
          FirstOpKind = UnOpKind;
6790
0
          FirstOpLoc = UnOp->getOperatorLoc();
6791
0
        }
6792
0
      } else
6793
0
        break;
6794
0
    }
6795
0
    if (FirstOpLoc.isValid()) {
6796
0
      if (ExtWarnMSTemplateArg)
6797
0
        S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6798
0
            << ArgIn->getSourceRange();
6799
6800
0
      if (FirstOpKind == UO_AddrOf)
6801
0
        AddressTaken = true;
6802
0
      else if (Arg->getType()->isPointerType()) {
6803
        // We cannot let pointers get dereferenced here, that is obviously not a
6804
        // constant expression.
6805
0
        assert(FirstOpKind == UO_Deref);
6806
0
        S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6807
0
            << Arg->getSourceRange();
6808
0
      }
6809
0
    }
6810
0
  } else {
6811
    // See through any implicit casts we added to fix the type.
6812
0
    Arg = Arg->IgnoreImpCasts();
6813
6814
    // C++ [temp.arg.nontype]p1:
6815
    //
6816
    //   A template-argument for a non-type, non-template
6817
    //   template-parameter shall be one of: [...]
6818
    //
6819
    //     -- the address of an object or function with external
6820
    //        linkage, including function templates and function
6821
    //        template-ids but excluding non-static class members,
6822
    //        expressed as & id-expression where the & is optional if
6823
    //        the name refers to a function or array, or if the
6824
    //        corresponding template-parameter is a reference; or
6825
6826
    // In C++98/03 mode, give an extension warning on any extra parentheses.
6827
    // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6828
0
    bool ExtraParens = false;
6829
0
    while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6830
0
      if (!Invalid && !ExtraParens) {
6831
0
        S.Diag(Arg->getBeginLoc(),
6832
0
               S.getLangOpts().CPlusPlus11
6833
0
                   ? diag::warn_cxx98_compat_template_arg_extra_parens
6834
0
                   : diag::ext_template_arg_extra_parens)
6835
0
            << Arg->getSourceRange();
6836
0
        ExtraParens = true;
6837
0
      }
6838
6839
0
      Arg = Parens->getSubExpr();
6840
0
    }
6841
6842
0
    while (SubstNonTypeTemplateParmExpr *subst =
6843
0
               dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6844
0
      Arg = subst->getReplacement()->IgnoreImpCasts();
6845
6846
0
    if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6847
0
      if (UnOp->getOpcode() == UO_AddrOf) {
6848
0
        Arg = UnOp->getSubExpr();
6849
0
        AddressTaken = true;
6850
0
        AddrOpLoc = UnOp->getOperatorLoc();
6851
0
      }
6852
0
    }
6853
6854
0
    while (SubstNonTypeTemplateParmExpr *subst =
6855
0
               dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6856
0
      Arg = subst->getReplacement()->IgnoreImpCasts();
6857
0
  }
6858
6859
0
  ValueDecl *Entity = nullptr;
6860
0
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6861
0
    Entity = DRE->getDecl();
6862
0
  else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6863
0
    Entity = CUE->getGuidDecl();
6864
6865
  // If our parameter has pointer type, check for a null template value.
6866
0
  if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6867
0
    switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6868
0
                                               Entity)) {
6869
0
    case NPV_NullPointer:
6870
0
      S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6871
0
      SugaredConverted = TemplateArgument(ParamType,
6872
0
                                          /*isNullPtr=*/true);
6873
0
      CanonicalConverted =
6874
0
          TemplateArgument(S.Context.getCanonicalType(ParamType),
6875
0
                           /*isNullPtr=*/true);
6876
0
      return false;
6877
6878
0
    case NPV_Error:
6879
0
      return true;
6880
6881
0
    case NPV_NotNullPointer:
6882
0
      break;
6883
0
    }
6884
0
  }
6885
6886
  // Stop checking the precise nature of the argument if it is value dependent,
6887
  // it should be checked when instantiated.
6888
0
  if (Arg->isValueDependent()) {
6889
0
    SugaredConverted = TemplateArgument(ArgIn);
6890
0
    CanonicalConverted =
6891
0
        S.Context.getCanonicalTemplateArgument(SugaredConverted);
6892
0
    return false;
6893
0
  }
6894
6895
0
  if (!Entity) {
6896
0
    S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6897
0
        << Arg->getSourceRange();
6898
0
    S.NoteTemplateParameterLocation(*Param);
6899
0
    return true;
6900
0
  }
6901
6902
  // Cannot refer to non-static data members
6903
0
  if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6904
0
    S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6905
0
        << Entity << Arg->getSourceRange();
6906
0
    S.NoteTemplateParameterLocation(*Param);
6907
0
    return true;
6908
0
  }
6909
6910
  // Cannot refer to non-static member functions
6911
0
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6912
0
    if (!Method->isStatic()) {
6913
0
      S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6914
0
          << Method << Arg->getSourceRange();
6915
0
      S.NoteTemplateParameterLocation(*Param);
6916
0
      return true;
6917
0
    }
6918
0
  }
6919
6920
0
  FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6921
0
  VarDecl *Var = dyn_cast<VarDecl>(Entity);
6922
0
  MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6923
6924
  // A non-type template argument must refer to an object or function.
6925
0
  if (!Func && !Var && !Guid) {
6926
    // We found something, but we don't know specifically what it is.
6927
0
    S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6928
0
        << Arg->getSourceRange();
6929
0
    S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6930
0
    return true;
6931
0
  }
6932
6933
  // Address / reference template args must have external linkage in C++98.
6934
0
  if (Entity->getFormalLinkage() == Linkage::Internal) {
6935
0
    S.Diag(Arg->getBeginLoc(),
6936
0
           S.getLangOpts().CPlusPlus11
6937
0
               ? diag::warn_cxx98_compat_template_arg_object_internal
6938
0
               : diag::ext_template_arg_object_internal)
6939
0
        << !Func << Entity << Arg->getSourceRange();
6940
0
    S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6941
0
      << !Func;
6942
0
  } else if (!Entity->hasLinkage()) {
6943
0
    S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6944
0
        << !Func << Entity << Arg->getSourceRange();
6945
0
    S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6946
0
      << !Func;
6947
0
    return true;
6948
0
  }
6949
6950
0
  if (Var) {
6951
    // A value of reference type is not an object.
6952
0
    if (Var->getType()->isReferenceType()) {
6953
0
      S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6954
0
          << Var->getType() << Arg->getSourceRange();
6955
0
      S.NoteTemplateParameterLocation(*Param);
6956
0
      return true;
6957
0
    }
6958
6959
    // A template argument must have static storage duration.
6960
0
    if (Var->getTLSKind()) {
6961
0
      S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6962
0
          << Arg->getSourceRange();
6963
0
      S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6964
0
      return true;
6965
0
    }
6966
0
  }
6967
6968
0
  if (AddressTaken && ParamType->isReferenceType()) {
6969
    // If we originally had an address-of operator, but the
6970
    // parameter has reference type, complain and (if things look
6971
    // like they will work) drop the address-of operator.
6972
0
    if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6973
0
                                          ParamType.getNonReferenceType())) {
6974
0
      S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6975
0
        << ParamType;
6976
0
      S.NoteTemplateParameterLocation(*Param);
6977
0
      return true;
6978
0
    }
6979
6980
0
    S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6981
0
      << ParamType
6982
0
      << FixItHint::CreateRemoval(AddrOpLoc);
6983
0
    S.NoteTemplateParameterLocation(*Param);
6984
6985
0
    ArgType = Entity->getType();
6986
0
  }
6987
6988
  // If the template parameter has pointer type, either we must have taken the
6989
  // address or the argument must decay to a pointer.
6990
0
  if (!AddressTaken && ParamType->isPointerType()) {
6991
0
    if (Func) {
6992
      // Function-to-pointer decay.
6993
0
      ArgType = S.Context.getPointerType(Func->getType());
6994
0
    } else if (Entity->getType()->isArrayType()) {
6995
      // Array-to-pointer decay.
6996
0
      ArgType = S.Context.getArrayDecayedType(Entity->getType());
6997
0
    } else {
6998
      // If the template parameter has pointer type but the address of
6999
      // this object was not taken, complain and (possibly) recover by
7000
      // taking the address of the entity.
7001
0
      ArgType = S.Context.getPointerType(Entity->getType());
7002
0
      if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
7003
0
        S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7004
0
          << ParamType;
7005
0
        S.NoteTemplateParameterLocation(*Param);
7006
0
        return true;
7007
0
      }
7008
7009
0
      S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7010
0
        << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7011
7012
0
      S.NoteTemplateParameterLocation(*Param);
7013
0
    }
7014
0
  }
7015
7016
0
  if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7017
0
                                                     Arg, ArgType))
7018
0
    return true;
7019
7020
  // Create the template argument.
7021
0
  SugaredConverted = TemplateArgument(Entity, ParamType);
7022
0
  CanonicalConverted =
7023
0
      TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
7024
0
                       S.Context.getCanonicalType(ParamType));
7025
0
  S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7026
0
  return false;
7027
0
}
7028
7029
/// Checks whether the given template argument is a pointer to
7030
/// member constant according to C++ [temp.arg.nontype]p1.
7031
static bool
7032
CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param,
7033
                                     QualType ParamType, Expr *&ResultArg,
7034
                                     TemplateArgument &SugaredConverted,
7035
0
                                     TemplateArgument &CanonicalConverted) {
7036
0
  bool Invalid = false;
7037
7038
0
  Expr *Arg = ResultArg;
7039
0
  bool ObjCLifetimeConversion;
7040
7041
  // C++ [temp.arg.nontype]p1:
7042
  //
7043
  //   A template-argument for a non-type, non-template
7044
  //   template-parameter shall be one of: [...]
7045
  //
7046
  //     -- a pointer to member expressed as described in 5.3.1.
7047
0
  DeclRefExpr *DRE = nullptr;
7048
7049
  // In C++98/03 mode, give an extension warning on any extra parentheses.
7050
  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7051
0
  bool ExtraParens = false;
7052
0
  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7053
0
    if (!Invalid && !ExtraParens) {
7054
0
      S.Diag(Arg->getBeginLoc(),
7055
0
             S.getLangOpts().CPlusPlus11
7056
0
                 ? diag::warn_cxx98_compat_template_arg_extra_parens
7057
0
                 : diag::ext_template_arg_extra_parens)
7058
0
          << Arg->getSourceRange();
7059
0
      ExtraParens = true;
7060
0
    }
7061
7062
0
    Arg = Parens->getSubExpr();
7063
0
  }
7064
7065
0
  while (SubstNonTypeTemplateParmExpr *subst =
7066
0
           dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7067
0
    Arg = subst->getReplacement()->IgnoreImpCasts();
7068
7069
  // A pointer-to-member constant written &Class::member.
7070
0
  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7071
0
    if (UnOp->getOpcode() == UO_AddrOf) {
7072
0
      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7073
0
      if (DRE && !DRE->getQualifier())
7074
0
        DRE = nullptr;
7075
0
    }
7076
0
  }
7077
  // A constant of pointer-to-member type.
7078
0
  else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7079
0
    ValueDecl *VD = DRE->getDecl();
7080
0
    if (VD->getType()->isMemberPointerType()) {
7081
0
      if (isa<NonTypeTemplateParmDecl>(VD)) {
7082
0
        if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7083
0
          SugaredConverted = TemplateArgument(Arg);
7084
0
          CanonicalConverted =
7085
0
              S.Context.getCanonicalTemplateArgument(SugaredConverted);
7086
0
        } else {
7087
0
          SugaredConverted = TemplateArgument(VD, ParamType);
7088
0
          CanonicalConverted =
7089
0
              TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7090
0
                               S.Context.getCanonicalType(ParamType));
7091
0
        }
7092
0
        return Invalid;
7093
0
      }
7094
0
    }
7095
7096
0
    DRE = nullptr;
7097
0
  }
7098
7099
0
  ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7100
7101
  // Check for a null pointer value.
7102
0
  switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7103
0
                                             Entity)) {
7104
0
  case NPV_Error:
7105
0
    return true;
7106
0
  case NPV_NullPointer:
7107
0
    S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7108
0
    SugaredConverted = TemplateArgument(ParamType,
7109
0
                                        /*isNullPtr*/ true);
7110
0
    CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7111
0
                                          /*isNullPtr*/ true);
7112
0
    return false;
7113
0
  case NPV_NotNullPointer:
7114
0
    break;
7115
0
  }
7116
7117
0
  if (S.IsQualificationConversion(ResultArg->getType(),
7118
0
                                  ParamType.getNonReferenceType(), false,
7119
0
                                  ObjCLifetimeConversion)) {
7120
0
    ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7121
0
                                    ResultArg->getValueKind())
7122
0
                    .get();
7123
0
  } else if (!S.Context.hasSameUnqualifiedType(
7124
0
                 ResultArg->getType(), ParamType.getNonReferenceType())) {
7125
    // We can't perform this conversion.
7126
0
    S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7127
0
        << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7128
0
    S.NoteTemplateParameterLocation(*Param);
7129
0
    return true;
7130
0
  }
7131
7132
0
  if (!DRE)
7133
0
    return S.Diag(Arg->getBeginLoc(),
7134
0
                  diag::err_template_arg_not_pointer_to_member_form)
7135
0
           << Arg->getSourceRange();
7136
7137
0
  if (isa<FieldDecl>(DRE->getDecl()) ||
7138
0
      isa<IndirectFieldDecl>(DRE->getDecl()) ||
7139
0
      isa<CXXMethodDecl>(DRE->getDecl())) {
7140
0
    assert((isa<FieldDecl>(DRE->getDecl()) ||
7141
0
            isa<IndirectFieldDecl>(DRE->getDecl()) ||
7142
0
            cast<CXXMethodDecl>(DRE->getDecl())
7143
0
                ->isImplicitObjectMemberFunction()) &&
7144
0
           "Only non-static member pointers can make it here");
7145
7146
    // Okay: this is the address of a non-static member, and therefore
7147
    // a member pointer constant.
7148
0
    if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7149
0
      SugaredConverted = TemplateArgument(Arg);
7150
0
      CanonicalConverted =
7151
0
          S.Context.getCanonicalTemplateArgument(SugaredConverted);
7152
0
    } else {
7153
0
      ValueDecl *D = DRE->getDecl();
7154
0
      SugaredConverted = TemplateArgument(D, ParamType);
7155
0
      CanonicalConverted =
7156
0
          TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
7157
0
                           S.Context.getCanonicalType(ParamType));
7158
0
    }
7159
0
    return Invalid;
7160
0
  }
7161
7162
  // We found something else, but we don't know specifically what it is.
7163
0
  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7164
0
      << Arg->getSourceRange();
7165
0
  S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7166
0
  return true;
7167
0
}
7168
7169
/// Check a template argument against its corresponding
7170
/// non-type template parameter.
7171
///
7172
/// This routine implements the semantics of C++ [temp.arg.nontype].
7173
/// If an error occurred, it returns ExprError(); otherwise, it
7174
/// returns the converted template argument. \p ParamType is the
7175
/// type of the non-type template parameter after it has been instantiated.
7176
ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7177
                                       QualType ParamType, Expr *Arg,
7178
                                       TemplateArgument &SugaredConverted,
7179
                                       TemplateArgument &CanonicalConverted,
7180
0
                                       CheckTemplateArgumentKind CTAK) {
7181
0
  SourceLocation StartLoc = Arg->getBeginLoc();
7182
7183
  // If the parameter type somehow involves auto, deduce the type now.
7184
0
  DeducedType *DeducedT = ParamType->getContainedDeducedType();
7185
0
  if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
7186
    // During template argument deduction, we allow 'decltype(auto)' to
7187
    // match an arbitrary dependent argument.
7188
    // FIXME: The language rules don't say what happens in this case.
7189
    // FIXME: We get an opaque dependent type out of decltype(auto) if the
7190
    // expression is merely instantiation-dependent; is this enough?
7191
0
    if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
7192
0
      auto *AT = dyn_cast<AutoType>(DeducedT);
7193
0
      if (AT && AT->isDecltypeAuto()) {
7194
0
        SugaredConverted = TemplateArgument(Arg);
7195
0
        CanonicalConverted = TemplateArgument(
7196
0
            Context.getCanonicalTemplateArgument(SugaredConverted));
7197
0
        return Arg;
7198
0
      }
7199
0
    }
7200
7201
    // When checking a deduced template argument, deduce from its type even if
7202
    // the type is dependent, in order to check the types of non-type template
7203
    // arguments line up properly in partial ordering.
7204
0
    Expr *DeductionArg = Arg;
7205
0
    if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
7206
0
      DeductionArg = PE->getPattern();
7207
0
    TypeSourceInfo *TSI =
7208
0
        Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7209
0
    if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
7210
0
      InitializedEntity Entity =
7211
0
          InitializedEntity::InitializeTemplateParameter(ParamType, Param);
7212
0
      InitializationKind Kind = InitializationKind::CreateForInit(
7213
0
          DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7214
0
      Expr *Inits[1] = {DeductionArg};
7215
0
      ParamType =
7216
0
          DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7217
0
      if (ParamType.isNull())
7218
0
        return ExprError();
7219
0
    } else {
7220
0
      TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7221
0
                                 Param->getDepth() + 1);
7222
0
      ParamType = QualType();
7223
0
      TemplateDeductionResult Result =
7224
0
          DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7225
0
                         /*DependentDeduction=*/true,
7226
                         // We do not check constraints right now because the
7227
                         // immediately-declared constraint of the auto type is
7228
                         // also an associated constraint, and will be checked
7229
                         // along with the other associated constraints after
7230
                         // checking the template argument list.
7231
0
                         /*IgnoreConstraints=*/true);
7232
0
      if (Result == TDK_AlreadyDiagnosed) {
7233
0
        if (ParamType.isNull())
7234
0
          return ExprError();
7235
0
      } else if (Result != TDK_Success) {
7236
0
        Diag(Arg->getExprLoc(),
7237
0
             diag::err_non_type_template_parm_type_deduction_failure)
7238
0
            << Param->getDeclName() << Param->getType() << Arg->getType()
7239
0
            << Arg->getSourceRange();
7240
0
        NoteTemplateParameterLocation(*Param);
7241
0
        return ExprError();
7242
0
      }
7243
0
    }
7244
    // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7245
    // an error. The error message normally references the parameter
7246
    // declaration, but here we'll pass the argument location because that's
7247
    // where the parameter type is deduced.
7248
0
    ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7249
0
    if (ParamType.isNull()) {
7250
0
      NoteTemplateParameterLocation(*Param);
7251
0
      return ExprError();
7252
0
    }
7253
0
  }
7254
7255
  // We should have already dropped all cv-qualifiers by now.
7256
0
  assert(!ParamType.hasQualifiers() &&
7257
0
         "non-type template parameter type cannot be qualified");
7258
7259
  // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7260
0
  if (CTAK == CTAK_Deduced &&
7261
0
      (ParamType->isReferenceType()
7262
0
           ? !Context.hasSameType(ParamType.getNonReferenceType(),
7263
0
                                  Arg->getType())
7264
0
           : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
7265
    // FIXME: If either type is dependent, we skip the check. This isn't
7266
    // correct, since during deduction we're supposed to have replaced each
7267
    // template parameter with some unique (non-dependent) placeholder.
7268
    // FIXME: If the argument type contains 'auto', we carry on and fail the
7269
    // type check in order to force specific types to be more specialized than
7270
    // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
7271
    // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
7272
0
    if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
7273
0
        !Arg->getType()->getContainedDeducedType()) {
7274
0
      SugaredConverted = TemplateArgument(Arg);
7275
0
      CanonicalConverted = TemplateArgument(
7276
0
          Context.getCanonicalTemplateArgument(SugaredConverted));
7277
0
      return Arg;
7278
0
    }
7279
    // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7280
    // we should actually be checking the type of the template argument in P,
7281
    // not the type of the template argument deduced from A, against the
7282
    // template parameter type.
7283
0
    Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7284
0
      << Arg->getType()
7285
0
      << ParamType.getUnqualifiedType();
7286
0
    NoteTemplateParameterLocation(*Param);
7287
0
    return ExprError();
7288
0
  }
7289
7290
  // If either the parameter has a dependent type or the argument is
7291
  // type-dependent, there's nothing we can check now.
7292
0
  if (ParamType->isDependentType() || Arg->isTypeDependent()) {
7293
    // Force the argument to the type of the parameter to maintain invariants.
7294
0
    auto *PE = dyn_cast<PackExpansionExpr>(Arg);
7295
0
    if (PE)
7296
0
      Arg = PE->getPattern();
7297
0
    ExprResult E = ImpCastExprToType(
7298
0
        Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7299
0
        ParamType->isLValueReferenceType()   ? VK_LValue
7300
0
        : ParamType->isRValueReferenceType() ? VK_XValue
7301
0
                                             : VK_PRValue);
7302
0
    if (E.isInvalid())
7303
0
      return ExprError();
7304
0
    if (PE) {
7305
      // Recreate a pack expansion if we unwrapped one.
7306
0
      E = new (Context)
7307
0
          PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
7308
0
                            PE->getNumExpansions());
7309
0
    }
7310
0
    SugaredConverted = TemplateArgument(E.get());
7311
0
    CanonicalConverted = TemplateArgument(
7312
0
        Context.getCanonicalTemplateArgument(SugaredConverted));
7313
0
    return E;
7314
0
  }
7315
7316
0
  QualType CanonParamType = Context.getCanonicalType(ParamType);
7317
  // Avoid making a copy when initializing a template parameter of class type
7318
  // from a template parameter object of the same type. This is going beyond
7319
  // the standard, but is required for soundness: in
7320
  //   template<A a> struct X { X *p; X<a> *q; };
7321
  // ... we need p and q to have the same type.
7322
  //
7323
  // Similarly, don't inject a call to a copy constructor when initializing
7324
  // from a template parameter of the same type.
7325
0
  Expr *InnerArg = Arg->IgnoreParenImpCasts();
7326
0
  if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7327
0
      Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7328
0
    NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7329
0
    if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7330
7331
0
      SugaredConverted = TemplateArgument(TPO, ParamType);
7332
0
      CanonicalConverted =
7333
0
          TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
7334
0
      return Arg;
7335
0
    }
7336
0
    if (isa<NonTypeTemplateParmDecl>(ND)) {
7337
0
      SugaredConverted = TemplateArgument(Arg);
7338
0
      CanonicalConverted =
7339
0
          Context.getCanonicalTemplateArgument(SugaredConverted);
7340
0
      return Arg;
7341
0
    }
7342
0
  }
7343
7344
  // The initialization of the parameter from the argument is
7345
  // a constant-evaluated context.
7346
0
  EnterExpressionEvaluationContext ConstantEvaluated(
7347
0
      *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7348
7349
0
  bool IsConvertedConstantExpression = true;
7350
0
  if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
7351
0
    InitializationKind Kind = InitializationKind::CreateForInit(
7352
0
        Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
7353
0
    Expr *Inits[1] = {Arg};
7354
0
    InitializedEntity Entity =
7355
0
        InitializedEntity::InitializeTemplateParameter(ParamType, Param);
7356
0
    InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7357
0
    ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7358
0
    if (Result.isInvalid() || !Result.get())
7359
0
      return ExprError();
7360
0
    Result = ActOnConstantExpression(Result.get());
7361
0
    if (Result.isInvalid() || !Result.get())
7362
0
      return ExprError();
7363
0
    Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7364
0
                              /*DiscardedValue=*/false,
7365
0
                              /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
7366
0
              .get();
7367
0
    IsConvertedConstantExpression = false;
7368
0
  }
7369
7370
0
  if (getLangOpts().CPlusPlus17) {
7371
    // C++17 [temp.arg.nontype]p1:
7372
    //   A template-argument for a non-type template parameter shall be
7373
    //   a converted constant expression of the type of the template-parameter.
7374
0
    APValue Value;
7375
0
    ExprResult ArgResult;
7376
0
    if (IsConvertedConstantExpression) {
7377
0
      ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
7378
0
                                                   CCEK_TemplateArg, Param);
7379
0
      if (ArgResult.isInvalid())
7380
0
        return ExprError();
7381
0
    } else {
7382
0
      ArgResult = Arg;
7383
0
    }
7384
7385
    // For a value-dependent argument, CheckConvertedConstantExpression is
7386
    // permitted (and expected) to be unable to determine a value.
7387
0
    if (ArgResult.get()->isValueDependent()) {
7388
0
      SugaredConverted = TemplateArgument(ArgResult.get());
7389
0
      CanonicalConverted =
7390
0
          Context.getCanonicalTemplateArgument(SugaredConverted);
7391
0
      return ArgResult;
7392
0
    }
7393
7394
0
    APValue PreNarrowingValue;
7395
0
    ArgResult = EvaluateConvertedConstantExpression(
7396
0
        ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
7397
0
        false, PreNarrowingValue);
7398
0
    if (ArgResult.isInvalid())
7399
0
      return ExprError();
7400
7401
    // Convert the APValue to a TemplateArgument.
7402
0
    switch (Value.getKind()) {
7403
0
    case APValue::None:
7404
0
      assert(ParamType->isNullPtrType());
7405
0
      SugaredConverted = TemplateArgument(ParamType, /*isNullPtr=*/true);
7406
0
      CanonicalConverted = TemplateArgument(CanonParamType, /*isNullPtr=*/true);
7407
0
      break;
7408
0
    case APValue::Indeterminate:
7409
0
      llvm_unreachable("result of constant evaluation should be initialized");
7410
0
      break;
7411
0
    case APValue::Int:
7412
0
      assert(ParamType->isIntegralOrEnumerationType());
7413
0
      SugaredConverted = TemplateArgument(Context, Value.getInt(), ParamType);
7414
0
      CanonicalConverted =
7415
0
          TemplateArgument(Context, Value.getInt(), CanonParamType);
7416
0
      break;
7417
0
    case APValue::MemberPointer: {
7418
0
      assert(ParamType->isMemberPointerType());
7419
7420
      // FIXME: We need TemplateArgument representation and mangling for these.
7421
0
      if (!Value.getMemberPointerPath().empty()) {
7422
0
        Diag(Arg->getBeginLoc(),
7423
0
             diag::err_template_arg_member_ptr_base_derived_not_supported)
7424
0
            << Value.getMemberPointerDecl() << ParamType
7425
0
            << Arg->getSourceRange();
7426
0
        return ExprError();
7427
0
      }
7428
7429
0
      auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
7430
0
      SugaredConverted = VD ? TemplateArgument(VD, ParamType)
7431
0
                            : TemplateArgument(ParamType, /*isNullPtr=*/true);
7432
0
      CanonicalConverted =
7433
0
          VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7434
0
                                CanonParamType)
7435
0
             : TemplateArgument(CanonParamType, /*isNullPtr=*/true);
7436
0
      break;
7437
0
    }
7438
0
    case APValue::LValue: {
7439
      //   For a non-type template-parameter of pointer or reference type,
7440
      //   the value of the constant expression shall not refer to
7441
0
      assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
7442
0
             ParamType->isNullPtrType());
7443
      // -- a temporary object
7444
      // -- a string literal
7445
      // -- the result of a typeid expression, or
7446
      // -- a predefined __func__ variable
7447
0
      APValue::LValueBase Base = Value.getLValueBase();
7448
0
      auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7449
0
      if (Base &&
7450
0
          (!VD ||
7451
0
           isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
7452
0
        Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7453
0
            << Arg->getSourceRange();
7454
0
        return ExprError();
7455
0
      }
7456
      // -- a subobject
7457
      // FIXME: Until C++20
7458
0
      if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
7459
0
          VD && VD->getType()->isArrayType() &&
7460
0
          Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7461
0
          !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7462
        // Per defect report (no number yet):
7463
        //   ... other than a pointer to the first element of a complete array
7464
        //       object.
7465
0
      } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7466
0
                 Value.isLValueOnePastTheEnd()) {
7467
0
        Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7468
0
          << Value.getAsString(Context, ParamType);
7469
0
        return ExprError();
7470
0
      }
7471
0
      assert((VD || !ParamType->isReferenceType()) &&
7472
0
             "null reference should not be a constant expression");
7473
0
      assert((!VD || !ParamType->isNullPtrType()) &&
7474
0
             "non-null value of type nullptr_t?");
7475
7476
0
      SugaredConverted = VD ? TemplateArgument(VD, ParamType)
7477
0
                            : TemplateArgument(ParamType, /*isNullPtr=*/true);
7478
0
      CanonicalConverted =
7479
0
          VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7480
0
                                CanonParamType)
7481
0
             : TemplateArgument(CanonParamType, /*isNullPtr=*/true);
7482
0
      break;
7483
0
    }
7484
0
    case APValue::Struct:
7485
0
    case APValue::Union: {
7486
      // Get or create the corresponding template parameter object.
7487
0
      TemplateParamObjectDecl *D =
7488
0
          Context.getTemplateParamObjectDecl(ParamType, Value);
7489
0
      SugaredConverted = TemplateArgument(D, ParamType);
7490
0
      CanonicalConverted =
7491
0
          TemplateArgument(D->getCanonicalDecl(), CanonParamType);
7492
0
      break;
7493
0
    }
7494
0
    case APValue::AddrLabelDiff:
7495
0
      return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7496
0
    case APValue::FixedPoint:
7497
0
    case APValue::Float:
7498
0
    case APValue::ComplexInt:
7499
0
    case APValue::ComplexFloat:
7500
0
    case APValue::Vector:
7501
0
    case APValue::Array:
7502
0
      return Diag(StartLoc, diag::err_non_type_template_arg_unsupported)
7503
0
             << ParamType;
7504
0
    }
7505
7506
0
    return ArgResult.get();
7507
0
  }
7508
7509
  // C++ [temp.arg.nontype]p5:
7510
  //   The following conversions are performed on each expression used
7511
  //   as a non-type template-argument. If a non-type
7512
  //   template-argument cannot be converted to the type of the
7513
  //   corresponding template-parameter then the program is
7514
  //   ill-formed.
7515
0
  if (ParamType->isIntegralOrEnumerationType()) {
7516
    // C++11:
7517
    //   -- for a non-type template-parameter of integral or
7518
    //      enumeration type, conversions permitted in a converted
7519
    //      constant expression are applied.
7520
    //
7521
    // C++98:
7522
    //   -- for a non-type template-parameter of integral or
7523
    //      enumeration type, integral promotions (4.5) and integral
7524
    //      conversions (4.7) are applied.
7525
7526
0
    if (getLangOpts().CPlusPlus11) {
7527
      // C++ [temp.arg.nontype]p1:
7528
      //   A template-argument for a non-type, non-template template-parameter
7529
      //   shall be one of:
7530
      //
7531
      //     -- for a non-type template-parameter of integral or enumeration
7532
      //        type, a converted constant expression of the type of the
7533
      //        template-parameter; or
7534
0
      llvm::APSInt Value;
7535
0
      ExprResult ArgResult =
7536
0
        CheckConvertedConstantExpression(Arg, ParamType, Value,
7537
0
                                         CCEK_TemplateArg);
7538
0
      if (ArgResult.isInvalid())
7539
0
        return ExprError();
7540
7541
      // We can't check arbitrary value-dependent arguments.
7542
0
      if (ArgResult.get()->isValueDependent()) {
7543
0
        SugaredConverted = TemplateArgument(ArgResult.get());
7544
0
        CanonicalConverted =
7545
0
            Context.getCanonicalTemplateArgument(SugaredConverted);
7546
0
        return ArgResult;
7547
0
      }
7548
7549
      // Widen the argument value to sizeof(parameter type). This is almost
7550
      // always a no-op, except when the parameter type is bool. In
7551
      // that case, this may extend the argument from 1 bit to 8 bits.
7552
0
      QualType IntegerType = ParamType;
7553
0
      if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7554
0
        IntegerType = Enum->getDecl()->getIntegerType();
7555
0
      Value = Value.extOrTrunc(IntegerType->isBitIntType()
7556
0
                                   ? Context.getIntWidth(IntegerType)
7557
0
                                   : Context.getTypeSize(IntegerType));
7558
7559
0
      SugaredConverted = TemplateArgument(Context, Value, ParamType);
7560
0
      CanonicalConverted =
7561
0
          TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7562
0
      return ArgResult;
7563
0
    }
7564
7565
0
    ExprResult ArgResult = DefaultLvalueConversion(Arg);
7566
0
    if (ArgResult.isInvalid())
7567
0
      return ExprError();
7568
0
    Arg = ArgResult.get();
7569
7570
0
    QualType ArgType = Arg->getType();
7571
7572
    // C++ [temp.arg.nontype]p1:
7573
    //   A template-argument for a non-type, non-template
7574
    //   template-parameter shall be one of:
7575
    //
7576
    //     -- an integral constant-expression of integral or enumeration
7577
    //        type; or
7578
    //     -- the name of a non-type template-parameter; or
7579
0
    llvm::APSInt Value;
7580
0
    if (!ArgType->isIntegralOrEnumerationType()) {
7581
0
      Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7582
0
          << ArgType << Arg->getSourceRange();
7583
0
      NoteTemplateParameterLocation(*Param);
7584
0
      return ExprError();
7585
0
    } else if (!Arg->isValueDependent()) {
7586
0
      class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7587
0
        QualType T;
7588
7589
0
      public:
7590
0
        TmplArgICEDiagnoser(QualType T) : T(T) { }
7591
7592
0
        SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7593
0
                                             SourceLocation Loc) override {
7594
0
          return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7595
0
        }
7596
0
      } Diagnoser(ArgType);
7597
7598
0
      Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7599
0
      if (!Arg)
7600
0
        return ExprError();
7601
0
    }
7602
7603
    // From here on out, all we care about is the unqualified form
7604
    // of the argument type.
7605
0
    ArgType = ArgType.getUnqualifiedType();
7606
7607
    // Try to convert the argument to the parameter's type.
7608
0
    if (Context.hasSameType(ParamType, ArgType)) {
7609
      // Okay: no conversion necessary
7610
0
    } else if (ParamType->isBooleanType()) {
7611
      // This is an integral-to-boolean conversion.
7612
0
      Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7613
0
    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7614
0
               !ParamType->isEnumeralType()) {
7615
      // This is an integral promotion or conversion.
7616
0
      Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7617
0
    } else {
7618
      // We can't perform this conversion.
7619
0
      Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7620
0
          << Arg->getType() << ParamType << Arg->getSourceRange();
7621
0
      NoteTemplateParameterLocation(*Param);
7622
0
      return ExprError();
7623
0
    }
7624
7625
    // Add the value of this argument to the list of converted
7626
    // arguments. We use the bitwidth and signedness of the template
7627
    // parameter.
7628
0
    if (Arg->isValueDependent()) {
7629
      // The argument is value-dependent. Create a new
7630
      // TemplateArgument with the converted expression.
7631
0
      SugaredConverted = TemplateArgument(Arg);
7632
0
      CanonicalConverted =
7633
0
          Context.getCanonicalTemplateArgument(SugaredConverted);
7634
0
      return Arg;
7635
0
    }
7636
7637
0
    QualType IntegerType = ParamType;
7638
0
    if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7639
0
      IntegerType = Enum->getDecl()->getIntegerType();
7640
0
    }
7641
7642
0
    if (ParamType->isBooleanType()) {
7643
      // Value must be zero or one.
7644
0
      Value = Value != 0;
7645
0
      unsigned AllowedBits = Context.getTypeSize(IntegerType);
7646
0
      if (Value.getBitWidth() != AllowedBits)
7647
0
        Value = Value.extOrTrunc(AllowedBits);
7648
0
      Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7649
0
    } else {
7650
0
      llvm::APSInt OldValue = Value;
7651
7652
      // Coerce the template argument's value to the value it will have
7653
      // based on the template parameter's type.
7654
0
      unsigned AllowedBits = IntegerType->isBitIntType()
7655
0
                                 ? Context.getIntWidth(IntegerType)
7656
0
                                 : Context.getTypeSize(IntegerType);
7657
0
      if (Value.getBitWidth() != AllowedBits)
7658
0
        Value = Value.extOrTrunc(AllowedBits);
7659
0
      Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7660
7661
      // Complain if an unsigned parameter received a negative value.
7662
0
      if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7663
0
          (OldValue.isSigned() && OldValue.isNegative())) {
7664
0
        Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7665
0
            << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7666
0
            << Arg->getSourceRange();
7667
0
        NoteTemplateParameterLocation(*Param);
7668
0
      }
7669
7670
      // Complain if we overflowed the template parameter's type.
7671
0
      unsigned RequiredBits;
7672
0
      if (IntegerType->isUnsignedIntegerOrEnumerationType())
7673
0
        RequiredBits = OldValue.getActiveBits();
7674
0
      else if (OldValue.isUnsigned())
7675
0
        RequiredBits = OldValue.getActiveBits() + 1;
7676
0
      else
7677
0
        RequiredBits = OldValue.getSignificantBits();
7678
0
      if (RequiredBits > AllowedBits) {
7679
0
        Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7680
0
            << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7681
0
            << Arg->getSourceRange();
7682
0
        NoteTemplateParameterLocation(*Param);
7683
0
      }
7684
0
    }
7685
7686
0
    QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7687
0
    SugaredConverted = TemplateArgument(Context, Value, T);
7688
0
    CanonicalConverted =
7689
0
        TemplateArgument(Context, Value, Context.getCanonicalType(T));
7690
0
    return Arg;
7691
0
  }
7692
7693
0
  QualType ArgType = Arg->getType();
7694
0
  DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7695
7696
  // Handle pointer-to-function, reference-to-function, and
7697
  // pointer-to-member-function all in (roughly) the same way.
7698
0
  if (// -- For a non-type template-parameter of type pointer to
7699
      //    function, only the function-to-pointer conversion (4.3) is
7700
      //    applied. If the template-argument represents a set of
7701
      //    overloaded functions (or a pointer to such), the matching
7702
      //    function is selected from the set (13.4).
7703
0
      (ParamType->isPointerType() &&
7704
0
       ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7705
      // -- For a non-type template-parameter of type reference to
7706
      //    function, no conversions apply. If the template-argument
7707
      //    represents a set of overloaded functions, the matching
7708
      //    function is selected from the set (13.4).
7709
0
      (ParamType->isReferenceType() &&
7710
0
       ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7711
      // -- For a non-type template-parameter of type pointer to
7712
      //    member function, no conversions apply. If the
7713
      //    template-argument represents a set of overloaded member
7714
      //    functions, the matching member function is selected from
7715
      //    the set (13.4).
7716
0
      (ParamType->isMemberPointerType() &&
7717
0
       ParamType->castAs<MemberPointerType>()->getPointeeType()
7718
0
         ->isFunctionType())) {
7719
7720
0
    if (Arg->getType() == Context.OverloadTy) {
7721
0
      if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7722
0
                                                                true,
7723
0
                                                                FoundResult)) {
7724
0
        if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7725
0
          return ExprError();
7726
7727
0
        ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7728
0
        if (Res.isInvalid())
7729
0
          return ExprError();
7730
0
        Arg = Res.get();
7731
0
        ArgType = Arg->getType();
7732
0
      } else
7733
0
        return ExprError();
7734
0
    }
7735
7736
0
    if (!ParamType->isMemberPointerType()) {
7737
0
      if (CheckTemplateArgumentAddressOfObjectOrFunction(
7738
0
              *this, Param, ParamType, Arg, SugaredConverted,
7739
0
              CanonicalConverted))
7740
0
        return ExprError();
7741
0
      return Arg;
7742
0
    }
7743
7744
0
    if (CheckTemplateArgumentPointerToMember(
7745
0
            *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7746
0
      return ExprError();
7747
0
    return Arg;
7748
0
  }
7749
7750
0
  if (ParamType->isPointerType()) {
7751
    //   -- for a non-type template-parameter of type pointer to
7752
    //      object, qualification conversions (4.4) and the
7753
    //      array-to-pointer conversion (4.2) are applied.
7754
    // C++0x also allows a value of std::nullptr_t.
7755
0
    assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7756
0
           "Only object pointers allowed here");
7757
7758
0
    if (CheckTemplateArgumentAddressOfObjectOrFunction(
7759
0
            *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7760
0
      return ExprError();
7761
0
    return Arg;
7762
0
  }
7763
7764
0
  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7765
    //   -- For a non-type template-parameter of type reference to
7766
    //      object, no conversions apply. The type referred to by the
7767
    //      reference may be more cv-qualified than the (otherwise
7768
    //      identical) type of the template-argument. The
7769
    //      template-parameter is bound directly to the
7770
    //      template-argument, which must be an lvalue.
7771
0
    assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7772
0
           "Only object references allowed here");
7773
7774
0
    if (Arg->getType() == Context.OverloadTy) {
7775
0
      if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
7776
0
                                                 ParamRefType->getPointeeType(),
7777
0
                                                                true,
7778
0
                                                                FoundResult)) {
7779
0
        if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7780
0
          return ExprError();
7781
0
        ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7782
0
        if (Res.isInvalid())
7783
0
          return ExprError();
7784
0
        Arg = Res.get();
7785
0
        ArgType = Arg->getType();
7786
0
      } else
7787
0
        return ExprError();
7788
0
    }
7789
7790
0
    if (CheckTemplateArgumentAddressOfObjectOrFunction(
7791
0
            *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7792
0
      return ExprError();
7793
0
    return Arg;
7794
0
  }
7795
7796
  // Deal with parameters of type std::nullptr_t.
7797
0
  if (ParamType->isNullPtrType()) {
7798
0
    if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7799
0
      SugaredConverted = TemplateArgument(Arg);
7800
0
      CanonicalConverted =
7801
0
          Context.getCanonicalTemplateArgument(SugaredConverted);
7802
0
      return Arg;
7803
0
    }
7804
7805
0
    switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7806
0
    case NPV_NotNullPointer:
7807
0
      Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7808
0
        << Arg->getType() << ParamType;
7809
0
      NoteTemplateParameterLocation(*Param);
7810
0
      return ExprError();
7811
7812
0
    case NPV_Error:
7813
0
      return ExprError();
7814
7815
0
    case NPV_NullPointer:
7816
0
      Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7817
0
      SugaredConverted = TemplateArgument(ParamType,
7818
0
                                          /*isNullPtr=*/true);
7819
0
      CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7820
0
                                            /*isNullPtr=*/true);
7821
0
      return Arg;
7822
0
    }
7823
0
  }
7824
7825
  //     -- For a non-type template-parameter of type pointer to data
7826
  //        member, qualification conversions (4.4) are applied.
7827
0
  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7828
7829
0
  if (CheckTemplateArgumentPointerToMember(
7830
0
          *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7831
0
    return ExprError();
7832
0
  return Arg;
7833
0
}
7834
7835
static void DiagnoseTemplateParameterListArityMismatch(
7836
    Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7837
    Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7838
7839
/// Check a template argument against its corresponding
7840
/// template template parameter.
7841
///
7842
/// This routine implements the semantics of C++ [temp.arg.template].
7843
/// It returns true if an error occurred, and false otherwise.
7844
bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7845
                                         TemplateParameterList *Params,
7846
0
                                         TemplateArgumentLoc &Arg) {
7847
0
  TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7848
0
  TemplateDecl *Template = Name.getAsTemplateDecl();
7849
0
  if (!Template) {
7850
    // Any dependent template name is fine.
7851
0
    assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7852
0
    return false;
7853
0
  }
7854
7855
0
  if (Template->isInvalidDecl())
7856
0
    return true;
7857
7858
  // C++0x [temp.arg.template]p1:
7859
  //   A template-argument for a template template-parameter shall be
7860
  //   the name of a class template or an alias template, expressed as an
7861
  //   id-expression. When the template-argument names a class template, only
7862
  //   primary class templates are considered when matching the
7863
  //   template template argument with the corresponding parameter;
7864
  //   partial specializations are not considered even if their
7865
  //   parameter lists match that of the template template parameter.
7866
  //
7867
  // Note that we also allow template template parameters here, which
7868
  // will happen when we are dealing with, e.g., class template
7869
  // partial specializations.
7870
0
  if (!isa<ClassTemplateDecl>(Template) &&
7871
0
      !isa<TemplateTemplateParmDecl>(Template) &&
7872
0
      !isa<TypeAliasTemplateDecl>(Template) &&
7873
0
      !isa<BuiltinTemplateDecl>(Template)) {
7874
0
    assert(isa<FunctionTemplateDecl>(Template) &&
7875
0
           "Only function templates are possible here");
7876
0
    Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7877
0
    Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7878
0
      << Template;
7879
0
  }
7880
7881
  // C++1z [temp.arg.template]p3: (DR 150)
7882
  //   A template-argument matches a template template-parameter P when P
7883
  //   is at least as specialized as the template-argument A.
7884
  // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
7885
  //  defect report resolution from C++17 and shouldn't be introduced by
7886
  //  concepts.
7887
0
  if (getLangOpts().RelaxedTemplateTemplateArgs) {
7888
    // Quick check for the common case:
7889
    //   If P contains a parameter pack, then A [...] matches P if each of A's
7890
    //   template parameters matches the corresponding template parameter in
7891
    //   the template-parameter-list of P.
7892
0
    if (TemplateParameterListsAreEqual(
7893
0
            Template->getTemplateParameters(), Params, false,
7894
0
            TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
7895
        // If the argument has no associated constraints, then the parameter is
7896
        // definitely at least as specialized as the argument.
7897
        // Otherwise - we need a more thorough check.
7898
0
        !Template->hasAssociatedConstraints())
7899
0
      return false;
7900
7901
0
    if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
7902
0
                                                          Arg.getLocation())) {
7903
      // P2113
7904
      // C++20[temp.func.order]p2
7905
      //   [...] If both deductions succeed, the partial ordering selects the
7906
      // more constrained template (if one exists) as determined below.
7907
0
      SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7908
0
      Params->getAssociatedConstraints(ParamsAC);
7909
      // C++2a[temp.arg.template]p3
7910
      //   [...] In this comparison, if P is unconstrained, the constraints on A
7911
      //   are not considered.
7912
0
      if (ParamsAC.empty())
7913
0
        return false;
7914
7915
0
      Template->getAssociatedConstraints(TemplateAC);
7916
7917
0
      bool IsParamAtLeastAsConstrained;
7918
0
      if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7919
0
                                 IsParamAtLeastAsConstrained))
7920
0
        return true;
7921
0
      if (!IsParamAtLeastAsConstrained) {
7922
0
        Diag(Arg.getLocation(),
7923
0
             diag::err_template_template_parameter_not_at_least_as_constrained)
7924
0
            << Template << Param << Arg.getSourceRange();
7925
0
        Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7926
0
        Diag(Template->getLocation(), diag::note_entity_declared_at)
7927
0
            << Template;
7928
0
        MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7929
0
                                                      TemplateAC);
7930
0
        return true;
7931
0
      }
7932
0
      return false;
7933
0
    }
7934
    // FIXME: Produce better diagnostics for deduction failures.
7935
0
  }
7936
7937
0
  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7938
0
                                         Params,
7939
0
                                         true,
7940
0
                                         TPL_TemplateTemplateArgumentMatch,
7941
0
                                         Arg.getLocation());
7942
0
}
7943
7944
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7945
                                                unsigned HereDiagID,
7946
0
                                                unsigned ExternalDiagID) {
7947
0
  if (Decl.getLocation().isValid())
7948
0
    return S.Diag(Decl.getLocation(), HereDiagID);
7949
7950
0
  SmallString<128> Str;
7951
0
  llvm::raw_svector_ostream Out(Str);
7952
0
  PrintingPolicy PP = S.getPrintingPolicy();
7953
0
  PP.TerseOutput = 1;
7954
0
  Decl.print(Out, PP);
7955
0
  return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7956
0
}
7957
7958
void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7959
0
                                std::optional<SourceRange> ParamRange) {
7960
0
  SemaDiagnosticBuilder DB =
7961
0
      noteLocation(*this, Decl, diag::note_template_decl_here,
7962
0
                   diag::note_template_decl_external);
7963
0
  if (ParamRange && ParamRange->isValid()) {
7964
0
    assert(Decl.getLocation().isValid() &&
7965
0
           "Parameter range has location when Decl does not");
7966
0
    DB << *ParamRange;
7967
0
  }
7968
0
}
7969
7970
0
void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7971
0
  noteLocation(*this, Decl, diag::note_template_param_here,
7972
0
               diag::note_template_param_external);
7973
0
}
7974
7975
/// Given a non-type template argument that refers to a
7976
/// declaration and the type of its corresponding non-type template
7977
/// parameter, produce an expression that properly refers to that
7978
/// declaration.
7979
ExprResult
7980
Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7981
                                              QualType ParamType,
7982
0
                                              SourceLocation Loc) {
7983
  // C++ [temp.param]p8:
7984
  //
7985
  //   A non-type template-parameter of type "array of T" or
7986
  //   "function returning T" is adjusted to be of type "pointer to
7987
  //   T" or "pointer to function returning T", respectively.
7988
0
  if (ParamType->isArrayType())
7989
0
    ParamType = Context.getArrayDecayedType(ParamType);
7990
0
  else if (ParamType->isFunctionType())
7991
0
    ParamType = Context.getPointerType(ParamType);
7992
7993
  // For a NULL non-type template argument, return nullptr casted to the
7994
  // parameter's type.
7995
0
  if (Arg.getKind() == TemplateArgument::NullPtr) {
7996
0
    return ImpCastExprToType(
7997
0
             new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7998
0
                             ParamType,
7999
0
                             ParamType->getAs<MemberPointerType>()
8000
0
                               ? CK_NullToMemberPointer
8001
0
                               : CK_NullToPointer);
8002
0
  }
8003
0
  assert(Arg.getKind() == TemplateArgument::Declaration &&
8004
0
         "Only declaration template arguments permitted here");
8005
8006
0
  ValueDecl *VD = Arg.getAsDecl();
8007
8008
0
  CXXScopeSpec SS;
8009
0
  if (ParamType->isMemberPointerType()) {
8010
    // If this is a pointer to member, we need to use a qualified name to
8011
    // form a suitable pointer-to-member constant.
8012
0
    assert(VD->getDeclContext()->isRecord() &&
8013
0
           (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8014
0
            isa<IndirectFieldDecl>(VD)));
8015
0
    QualType ClassType
8016
0
      = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
8017
0
    NestedNameSpecifier *Qualifier
8018
0
      = NestedNameSpecifier::Create(Context, nullptr, false,
8019
0
                                    ClassType.getTypePtr());
8020
0
    SS.MakeTrivial(Context, Qualifier, Loc);
8021
0
  }
8022
8023
0
  ExprResult RefExpr = BuildDeclarationNameExpr(
8024
0
      SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8025
0
  if (RefExpr.isInvalid())
8026
0
    return ExprError();
8027
8028
  // For a pointer, the argument declaration is the pointee. Take its address.
8029
0
  QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8030
0
  if (ParamType->isPointerType() && !ElemT.isNull() &&
8031
0
      Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8032
    // Decay an array argument if we want a pointer to its first element.
8033
0
    RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8034
0
    if (RefExpr.isInvalid())
8035
0
      return ExprError();
8036
0
  } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8037
    // For any other pointer, take the address (or form a pointer-to-member).
8038
0
    RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8039
0
    if (RefExpr.isInvalid())
8040
0
      return ExprError();
8041
0
  } else if (ParamType->isRecordType()) {
8042
0
    assert(isa<TemplateParamObjectDecl>(VD) &&
8043
0
           "arg for class template param not a template parameter object");
8044
    // No conversions apply in this case.
8045
0
    return RefExpr;
8046
0
  } else {
8047
0
    assert(ParamType->isReferenceType() &&
8048
0
           "unexpected type for decl template argument");
8049
0
  }
8050
8051
  // At this point we should have the right value category.
8052
0
  assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8053
0
         "value kind mismatch for non-type template argument");
8054
8055
  // The type of the template parameter can differ from the type of the
8056
  // argument in various ways; convert it now if necessary.
8057
0
  QualType DestExprType = ParamType.getNonLValueExprType(Context);
8058
0
  if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
8059
0
    CastKind CK;
8060
0
    QualType Ignored;
8061
0
    if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
8062
0
        IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
8063
0
      CK = CK_NoOp;
8064
0
    } else if (ParamType->isVoidPointerType() &&
8065
0
               RefExpr.get()->getType()->isPointerType()) {
8066
0
      CK = CK_BitCast;
8067
0
    } else {
8068
      // FIXME: Pointers to members can need conversion derived-to-base or
8069
      // base-to-derived conversions. We currently don't retain enough
8070
      // information to convert properly (we need to track a cast path or
8071
      // subobject number in the template argument).
8072
0
      llvm_unreachable(
8073
0
          "unexpected conversion required for non-type template argument");
8074
0
    }
8075
0
    RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8076
0
                                RefExpr.get()->getValueKind());
8077
0
  }
8078
8079
0
  return RefExpr;
8080
0
}
8081
8082
/// Construct a new expression that refers to the given
8083
/// integral template argument with the given source-location
8084
/// information.
8085
///
8086
/// This routine takes care of the mapping from an integral template
8087
/// argument (which may have any integral type) to the appropriate
8088
/// literal value.
8089
ExprResult
8090
Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
8091
0
                                                  SourceLocation Loc) {
8092
0
  assert(Arg.getKind() == TemplateArgument::Integral &&
8093
0
         "Operation is only valid for integral template arguments");
8094
0
  QualType OrigT = Arg.getIntegralType();
8095
8096
  // If this is an enum type that we're instantiating, we need to use an integer
8097
  // type the same size as the enumerator.  We don't want to build an
8098
  // IntegerLiteral with enum type.  The integer type of an enum type can be of
8099
  // any integral type with C++11 enum classes, make sure we create the right
8100
  // type of literal for it.
8101
0
  QualType T = OrigT;
8102
0
  if (const EnumType *ET = OrigT->getAs<EnumType>())
8103
0
    T = ET->getDecl()->getIntegerType();
8104
8105
0
  Expr *E;
8106
0
  if (T->isAnyCharacterType()) {
8107
0
    CharacterLiteralKind Kind;
8108
0
    if (T->isWideCharType())
8109
0
      Kind = CharacterLiteralKind::Wide;
8110
0
    else if (T->isChar8Type() && getLangOpts().Char8)
8111
0
      Kind = CharacterLiteralKind::UTF8;
8112
0
    else if (T->isChar16Type())
8113
0
      Kind = CharacterLiteralKind::UTF16;
8114
0
    else if (T->isChar32Type())
8115
0
      Kind = CharacterLiteralKind::UTF32;
8116
0
    else
8117
0
      Kind = CharacterLiteralKind::Ascii;
8118
8119
0
    E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
8120
0
                                       Kind, T, Loc);
8121
0
  } else if (T->isBooleanType()) {
8122
0
    E = CXXBoolLiteralExpr::Create(Context, Arg.getAsIntegral().getBoolValue(),
8123
0
                                   T, Loc);
8124
0
  } else if (T->isNullPtrType()) {
8125
0
    E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
8126
0
  } else {
8127
0
    E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
8128
0
  }
8129
8130
0
  if (OrigT->isEnumeralType()) {
8131
    // FIXME: This is a hack. We need a better way to handle substituted
8132
    // non-type template parameters.
8133
0
    E = CStyleCastExpr::Create(Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8134
0
                               nullptr, CurFPFeatureOverrides(),
8135
0
                               Context.getTrivialTypeSourceInfo(OrigT, Loc),
8136
0
                               Loc, Loc);
8137
0
  }
8138
8139
0
  return E;
8140
0
}
8141
8142
/// Match two template parameters within template parameter lists.
8143
static bool MatchTemplateParameterKind(
8144
    Sema &S, NamedDecl *New,
8145
    const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8146
    const NamedDecl *OldInstFrom, bool Complain,
8147
0
    Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8148
  // Check the actual kind (type, non-type, template).
8149
0
  if (Old->getKind() != New->getKind()) {
8150
0
    if (Complain) {
8151
0
      unsigned NextDiag = diag::err_template_param_different_kind;
8152
0
      if (TemplateArgLoc.isValid()) {
8153
0
        S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8154
0
        NextDiag = diag::note_template_param_different_kind;
8155
0
      }
8156
0
      S.Diag(New->getLocation(), NextDiag)
8157
0
        << (Kind != Sema::TPL_TemplateMatch);
8158
0
      S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8159
0
        << (Kind != Sema::TPL_TemplateMatch);
8160
0
    }
8161
8162
0
    return false;
8163
0
  }
8164
8165
  // Check that both are parameter packs or neither are parameter packs.
8166
  // However, if we are matching a template template argument to a
8167
  // template template parameter, the template template parameter can have
8168
  // a parameter pack where the template template argument does not.
8169
0
  if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
8170
0
      !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
8171
0
        Old->isTemplateParameterPack())) {
8172
0
    if (Complain) {
8173
0
      unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8174
0
      if (TemplateArgLoc.isValid()) {
8175
0
        S.Diag(TemplateArgLoc,
8176
0
             diag::err_template_arg_template_params_mismatch);
8177
0
        NextDiag = diag::note_template_parameter_pack_non_pack;
8178
0
      }
8179
8180
0
      unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8181
0
                      : isa<NonTypeTemplateParmDecl>(New)? 1
8182
0
                      : 2;
8183
0
      S.Diag(New->getLocation(), NextDiag)
8184
0
        << ParamKind << New->isParameterPack();
8185
0
      S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8186
0
        << ParamKind << Old->isParameterPack();
8187
0
    }
8188
8189
0
    return false;
8190
0
  }
8191
8192
  // For non-type template parameters, check the type of the parameter.
8193
0
  if (NonTypeTemplateParmDecl *OldNTTP
8194
0
                                    = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8195
0
    NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
8196
8197
    // If we are matching a template template argument to a template
8198
    // template parameter and one of the non-type template parameter types
8199
    // is dependent, then we must wait until template instantiation time
8200
    // to actually compare the arguments.
8201
0
    if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
8202
0
        (!OldNTTP->getType()->isDependentType() &&
8203
0
         !NewNTTP->getType()->isDependentType())) {
8204
      // C++20 [temp.over.link]p6:
8205
      //   Two [non-type] template-parameters are equivalent [if] they have
8206
      //   equivalent types ignoring the use of type-constraints for
8207
      //   placeholder types
8208
0
      QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8209
0
      QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8210
0
      if (!S.Context.hasSameType(OldType, NewType)) {
8211
0
        if (Complain) {
8212
0
          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8213
0
          if (TemplateArgLoc.isValid()) {
8214
0
            S.Diag(TemplateArgLoc,
8215
0
                   diag::err_template_arg_template_params_mismatch);
8216
0
            NextDiag = diag::note_template_nontype_parm_different_type;
8217
0
          }
8218
0
          S.Diag(NewNTTP->getLocation(), NextDiag)
8219
0
            << NewNTTP->getType()
8220
0
            << (Kind != Sema::TPL_TemplateMatch);
8221
0
          S.Diag(OldNTTP->getLocation(),
8222
0
                 diag::note_template_nontype_parm_prev_declaration)
8223
0
            << OldNTTP->getType();
8224
0
        }
8225
8226
0
        return false;
8227
0
      }
8228
0
    }
8229
0
  }
8230
  // For template template parameters, check the template parameter types.
8231
  // The template parameter lists of template template
8232
  // parameters must agree.
8233
0
  else if (TemplateTemplateParmDecl *OldTTP =
8234
0
               dyn_cast<TemplateTemplateParmDecl>(Old)) {
8235
0
    TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
8236
0
    if (!S.TemplateParameterListsAreEqual(
8237
0
            NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8238
0
            OldTTP->getTemplateParameters(), Complain,
8239
0
            (Kind == Sema::TPL_TemplateMatch
8240
0
                 ? Sema::TPL_TemplateTemplateParmMatch
8241
0
                 : Kind),
8242
0
            TemplateArgLoc))
8243
0
      return false;
8244
0
  }
8245
8246
0
  if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8247
0
      Kind != Sema::TPL_TemplateTemplateArgumentMatch &&
8248
0
      !isa<TemplateTemplateParmDecl>(Old)) {
8249
0
    const Expr *NewC = nullptr, *OldC = nullptr;
8250
8251
0
    if (isa<TemplateTypeParmDecl>(New)) {
8252
0
      if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8253
0
        NewC = TC->getImmediatelyDeclaredConstraint();
8254
0
      if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8255
0
        OldC = TC->getImmediatelyDeclaredConstraint();
8256
0
    } else if (isa<NonTypeTemplateParmDecl>(New)) {
8257
0
      if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8258
0
                              ->getPlaceholderTypeConstraint())
8259
0
        NewC = E;
8260
0
      if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8261
0
                              ->getPlaceholderTypeConstraint())
8262
0
        OldC = E;
8263
0
    } else
8264
0
      llvm_unreachable("unexpected template parameter type");
8265
8266
0
    auto Diagnose = [&] {
8267
0
      S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8268
0
           diag::err_template_different_type_constraint);
8269
0
      S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8270
0
           diag::note_template_prev_declaration) << /*declaration*/0;
8271
0
    };
8272
8273
0
    if (!NewC != !OldC) {
8274
0
      if (Complain)
8275
0
        Diagnose();
8276
0
      return false;
8277
0
    }
8278
8279
0
    if (NewC) {
8280
0
      if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8281
0
                                           NewC)) {
8282
0
        if (Complain)
8283
0
          Diagnose();
8284
0
        return false;
8285
0
      }
8286
0
    }
8287
0
  }
8288
8289
0
  return true;
8290
0
}
8291
8292
/// Diagnose a known arity mismatch when comparing template argument
8293
/// lists.
8294
static
8295
void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8296
                                                TemplateParameterList *New,
8297
                                                TemplateParameterList *Old,
8298
                                      Sema::TemplateParameterListEqualKind Kind,
8299
0
                                                SourceLocation TemplateArgLoc) {
8300
0
  unsigned NextDiag = diag::err_template_param_list_different_arity;
8301
0
  if (TemplateArgLoc.isValid()) {
8302
0
    S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8303
0
    NextDiag = diag::note_template_param_list_different_arity;
8304
0
  }
8305
0
  S.Diag(New->getTemplateLoc(), NextDiag)
8306
0
    << (New->size() > Old->size())
8307
0
    << (Kind != Sema::TPL_TemplateMatch)
8308
0
    << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8309
0
  S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8310
0
    << (Kind != Sema::TPL_TemplateMatch)
8311
0
    << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8312
0
}
8313
8314
/// Determine whether the given template parameter lists are
8315
/// equivalent.
8316
///
8317
/// \param New  The new template parameter list, typically written in the
8318
/// source code as part of a new template declaration.
8319
///
8320
/// \param Old  The old template parameter list, typically found via
8321
/// name lookup of the template declared with this template parameter
8322
/// list.
8323
///
8324
/// \param Complain  If true, this routine will produce a diagnostic if
8325
/// the template parameter lists are not equivalent.
8326
///
8327
/// \param Kind describes how we are to match the template parameter lists.
8328
///
8329
/// \param TemplateArgLoc If this source location is valid, then we
8330
/// are actually checking the template parameter list of a template
8331
/// argument (New) against the template parameter list of its
8332
/// corresponding template template parameter (Old). We produce
8333
/// slightly different diagnostics in this scenario.
8334
///
8335
/// \returns True if the template parameter lists are equal, false
8336
/// otherwise.
8337
bool Sema::TemplateParameterListsAreEqual(
8338
    const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8339
    const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8340
0
    TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8341
0
  if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
8342
0
    if (Complain)
8343
0
      DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8344
0
                                                 TemplateArgLoc);
8345
8346
0
    return false;
8347
0
  }
8348
8349
  // C++0x [temp.arg.template]p3:
8350
  //   A template-argument matches a template template-parameter (call it P)
8351
  //   when each of the template parameters in the template-parameter-list of
8352
  //   the template-argument's corresponding class template or alias template
8353
  //   (call it A) matches the corresponding template parameter in the
8354
  //   template-parameter-list of P. [...]
8355
0
  TemplateParameterList::iterator NewParm = New->begin();
8356
0
  TemplateParameterList::iterator NewParmEnd = New->end();
8357
0
  for (TemplateParameterList::iterator OldParm = Old->begin(),
8358
0
                                    OldParmEnd = Old->end();
8359
0
       OldParm != OldParmEnd; ++OldParm) {
8360
0
    if (Kind != TPL_TemplateTemplateArgumentMatch ||
8361
0
        !(*OldParm)->isTemplateParameterPack()) {
8362
0
      if (NewParm == NewParmEnd) {
8363
0
        if (Complain)
8364
0
          DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8365
0
                                                     TemplateArgLoc);
8366
8367
0
        return false;
8368
0
      }
8369
8370
0
      if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8371
0
                                      OldInstFrom, Complain, Kind,
8372
0
                                      TemplateArgLoc))
8373
0
        return false;
8374
8375
0
      ++NewParm;
8376
0
      continue;
8377
0
    }
8378
8379
    // C++0x [temp.arg.template]p3:
8380
    //   [...] When P's template- parameter-list contains a template parameter
8381
    //   pack (14.5.3), the template parameter pack will match zero or more
8382
    //   template parameters or template parameter packs in the
8383
    //   template-parameter-list of A with the same type and form as the
8384
    //   template parameter pack in P (ignoring whether those template
8385
    //   parameters are template parameter packs).
8386
0
    for (; NewParm != NewParmEnd; ++NewParm) {
8387
0
      if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8388
0
                                      OldInstFrom, Complain, Kind,
8389
0
                                      TemplateArgLoc))
8390
0
        return false;
8391
0
    }
8392
0
  }
8393
8394
  // Make sure we exhausted all of the arguments.
8395
0
  if (NewParm != NewParmEnd) {
8396
0
    if (Complain)
8397
0
      DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8398
0
                                                 TemplateArgLoc);
8399
8400
0
    return false;
8401
0
  }
8402
8403
0
  if (Kind != TPL_TemplateTemplateArgumentMatch &&
8404
0
      Kind != TPL_TemplateParamsEquivalent) {
8405
0
    const Expr *NewRC = New->getRequiresClause();
8406
0
    const Expr *OldRC = Old->getRequiresClause();
8407
8408
0
    auto Diagnose = [&] {
8409
0
      Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8410
0
           diag::err_template_different_requires_clause);
8411
0
      Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8412
0
           diag::note_template_prev_declaration) << /*declaration*/0;
8413
0
    };
8414
8415
0
    if (!NewRC != !OldRC) {
8416
0
      if (Complain)
8417
0
        Diagnose();
8418
0
      return false;
8419
0
    }
8420
8421
0
    if (NewRC) {
8422
0
      if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8423
0
                                         NewRC)) {
8424
0
        if (Complain)
8425
0
          Diagnose();
8426
0
        return false;
8427
0
      }
8428
0
    }
8429
0
  }
8430
8431
0
  return true;
8432
0
}
8433
8434
/// Check whether a template can be declared within this scope.
8435
///
8436
/// If the template declaration is valid in this scope, returns
8437
/// false. Otherwise, issues a diagnostic and returns true.
8438
bool
8439
0
Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8440
0
  if (!S)
8441
0
    return false;
8442
8443
  // Find the nearest enclosing declaration scope.
8444
0
  while ((S->getFlags() & Scope::DeclScope) == 0 ||
8445
0
         (S->getFlags() & Scope::TemplateParamScope) != 0)
8446
0
    S = S->getParent();
8447
8448
  // C++ [temp.pre]p6: [P2096]
8449
  //   A template, explicit specialization, or partial specialization shall not
8450
  //   have C linkage.
8451
0
  DeclContext *Ctx = S->getEntity();
8452
0
  if (Ctx && Ctx->isExternCContext()) {
8453
0
    Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
8454
0
        << TemplateParams->getSourceRange();
8455
0
    if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8456
0
      Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8457
0
    return true;
8458
0
  }
8459
0
  Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8460
8461
  // C++ [temp]p2:
8462
  //   A template-declaration can appear only as a namespace scope or
8463
  //   class scope declaration.
8464
  // C++ [temp.expl.spec]p3:
8465
  //   An explicit specialization may be declared in any scope in which the
8466
  //   corresponding primary template may be defined.
8467
  // C++ [temp.class.spec]p6: [P2096]
8468
  //   A partial specialization may be declared in any scope in which the
8469
  //   corresponding primary template may be defined.
8470
0
  if (Ctx) {
8471
0
    if (Ctx->isFileContext())
8472
0
      return false;
8473
0
    if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8474
      // C++ [temp.mem]p2:
8475
      //   A local class shall not have member templates.
8476
0
      if (RD->isLocalClass())
8477
0
        return Diag(TemplateParams->getTemplateLoc(),
8478
0
                    diag::err_template_inside_local_class)
8479
0
          << TemplateParams->getSourceRange();
8480
0
      else
8481
0
        return false;
8482
0
    }
8483
0
  }
8484
8485
0
  return Diag(TemplateParams->getTemplateLoc(),
8486
0
              diag::err_template_outside_namespace_or_class_scope)
8487
0
    << TemplateParams->getSourceRange();
8488
0
}
8489
8490
/// Determine what kind of template specialization the given declaration
8491
/// is.
8492
0
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8493
0
  if (!D)
8494
0
    return TSK_Undeclared;
8495
8496
0
  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8497
0
    return Record->getTemplateSpecializationKind();
8498
0
  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8499
0
    return Function->getTemplateSpecializationKind();
8500
0
  if (VarDecl *Var = dyn_cast<VarDecl>(D))
8501
0
    return Var->getTemplateSpecializationKind();
8502
8503
0
  return TSK_Undeclared;
8504
0
}
8505
8506
/// Check whether a specialization is well-formed in the current
8507
/// context.
8508
///
8509
/// This routine determines whether a template specialization can be declared
8510
/// in the current context (C++ [temp.expl.spec]p2).
8511
///
8512
/// \param S the semantic analysis object for which this check is being
8513
/// performed.
8514
///
8515
/// \param Specialized the entity being specialized or instantiated, which
8516
/// may be a kind of template (class template, function template, etc.) or
8517
/// a member of a class template (member function, static data member,
8518
/// member class).
8519
///
8520
/// \param PrevDecl the previous declaration of this entity, if any.
8521
///
8522
/// \param Loc the location of the explicit specialization or instantiation of
8523
/// this entity.
8524
///
8525
/// \param IsPartialSpecialization whether this is a partial specialization of
8526
/// a class template.
8527
///
8528
/// \returns true if there was an error that we cannot recover from, false
8529
/// otherwise.
8530
static bool CheckTemplateSpecializationScope(Sema &S,
8531
                                             NamedDecl *Specialized,
8532
                                             NamedDecl *PrevDecl,
8533
                                             SourceLocation Loc,
8534
0
                                             bool IsPartialSpecialization) {
8535
  // Keep these "kind" numbers in sync with the %select statements in the
8536
  // various diagnostics emitted by this routine.
8537
0
  int EntityKind = 0;
8538
0
  if (isa<ClassTemplateDecl>(Specialized))
8539
0
    EntityKind = IsPartialSpecialization? 1 : 0;
8540
0
  else if (isa<VarTemplateDecl>(Specialized))
8541
0
    EntityKind = IsPartialSpecialization ? 3 : 2;
8542
0
  else if (isa<FunctionTemplateDecl>(Specialized))
8543
0
    EntityKind = 4;
8544
0
  else if (isa<CXXMethodDecl>(Specialized))
8545
0
    EntityKind = 5;
8546
0
  else if (isa<VarDecl>(Specialized))
8547
0
    EntityKind = 6;
8548
0
  else if (isa<RecordDecl>(Specialized))
8549
0
    EntityKind = 7;
8550
0
  else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8551
0
    EntityKind = 8;
8552
0
  else {
8553
0
    S.Diag(Loc, diag::err_template_spec_unknown_kind)
8554
0
      << S.getLangOpts().CPlusPlus11;
8555
0
    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8556
0
    return true;
8557
0
  }
8558
8559
  // C++ [temp.expl.spec]p2:
8560
  //   An explicit specialization may be declared in any scope in which
8561
  //   the corresponding primary template may be defined.
8562
0
  if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8563
0
    S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8564
0
      << Specialized;
8565
0
    return true;
8566
0
  }
8567
8568
  // C++ [temp.class.spec]p6:
8569
  //   A class template partial specialization may be declared in any
8570
  //   scope in which the primary template may be defined.
8571
0
  DeclContext *SpecializedContext =
8572
0
      Specialized->getDeclContext()->getRedeclContext();
8573
0
  DeclContext *DC = S.CurContext->getRedeclContext();
8574
8575
  // Make sure that this redeclaration (or definition) occurs in the same
8576
  // scope or an enclosing namespace.
8577
0
  if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8578
0
                            : DC->Equals(SpecializedContext))) {
8579
0
    if (isa<TranslationUnitDecl>(SpecializedContext))
8580
0
      S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8581
0
        << EntityKind << Specialized;
8582
0
    else {
8583
0
      auto *ND = cast<NamedDecl>(SpecializedContext);
8584
0
      int Diag = diag::err_template_spec_redecl_out_of_scope;
8585
0
      if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8586
0
        Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8587
0
      S.Diag(Loc, Diag) << EntityKind << Specialized
8588
0
                        << ND << isa<CXXRecordDecl>(ND);
8589
0
    }
8590
8591
0
    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8592
8593
    // Don't allow specializing in the wrong class during error recovery.
8594
    // Otherwise, things can go horribly wrong.
8595
0
    if (DC->isRecord())
8596
0
      return true;
8597
0
  }
8598
8599
0
  return false;
8600
0
}
8601
8602
0
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8603
0
  if (!E->isTypeDependent())
8604
0
    return SourceLocation();
8605
0
  DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8606
0
  Checker.TraverseStmt(E);
8607
0
  if (Checker.MatchLoc.isInvalid())
8608
0
    return E->getSourceRange();
8609
0
  return Checker.MatchLoc;
8610
0
}
8611
8612
0
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8613
0
  if (!TL.getType()->isDependentType())
8614
0
    return SourceLocation();
8615
0
  DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8616
0
  Checker.TraverseTypeLoc(TL);
8617
0
  if (Checker.MatchLoc.isInvalid())
8618
0
    return TL.getSourceRange();
8619
0
  return Checker.MatchLoc;
8620
0
}
8621
8622
/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8623
/// that checks non-type template partial specialization arguments.
8624
static bool CheckNonTypeTemplatePartialSpecializationArgs(
8625
    Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8626
0
    const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8627
0
  for (unsigned I = 0; I != NumArgs; ++I) {
8628
0
    if (Args[I].getKind() == TemplateArgument::Pack) {
8629
0
      if (CheckNonTypeTemplatePartialSpecializationArgs(
8630
0
              S, TemplateNameLoc, Param, Args[I].pack_begin(),
8631
0
              Args[I].pack_size(), IsDefaultArgument))
8632
0
        return true;
8633
8634
0
      continue;
8635
0
    }
8636
8637
0
    if (Args[I].getKind() != TemplateArgument::Expression)
8638
0
      continue;
8639
8640
0
    Expr *ArgExpr = Args[I].getAsExpr();
8641
8642
    // We can have a pack expansion of any of the bullets below.
8643
0
    if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8644
0
      ArgExpr = Expansion->getPattern();
8645
8646
    // Strip off any implicit casts we added as part of type checking.
8647
0
    while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8648
0
      ArgExpr = ICE->getSubExpr();
8649
8650
    // C++ [temp.class.spec]p8:
8651
    //   A non-type argument is non-specialized if it is the name of a
8652
    //   non-type parameter. All other non-type arguments are
8653
    //   specialized.
8654
    //
8655
    // Below, we check the two conditions that only apply to
8656
    // specialized non-type arguments, so skip any non-specialized
8657
    // arguments.
8658
0
    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8659
0
      if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8660
0
        continue;
8661
8662
    // C++ [temp.class.spec]p9:
8663
    //   Within the argument list of a class template partial
8664
    //   specialization, the following restrictions apply:
8665
    //     -- A partially specialized non-type argument expression
8666
    //        shall not involve a template parameter of the partial
8667
    //        specialization except when the argument expression is a
8668
    //        simple identifier.
8669
    //     -- The type of a template parameter corresponding to a
8670
    //        specialized non-type argument shall not be dependent on a
8671
    //        parameter of the specialization.
8672
    // DR1315 removes the first bullet, leaving an incoherent set of rules.
8673
    // We implement a compromise between the original rules and DR1315:
8674
    //     --  A specialized non-type template argument shall not be
8675
    //         type-dependent and the corresponding template parameter
8676
    //         shall have a non-dependent type.
8677
0
    SourceRange ParamUseRange =
8678
0
        findTemplateParameterInType(Param->getDepth(), ArgExpr);
8679
0
    if (ParamUseRange.isValid()) {
8680
0
      if (IsDefaultArgument) {
8681
0
        S.Diag(TemplateNameLoc,
8682
0
               diag::err_dependent_non_type_arg_in_partial_spec);
8683
0
        S.Diag(ParamUseRange.getBegin(),
8684
0
               diag::note_dependent_non_type_default_arg_in_partial_spec)
8685
0
          << ParamUseRange;
8686
0
      } else {
8687
0
        S.Diag(ParamUseRange.getBegin(),
8688
0
               diag::err_dependent_non_type_arg_in_partial_spec)
8689
0
          << ParamUseRange;
8690
0
      }
8691
0
      return true;
8692
0
    }
8693
8694
0
    ParamUseRange = findTemplateParameter(
8695
0
        Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8696
0
    if (ParamUseRange.isValid()) {
8697
0
      S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8698
0
             diag::err_dependent_typed_non_type_arg_in_partial_spec)
8699
0
          << Param->getType();
8700
0
      S.NoteTemplateParameterLocation(*Param);
8701
0
      return true;
8702
0
    }
8703
0
  }
8704
8705
0
  return false;
8706
0
}
8707
8708
/// Check the non-type template arguments of a class template
8709
/// partial specialization according to C++ [temp.class.spec]p9.
8710
///
8711
/// \param TemplateNameLoc the location of the template name.
8712
/// \param PrimaryTemplate the template parameters of the primary class
8713
///        template.
8714
/// \param NumExplicit the number of explicitly-specified template arguments.
8715
/// \param TemplateArgs the template arguments of the class template
8716
///        partial specialization.
8717
///
8718
/// \returns \c true if there was an error, \c false otherwise.
8719
bool Sema::CheckTemplatePartialSpecializationArgs(
8720
    SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8721
0
    unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8722
  // We have to be conservative when checking a template in a dependent
8723
  // context.
8724
0
  if (PrimaryTemplate->getDeclContext()->isDependentContext())
8725
0
    return false;
8726
8727
0
  TemplateParameterList *TemplateParams =
8728
0
      PrimaryTemplate->getTemplateParameters();
8729
0
  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8730
0
    NonTypeTemplateParmDecl *Param
8731
0
      = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8732
0
    if (!Param)
8733
0
      continue;
8734
8735
0
    if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8736
0
                                                      Param, &TemplateArgs[I],
8737
0
                                                      1, I >= NumExplicit))
8738
0
      return true;
8739
0
  }
8740
8741
0
  return false;
8742
0
}
8743
8744
DeclResult Sema::ActOnClassTemplateSpecialization(
8745
    Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8746
    SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8747
    TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8748
0
    MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8749
0
  assert(TUK != TUK_Reference && "References are not specializations");
8750
8751
  // NOTE: KWLoc is the location of the tag keyword. This will instead
8752
  // store the location of the outermost template keyword in the declaration.
8753
0
  SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
8754
0
    ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
8755
0
  SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8756
0
  SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8757
0
  SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8758
8759
  // Find the class template we're specializing
8760
0
  TemplateName Name = TemplateId.Template.get();
8761
0
  ClassTemplateDecl *ClassTemplate
8762
0
    = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8763
8764
0
  if (!ClassTemplate) {
8765
0
    Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8766
0
      << (Name.getAsTemplateDecl() &&
8767
0
          isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8768
0
    return true;
8769
0
  }
8770
8771
0
  bool isMemberSpecialization = false;
8772
0
  bool isPartialSpecialization = false;
8773
8774
  // Check the validity of the template headers that introduce this
8775
  // template.
8776
  // FIXME: We probably shouldn't complain about these headers for
8777
  // friend declarations.
8778
0
  bool Invalid = false;
8779
0
  TemplateParameterList *TemplateParams =
8780
0
      MatchTemplateParametersToScopeSpecifier(
8781
0
          KWLoc, TemplateNameLoc, SS, &TemplateId,
8782
0
          TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
8783
0
          Invalid);
8784
0
  if (Invalid)
8785
0
    return true;
8786
8787
  // Check that we can declare a template specialization here.
8788
0
  if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8789
0
    return true;
8790
8791
0
  if (TemplateParams && TemplateParams->size() > 0) {
8792
0
    isPartialSpecialization = true;
8793
8794
0
    if (TUK == TUK_Friend) {
8795
0
      Diag(KWLoc, diag::err_partial_specialization_friend)
8796
0
        << SourceRange(LAngleLoc, RAngleLoc);
8797
0
      return true;
8798
0
    }
8799
8800
    // C++ [temp.class.spec]p10:
8801
    //   The template parameter list of a specialization shall not
8802
    //   contain default template argument values.
8803
0
    for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8804
0
      Decl *Param = TemplateParams->getParam(I);
8805
0
      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8806
0
        if (TTP->hasDefaultArgument()) {
8807
0
          Diag(TTP->getDefaultArgumentLoc(),
8808
0
               diag::err_default_arg_in_partial_spec);
8809
0
          TTP->removeDefaultArgument();
8810
0
        }
8811
0
      } else if (NonTypeTemplateParmDecl *NTTP
8812
0
                   = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8813
0
        if (Expr *DefArg = NTTP->getDefaultArgument()) {
8814
0
          Diag(NTTP->getDefaultArgumentLoc(),
8815
0
               diag::err_default_arg_in_partial_spec)
8816
0
            << DefArg->getSourceRange();
8817
0
          NTTP->removeDefaultArgument();
8818
0
        }
8819
0
      } else {
8820
0
        TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8821
0
        if (TTP->hasDefaultArgument()) {
8822
0
          Diag(TTP->getDefaultArgument().getLocation(),
8823
0
               diag::err_default_arg_in_partial_spec)
8824
0
            << TTP->getDefaultArgument().getSourceRange();
8825
0
          TTP->removeDefaultArgument();
8826
0
        }
8827
0
      }
8828
0
    }
8829
0
  } else if (TemplateParams) {
8830
0
    if (TUK == TUK_Friend)
8831
0
      Diag(KWLoc, diag::err_template_spec_friend)
8832
0
        << FixItHint::CreateRemoval(
8833
0
                                SourceRange(TemplateParams->getTemplateLoc(),
8834
0
                                            TemplateParams->getRAngleLoc()))
8835
0
        << SourceRange(LAngleLoc, RAngleLoc);
8836
0
  } else {
8837
0
    assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
8838
0
  }
8839
8840
  // Check that the specialization uses the same tag kind as the
8841
  // original template.
8842
0
  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8843
0
  assert(Kind != TagTypeKind::Enum &&
8844
0
         "Invalid enum tag in class template spec!");
8845
0
  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8846
0
                                    Kind, TUK == TUK_Definition, KWLoc,
8847
0
                                    ClassTemplate->getIdentifier())) {
8848
0
    Diag(KWLoc, diag::err_use_with_wrong_tag)
8849
0
      << ClassTemplate
8850
0
      << FixItHint::CreateReplacement(KWLoc,
8851
0
                            ClassTemplate->getTemplatedDecl()->getKindName());
8852
0
    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8853
0
         diag::note_previous_use);
8854
0
    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8855
0
  }
8856
8857
  // Translate the parser's template argument list in our AST format.
8858
0
  TemplateArgumentListInfo TemplateArgs =
8859
0
      makeTemplateArgumentListInfo(*this, TemplateId);
8860
8861
  // Check for unexpanded parameter packs in any of the template arguments.
8862
0
  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8863
0
    if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8864
0
                                        isPartialSpecialization
8865
0
                                            ? UPPC_PartialSpecialization
8866
0
                                            : UPPC_ExplicitSpecialization))
8867
0
      return true;
8868
8869
  // Check that the template argument list is well-formed for this
8870
  // template.
8871
0
  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8872
0
  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8873
0
                                false, SugaredConverted, CanonicalConverted,
8874
0
                                /*UpdateArgsWithConversions=*/true))
8875
0
    return true;
8876
8877
  // Find the class template (partial) specialization declaration that
8878
  // corresponds to these arguments.
8879
0
  if (isPartialSpecialization) {
8880
0
    if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8881
0
                                               TemplateArgs.size(),
8882
0
                                               CanonicalConverted))
8883
0
      return true;
8884
8885
    // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8886
    // also do it during instantiation.
8887
0
    if (!Name.isDependent() &&
8888
0
        !TemplateSpecializationType::anyDependentTemplateArguments(
8889
0
            TemplateArgs, CanonicalConverted)) {
8890
0
      Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8891
0
        << ClassTemplate->getDeclName();
8892
0
      isPartialSpecialization = false;
8893
0
    }
8894
0
  }
8895
8896
0
  void *InsertPos = nullptr;
8897
0
  ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8898
8899
0
  if (isPartialSpecialization)
8900
0
    PrevDecl = ClassTemplate->findPartialSpecialization(
8901
0
        CanonicalConverted, TemplateParams, InsertPos);
8902
0
  else
8903
0
    PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8904
8905
0
  ClassTemplateSpecializationDecl *Specialization = nullptr;
8906
8907
  // Check whether we can declare a class template specialization in
8908
  // the current scope.
8909
0
  if (TUK != TUK_Friend &&
8910
0
      CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
8911
0
                                       TemplateNameLoc,
8912
0
                                       isPartialSpecialization))
8913
0
    return true;
8914
8915
  // The canonical type
8916
0
  QualType CanonType;
8917
0
  if (isPartialSpecialization) {
8918
    // Build the canonical type that describes the converted template
8919
    // arguments of the class template partial specialization.
8920
0
    TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8921
0
    CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8922
0
                                                      CanonicalConverted);
8923
8924
0
    if (Context.hasSameType(CanonType,
8925
0
                        ClassTemplate->getInjectedClassNameSpecialization()) &&
8926
0
        (!Context.getLangOpts().CPlusPlus20 ||
8927
0
         !TemplateParams->hasAssociatedConstraints())) {
8928
      // C++ [temp.class.spec]p9b3:
8929
      //
8930
      //   -- The argument list of the specialization shall not be identical
8931
      //      to the implicit argument list of the primary template.
8932
      //
8933
      // This rule has since been removed, because it's redundant given DR1495,
8934
      // but we keep it because it produces better diagnostics and recovery.
8935
0
      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8936
0
        << /*class template*/0 << (TUK == TUK_Definition)
8937
0
        << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8938
0
      return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
8939
0
                                ClassTemplate->getIdentifier(),
8940
0
                                TemplateNameLoc,
8941
0
                                Attr,
8942
0
                                TemplateParams,
8943
0
                                AS_none, /*ModulePrivateLoc=*/SourceLocation(),
8944
0
                                /*FriendLoc*/SourceLocation(),
8945
0
                                TemplateParameterLists.size() - 1,
8946
0
                                TemplateParameterLists.data());
8947
0
    }
8948
8949
    // Create a new class template partial specialization declaration node.
8950
0
    ClassTemplatePartialSpecializationDecl *PrevPartial
8951
0
      = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8952
0
    ClassTemplatePartialSpecializationDecl *Partial =
8953
0
        ClassTemplatePartialSpecializationDecl::Create(
8954
0
            Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
8955
0
            TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
8956
0
            TemplateArgs, CanonType, PrevPartial);
8957
0
    SetNestedNameSpecifier(*this, Partial, SS);
8958
0
    if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8959
0
      Partial->setTemplateParameterListsInfo(
8960
0
          Context, TemplateParameterLists.drop_back(1));
8961
0
    }
8962
8963
0
    if (!PrevPartial)
8964
0
      ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8965
0
    Specialization = Partial;
8966
8967
    // If we are providing an explicit specialization of a member class
8968
    // template specialization, make a note of that.
8969
0
    if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8970
0
      PrevPartial->setMemberSpecialization();
8971
8972
0
    CheckTemplatePartialSpecialization(Partial);
8973
0
  } else {
8974
    // Create a new class template specialization declaration node for
8975
    // this explicit specialization or friend declaration.
8976
0
    Specialization = ClassTemplateSpecializationDecl::Create(
8977
0
        Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8978
0
        ClassTemplate, CanonicalConverted, PrevDecl);
8979
0
    SetNestedNameSpecifier(*this, Specialization, SS);
8980
0
    if (TemplateParameterLists.size() > 0) {
8981
0
      Specialization->setTemplateParameterListsInfo(Context,
8982
0
                                                    TemplateParameterLists);
8983
0
    }
8984
8985
0
    if (!PrevDecl)
8986
0
      ClassTemplate->AddSpecialization(Specialization, InsertPos);
8987
8988
0
    if (CurContext->isDependentContext()) {
8989
0
      TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8990
0
      CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8991
0
                                                        CanonicalConverted);
8992
0
    } else {
8993
0
      CanonType = Context.getTypeDeclType(Specialization);
8994
0
    }
8995
0
  }
8996
8997
  // C++ [temp.expl.spec]p6:
8998
  //   If a template, a member template or the member of a class template is
8999
  //   explicitly specialized then that specialization shall be declared
9000
  //   before the first use of that specialization that would cause an implicit
9001
  //   instantiation to take place, in every translation unit in which such a
9002
  //   use occurs; no diagnostic is required.
9003
0
  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9004
0
    bool Okay = false;
9005
0
    for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9006
      // Is there any previous explicit specialization declaration?
9007
0
      if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
9008
0
        Okay = true;
9009
0
        break;
9010
0
      }
9011
0
    }
9012
9013
0
    if (!Okay) {
9014
0
      SourceRange Range(TemplateNameLoc, RAngleLoc);
9015
0
      Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9016
0
        << Context.getTypeDeclType(Specialization) << Range;
9017
9018
0
      Diag(PrevDecl->getPointOfInstantiation(),
9019
0
           diag::note_instantiation_required_here)
9020
0
        << (PrevDecl->getTemplateSpecializationKind()
9021
0
                                                != TSK_ImplicitInstantiation);
9022
0
      return true;
9023
0
    }
9024
0
  }
9025
9026
  // If this is not a friend, note that this is an explicit specialization.
9027
0
  if (TUK != TUK_Friend)
9028
0
    Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9029
9030
  // Check that this isn't a redefinition of this specialization.
9031
0
  if (TUK == TUK_Definition) {
9032
0
    RecordDecl *Def = Specialization->getDefinition();
9033
0
    NamedDecl *Hidden = nullptr;
9034
0
    if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
9035
0
      SkipBody->ShouldSkip = true;
9036
0
      SkipBody->Previous = Def;
9037
0
      makeMergedDefinitionVisible(Hidden);
9038
0
    } else if (Def) {
9039
0
      SourceRange Range(TemplateNameLoc, RAngleLoc);
9040
0
      Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9041
0
      Diag(Def->getLocation(), diag::note_previous_definition);
9042
0
      Specialization->setInvalidDecl();
9043
0
      return true;
9044
0
    }
9045
0
  }
9046
9047
0
  ProcessDeclAttributeList(S, Specialization, Attr);
9048
9049
  // Add alignment attributes if necessary; these attributes are checked when
9050
  // the ASTContext lays out the structure.
9051
0
  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9052
0
    AddAlignmentAttributesForRecord(Specialization);
9053
0
    AddMsStructLayoutForRecord(Specialization);
9054
0
  }
9055
9056
0
  if (ModulePrivateLoc.isValid())
9057
0
    Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9058
0
      << (isPartialSpecialization? 1 : 0)
9059
0
      << FixItHint::CreateRemoval(ModulePrivateLoc);
9060
9061
  // Build the fully-sugared type for this class template
9062
  // specialization as the user wrote in the specialization
9063
  // itself. This means that we'll pretty-print the type retrieved
9064
  // from the specialization's declaration the way that the user
9065
  // actually wrote the specialization, rather than formatting the
9066
  // name based on the "canonical" representation used to store the
9067
  // template arguments in the specialization.
9068
0
  TypeSourceInfo *WrittenTy
9069
0
    = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
9070
0
                                                TemplateArgs, CanonType);
9071
0
  if (TUK != TUK_Friend) {
9072
0
    Specialization->setTypeAsWritten(WrittenTy);
9073
0
    Specialization->setTemplateKeywordLoc(TemplateKWLoc);
9074
0
  }
9075
9076
  // C++ [temp.expl.spec]p9:
9077
  //   A template explicit specialization is in the scope of the
9078
  //   namespace in which the template was defined.
9079
  //
9080
  // We actually implement this paragraph where we set the semantic
9081
  // context (in the creation of the ClassTemplateSpecializationDecl),
9082
  // but we also maintain the lexical context where the actual
9083
  // definition occurs.
9084
0
  Specialization->setLexicalDeclContext(CurContext);
9085
9086
  // We may be starting the definition of this specialization.
9087
0
  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
9088
0
    Specialization->startDefinition();
9089
9090
0
  if (TUK == TUK_Friend) {
9091
0
    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
9092
0
                                            TemplateNameLoc,
9093
0
                                            WrittenTy,
9094
0
                                            /*FIXME:*/KWLoc);
9095
0
    Friend->setAccess(AS_public);
9096
0
    CurContext->addDecl(Friend);
9097
0
  } else {
9098
    // Add the specialization into its lexical context, so that it can
9099
    // be seen when iterating through the list of declarations in that
9100
    // context. However, specializations are not found by name lookup.
9101
0
    CurContext->addDecl(Specialization);
9102
0
  }
9103
9104
0
  if (SkipBody && SkipBody->ShouldSkip)
9105
0
    return SkipBody->Previous;
9106
9107
0
  return Specialization;
9108
0
}
9109
9110
Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9111
                              MultiTemplateParamsArg TemplateParameterLists,
9112
0
                                    Declarator &D) {
9113
0
  Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9114
0
  ActOnDocumentableDecl(NewDecl);
9115
0
  return NewDecl;
9116
0
}
9117
9118
Decl *Sema::ActOnConceptDefinition(Scope *S,
9119
                              MultiTemplateParamsArg TemplateParameterLists,
9120
                                   IdentifierInfo *Name, SourceLocation NameLoc,
9121
0
                                   Expr *ConstraintExpr) {
9122
0
  DeclContext *DC = CurContext;
9123
9124
0
  if (!DC->getRedeclContext()->isFileContext()) {
9125
0
    Diag(NameLoc,
9126
0
      diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9127
0
    return nullptr;
9128
0
  }
9129
9130
0
  if (TemplateParameterLists.size() > 1) {
9131
0
    Diag(NameLoc, diag::err_concept_extra_headers);
9132
0
    return nullptr;
9133
0
  }
9134
9135
0
  TemplateParameterList *Params = TemplateParameterLists.front();
9136
9137
0
  if (Params->size() == 0) {
9138
0
    Diag(NameLoc, diag::err_concept_no_parameters);
9139
0
    return nullptr;
9140
0
  }
9141
9142
  // Ensure that the parameter pack, if present, is the last parameter in the
9143
  // template.
9144
0
  for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9145
0
                                             ParamEnd = Params->end();
9146
0
       ParamIt != ParamEnd; ++ParamIt) {
9147
0
    Decl const *Param = *ParamIt;
9148
0
    if (Param->isParameterPack()) {
9149
0
      if (++ParamIt == ParamEnd)
9150
0
        break;
9151
0
      Diag(Param->getLocation(),
9152
0
           diag::err_template_param_pack_must_be_last_template_parameter);
9153
0
      return nullptr;
9154
0
    }
9155
0
  }
9156
9157
0
  if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
9158
0
    return nullptr;
9159
9160
0
  ConceptDecl *NewDecl =
9161
0
      ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr);
9162
9163
0
  if (NewDecl->hasAssociatedConstraints()) {
9164
    // C++2a [temp.concept]p4:
9165
    // A concept shall not have associated constraints.
9166
0
    Diag(NameLoc, diag::err_concept_no_associated_constraints);
9167
0
    NewDecl->setInvalidDecl();
9168
0
  }
9169
9170
  // Check for conflicting previous declaration.
9171
0
  DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
9172
0
  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9173
0
                        forRedeclarationInCurContext());
9174
0
  LookupName(Previous, S);
9175
0
  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
9176
0
                       /*AllowInlineNamespace*/false);
9177
0
  bool AddToScope = true;
9178
0
  CheckConceptRedefinition(NewDecl, Previous, AddToScope);
9179
9180
0
  ActOnDocumentableDecl(NewDecl);
9181
0
  if (AddToScope)
9182
0
    PushOnScopeChains(NewDecl, S);
9183
0
  return NewDecl;
9184
0
}
9185
9186
void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9187
0
                                    LookupResult &Previous, bool &AddToScope) {
9188
0
  AddToScope = true;
9189
9190
0
  if (Previous.empty())
9191
0
    return;
9192
9193
0
  auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9194
0
  if (!OldConcept) {
9195
0
    auto *Old = Previous.getRepresentativeDecl();
9196
0
    Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9197
0
        << NewDecl->getDeclName();
9198
0
    notePreviousDefinition(Old, NewDecl->getLocation());
9199
0
    AddToScope = false;
9200
0
    return;
9201
0
  }
9202
  // Check if we can merge with a concept declaration.
9203
0
  bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9204
0
  if (!IsSame) {
9205
0
    Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9206
0
        << NewDecl->getDeclName();
9207
0
    notePreviousDefinition(OldConcept, NewDecl->getLocation());
9208
0
    AddToScope = false;
9209
0
    return;
9210
0
  }
9211
0
  if (hasReachableDefinition(OldConcept) &&
9212
0
      IsRedefinitionInModule(NewDecl, OldConcept)) {
9213
0
    Diag(NewDecl->getLocation(), diag::err_redefinition)
9214
0
        << NewDecl->getDeclName();
9215
0
    notePreviousDefinition(OldConcept, NewDecl->getLocation());
9216
0
    AddToScope = false;
9217
0
    return;
9218
0
  }
9219
0
  if (!Previous.isSingleResult()) {
9220
    // FIXME: we should produce an error in case of ambig and failed lookups.
9221
    //        Other decls (e.g. namespaces) also have this shortcoming.
9222
0
    return;
9223
0
  }
9224
  // We unwrap canonical decl late to check for module visibility.
9225
0
  Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9226
0
}
9227
9228
/// \brief Strips various properties off an implicit instantiation
9229
/// that has just been explicitly specialized.
9230
0
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9231
0
  if (MinGW || (isa<FunctionDecl>(D) &&
9232
0
                cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())) {
9233
0
    D->dropAttr<DLLImportAttr>();
9234
0
    D->dropAttr<DLLExportAttr>();
9235
0
  }
9236
9237
0
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9238
0
    FD->setInlineSpecified(false);
9239
0
}
9240
9241
/// Compute the diagnostic location for an explicit instantiation
9242
//  declaration or definition.
9243
static SourceLocation DiagLocForExplicitInstantiation(
9244
0
    NamedDecl* D, SourceLocation PointOfInstantiation) {
9245
  // Explicit instantiations following a specialization have no effect and
9246
  // hence no PointOfInstantiation. In that case, walk decl backwards
9247
  // until a valid name loc is found.
9248
0
  SourceLocation PrevDiagLoc = PointOfInstantiation;
9249
0
  for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9250
0
       Prev = Prev->getPreviousDecl()) {
9251
0
    PrevDiagLoc = Prev->getLocation();
9252
0
  }
9253
0
  assert(PrevDiagLoc.isValid() &&
9254
0
         "Explicit instantiation without point of instantiation?");
9255
0
  return PrevDiagLoc;
9256
0
}
9257
9258
/// Diagnose cases where we have an explicit template specialization
9259
/// before/after an explicit template instantiation, producing diagnostics
9260
/// for those cases where they are required and determining whether the
9261
/// new specialization/instantiation will have any effect.
9262
///
9263
/// \param NewLoc the location of the new explicit specialization or
9264
/// instantiation.
9265
///
9266
/// \param NewTSK the kind of the new explicit specialization or instantiation.
9267
///
9268
/// \param PrevDecl the previous declaration of the entity.
9269
///
9270
/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
9271
///
9272
/// \param PrevPointOfInstantiation if valid, indicates where the previous
9273
/// declaration was instantiated (either implicitly or explicitly).
9274
///
9275
/// \param HasNoEffect will be set to true to indicate that the new
9276
/// specialization or instantiation has no effect and should be ignored.
9277
///
9278
/// \returns true if there was an error that should prevent the introduction of
9279
/// the new declaration into the AST, false otherwise.
9280
bool
9281
Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9282
                                             TemplateSpecializationKind NewTSK,
9283
                                             NamedDecl *PrevDecl,
9284
                                             TemplateSpecializationKind PrevTSK,
9285
                                        SourceLocation PrevPointOfInstantiation,
9286
0
                                             bool &HasNoEffect) {
9287
0
  HasNoEffect = false;
9288
9289
0
  switch (NewTSK) {
9290
0
  case TSK_Undeclared:
9291
0
  case TSK_ImplicitInstantiation:
9292
0
    assert(
9293
0
        (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9294
0
        "previous declaration must be implicit!");
9295
0
    return false;
9296
9297
0
  case TSK_ExplicitSpecialization:
9298
0
    switch (PrevTSK) {
9299
0
    case TSK_Undeclared:
9300
0
    case TSK_ExplicitSpecialization:
9301
      // Okay, we're just specializing something that is either already
9302
      // explicitly specialized or has merely been mentioned without any
9303
      // instantiation.
9304
0
      return false;
9305
9306
0
    case TSK_ImplicitInstantiation:
9307
0
      if (PrevPointOfInstantiation.isInvalid()) {
9308
        // The declaration itself has not actually been instantiated, so it is
9309
        // still okay to specialize it.
9310
0
        StripImplicitInstantiation(
9311
0
            PrevDecl,
9312
0
            Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
9313
0
        return false;
9314
0
      }
9315
      // Fall through
9316
0
      [[fallthrough]];
9317
9318
0
    case TSK_ExplicitInstantiationDeclaration:
9319
0
    case TSK_ExplicitInstantiationDefinition:
9320
0
      assert((PrevTSK == TSK_ImplicitInstantiation ||
9321
0
              PrevPointOfInstantiation.isValid()) &&
9322
0
             "Explicit instantiation without point of instantiation?");
9323
9324
      // C++ [temp.expl.spec]p6:
9325
      //   If a template, a member template or the member of a class template
9326
      //   is explicitly specialized then that specialization shall be declared
9327
      //   before the first use of that specialization that would cause an
9328
      //   implicit instantiation to take place, in every translation unit in
9329
      //   which such a use occurs; no diagnostic is required.
9330
0
      for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9331
        // Is there any previous explicit specialization declaration?
9332
0
        if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
9333
0
          return false;
9334
0
      }
9335
9336
0
      Diag(NewLoc, diag::err_specialization_after_instantiation)
9337
0
        << PrevDecl;
9338
0
      Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9339
0
        << (PrevTSK != TSK_ImplicitInstantiation);
9340
9341
0
      return true;
9342
0
    }
9343
0
    llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9344
9345
0
  case TSK_ExplicitInstantiationDeclaration:
9346
0
    switch (PrevTSK) {
9347
0
    case TSK_ExplicitInstantiationDeclaration:
9348
      // This explicit instantiation declaration is redundant (that's okay).
9349
0
      HasNoEffect = true;
9350
0
      return false;
9351
9352
0
    case TSK_Undeclared:
9353
0
    case TSK_ImplicitInstantiation:
9354
      // We're explicitly instantiating something that may have already been
9355
      // implicitly instantiated; that's fine.
9356
0
      return false;
9357
9358
0
    case TSK_ExplicitSpecialization:
9359
      // C++0x [temp.explicit]p4:
9360
      //   For a given set of template parameters, if an explicit instantiation
9361
      //   of a template appears after a declaration of an explicit
9362
      //   specialization for that template, the explicit instantiation has no
9363
      //   effect.
9364
0
      HasNoEffect = true;
9365
0
      return false;
9366
9367
0
    case TSK_ExplicitInstantiationDefinition:
9368
      // C++0x [temp.explicit]p10:
9369
      //   If an entity is the subject of both an explicit instantiation
9370
      //   declaration and an explicit instantiation definition in the same
9371
      //   translation unit, the definition shall follow the declaration.
9372
0
      Diag(NewLoc,
9373
0
           diag::err_explicit_instantiation_declaration_after_definition);
9374
9375
      // Explicit instantiations following a specialization have no effect and
9376
      // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9377
      // until a valid name loc is found.
9378
0
      Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9379
0
           diag::note_explicit_instantiation_definition_here);
9380
0
      HasNoEffect = true;
9381
0
      return false;
9382
0
    }
9383
0
    llvm_unreachable("Unexpected TemplateSpecializationKind!");
9384
9385
0
  case TSK_ExplicitInstantiationDefinition:
9386
0
    switch (PrevTSK) {
9387
0
    case TSK_Undeclared:
9388
0
    case TSK_ImplicitInstantiation:
9389
      // We're explicitly instantiating something that may have already been
9390
      // implicitly instantiated; that's fine.
9391
0
      return false;
9392
9393
0
    case TSK_ExplicitSpecialization:
9394
      // C++ DR 259, C++0x [temp.explicit]p4:
9395
      //   For a given set of template parameters, if an explicit
9396
      //   instantiation of a template appears after a declaration of
9397
      //   an explicit specialization for that template, the explicit
9398
      //   instantiation has no effect.
9399
0
      Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9400
0
        << PrevDecl;
9401
0
      Diag(PrevDecl->getLocation(),
9402
0
           diag::note_previous_template_specialization);
9403
0
      HasNoEffect = true;
9404
0
      return false;
9405
9406
0
    case TSK_ExplicitInstantiationDeclaration:
9407
      // We're explicitly instantiating a definition for something for which we
9408
      // were previously asked to suppress instantiations. That's fine.
9409
9410
      // C++0x [temp.explicit]p4:
9411
      //   For a given set of template parameters, if an explicit instantiation
9412
      //   of a template appears after a declaration of an explicit
9413
      //   specialization for that template, the explicit instantiation has no
9414
      //   effect.
9415
0
      for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9416
        // Is there any previous explicit specialization declaration?
9417
0
        if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
9418
0
          HasNoEffect = true;
9419
0
          break;
9420
0
        }
9421
0
      }
9422
9423
0
      return false;
9424
9425
0
    case TSK_ExplicitInstantiationDefinition:
9426
      // C++0x [temp.spec]p5:
9427
      //   For a given template and a given set of template-arguments,
9428
      //     - an explicit instantiation definition shall appear at most once
9429
      //       in a program,
9430
9431
      // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9432
0
      Diag(NewLoc, (getLangOpts().MSVCCompat)
9433
0
                       ? diag::ext_explicit_instantiation_duplicate
9434
0
                       : diag::err_explicit_instantiation_duplicate)
9435
0
          << PrevDecl;
9436
0
      Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9437
0
           diag::note_previous_explicit_instantiation);
9438
0
      HasNoEffect = true;
9439
0
      return false;
9440
0
    }
9441
0
  }
9442
9443
0
  llvm_unreachable("Missing specialization/instantiation case?");
9444
0
}
9445
9446
/// Perform semantic analysis for the given dependent function
9447
/// template specialization.
9448
///
9449
/// The only possible way to get a dependent function template specialization
9450
/// is with a friend declaration, like so:
9451
///
9452
/// \code
9453
///   template \<class T> void foo(T);
9454
///   template \<class T> class A {
9455
///     friend void foo<>(T);
9456
///   };
9457
/// \endcode
9458
///
9459
/// There really isn't any useful analysis we can do here, so we
9460
/// just store the information.
9461
bool Sema::CheckDependentFunctionTemplateSpecialization(
9462
    FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9463
0
    LookupResult &Previous) {
9464
  // Remove anything from Previous that isn't a function template in
9465
  // the correct context.
9466
0
  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9467
0
  LookupResult::Filter F = Previous.makeFilter();
9468
0
  enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9469
0
  SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9470
0
  while (F.hasNext()) {
9471
0
    NamedDecl *D = F.next()->getUnderlyingDecl();
9472
0
    if (!isa<FunctionTemplateDecl>(D)) {
9473
0
      F.erase();
9474
0
      DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9475
0
      continue;
9476
0
    }
9477
9478
0
    if (!FDLookupContext->InEnclosingNamespaceSetOf(
9479
0
            D->getDeclContext()->getRedeclContext())) {
9480
0
      F.erase();
9481
0
      DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9482
0
      continue;
9483
0
    }
9484
0
  }
9485
0
  F.done();
9486
9487
0
  bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9488
0
  if (Previous.empty()) {
9489
0
    Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9490
0
        << IsFriend;
9491
0
    for (auto &P : DiscardedCandidates)
9492
0
      Diag(P.second->getLocation(),
9493
0
           diag::note_dependent_function_template_spec_discard_reason)
9494
0
          << P.first << IsFriend;
9495
0
    return true;
9496
0
  }
9497
9498
0
  FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
9499
0
                                         ExplicitTemplateArgs);
9500
0
  return false;
9501
0
}
9502
9503
/// Perform semantic analysis for the given function template
9504
/// specialization.
9505
///
9506
/// This routine performs all of the semantic analysis required for an
9507
/// explicit function template specialization. On successful completion,
9508
/// the function declaration \p FD will become a function template
9509
/// specialization.
9510
///
9511
/// \param FD the function declaration, which will be updated to become a
9512
/// function template specialization.
9513
///
9514
/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
9515
/// if any. Note that this may be valid info even when 0 arguments are
9516
/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
9517
/// as it anyway contains info on the angle brackets locations.
9518
///
9519
/// \param Previous the set of declarations that may be specialized by
9520
/// this function specialization.
9521
///
9522
/// \param QualifiedFriend whether this is a lookup for a qualified friend
9523
/// declaration with no explicit template argument list that might be
9524
/// befriending a function template specialization.
9525
bool Sema::CheckFunctionTemplateSpecialization(
9526
    FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9527
0
    LookupResult &Previous, bool QualifiedFriend) {
9528
  // The set of function template specializations that could match this
9529
  // explicit function template specialization.
9530
0
  UnresolvedSet<8> Candidates;
9531
0
  TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9532
0
                                            /*ForTakingAddress=*/false);
9533
9534
0
  llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9535
0
      ConvertedTemplateArgs;
9536
9537
0
  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9538
0
  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9539
0
         I != E; ++I) {
9540
0
    NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9541
0
    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9542
      // Only consider templates found within the same semantic lookup scope as
9543
      // FD.
9544
0
      if (!FDLookupContext->InEnclosingNamespaceSetOf(
9545
0
                                Ovl->getDeclContext()->getRedeclContext()))
9546
0
        continue;
9547
9548
      // When matching a constexpr member function template specialization
9549
      // against the primary template, we don't yet know whether the
9550
      // specialization has an implicit 'const' (because we don't know whether
9551
      // it will be a static member function until we know which template it
9552
      // specializes), so adjust it now assuming it specializes this template.
9553
0
      QualType FT = FD->getType();
9554
0
      if (FD->isConstexpr()) {
9555
0
        CXXMethodDecl *OldMD =
9556
0
          dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9557
0
        if (OldMD && OldMD->isConst()) {
9558
0
          const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9559
0
          FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9560
0
          EPI.TypeQuals.addConst();
9561
0
          FT = Context.getFunctionType(FPT->getReturnType(),
9562
0
                                       FPT->getParamTypes(), EPI);
9563
0
        }
9564
0
      }
9565
9566
0
      TemplateArgumentListInfo Args;
9567
0
      if (ExplicitTemplateArgs)
9568
0
        Args = *ExplicitTemplateArgs;
9569
9570
      // C++ [temp.expl.spec]p11:
9571
      //   A trailing template-argument can be left unspecified in the
9572
      //   template-id naming an explicit function template specialization
9573
      //   provided it can be deduced from the function argument type.
9574
      // Perform template argument deduction to determine whether we may be
9575
      // specializing this template.
9576
      // FIXME: It is somewhat wasteful to build
9577
0
      TemplateDeductionInfo Info(FailedCandidates.getLocation());
9578
0
      FunctionDecl *Specialization = nullptr;
9579
0
      if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9580
0
              cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9581
0
              ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
9582
0
              Info)) {
9583
        // Template argument deduction failed; record why it failed, so
9584
        // that we can provide nifty diagnostics.
9585
0
        FailedCandidates.addCandidate().set(
9586
0
            I.getPair(), FunTmpl->getTemplatedDecl(),
9587
0
            MakeDeductionFailureInfo(Context, TDK, Info));
9588
0
        (void)TDK;
9589
0
        continue;
9590
0
      }
9591
9592
      // Target attributes are part of the cuda function signature, so
9593
      // the deduced template's cuda target must match that of the
9594
      // specialization.  Given that C++ template deduction does not
9595
      // take target attributes into account, we reject candidates
9596
      // here that have a different target.
9597
0
      if (LangOpts.CUDA &&
9598
0
          IdentifyCUDATarget(Specialization,
9599
0
                             /* IgnoreImplicitHDAttr = */ true) !=
9600
0
              IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9601
0
        FailedCandidates.addCandidate().set(
9602
0
            I.getPair(), FunTmpl->getTemplatedDecl(),
9603
0
            MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9604
0
        continue;
9605
0
      }
9606
9607
      // Record this candidate.
9608
0
      if (ExplicitTemplateArgs)
9609
0
        ConvertedTemplateArgs[Specialization] = std::move(Args);
9610
0
      Candidates.addDecl(Specialization, I.getAccess());
9611
0
    }
9612
0
  }
9613
9614
  // For a qualified friend declaration (with no explicit marker to indicate
9615
  // that a template specialization was intended), note all (template and
9616
  // non-template) candidates.
9617
0
  if (QualifiedFriend && Candidates.empty()) {
9618
0
    Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9619
0
        << FD->getDeclName() << FDLookupContext;
9620
    // FIXME: We should form a single candidate list and diagnose all
9621
    // candidates at once, to get proper sorting and limiting.
9622
0
    for (auto *OldND : Previous) {
9623
0
      if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9624
0
        NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9625
0
    }
9626
0
    FailedCandidates.NoteCandidates(*this, FD->getLocation());
9627
0
    return true;
9628
0
  }
9629
9630
  // Find the most specialized function template.
9631
0
  UnresolvedSetIterator Result = getMostSpecialized(
9632
0
      Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9633
0
      PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9634
0
      PDiag(diag::err_function_template_spec_ambiguous)
9635
0
          << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9636
0
      PDiag(diag::note_function_template_spec_matched));
9637
9638
0
  if (Result == Candidates.end())
9639
0
    return true;
9640
9641
  // Ignore access information;  it doesn't figure into redeclaration checking.
9642
0
  FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9643
9644
0
  FunctionTemplateSpecializationInfo *SpecInfo
9645
0
    = Specialization->getTemplateSpecializationInfo();
9646
0
  assert(SpecInfo && "Function template specialization info missing?");
9647
9648
  // Note: do not overwrite location info if previous template
9649
  // specialization kind was explicit.
9650
0
  TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9651
0
  if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9652
0
    Specialization->setLocation(FD->getLocation());
9653
0
    Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9654
    // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9655
    // function can differ from the template declaration with respect to
9656
    // the constexpr specifier.
9657
    // FIXME: We need an update record for this AST mutation.
9658
    // FIXME: What if there are multiple such prior declarations (for instance,
9659
    // from different modules)?
9660
0
    Specialization->setConstexprKind(FD->getConstexprKind());
9661
0
  }
9662
9663
  // FIXME: Check if the prior specialization has a point of instantiation.
9664
  // If so, we have run afoul of .
9665
9666
  // If this is a friend declaration, then we're not really declaring
9667
  // an explicit specialization.
9668
0
  bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9669
9670
  // Check the scope of this explicit specialization.
9671
0
  if (!isFriend &&
9672
0
      CheckTemplateSpecializationScope(*this,
9673
0
                                       Specialization->getPrimaryTemplate(),
9674
0
                                       Specialization, FD->getLocation(),
9675
0
                                       false))
9676
0
    return true;
9677
9678
  // C++ [temp.expl.spec]p6:
9679
  //   If a template, a member template or the member of a class template is
9680
  //   explicitly specialized then that specialization shall be declared
9681
  //   before the first use of that specialization that would cause an implicit
9682
  //   instantiation to take place, in every translation unit in which such a
9683
  //   use occurs; no diagnostic is required.
9684
0
  bool HasNoEffect = false;
9685
0
  if (!isFriend &&
9686
0
      CheckSpecializationInstantiationRedecl(FD->getLocation(),
9687
0
                                             TSK_ExplicitSpecialization,
9688
0
                                             Specialization,
9689
0
                                   SpecInfo->getTemplateSpecializationKind(),
9690
0
                                         SpecInfo->getPointOfInstantiation(),
9691
0
                                             HasNoEffect))
9692
0
    return true;
9693
9694
  // Mark the prior declaration as an explicit specialization, so that later
9695
  // clients know that this is an explicit specialization.
9696
0
  if (!isFriend) {
9697
    // Since explicit specializations do not inherit '=delete' from their
9698
    // primary function template - check if the 'specialization' that was
9699
    // implicitly generated (during template argument deduction for partial
9700
    // ordering) from the most specialized of all the function templates that
9701
    // 'FD' could have been specializing, has a 'deleted' definition.  If so,
9702
    // first check that it was implicitly generated during template argument
9703
    // deduction by making sure it wasn't referenced, and then reset the deleted
9704
    // flag to not-deleted, so that we can inherit that information from 'FD'.
9705
0
    if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9706
0
        !Specialization->getCanonicalDecl()->isReferenced()) {
9707
      // FIXME: This assert will not hold in the presence of modules.
9708
0
      assert(
9709
0
          Specialization->getCanonicalDecl() == Specialization &&
9710
0
          "This must be the only existing declaration of this specialization");
9711
      // FIXME: We need an update record for this AST mutation.
9712
0
      Specialization->setDeletedAsWritten(false);
9713
0
    }
9714
    // FIXME: We need an update record for this AST mutation.
9715
0
    SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9716
0
    MarkUnusedFileScopedDecl(Specialization);
9717
0
  }
9718
9719
  // Turn the given function declaration into a function template
9720
  // specialization, with the template arguments from the previous
9721
  // specialization.
9722
  // Take copies of (semantic and syntactic) template argument lists.
9723
0
  const TemplateArgumentList* TemplArgs = new (Context)
9724
0
    TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
9725
0
  FD->setFunctionTemplateSpecialization(
9726
0
      Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9727
0
      SpecInfo->getTemplateSpecializationKind(),
9728
0
      ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9729
9730
  // A function template specialization inherits the target attributes
9731
  // of its template.  (We require the attributes explicitly in the
9732
  // code to match, but a template may have implicit attributes by
9733
  // virtue e.g. of being constexpr, and it passes these implicit
9734
  // attributes on to its specializations.)
9735
0
  if (LangOpts.CUDA)
9736
0
    inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
9737
9738
  // The "previous declaration" for this function template specialization is
9739
  // the prior function template specialization.
9740
0
  Previous.clear();
9741
0
  Previous.addDecl(Specialization);
9742
0
  return false;
9743
0
}
9744
9745
/// Perform semantic analysis for the given non-template member
9746
/// specialization.
9747
///
9748
/// This routine performs all of the semantic analysis required for an
9749
/// explicit member function specialization. On successful completion,
9750
/// the function declaration \p FD will become a member function
9751
/// specialization.
9752
///
9753
/// \param Member the member declaration, which will be updated to become a
9754
/// specialization.
9755
///
9756
/// \param Previous the set of declarations, one of which may be specialized
9757
/// by this function specialization;  the set will be modified to contain the
9758
/// redeclared member.
9759
bool
9760
0
Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9761
0
  assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
9762
9763
  // Try to find the member we are instantiating.
9764
0
  NamedDecl *FoundInstantiation = nullptr;
9765
0
  NamedDecl *Instantiation = nullptr;
9766
0
  NamedDecl *InstantiatedFrom = nullptr;
9767
0
  MemberSpecializationInfo *MSInfo = nullptr;
9768
9769
0
  if (Previous.empty()) {
9770
    // Nowhere to look anyway.
9771
0
  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9772
0
    for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9773
0
           I != E; ++I) {
9774
0
      NamedDecl *D = (*I)->getUnderlyingDecl();
9775
0
      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
9776
0
        QualType Adjusted = Function->getType();
9777
0
        if (!hasExplicitCallingConv(Adjusted))
9778
0
          Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9779
        // This doesn't handle deduced return types, but both function
9780
        // declarations should be undeduced at this point.
9781
0
        if (Context.hasSameType(Adjusted, Method->getType())) {
9782
0
          FoundInstantiation = *I;
9783
0
          Instantiation = Method;
9784
0
          InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
9785
0
          MSInfo = Method->getMemberSpecializationInfo();
9786
0
          break;
9787
0
        }
9788
0
      }
9789
0
    }
9790
0
  } else if (isa<VarDecl>(Member)) {
9791
0
    VarDecl *PrevVar;
9792
0
    if (Previous.isSingleResult() &&
9793
0
        (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9794
0
      if (PrevVar->isStaticDataMember()) {
9795
0
        FoundInstantiation = Previous.getRepresentativeDecl();
9796
0
        Instantiation = PrevVar;
9797
0
        InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9798
0
        MSInfo = PrevVar->getMemberSpecializationInfo();
9799
0
      }
9800
0
  } else if (isa<RecordDecl>(Member)) {
9801
0
    CXXRecordDecl *PrevRecord;
9802
0
    if (Previous.isSingleResult() &&
9803
0
        (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9804
0
      FoundInstantiation = Previous.getRepresentativeDecl();
9805
0
      Instantiation = PrevRecord;
9806
0
      InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9807
0
      MSInfo = PrevRecord->getMemberSpecializationInfo();
9808
0
    }
9809
0
  } else if (isa<EnumDecl>(Member)) {
9810
0
    EnumDecl *PrevEnum;
9811
0
    if (Previous.isSingleResult() &&
9812
0
        (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9813
0
      FoundInstantiation = Previous.getRepresentativeDecl();
9814
0
      Instantiation = PrevEnum;
9815
0
      InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9816
0
      MSInfo = PrevEnum->getMemberSpecializationInfo();
9817
0
    }
9818
0
  }
9819
9820
0
  if (!Instantiation) {
9821
    // There is no previous declaration that matches. Since member
9822
    // specializations are always out-of-line, the caller will complain about
9823
    // this mismatch later.
9824
0
    return false;
9825
0
  }
9826
9827
  // A member specialization in a friend declaration isn't really declaring
9828
  // an explicit specialization, just identifying a specific (possibly implicit)
9829
  // specialization. Don't change the template specialization kind.
9830
  //
9831
  // FIXME: Is this really valid? Other compilers reject.
9832
0
  if (Member->getFriendObjectKind() != Decl::FOK_None) {
9833
    // Preserve instantiation information.
9834
0
    if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9835
0
      cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9836
0
                                      cast<CXXMethodDecl>(InstantiatedFrom),
9837
0
        cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9838
0
    } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9839
0
      cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9840
0
                                      cast<CXXRecordDecl>(InstantiatedFrom),
9841
0
        cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9842
0
    }
9843
9844
0
    Previous.clear();
9845
0
    Previous.addDecl(FoundInstantiation);
9846
0
    return false;
9847
0
  }
9848
9849
  // Make sure that this is a specialization of a member.
9850
0
  if (!InstantiatedFrom) {
9851
0
    Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9852
0
      << Member;
9853
0
    Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9854
0
    return true;
9855
0
  }
9856
9857
  // C++ [temp.expl.spec]p6:
9858
  //   If a template, a member template or the member of a class template is
9859
  //   explicitly specialized then that specialization shall be declared
9860
  //   before the first use of that specialization that would cause an implicit
9861
  //   instantiation to take place, in every translation unit in which such a
9862
  //   use occurs; no diagnostic is required.
9863
0
  assert(MSInfo && "Member specialization info missing?");
9864
9865
0
  bool HasNoEffect = false;
9866
0
  if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
9867
0
                                             TSK_ExplicitSpecialization,
9868
0
                                             Instantiation,
9869
0
                                     MSInfo->getTemplateSpecializationKind(),
9870
0
                                           MSInfo->getPointOfInstantiation(),
9871
0
                                             HasNoEffect))
9872
0
    return true;
9873
9874
  // Check the scope of this explicit specialization.
9875
0
  if (CheckTemplateSpecializationScope(*this,
9876
0
                                       InstantiatedFrom,
9877
0
                                       Instantiation, Member->getLocation(),
9878
0
                                       false))
9879
0
    return true;
9880
9881
  // Note that this member specialization is an "instantiation of" the
9882
  // corresponding member of the original template.
9883
0
  if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9884
0
    FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9885
0
    if (InstantiationFunction->getTemplateSpecializationKind() ==
9886
0
          TSK_ImplicitInstantiation) {
9887
      // Explicit specializations of member functions of class templates do not
9888
      // inherit '=delete' from the member function they are specializing.
9889
0
      if (InstantiationFunction->isDeleted()) {
9890
        // FIXME: This assert will not hold in the presence of modules.
9891
0
        assert(InstantiationFunction->getCanonicalDecl() ==
9892
0
               InstantiationFunction);
9893
        // FIXME: We need an update record for this AST mutation.
9894
0
        InstantiationFunction->setDeletedAsWritten(false);
9895
0
      }
9896
0
    }
9897
9898
0
    MemberFunction->setInstantiationOfMemberFunction(
9899
0
        cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9900
0
  } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9901
0
    MemberVar->setInstantiationOfStaticDataMember(
9902
0
        cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9903
0
  } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9904
0
    MemberClass->setInstantiationOfMemberClass(
9905
0
        cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9906
0
  } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9907
0
    MemberEnum->setInstantiationOfMemberEnum(
9908
0
        cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9909
0
  } else {
9910
0
    llvm_unreachable("unknown member specialization kind");
9911
0
  }
9912
9913
  // Save the caller the trouble of having to figure out which declaration
9914
  // this specialization matches.
9915
0
  Previous.clear();
9916
0
  Previous.addDecl(FoundInstantiation);
9917
0
  return false;
9918
0
}
9919
9920
/// Complete the explicit specialization of a member of a class template by
9921
/// updating the instantiated member to be marked as an explicit specialization.
9922
///
9923
/// \param OrigD The member declaration instantiated from the template.
9924
/// \param Loc The location of the explicit specialization of the member.
9925
template<typename DeclT>
9926
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9927
0
                                             SourceLocation Loc) {
9928
0
  if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9929
0
    return;
9930
9931
  // FIXME: Inform AST mutation listeners of this AST mutation.
9932
  // FIXME: If there are multiple in-class declarations of the member (from
9933
  // multiple modules, or a declaration and later definition of a member type),
9934
  // should we update all of them?
9935
0
  OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9936
0
  OrigD->setLocation(Loc);
9937
0
}
Unexecuted instantiation: SemaTemplate.cpp:void completeMemberSpecializationImpl<clang::CXXMethodDecl>(clang::Sema&, clang::CXXMethodDecl*, clang::SourceLocation)
Unexecuted instantiation: SemaTemplate.cpp:void completeMemberSpecializationImpl<clang::VarDecl>(clang::Sema&, clang::VarDecl*, clang::SourceLocation)
Unexecuted instantiation: SemaTemplate.cpp:void completeMemberSpecializationImpl<clang::CXXRecordDecl>(clang::Sema&, clang::CXXRecordDecl*, clang::SourceLocation)
Unexecuted instantiation: SemaTemplate.cpp:void completeMemberSpecializationImpl<clang::EnumDecl>(clang::Sema&, clang::EnumDecl*, clang::SourceLocation)
9938
9939
void Sema::CompleteMemberSpecialization(NamedDecl *Member,
9940
0
                                        LookupResult &Previous) {
9941
0
  NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9942
0
  if (Instantiation == Member)
9943
0
    return;
9944
9945
0
  if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9946
0
    completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9947
0
  else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9948
0
    completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9949
0
  else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9950
0
    completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9951
0
  else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9952
0
    completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9953
0
  else
9954
0
    llvm_unreachable("unknown member specialization kind");
9955
0
}
9956
9957
/// Check the scope of an explicit instantiation.
9958
///
9959
/// \returns true if a serious error occurs, false otherwise.
9960
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
9961
                                            SourceLocation InstLoc,
9962
0
                                            bool WasQualifiedName) {
9963
0
  DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
9964
0
  DeclContext *CurContext = S.CurContext->getRedeclContext();
9965
9966
0
  if (CurContext->isRecord()) {
9967
0
    S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9968
0
      << D;
9969
0
    return true;
9970
0
  }
9971
9972
  // C++11 [temp.explicit]p3:
9973
  //   An explicit instantiation shall appear in an enclosing namespace of its
9974
  //   template. If the name declared in the explicit instantiation is an
9975
  //   unqualified name, the explicit instantiation shall appear in the
9976
  //   namespace where its template is declared or, if that namespace is inline
9977
  //   (7.3.1), any namespace from its enclosing namespace set.
9978
  //
9979
  // This is DR275, which we do not retroactively apply to C++98/03.
9980
0
  if (WasQualifiedName) {
9981
0
    if (CurContext->Encloses(OrigContext))
9982
0
      return false;
9983
0
  } else {
9984
0
    if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9985
0
      return false;
9986
0
  }
9987
9988
0
  if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9989
0
    if (WasQualifiedName)
9990
0
      S.Diag(InstLoc,
9991
0
             S.getLangOpts().CPlusPlus11?
9992
0
               diag::err_explicit_instantiation_out_of_scope :
9993
0
               diag::warn_explicit_instantiation_out_of_scope_0x)
9994
0
        << D << NS;
9995
0
    else
9996
0
      S.Diag(InstLoc,
9997
0
             S.getLangOpts().CPlusPlus11?
9998
0
               diag::err_explicit_instantiation_unqualified_wrong_namespace :
9999
0
               diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10000
0
        << D << NS;
10001
0
  } else
10002
0
    S.Diag(InstLoc,
10003
0
           S.getLangOpts().CPlusPlus11?
10004
0
             diag::err_explicit_instantiation_must_be_global :
10005
0
             diag::warn_explicit_instantiation_must_be_global_0x)
10006
0
      << D;
10007
0
  S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10008
0
  return false;
10009
0
}
10010
10011
/// Common checks for whether an explicit instantiation of \p D is valid.
10012
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10013
                                       SourceLocation InstLoc,
10014
                                       bool WasQualifiedName,
10015
0
                                       TemplateSpecializationKind TSK) {
10016
  // C++ [temp.explicit]p13:
10017
  //   An explicit instantiation declaration shall not name a specialization of
10018
  //   a template with internal linkage.
10019
0
  if (TSK == TSK_ExplicitInstantiationDeclaration &&
10020
0
      D->getFormalLinkage() == Linkage::Internal) {
10021
0
    S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10022
0
    return true;
10023
0
  }
10024
10025
  // C++11 [temp.explicit]p3: [DR 275]
10026
  //   An explicit instantiation shall appear in an enclosing namespace of its
10027
  //   template.
10028
0
  if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10029
0
    return true;
10030
10031
0
  return false;
10032
0
}
10033
10034
/// Determine whether the given scope specifier has a template-id in it.
10035
0
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10036
0
  if (!SS.isSet())
10037
0
    return false;
10038
10039
  // C++11 [temp.explicit]p3:
10040
  //   If the explicit instantiation is for a member function, a member class
10041
  //   or a static data member of a class template specialization, the name of
10042
  //   the class template specialization in the qualified-id for the member
10043
  //   name shall be a simple-template-id.
10044
  //
10045
  // C++98 has the same restriction, just worded differently.
10046
0
  for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
10047
0
       NNS = NNS->getPrefix())
10048
0
    if (const Type *T = NNS->getAsType())
10049
0
      if (isa<TemplateSpecializationType>(T))
10050
0
        return true;
10051
10052
0
  return false;
10053
0
}
10054
10055
/// Make a dllexport or dllimport attr on a class template specialization take
10056
/// effect.
10057
static void dllExportImportClassTemplateSpecialization(
10058
0
    Sema &S, ClassTemplateSpecializationDecl *Def) {
10059
0
  auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10060
0
  assert(A && "dllExportImportClassTemplateSpecialization called "
10061
0
              "on Def without dllexport or dllimport");
10062
10063
  // We reject explicit instantiations in class scope, so there should
10064
  // never be any delayed exported classes to worry about.
10065
0
  assert(S.DelayedDllExportClasses.empty() &&
10066
0
         "delayed exports present at explicit instantiation");
10067
0
  S.checkClassLevelDLLAttribute(Def);
10068
10069
  // Propagate attribute to base class templates.
10070
0
  for (auto &B : Def->bases()) {
10071
0
    if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10072
0
            B.getType()->getAsCXXRecordDecl()))
10073
0
      S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
10074
0
  }
10075
10076
0
  S.referenceDLLExportedClassMethods();
10077
0
}
10078
10079
// Explicit instantiation of a class template specialization
10080
DeclResult Sema::ActOnExplicitInstantiation(
10081
    Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10082
    unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10083
    TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10084
    SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10085
0
    SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10086
  // Find the class template we're specializing
10087
0
  TemplateName Name = TemplateD.get();
10088
0
  TemplateDecl *TD = Name.getAsTemplateDecl();
10089
  // Check that the specialization uses the same tag kind as the
10090
  // original template.
10091
0
  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10092
0
  assert(Kind != TagTypeKind::Enum &&
10093
0
         "Invalid enum tag in class template explicit instantiation!");
10094
10095
0
  ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10096
10097
0
  if (!ClassTemplate) {
10098
0
    NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10099
0
    Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
10100
0
        << TD << NTK << llvm::to_underlying(Kind);
10101
0
    Diag(TD->getLocation(), diag::note_previous_use);
10102
0
    return true;
10103
0
  }
10104
10105
0
  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10106
0
                                    Kind, /*isDefinition*/false, KWLoc,
10107
0
                                    ClassTemplate->getIdentifier())) {
10108
0
    Diag(KWLoc, diag::err_use_with_wrong_tag)
10109
0
      << ClassTemplate
10110
0
      << FixItHint::CreateReplacement(KWLoc,
10111
0
                            ClassTemplate->getTemplatedDecl()->getKindName());
10112
0
    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10113
0
         diag::note_previous_use);
10114
0
    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10115
0
  }
10116
10117
  // C++0x [temp.explicit]p2:
10118
  //   There are two forms of explicit instantiation: an explicit instantiation
10119
  //   definition and an explicit instantiation declaration. An explicit
10120
  //   instantiation declaration begins with the extern keyword. [...]
10121
0
  TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10122
0
                                       ? TSK_ExplicitInstantiationDefinition
10123
0
                                       : TSK_ExplicitInstantiationDeclaration;
10124
10125
0
  if (TSK == TSK_ExplicitInstantiationDeclaration &&
10126
0
      !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10127
    // Check for dllexport class template instantiation declarations,
10128
    // except for MinGW mode.
10129
0
    for (const ParsedAttr &AL : Attr) {
10130
0
      if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10131
0
        Diag(ExternLoc,
10132
0
             diag::warn_attribute_dllexport_explicit_instantiation_decl);
10133
0
        Diag(AL.getLoc(), diag::note_attribute);
10134
0
        break;
10135
0
      }
10136
0
    }
10137
10138
0
    if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10139
0
      Diag(ExternLoc,
10140
0
           diag::warn_attribute_dllexport_explicit_instantiation_decl);
10141
0
      Diag(A->getLocation(), diag::note_attribute);
10142
0
    }
10143
0
  }
10144
10145
  // In MSVC mode, dllimported explicit instantiation definitions are treated as
10146
  // instantiation declarations for most purposes.
10147
0
  bool DLLImportExplicitInstantiationDef = false;
10148
0
  if (TSK == TSK_ExplicitInstantiationDefinition &&
10149
0
      Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10150
    // Check for dllimport class template instantiation definitions.
10151
0
    bool DLLImport =
10152
0
        ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10153
0
    for (const ParsedAttr &AL : Attr) {
10154
0
      if (AL.getKind() == ParsedAttr::AT_DLLImport)
10155
0
        DLLImport = true;
10156
0
      if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10157
        // dllexport trumps dllimport here.
10158
0
        DLLImport = false;
10159
0
        break;
10160
0
      }
10161
0
    }
10162
0
    if (DLLImport) {
10163
0
      TSK = TSK_ExplicitInstantiationDeclaration;
10164
0
      DLLImportExplicitInstantiationDef = true;
10165
0
    }
10166
0
  }
10167
10168
  // Translate the parser's template argument list in our AST format.
10169
0
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10170
0
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10171
10172
  // Check that the template argument list is well-formed for this
10173
  // template.
10174
0
  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
10175
0
  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10176
0
                                false, SugaredConverted, CanonicalConverted,
10177
0
                                /*UpdateArgsWithConversions=*/true))
10178
0
    return true;
10179
10180
  // Find the class template specialization declaration that
10181
  // corresponds to these arguments.
10182
0
  void *InsertPos = nullptr;
10183
0
  ClassTemplateSpecializationDecl *PrevDecl =
10184
0
      ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
10185
10186
0
  TemplateSpecializationKind PrevDecl_TSK
10187
0
    = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10188
10189
0
  if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10190
0
      Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10191
    // Check for dllexport class template instantiation definitions in MinGW
10192
    // mode, if a previous declaration of the instantiation was seen.
10193
0
    for (const ParsedAttr &AL : Attr) {
10194
0
      if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10195
0
        Diag(AL.getLoc(),
10196
0
             diag::warn_attribute_dllexport_explicit_instantiation_def);
10197
0
        break;
10198
0
      }
10199
0
    }
10200
0
  }
10201
10202
0
  if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10203
0
                                 SS.isSet(), TSK))
10204
0
    return true;
10205
10206
0
  ClassTemplateSpecializationDecl *Specialization = nullptr;
10207
10208
0
  bool HasNoEffect = false;
10209
0
  if (PrevDecl) {
10210
0
    if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10211
0
                                               PrevDecl, PrevDecl_TSK,
10212
0
                                            PrevDecl->getPointOfInstantiation(),
10213
0
                                               HasNoEffect))
10214
0
      return PrevDecl;
10215
10216
    // Even though HasNoEffect == true means that this explicit instantiation
10217
    // has no effect on semantics, we go on to put its syntax in the AST.
10218
10219
0
    if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10220
0
        PrevDecl_TSK == TSK_Undeclared) {
10221
      // Since the only prior class template specialization with these
10222
      // arguments was referenced but not declared, reuse that
10223
      // declaration node as our own, updating the source location
10224
      // for the template name to reflect our new declaration.
10225
      // (Other source locations will be updated later.)
10226
0
      Specialization = PrevDecl;
10227
0
      Specialization->setLocation(TemplateNameLoc);
10228
0
      PrevDecl = nullptr;
10229
0
    }
10230
10231
0
    if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10232
0
        DLLImportExplicitInstantiationDef) {
10233
      // The new specialization might add a dllimport attribute.
10234
0
      HasNoEffect = false;
10235
0
    }
10236
0
  }
10237
10238
0
  if (!Specialization) {
10239
    // Create a new class template specialization declaration node for
10240
    // this explicit specialization.
10241
0
    Specialization = ClassTemplateSpecializationDecl::Create(
10242
0
        Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10243
0
        ClassTemplate, CanonicalConverted, PrevDecl);
10244
0
    SetNestedNameSpecifier(*this, Specialization, SS);
10245
10246
    // A MSInheritanceAttr attached to the previous declaration must be
10247
    // propagated to the new node prior to instantiation.
10248
0
    if (PrevDecl) {
10249
0
      if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10250
0
        auto *Clone = A->clone(getASTContext());
10251
0
        Clone->setInherited(true);
10252
0
        Specialization->addAttr(Clone);
10253
0
        Consumer.AssignInheritanceModel(Specialization);
10254
0
      }
10255
0
    }
10256
10257
0
    if (!HasNoEffect && !PrevDecl) {
10258
      // Insert the new specialization.
10259
0
      ClassTemplate->AddSpecialization(Specialization, InsertPos);
10260
0
    }
10261
0
  }
10262
10263
  // Build the fully-sugared type for this explicit instantiation as
10264
  // the user wrote in the explicit instantiation itself. This means
10265
  // that we'll pretty-print the type retrieved from the
10266
  // specialization's declaration the way that the user actually wrote
10267
  // the explicit instantiation, rather than formatting the name based
10268
  // on the "canonical" representation used to store the template
10269
  // arguments in the specialization.
10270
0
  TypeSourceInfo *WrittenTy
10271
0
    = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
10272
0
                                                TemplateArgs,
10273
0
                                  Context.getTypeDeclType(Specialization));
10274
0
  Specialization->setTypeAsWritten(WrittenTy);
10275
10276
  // Set source locations for keywords.
10277
0
  Specialization->setExternLoc(ExternLoc);
10278
0
  Specialization->setTemplateKeywordLoc(TemplateLoc);
10279
0
  Specialization->setBraceRange(SourceRange());
10280
10281
0
  bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10282
0
  ProcessDeclAttributeList(S, Specialization, Attr);
10283
10284
  // Add the explicit instantiation into its lexical context. However,
10285
  // since explicit instantiations are never found by name lookup, we
10286
  // just put it into the declaration context directly.
10287
0
  Specialization->setLexicalDeclContext(CurContext);
10288
0
  CurContext->addDecl(Specialization);
10289
10290
  // Syntax is now OK, so return if it has no other effect on semantics.
10291
0
  if (HasNoEffect) {
10292
    // Set the template specialization kind.
10293
0
    Specialization->setTemplateSpecializationKind(TSK);
10294
0
    return Specialization;
10295
0
  }
10296
10297
  // C++ [temp.explicit]p3:
10298
  //   A definition of a class template or class member template
10299
  //   shall be in scope at the point of the explicit instantiation of
10300
  //   the class template or class member template.
10301
  //
10302
  // This check comes when we actually try to perform the
10303
  // instantiation.
10304
0
  ClassTemplateSpecializationDecl *Def
10305
0
    = cast_or_null<ClassTemplateSpecializationDecl>(
10306
0
                                              Specialization->getDefinition());
10307
0
  if (!Def)
10308
0
    InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
10309
0
  else if (TSK == TSK_ExplicitInstantiationDefinition) {
10310
0
    MarkVTableUsed(TemplateNameLoc, Specialization, true);
10311
0
    Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10312
0
  }
10313
10314
  // Instantiate the members of this class template specialization.
10315
0
  Def = cast_or_null<ClassTemplateSpecializationDecl>(
10316
0
                                       Specialization->getDefinition());
10317
0
  if (Def) {
10318
0
    TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10319
    // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10320
    // TSK_ExplicitInstantiationDefinition
10321
0
    if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10322
0
        (TSK == TSK_ExplicitInstantiationDefinition ||
10323
0
         DLLImportExplicitInstantiationDef)) {
10324
      // FIXME: Need to notify the ASTMutationListener that we did this.
10325
0
      Def->setTemplateSpecializationKind(TSK);
10326
10327
0
      if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10328
0
          (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
10329
0
           !Context.getTargetInfo().getTriple().isPS())) {
10330
        // An explicit instantiation definition can add a dll attribute to a
10331
        // template with a previous instantiation declaration. MinGW doesn't
10332
        // allow this.
10333
0
        auto *A = cast<InheritableAttr>(
10334
0
            getDLLAttr(Specialization)->clone(getASTContext()));
10335
0
        A->setInherited(true);
10336
0
        Def->addAttr(A);
10337
0
        dllExportImportClassTemplateSpecialization(*this, Def);
10338
0
      }
10339
0
    }
10340
10341
    // Fix a TSK_ImplicitInstantiation followed by a
10342
    // TSK_ExplicitInstantiationDefinition
10343
0
    bool NewlyDLLExported =
10344
0
        !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10345
0
    if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10346
0
        (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
10347
0
         !Context.getTargetInfo().getTriple().isPS())) {
10348
      // An explicit instantiation definition can add a dll attribute to a
10349
      // template with a previous implicit instantiation. MinGW doesn't allow
10350
      // this. We limit clang to only adding dllexport, to avoid potentially
10351
      // strange codegen behavior. For example, if we extend this conditional
10352
      // to dllimport, and we have a source file calling a method on an
10353
      // implicitly instantiated template class instance and then declaring a
10354
      // dllimport explicit instantiation definition for the same template
10355
      // class, the codegen for the method call will not respect the dllimport,
10356
      // while it will with cl. The Def will already have the DLL attribute,
10357
      // since the Def and Specialization will be the same in the case of
10358
      // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10359
      // attribute to the Specialization; we just need to make it take effect.
10360
0
      assert(Def == Specialization &&
10361
0
             "Def and Specialization should match for implicit instantiation");
10362
0
      dllExportImportClassTemplateSpecialization(*this, Def);
10363
0
    }
10364
10365
    // In MinGW mode, export the template instantiation if the declaration
10366
    // was marked dllexport.
10367
0
    if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10368
0
        Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10369
0
        PrevDecl->hasAttr<DLLExportAttr>()) {
10370
0
      dllExportImportClassTemplateSpecialization(*this, Def);
10371
0
    }
10372
10373
    // Set the template specialization kind. Make sure it is set before
10374
    // instantiating the members which will trigger ASTConsumer callbacks.
10375
0
    Specialization->setTemplateSpecializationKind(TSK);
10376
0
    InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10377
0
  } else {
10378
10379
    // Set the template specialization kind.
10380
0
    Specialization->setTemplateSpecializationKind(TSK);
10381
0
  }
10382
10383
0
  return Specialization;
10384
0
}
10385
10386
// Explicit instantiation of a member class of a class template.
10387
DeclResult
10388
Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10389
                                 SourceLocation TemplateLoc, unsigned TagSpec,
10390
                                 SourceLocation KWLoc, CXXScopeSpec &SS,
10391
                                 IdentifierInfo *Name, SourceLocation NameLoc,
10392
0
                                 const ParsedAttributesView &Attr) {
10393
10394
0
  bool Owned = false;
10395
0
  bool IsDependent = false;
10396
0
  Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name,
10397
0
               NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10398
0
               MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10399
0
               false, TypeResult(), /*IsTypeSpecifier*/ false,
10400
0
               /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get();
10401
0
  assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10402
10403
0
  if (!TagD)
10404
0
    return true;
10405
10406
0
  TagDecl *Tag = cast<TagDecl>(TagD);
10407
0
  assert(!Tag->isEnum() && "shouldn't see enumerations here");
10408
10409
0
  if (Tag->isInvalidDecl())
10410
0
    return true;
10411
10412
0
  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10413
0
  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10414
0
  if (!Pattern) {
10415
0
    Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10416
0
      << Context.getTypeDeclType(Record);
10417
0
    Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10418
0
    return true;
10419
0
  }
10420
10421
  // C++0x [temp.explicit]p2:
10422
  //   If the explicit instantiation is for a class or member class, the
10423
  //   elaborated-type-specifier in the declaration shall include a
10424
  //   simple-template-id.
10425
  //
10426
  // C++98 has the same restriction, just worded differently.
10427
0
  if (!ScopeSpecifierHasTemplateId(SS))
10428
0
    Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10429
0
      << Record << SS.getRange();
10430
10431
  // C++0x [temp.explicit]p2:
10432
  //   There are two forms of explicit instantiation: an explicit instantiation
10433
  //   definition and an explicit instantiation declaration. An explicit
10434
  //   instantiation declaration begins with the extern keyword. [...]
10435
0
  TemplateSpecializationKind TSK
10436
0
    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10437
0
                           : TSK_ExplicitInstantiationDeclaration;
10438
10439
0
  CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10440
10441
  // Verify that it is okay to explicitly instantiate here.
10442
0
  CXXRecordDecl *PrevDecl
10443
0
    = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10444
0
  if (!PrevDecl && Record->getDefinition())
10445
0
    PrevDecl = Record;
10446
0
  if (PrevDecl) {
10447
0
    MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10448
0
    bool HasNoEffect = false;
10449
0
    assert(MSInfo && "No member specialization information?");
10450
0
    if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10451
0
                                               PrevDecl,
10452
0
                                        MSInfo->getTemplateSpecializationKind(),
10453
0
                                             MSInfo->getPointOfInstantiation(),
10454
0
                                               HasNoEffect))
10455
0
      return true;
10456
0
    if (HasNoEffect)
10457
0
      return TagD;
10458
0
  }
10459
10460
0
  CXXRecordDecl *RecordDef
10461
0
    = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10462
0
  if (!RecordDef) {
10463
    // C++ [temp.explicit]p3:
10464
    //   A definition of a member class of a class template shall be in scope
10465
    //   at the point of an explicit instantiation of the member class.
10466
0
    CXXRecordDecl *Def
10467
0
      = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10468
0
    if (!Def) {
10469
0
      Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10470
0
        << 0 << Record->getDeclName() << Record->getDeclContext();
10471
0
      Diag(Pattern->getLocation(), diag::note_forward_declaration)
10472
0
        << Pattern;
10473
0
      return true;
10474
0
    } else {
10475
0
      if (InstantiateClass(NameLoc, Record, Def,
10476
0
                           getTemplateInstantiationArgs(Record),
10477
0
                           TSK))
10478
0
        return true;
10479
10480
0
      RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10481
0
      if (!RecordDef)
10482
0
        return true;
10483
0
    }
10484
0
  }
10485
10486
  // Instantiate all of the members of the class.
10487
0
  InstantiateClassMembers(NameLoc, RecordDef,
10488
0
                          getTemplateInstantiationArgs(Record), TSK);
10489
10490
0
  if (TSK == TSK_ExplicitInstantiationDefinition)
10491
0
    MarkVTableUsed(NameLoc, RecordDef, true);
10492
10493
  // FIXME: We don't have any representation for explicit instantiations of
10494
  // member classes. Such a representation is not needed for compilation, but it
10495
  // should be available for clients that want to see all of the declarations in
10496
  // the source code.
10497
0
  return TagD;
10498
0
}
10499
10500
DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10501
                                            SourceLocation ExternLoc,
10502
                                            SourceLocation TemplateLoc,
10503
0
                                            Declarator &D) {
10504
  // Explicit instantiations always require a name.
10505
  // TODO: check if/when DNInfo should replace Name.
10506
0
  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10507
0
  DeclarationName Name = NameInfo.getName();
10508
0
  if (!Name) {
10509
0
    if (!D.isInvalidType())
10510
0
      Diag(D.getDeclSpec().getBeginLoc(),
10511
0
           diag::err_explicit_instantiation_requires_name)
10512
0
          << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10513
10514
0
    return true;
10515
0
  }
10516
10517
  // The scope passed in may not be a decl scope.  Zip up the scope tree until
10518
  // we find one that is.
10519
0
  while ((S->getFlags() & Scope::DeclScope) == 0 ||
10520
0
         (S->getFlags() & Scope::TemplateParamScope) != 0)
10521
0
    S = S->getParent();
10522
10523
  // Determine the type of the declaration.
10524
0
  TypeSourceInfo *T = GetTypeForDeclarator(D, S);
10525
0
  QualType R = T->getType();
10526
0
  if (R.isNull())
10527
0
    return true;
10528
10529
  // C++ [dcl.stc]p1:
10530
  //   A storage-class-specifier shall not be specified in [...] an explicit
10531
  //   instantiation (14.7.2) directive.
10532
0
  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10533
0
    Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10534
0
      << Name;
10535
0
    return true;
10536
0
  } else if (D.getDeclSpec().getStorageClassSpec()
10537
0
                                                != DeclSpec::SCS_unspecified) {
10538
    // Complain about then remove the storage class specifier.
10539
0
    Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10540
0
      << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10541
10542
0
    D.getMutableDeclSpec().ClearStorageClassSpecs();
10543
0
  }
10544
10545
  // C++0x [temp.explicit]p1:
10546
  //   [...] An explicit instantiation of a function template shall not use the
10547
  //   inline or constexpr specifiers.
10548
  // Presumably, this also applies to member functions of class templates as
10549
  // well.
10550
0
  if (D.getDeclSpec().isInlineSpecified())
10551
0
    Diag(D.getDeclSpec().getInlineSpecLoc(),
10552
0
         getLangOpts().CPlusPlus11 ?
10553
0
           diag::err_explicit_instantiation_inline :
10554
0
           diag::warn_explicit_instantiation_inline_0x)
10555
0
      << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10556
0
  if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10557
    // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10558
    // not already specified.
10559
0
    Diag(D.getDeclSpec().getConstexprSpecLoc(),
10560
0
         diag::err_explicit_instantiation_constexpr);
10561
10562
  // A deduction guide is not on the list of entities that can be explicitly
10563
  // instantiated.
10564
0
  if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10565
0
    Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10566
0
        << /*explicit instantiation*/ 0;
10567
0
    return true;
10568
0
  }
10569
10570
  // C++0x [temp.explicit]p2:
10571
  //   There are two forms of explicit instantiation: an explicit instantiation
10572
  //   definition and an explicit instantiation declaration. An explicit
10573
  //   instantiation declaration begins with the extern keyword. [...]
10574
0
  TemplateSpecializationKind TSK
10575
0
    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10576
0
                           : TSK_ExplicitInstantiationDeclaration;
10577
10578
0
  LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10579
0
  LookupParsedName(Previous, S, &D.getCXXScopeSpec());
10580
10581
0
  if (!R->isFunctionType()) {
10582
    // C++ [temp.explicit]p1:
10583
    //   A [...] static data member of a class template can be explicitly
10584
    //   instantiated from the member definition associated with its class
10585
    //   template.
10586
    // C++1y [temp.explicit]p1:
10587
    //   A [...] variable [...] template specialization can be explicitly
10588
    //   instantiated from its template.
10589
0
    if (Previous.isAmbiguous())
10590
0
      return true;
10591
10592
0
    VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10593
0
    VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10594
10595
0
    if (!PrevTemplate) {
10596
0
      if (!Prev || !Prev->isStaticDataMember()) {
10597
        // We expect to see a static data member here.
10598
0
        Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10599
0
            << Name;
10600
0
        for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10601
0
             P != PEnd; ++P)
10602
0
          Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10603
0
        return true;
10604
0
      }
10605
10606
0
      if (!Prev->getInstantiatedFromStaticDataMember()) {
10607
        // FIXME: Check for explicit specialization?
10608
0
        Diag(D.getIdentifierLoc(),
10609
0
             diag::err_explicit_instantiation_data_member_not_instantiated)
10610
0
            << Prev;
10611
0
        Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10612
        // FIXME: Can we provide a note showing where this was declared?
10613
0
        return true;
10614
0
      }
10615
0
    } else {
10616
      // Explicitly instantiate a variable template.
10617
10618
      // C++1y [dcl.spec.auto]p6:
10619
      //   ... A program that uses auto or decltype(auto) in a context not
10620
      //   explicitly allowed in this section is ill-formed.
10621
      //
10622
      // This includes auto-typed variable template instantiations.
10623
0
      if (R->isUndeducedType()) {
10624
0
        Diag(T->getTypeLoc().getBeginLoc(),
10625
0
             diag::err_auto_not_allowed_var_inst);
10626
0
        return true;
10627
0
      }
10628
10629
0
      if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10630
        // C++1y [temp.explicit]p3:
10631
        //   If the explicit instantiation is for a variable, the unqualified-id
10632
        //   in the declaration shall be a template-id.
10633
0
        Diag(D.getIdentifierLoc(),
10634
0
             diag::err_explicit_instantiation_without_template_id)
10635
0
          << PrevTemplate;
10636
0
        Diag(PrevTemplate->getLocation(),
10637
0
             diag::note_explicit_instantiation_here);
10638
0
        return true;
10639
0
      }
10640
10641
      // Translate the parser's template argument list into our AST format.
10642
0
      TemplateArgumentListInfo TemplateArgs =
10643
0
          makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10644
10645
0
      DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10646
0
                                          D.getIdentifierLoc(), TemplateArgs);
10647
0
      if (Res.isInvalid())
10648
0
        return true;
10649
10650
0
      if (!Res.isUsable()) {
10651
        // We somehow specified dependent template arguments in an explicit
10652
        // instantiation. This should probably only happen during error
10653
        // recovery.
10654
0
        Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10655
0
        return true;
10656
0
      }
10657
10658
      // Ignore access control bits, we don't need them for redeclaration
10659
      // checking.
10660
0
      Prev = cast<VarDecl>(Res.get());
10661
0
    }
10662
10663
    // C++0x [temp.explicit]p2:
10664
    //   If the explicit instantiation is for a member function, a member class
10665
    //   or a static data member of a class template specialization, the name of
10666
    //   the class template specialization in the qualified-id for the member
10667
    //   name shall be a simple-template-id.
10668
    //
10669
    // C++98 has the same restriction, just worded differently.
10670
    //
10671
    // This does not apply to variable template specializations, where the
10672
    // template-id is in the unqualified-id instead.
10673
0
    if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10674
0
      Diag(D.getIdentifierLoc(),
10675
0
           diag::ext_explicit_instantiation_without_qualified_id)
10676
0
        << Prev << D.getCXXScopeSpec().getRange();
10677
10678
0
    CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10679
10680
    // Verify that it is okay to explicitly instantiate here.
10681
0
    TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10682
0
    SourceLocation POI = Prev->getPointOfInstantiation();
10683
0
    bool HasNoEffect = false;
10684
0
    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10685
0
                                               PrevTSK, POI, HasNoEffect))
10686
0
      return true;
10687
10688
0
    if (!HasNoEffect) {
10689
      // Instantiate static data member or variable template.
10690
0
      Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10691
      // Merge attributes.
10692
0
      ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10693
0
      if (TSK == TSK_ExplicitInstantiationDefinition)
10694
0
        InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10695
0
    }
10696
10697
    // Check the new variable specialization against the parsed input.
10698
0
    if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10699
0
      Diag(T->getTypeLoc().getBeginLoc(),
10700
0
           diag::err_invalid_var_template_spec_type)
10701
0
          << 0 << PrevTemplate << R << Prev->getType();
10702
0
      Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10703
0
          << 2 << PrevTemplate->getDeclName();
10704
0
      return true;
10705
0
    }
10706
10707
    // FIXME: Create an ExplicitInstantiation node?
10708
0
    return (Decl*) nullptr;
10709
0
  }
10710
10711
  // If the declarator is a template-id, translate the parser's template
10712
  // argument list into our AST format.
10713
0
  bool HasExplicitTemplateArgs = false;
10714
0
  TemplateArgumentListInfo TemplateArgs;
10715
0
  if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10716
0
    TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10717
0
    HasExplicitTemplateArgs = true;
10718
0
  }
10719
10720
  // C++ [temp.explicit]p1:
10721
  //   A [...] function [...] can be explicitly instantiated from its template.
10722
  //   A member function [...] of a class template can be explicitly
10723
  //  instantiated from the member definition associated with its class
10724
  //  template.
10725
0
  UnresolvedSet<8> TemplateMatches;
10726
0
  FunctionDecl *NonTemplateMatch = nullptr;
10727
0
  TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
10728
0
  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10729
0
       P != PEnd; ++P) {
10730
0
    NamedDecl *Prev = *P;
10731
0
    if (!HasExplicitTemplateArgs) {
10732
0
      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10733
0
        QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10734
0
                                                /*AdjustExceptionSpec*/true);
10735
0
        if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10736
0
          if (Method->getPrimaryTemplate()) {
10737
0
            TemplateMatches.addDecl(Method, P.getAccess());
10738
0
          } else {
10739
            // FIXME: Can this assert ever happen?  Needs a test.
10740
0
            assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
10741
0
            NonTemplateMatch = Method;
10742
0
          }
10743
0
        }
10744
0
      }
10745
0
    }
10746
10747
0
    FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10748
0
    if (!FunTmpl)
10749
0
      continue;
10750
10751
0
    TemplateDeductionInfo Info(FailedCandidates.getLocation());
10752
0
    FunctionDecl *Specialization = nullptr;
10753
0
    if (TemplateDeductionResult TDK
10754
0
          = DeduceTemplateArguments(FunTmpl,
10755
0
                               (HasExplicitTemplateArgs ? &TemplateArgs
10756
0
                                                        : nullptr),
10757
0
                                    R, Specialization, Info)) {
10758
      // Keep track of almost-matches.
10759
0
      FailedCandidates.addCandidate()
10760
0
          .set(P.getPair(), FunTmpl->getTemplatedDecl(),
10761
0
               MakeDeductionFailureInfo(Context, TDK, Info));
10762
0
      (void)TDK;
10763
0
      continue;
10764
0
    }
10765
10766
    // Target attributes are part of the cuda function signature, so
10767
    // the cuda target of the instantiated function must match that of its
10768
    // template.  Given that C++ template deduction does not take
10769
    // target attributes into account, we reject candidates here that
10770
    // have a different target.
10771
0
    if (LangOpts.CUDA &&
10772
0
        IdentifyCUDATarget(Specialization,
10773
0
                           /* IgnoreImplicitHDAttr = */ true) !=
10774
0
            IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
10775
0
      FailedCandidates.addCandidate().set(
10776
0
          P.getPair(), FunTmpl->getTemplatedDecl(),
10777
0
          MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
10778
0
      continue;
10779
0
    }
10780
10781
0
    TemplateMatches.addDecl(Specialization, P.getAccess());
10782
0
  }
10783
10784
0
  FunctionDecl *Specialization = NonTemplateMatch;
10785
0
  if (!Specialization) {
10786
    // Find the most specialized function template specialization.
10787
0
    UnresolvedSetIterator Result = getMostSpecialized(
10788
0
        TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
10789
0
        D.getIdentifierLoc(),
10790
0
        PDiag(diag::err_explicit_instantiation_not_known) << Name,
10791
0
        PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10792
0
        PDiag(diag::note_explicit_instantiation_candidate));
10793
10794
0
    if (Result == TemplateMatches.end())
10795
0
      return true;
10796
10797
    // Ignore access control bits, we don't need them for redeclaration checking.
10798
0
    Specialization = cast<FunctionDecl>(*Result);
10799
0
  }
10800
10801
  // C++11 [except.spec]p4
10802
  // In an explicit instantiation an exception-specification may be specified,
10803
  // but is not required.
10804
  // If an exception-specification is specified in an explicit instantiation
10805
  // directive, it shall be compatible with the exception-specifications of
10806
  // other declarations of that function.
10807
0
  if (auto *FPT = R->getAs<FunctionProtoType>())
10808
0
    if (FPT->hasExceptionSpec()) {
10809
0
      unsigned DiagID =
10810
0
          diag::err_mismatched_exception_spec_explicit_instantiation;
10811
0
      if (getLangOpts().MicrosoftExt)
10812
0
        DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10813
0
      bool Result = CheckEquivalentExceptionSpec(
10814
0
          PDiag(DiagID) << Specialization->getType(),
10815
0
          PDiag(diag::note_explicit_instantiation_here),
10816
0
          Specialization->getType()->getAs<FunctionProtoType>(),
10817
0
          Specialization->getLocation(), FPT, D.getBeginLoc());
10818
      // In Microsoft mode, mismatching exception specifications just cause a
10819
      // warning.
10820
0
      if (!getLangOpts().MicrosoftExt && Result)
10821
0
        return true;
10822
0
    }
10823
10824
0
  if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10825
0
    Diag(D.getIdentifierLoc(),
10826
0
         diag::err_explicit_instantiation_member_function_not_instantiated)
10827
0
      << Specialization
10828
0
      << (Specialization->getTemplateSpecializationKind() ==
10829
0
          TSK_ExplicitSpecialization);
10830
0
    Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10831
0
    return true;
10832
0
  }
10833
10834
0
  FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10835
0
  if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10836
0
    PrevDecl = Specialization;
10837
10838
0
  if (PrevDecl) {
10839
0
    bool HasNoEffect = false;
10840
0
    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10841
0
                                               PrevDecl,
10842
0
                                     PrevDecl->getTemplateSpecializationKind(),
10843
0
                                          PrevDecl->getPointOfInstantiation(),
10844
0
                                               HasNoEffect))
10845
0
      return true;
10846
10847
    // FIXME: We may still want to build some representation of this
10848
    // explicit specialization.
10849
0
    if (HasNoEffect)
10850
0
      return (Decl*) nullptr;
10851
0
  }
10852
10853
  // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10854
  // functions
10855
  //     valarray<size_t>::valarray(size_t) and
10856
  //     valarray<size_t>::~valarray()
10857
  // that it declared to have internal linkage with the internal_linkage
10858
  // attribute. Ignore the explicit instantiation declaration in this case.
10859
0
  if (Specialization->hasAttr<InternalLinkageAttr>() &&
10860
0
      TSK == TSK_ExplicitInstantiationDeclaration) {
10861
0
    if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10862
0
      if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10863
0
          RD->isInStdNamespace())
10864
0
        return (Decl*) nullptr;
10865
0
  }
10866
10867
0
  ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10868
10869
  // In MSVC mode, dllimported explicit instantiation definitions are treated as
10870
  // instantiation declarations.
10871
0
  if (TSK == TSK_ExplicitInstantiationDefinition &&
10872
0
      Specialization->hasAttr<DLLImportAttr>() &&
10873
0
      Context.getTargetInfo().getCXXABI().isMicrosoft())
10874
0
    TSK = TSK_ExplicitInstantiationDeclaration;
10875
10876
0
  Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10877
10878
0
  if (Specialization->isDefined()) {
10879
    // Let the ASTConsumer know that this function has been explicitly
10880
    // instantiated now, and its linkage might have changed.
10881
0
    Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
10882
0
  } else if (TSK == TSK_ExplicitInstantiationDefinition)
10883
0
    InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10884
10885
  // C++0x [temp.explicit]p2:
10886
  //   If the explicit instantiation is for a member function, a member class
10887
  //   or a static data member of a class template specialization, the name of
10888
  //   the class template specialization in the qualified-id for the member
10889
  //   name shall be a simple-template-id.
10890
  //
10891
  // C++98 has the same restriction, just worded differently.
10892
0
  FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10893
0
  if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10894
0
      D.getCXXScopeSpec().isSet() &&
10895
0
      !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10896
0
    Diag(D.getIdentifierLoc(),
10897
0
         diag::ext_explicit_instantiation_without_qualified_id)
10898
0
    << Specialization << D.getCXXScopeSpec().getRange();
10899
10900
0
  CheckExplicitInstantiation(
10901
0
      *this,
10902
0
      FunTmpl ? (NamedDecl *)FunTmpl
10903
0
              : Specialization->getInstantiatedFromMemberFunction(),
10904
0
      D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10905
10906
  // FIXME: Create some kind of ExplicitInstantiationDecl here.
10907
0
  return (Decl*) nullptr;
10908
0
}
10909
10910
TypeResult
10911
Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10912
                        const CXXScopeSpec &SS, IdentifierInfo *Name,
10913
0
                        SourceLocation TagLoc, SourceLocation NameLoc) {
10914
  // This has to hold, because SS is expected to be defined.
10915
0
  assert(Name && "Expected a name in a dependent tag");
10916
10917
0
  NestedNameSpecifier *NNS = SS.getScopeRep();
10918
0
  if (!NNS)
10919
0
    return true;
10920
10921
0
  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10922
10923
0
  if (TUK == TUK_Declaration || TUK == TUK_Definition) {
10924
0
    Diag(NameLoc, diag::err_dependent_tag_decl)
10925
0
        << (TUK == TUK_Definition) << llvm::to_underlying(Kind)
10926
0
        << SS.getRange();
10927
0
    return true;
10928
0
  }
10929
10930
  // Create the resulting type.
10931
0
  ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10932
0
  QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10933
10934
  // Create type-source location information for this type.
10935
0
  TypeLocBuilder TLB;
10936
0
  DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
10937
0
  TL.setElaboratedKeywordLoc(TagLoc);
10938
0
  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10939
0
  TL.setNameLoc(NameLoc);
10940
0
  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
10941
0
}
10942
10943
TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10944
                                   const CXXScopeSpec &SS,
10945
                                   const IdentifierInfo &II,
10946
                                   SourceLocation IdLoc,
10947
0
                                   ImplicitTypenameContext IsImplicitTypename) {
10948
0
  if (SS.isInvalid())
10949
0
    return true;
10950
10951
0
  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10952
0
    Diag(TypenameLoc,
10953
0
         getLangOpts().CPlusPlus11 ?
10954
0
           diag::warn_cxx98_compat_typename_outside_of_template :
10955
0
           diag::ext_typename_outside_of_template)
10956
0
      << FixItHint::CreateRemoval(TypenameLoc);
10957
10958
0
  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10959
0
  TypeSourceInfo *TSI = nullptr;
10960
0
  QualType T =
10961
0
      CheckTypenameType((TypenameLoc.isValid() ||
10962
0
                         IsImplicitTypename == ImplicitTypenameContext::Yes)
10963
0
                            ? ElaboratedTypeKeyword::Typename
10964
0
                            : ElaboratedTypeKeyword::None,
10965
0
                        TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10966
0
                        /*DeducedTSTContext=*/true);
10967
0
  if (T.isNull())
10968
0
    return true;
10969
0
  return CreateParsedType(T, TSI);
10970
0
}
10971
10972
TypeResult
10973
Sema::ActOnTypenameType(Scope *S,
10974
                        SourceLocation TypenameLoc,
10975
                        const CXXScopeSpec &SS,
10976
                        SourceLocation TemplateKWLoc,
10977
                        TemplateTy TemplateIn,
10978
                        IdentifierInfo *TemplateII,
10979
                        SourceLocation TemplateIILoc,
10980
                        SourceLocation LAngleLoc,
10981
                        ASTTemplateArgsPtr TemplateArgsIn,
10982
0
                        SourceLocation RAngleLoc) {
10983
0
  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10984
0
    Diag(TypenameLoc,
10985
0
         getLangOpts().CPlusPlus11 ?
10986
0
           diag::warn_cxx98_compat_typename_outside_of_template :
10987
0
           diag::ext_typename_outside_of_template)
10988
0
      << FixItHint::CreateRemoval(TypenameLoc);
10989
10990
  // Strangely, non-type results are not ignored by this lookup, so the
10991
  // program is ill-formed if it finds an injected-class-name.
10992
0
  if (TypenameLoc.isValid()) {
10993
0
    auto *LookupRD =
10994
0
        dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10995
0
    if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10996
0
      Diag(TemplateIILoc,
10997
0
           diag::ext_out_of_line_qualified_id_type_names_constructor)
10998
0
        << TemplateII << 0 /*injected-class-name used as template name*/
10999
0
        << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11000
0
    }
11001
0
  }
11002
11003
  // Translate the parser's template argument list in our AST format.
11004
0
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11005
0
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11006
11007
0
  TemplateName Template = TemplateIn.get();
11008
0
  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
11009
    // Construct a dependent template specialization type.
11010
0
    assert(DTN && "dependent template has non-dependent name?");
11011
0
    assert(DTN->getQualifier() == SS.getScopeRep());
11012
0
    QualType T = Context.getDependentTemplateSpecializationType(
11013
0
        ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
11014
0
        DTN->getIdentifier(), TemplateArgs.arguments());
11015
11016
    // Create source-location information for this type.
11017
0
    TypeLocBuilder Builder;
11018
0
    DependentTemplateSpecializationTypeLoc SpecTL
11019
0
    = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
11020
0
    SpecTL.setElaboratedKeywordLoc(TypenameLoc);
11021
0
    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
11022
0
    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11023
0
    SpecTL.setTemplateNameLoc(TemplateIILoc);
11024
0
    SpecTL.setLAngleLoc(LAngleLoc);
11025
0
    SpecTL.setRAngleLoc(RAngleLoc);
11026
0
    for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11027
0
      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11028
0
    return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
11029
0
  }
11030
11031
0
  QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
11032
0
  if (T.isNull())
11033
0
    return true;
11034
11035
  // Provide source-location information for the template specialization type.
11036
0
  TypeLocBuilder Builder;
11037
0
  TemplateSpecializationTypeLoc SpecTL
11038
0
    = Builder.push<TemplateSpecializationTypeLoc>(T);
11039
0
  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11040
0
  SpecTL.setTemplateNameLoc(TemplateIILoc);
11041
0
  SpecTL.setLAngleLoc(LAngleLoc);
11042
0
  SpecTL.setRAngleLoc(RAngleLoc);
11043
0
  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11044
0
    SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11045
11046
0
  T = Context.getElaboratedType(ElaboratedTypeKeyword::Typename,
11047
0
                                SS.getScopeRep(), T);
11048
0
  ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
11049
0
  TL.setElaboratedKeywordLoc(TypenameLoc);
11050
0
  TL.setQualifierLoc(SS.getWithLocInContext(Context));
11051
11052
0
  TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11053
0
  return CreateParsedType(T, TSI);
11054
0
}
11055
11056
11057
/// Determine whether this failed name lookup should be treated as being
11058
/// disabled by a usage of std::enable_if.
11059
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11060
0
                       SourceRange &CondRange, Expr *&Cond) {
11061
  // We must be looking for a ::type...
11062
0
  if (!II.isStr("type"))
11063
0
    return false;
11064
11065
  // ... within an explicitly-written template specialization...
11066
0
  if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
11067
0
    return false;
11068
0
  TypeLoc EnableIfTy = NNS.getTypeLoc();
11069
0
  TemplateSpecializationTypeLoc EnableIfTSTLoc =
11070
0
      EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
11071
0
  if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11072
0
    return false;
11073
0
  const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11074
11075
  // ... which names a complete class template declaration...
11076
0
  const TemplateDecl *EnableIfDecl =
11077
0
    EnableIfTST->getTemplateName().getAsTemplateDecl();
11078
0
  if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11079
0
    return false;
11080
11081
  // ... called "enable_if".
11082
0
  const IdentifierInfo *EnableIfII =
11083
0
    EnableIfDecl->getDeclName().getAsIdentifierInfo();
11084
0
  if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11085
0
    return false;
11086
11087
  // Assume the first template argument is the condition.
11088
0
  CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11089
11090
  // Dig out the condition.
11091
0
  Cond = nullptr;
11092
0
  if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11093
0
        != TemplateArgument::Expression)
11094
0
    return true;
11095
11096
0
  Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11097
11098
  // Ignore Boolean literals; they add no value.
11099
0
  if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11100
0
    Cond = nullptr;
11101
11102
0
  return true;
11103
0
}
11104
11105
QualType
11106
Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11107
                        SourceLocation KeywordLoc,
11108
                        NestedNameSpecifierLoc QualifierLoc,
11109
                        const IdentifierInfo &II,
11110
                        SourceLocation IILoc,
11111
                        TypeSourceInfo **TSI,
11112
0
                        bool DeducedTSTContext) {
11113
0
  QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11114
0
                                 DeducedTSTContext);
11115
0
  if (T.isNull())
11116
0
    return QualType();
11117
11118
0
  *TSI = Context.CreateTypeSourceInfo(T);
11119
0
  if (isa<DependentNameType>(T)) {
11120
0
    DependentNameTypeLoc TL =
11121
0
        (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
11122
0
    TL.setElaboratedKeywordLoc(KeywordLoc);
11123
0
    TL.setQualifierLoc(QualifierLoc);
11124
0
    TL.setNameLoc(IILoc);
11125
0
  } else {
11126
0
    ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
11127
0
    TL.setElaboratedKeywordLoc(KeywordLoc);
11128
0
    TL.setQualifierLoc(QualifierLoc);
11129
0
    TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
11130
0
  }
11131
0
  return T;
11132
0
}
11133
11134
/// Build the type that describes a C++ typename specifier,
11135
/// e.g., "typename T::type".
11136
QualType
11137
Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11138
                        SourceLocation KeywordLoc,
11139
                        NestedNameSpecifierLoc QualifierLoc,
11140
                        const IdentifierInfo &II,
11141
0
                        SourceLocation IILoc, bool DeducedTSTContext) {
11142
0
  CXXScopeSpec SS;
11143
0
  SS.Adopt(QualifierLoc);
11144
11145
0
  DeclContext *Ctx = nullptr;
11146
0
  if (QualifierLoc) {
11147
0
    Ctx = computeDeclContext(SS);
11148
0
    if (!Ctx) {
11149
      // If the nested-name-specifier is dependent and couldn't be
11150
      // resolved to a type, build a typename type.
11151
0
      assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
11152
0
      return Context.getDependentNameType(Keyword,
11153
0
                                          QualifierLoc.getNestedNameSpecifier(),
11154
0
                                          &II);
11155
0
    }
11156
11157
    // If the nested-name-specifier refers to the current instantiation,
11158
    // the "typename" keyword itself is superfluous. In C++03, the
11159
    // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11160
    // allows such extraneous "typename" keywords, and we retroactively
11161
    // apply this DR to C++03 code with only a warning. In any case we continue.
11162
11163
0
    if (RequireCompleteDeclContext(SS, Ctx))
11164
0
      return QualType();
11165
0
  }
11166
11167
0
  DeclarationName Name(&II);
11168
0
  LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11169
0
  if (Ctx)
11170
0
    LookupQualifiedName(Result, Ctx, SS);
11171
0
  else
11172
0
    LookupName(Result, CurScope);
11173
0
  unsigned DiagID = 0;
11174
0
  Decl *Referenced = nullptr;
11175
0
  switch (Result.getResultKind()) {
11176
0
  case LookupResult::NotFound: {
11177
    // If we're looking up 'type' within a template named 'enable_if', produce
11178
    // a more specific diagnostic.
11179
0
    SourceRange CondRange;
11180
0
    Expr *Cond = nullptr;
11181
0
    if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11182
      // If we have a condition, narrow it down to the specific failed
11183
      // condition.
11184
0
      if (Cond) {
11185
0
        Expr *FailedCond;
11186
0
        std::string FailedDescription;
11187
0
        std::tie(FailedCond, FailedDescription) =
11188
0
          findFailedBooleanCondition(Cond);
11189
11190
0
        Diag(FailedCond->getExprLoc(),
11191
0
             diag::err_typename_nested_not_found_requirement)
11192
0
          << FailedDescription
11193
0
          << FailedCond->getSourceRange();
11194
0
        return QualType();
11195
0
      }
11196
11197
0
      Diag(CondRange.getBegin(),
11198
0
           diag::err_typename_nested_not_found_enable_if)
11199
0
          << Ctx << CondRange;
11200
0
      return QualType();
11201
0
    }
11202
11203
0
    DiagID = Ctx ? diag::err_typename_nested_not_found
11204
0
                 : diag::err_unknown_typename;
11205
0
    break;
11206
0
  }
11207
11208
0
  case LookupResult::FoundUnresolvedValue: {
11209
    // We found a using declaration that is a value. Most likely, the using
11210
    // declaration itself is meant to have the 'typename' keyword.
11211
0
    SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11212
0
                          IILoc);
11213
0
    Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11214
0
      << Name << Ctx << FullRange;
11215
0
    if (UnresolvedUsingValueDecl *Using
11216
0
          = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11217
0
      SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11218
0
      Diag(Loc, diag::note_using_value_decl_missing_typename)
11219
0
        << FixItHint::CreateInsertion(Loc, "typename ");
11220
0
    }
11221
0
  }
11222
  // Fall through to create a dependent typename type, from which we can recover
11223
  // better.
11224
0
  [[fallthrough]];
11225
11226
0
  case LookupResult::NotFoundInCurrentInstantiation:
11227
    // Okay, it's a member of an unknown instantiation.
11228
0
    return Context.getDependentNameType(Keyword,
11229
0
                                        QualifierLoc.getNestedNameSpecifier(),
11230
0
                                        &II);
11231
11232
0
  case LookupResult::Found:
11233
0
    if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11234
      // C++ [class.qual]p2:
11235
      //   In a lookup in which function names are not ignored and the
11236
      //   nested-name-specifier nominates a class C, if the name specified
11237
      //   after the nested-name-specifier, when looked up in C, is the
11238
      //   injected-class-name of C [...] then the name is instead considered
11239
      //   to name the constructor of class C.
11240
      //
11241
      // Unlike in an elaborated-type-specifier, function names are not ignored
11242
      // in typename-specifier lookup. However, they are ignored in all the
11243
      // contexts where we form a typename type with no keyword (that is, in
11244
      // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11245
      //
11246
      // FIXME: That's not strictly true: mem-initializer-id lookup does not
11247
      // ignore functions, but that appears to be an oversight.
11248
0
      auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
11249
0
      auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
11250
0
      if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
11251
0
          FoundRD->isInjectedClassName() &&
11252
0
          declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
11253
0
        Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
11254
0
            << &II << 1 << 0 /*'typename' keyword used*/;
11255
11256
      // We found a type. Build an ElaboratedType, since the
11257
      // typename-specifier was just sugar.
11258
0
      MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
11259
0
      return Context.getElaboratedType(Keyword,
11260
0
                                       QualifierLoc.getNestedNameSpecifier(),
11261
0
                                       Context.getTypeDeclType(Type));
11262
0
    }
11263
11264
    // C++ [dcl.type.simple]p2:
11265
    //   A type-specifier of the form
11266
    //     typename[opt] nested-name-specifier[opt] template-name
11267
    //   is a placeholder for a deduced class type [...].
11268
0
    if (getLangOpts().CPlusPlus17) {
11269
0
      if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11270
0
        if (!DeducedTSTContext) {
11271
0
          QualType T(QualifierLoc
11272
0
                         ? QualifierLoc.getNestedNameSpecifier()->getAsType()
11273
0
                         : nullptr, 0);
11274
0
          if (!T.isNull())
11275
0
            Diag(IILoc, diag::err_dependent_deduced_tst)
11276
0
              << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
11277
0
          else
11278
0
            Diag(IILoc, diag::err_deduced_tst)
11279
0
              << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
11280
0
          NoteTemplateLocation(*TD);
11281
0
          return QualType();
11282
0
        }
11283
0
        return Context.getElaboratedType(
11284
0
            Keyword, QualifierLoc.getNestedNameSpecifier(),
11285
0
            Context.getDeducedTemplateSpecializationType(TemplateName(TD),
11286
0
                                                         QualType(), false));
11287
0
      }
11288
0
    }
11289
11290
0
    DiagID = Ctx ? diag::err_typename_nested_not_type
11291
0
                 : diag::err_typename_not_type;
11292
0
    Referenced = Result.getFoundDecl();
11293
0
    break;
11294
11295
0
  case LookupResult::FoundOverloaded:
11296
0
    DiagID = Ctx ? diag::err_typename_nested_not_type
11297
0
                 : diag::err_typename_not_type;
11298
0
    Referenced = *Result.begin();
11299
0
    break;
11300
11301
0
  case LookupResult::Ambiguous:
11302
0
    return QualType();
11303
0
  }
11304
11305
  // If we get here, it's because name lookup did not find a
11306
  // type. Emit an appropriate diagnostic and return an error.
11307
0
  SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11308
0
                        IILoc);
11309
0
  if (Ctx)
11310
0
    Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11311
0
  else
11312
0
    Diag(IILoc, DiagID) << FullRange << Name;
11313
0
  if (Referenced)
11314
0
    Diag(Referenced->getLocation(),
11315
0
         Ctx ? diag::note_typename_member_refers_here
11316
0
             : diag::note_typename_refers_here)
11317
0
      << Name;
11318
0
  return QualType();
11319
0
}
11320
11321
namespace {
11322
  // See Sema::RebuildTypeInCurrentInstantiation
11323
  class CurrentInstantiationRebuilder
11324
    : public TreeTransform<CurrentInstantiationRebuilder> {
11325
    SourceLocation Loc;
11326
    DeclarationName Entity;
11327
11328
  public:
11329
    typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11330
11331
    CurrentInstantiationRebuilder(Sema &SemaRef,
11332
                                  SourceLocation Loc,
11333
                                  DeclarationName Entity)
11334
    : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11335
0
      Loc(Loc), Entity(Entity) { }
11336
11337
    /// Determine whether the given type \p T has already been
11338
    /// transformed.
11339
    ///
11340
    /// For the purposes of type reconstruction, a type has already been
11341
    /// transformed if it is NULL or if it is not dependent.
11342
0
    bool AlreadyTransformed(QualType T) {
11343
0
      return T.isNull() || !T->isInstantiationDependentType();
11344
0
    }
11345
11346
    /// Returns the location of the entity whose type is being
11347
    /// rebuilt.
11348
0
    SourceLocation getBaseLocation() { return Loc; }
11349
11350
    /// Returns the name of the entity whose type is being rebuilt.
11351
0
    DeclarationName getBaseEntity() { return Entity; }
11352
11353
    /// Sets the "base" location and entity when that
11354
    /// information is known based on another transformation.
11355
0
    void setBase(SourceLocation Loc, DeclarationName Entity) {
11356
0
      this->Loc = Loc;
11357
0
      this->Entity = Entity;
11358
0
    }
11359
11360
0
    ExprResult TransformLambdaExpr(LambdaExpr *E) {
11361
      // Lambdas never need to be transformed.
11362
0
      return E;
11363
0
    }
11364
  };
11365
} // end anonymous namespace
11366
11367
/// Rebuilds a type within the context of the current instantiation.
11368
///
11369
/// The type \p T is part of the type of an out-of-line member definition of
11370
/// a class template (or class template partial specialization) that was parsed
11371
/// and constructed before we entered the scope of the class template (or
11372
/// partial specialization thereof). This routine will rebuild that type now
11373
/// that we have entered the declarator's scope, which may produce different
11374
/// canonical types, e.g.,
11375
///
11376
/// \code
11377
/// template<typename T>
11378
/// struct X {
11379
///   typedef T* pointer;
11380
///   pointer data();
11381
/// };
11382
///
11383
/// template<typename T>
11384
/// typename X<T>::pointer X<T>::data() { ... }
11385
/// \endcode
11386
///
11387
/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
11388
/// since we do not know that we can look into X<T> when we parsed the type.
11389
/// This function will rebuild the type, performing the lookup of "pointer"
11390
/// in X<T> and returning an ElaboratedType whose canonical type is the same
11391
/// as the canonical type of T*, allowing the return types of the out-of-line
11392
/// definition and the declaration to match.
11393
TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11394
                                                        SourceLocation Loc,
11395
0
                                                        DeclarationName Name) {
11396
0
  if (!T || !T->getType()->isInstantiationDependentType())
11397
0
    return T;
11398
11399
0
  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11400
0
  return Rebuilder.TransformType(T);
11401
0
}
11402
11403
0
ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11404
0
  CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11405
0
                                          DeclarationName());
11406
0
  return Rebuilder.TransformExpr(E);
11407
0
}
11408
11409
0
bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11410
0
  if (SS.isInvalid())
11411
0
    return true;
11412
11413
0
  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11414
0
  CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11415
0
                                          DeclarationName());
11416
0
  NestedNameSpecifierLoc Rebuilt
11417
0
    = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11418
0
  if (!Rebuilt)
11419
0
    return true;
11420
11421
0
  SS.Adopt(Rebuilt);
11422
0
  return false;
11423
0
}
11424
11425
/// Rebuild the template parameters now that we know we're in a current
11426
/// instantiation.
11427
bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11428
0
                                               TemplateParameterList *Params) {
11429
0
  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11430
0
    Decl *Param = Params->getParam(I);
11431
11432
    // There is nothing to rebuild in a type parameter.
11433
0
    if (isa<TemplateTypeParmDecl>(Param))
11434
0
      continue;
11435
11436
    // Rebuild the template parameter list of a template template parameter.
11437
0
    if (TemplateTemplateParmDecl *TTP
11438
0
        = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11439
0
      if (RebuildTemplateParamsInCurrentInstantiation(
11440
0
            TTP->getTemplateParameters()))
11441
0
        return true;
11442
11443
0
      continue;
11444
0
    }
11445
11446
    // Rebuild the type of a non-type template parameter.
11447
0
    NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11448
0
    TypeSourceInfo *NewTSI
11449
0
      = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
11450
0
                                          NTTP->getLocation(),
11451
0
                                          NTTP->getDeclName());
11452
0
    if (!NewTSI)
11453
0
      return true;
11454
11455
0
    if (NewTSI->getType()->isUndeducedType()) {
11456
      // C++17 [temp.dep.expr]p3:
11457
      //   An id-expression is type-dependent if it contains
11458
      //    - an identifier associated by name lookup with a non-type
11459
      //      template-parameter declared with a type that contains a
11460
      //      placeholder type (7.1.7.4),
11461
0
      NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11462
0
    }
11463
11464
0
    if (NewTSI != NTTP->getTypeSourceInfo()) {
11465
0
      NTTP->setTypeSourceInfo(NewTSI);
11466
0
      NTTP->setType(NewTSI->getType());
11467
0
    }
11468
0
  }
11469
11470
0
  return false;
11471
0
}
11472
11473
/// Produces a formatted string that describes the binding of
11474
/// template parameters to template arguments.
11475
std::string
11476
Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11477
0
                                      const TemplateArgumentList &Args) {
11478
0
  return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11479
0
}
11480
11481
std::string
11482
Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11483
                                      const TemplateArgument *Args,
11484
0
                                      unsigned NumArgs) {
11485
0
  SmallString<128> Str;
11486
0
  llvm::raw_svector_ostream Out(Str);
11487
11488
0
  if (!Params || Params->size() == 0 || NumArgs == 0)
11489
0
    return std::string();
11490
11491
0
  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11492
0
    if (I >= NumArgs)
11493
0
      break;
11494
11495
0
    if (I == 0)
11496
0
      Out << "[with ";
11497
0
    else
11498
0
      Out << ", ";
11499
11500
0
    if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11501
0
      Out << Id->getName();
11502
0
    } else {
11503
0
      Out << '$' << I;
11504
0
    }
11505
11506
0
    Out << " = ";
11507
0
    Args[I].print(getPrintingPolicy(), Out,
11508
0
                  TemplateParameterList::shouldIncludeTypeForArgument(
11509
0
                      getPrintingPolicy(), Params, I));
11510
0
  }
11511
11512
0
  Out << ']';
11513
0
  return std::string(Out.str());
11514
0
}
11515
11516
void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11517
0
                                    CachedTokens &Toks) {
11518
0
  if (!FD)
11519
0
    return;
11520
11521
0
  auto LPT = std::make_unique<LateParsedTemplate>();
11522
11523
  // Take tokens to avoid allocations
11524
0
  LPT->Toks.swap(Toks);
11525
0
  LPT->D = FnD;
11526
0
  LPT->FPO = getCurFPFeatures();
11527
0
  LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11528
11529
0
  FD->setLateTemplateParsed(true);
11530
0
}
11531
11532
0
void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11533
0
  if (!FD)
11534
0
    return;
11535
0
  FD->setLateTemplateParsed(false);
11536
0
}
11537
11538
0
bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11539
0
  DeclContext *DC = CurContext;
11540
11541
0
  while (DC) {
11542
0
    if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11543
0
      const FunctionDecl *FD = RD->isLocalClass();
11544
0
      return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11545
0
    } else if (DC->isTranslationUnit() || DC->isNamespace())
11546
0
      return false;
11547
11548
0
    DC = DC->getParent();
11549
0
  }
11550
0
  return false;
11551
0
}
11552
11553
namespace {
11554
/// Walk the path from which a declaration was instantiated, and check
11555
/// that every explicit specialization along that path is visible. This enforces
11556
/// C++ [temp.expl.spec]/6:
11557
///
11558
///   If a template, a member template or a member of a class template is
11559
///   explicitly specialized then that specialization shall be declared before
11560
///   the first use of that specialization that would cause an implicit
11561
///   instantiation to take place, in every translation unit in which such a
11562
///   use occurs; no diagnostic is required.
11563
///
11564
/// and also C++ [temp.class.spec]/1:
11565
///
11566
///   A partial specialization shall be declared before the first use of a
11567
///   class template specialization that would make use of the partial
11568
///   specialization as the result of an implicit or explicit instantiation
11569
///   in every translation unit in which such a use occurs; no diagnostic is
11570
///   required.
11571
class ExplicitSpecializationVisibilityChecker {
11572
  Sema &S;
11573
  SourceLocation Loc;
11574
  llvm::SmallVector<Module *, 8> Modules;
11575
  Sema::AcceptableKind Kind;
11576
11577
public:
11578
  ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11579
                                          Sema::AcceptableKind Kind)
11580
0
      : S(S), Loc(Loc), Kind(Kind) {}
11581
11582
0
  void check(NamedDecl *ND) {
11583
0
    if (auto *FD = dyn_cast<FunctionDecl>(ND))
11584
0
      return checkImpl(FD);
11585
0
    if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11586
0
      return checkImpl(RD);
11587
0
    if (auto *VD = dyn_cast<VarDecl>(ND))
11588
0
      return checkImpl(VD);
11589
0
    if (auto *ED = dyn_cast<EnumDecl>(ND))
11590
0
      return checkImpl(ED);
11591
0
  }
11592
11593
private:
11594
0
  void diagnose(NamedDecl *D, bool IsPartialSpec) {
11595
0
    auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11596
0
                              : Sema::MissingImportKind::ExplicitSpecialization;
11597
0
    const bool Recover = true;
11598
11599
    // If we got a custom set of modules (because only a subset of the
11600
    // declarations are interesting), use them, otherwise let
11601
    // diagnoseMissingImport intelligently pick some.
11602
0
    if (Modules.empty())
11603
0
      S.diagnoseMissingImport(Loc, D, Kind, Recover);
11604
0
    else
11605
0
      S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11606
0
  }
11607
11608
0
  bool CheckMemberSpecialization(const NamedDecl *D) {
11609
0
    return Kind == Sema::AcceptableKind::Visible
11610
0
               ? S.hasVisibleMemberSpecialization(D)
11611
0
               : S.hasReachableMemberSpecialization(D);
11612
0
  }
11613
11614
0
  bool CheckExplicitSpecialization(const NamedDecl *D) {
11615
0
    return Kind == Sema::AcceptableKind::Visible
11616
0
               ? S.hasVisibleExplicitSpecialization(D)
11617
0
               : S.hasReachableExplicitSpecialization(D);
11618
0
  }
11619
11620
0
  bool CheckDeclaration(const NamedDecl *D) {
11621
0
    return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11622
0
                                                 : S.hasReachableDeclaration(D);
11623
0
  }
11624
11625
  // Check a specific declaration. There are three problematic cases:
11626
  //
11627
  //  1) The declaration is an explicit specialization of a template
11628
  //     specialization.
11629
  //  2) The declaration is an explicit specialization of a member of an
11630
  //     templated class.
11631
  //  3) The declaration is an instantiation of a template, and that template
11632
  //     is an explicit specialization of a member of a templated class.
11633
  //
11634
  // We don't need to go any deeper than that, as the instantiation of the
11635
  // surrounding class / etc is not triggered by whatever triggered this
11636
  // instantiation, and thus should be checked elsewhere.
11637
  template<typename SpecDecl>
11638
0
  void checkImpl(SpecDecl *Spec) {
11639
0
    bool IsHiddenExplicitSpecialization = false;
11640
0
    if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11641
0
      IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11642
0
                                           ? !CheckMemberSpecialization(Spec)
11643
0
                                           : !CheckExplicitSpecialization(Spec);
11644
0
    } else {
11645
0
      checkInstantiated(Spec);
11646
0
    }
11647
11648
0
    if (IsHiddenExplicitSpecialization)
11649
0
      diagnose(Spec->getMostRecentDecl(), false);
11650
0
  }
Unexecuted instantiation: SemaTemplate.cpp:void (anonymous namespace)::ExplicitSpecializationVisibilityChecker::checkImpl<clang::FunctionDecl>(clang::FunctionDecl*)
Unexecuted instantiation: SemaTemplate.cpp:void (anonymous namespace)::ExplicitSpecializationVisibilityChecker::checkImpl<clang::CXXRecordDecl>(clang::CXXRecordDecl*)
Unexecuted instantiation: SemaTemplate.cpp:void (anonymous namespace)::ExplicitSpecializationVisibilityChecker::checkImpl<clang::VarDecl>(clang::VarDecl*)
Unexecuted instantiation: SemaTemplate.cpp:void (anonymous namespace)::ExplicitSpecializationVisibilityChecker::checkImpl<clang::EnumDecl>(clang::EnumDecl*)
11651
11652
0
  void checkInstantiated(FunctionDecl *FD) {
11653
0
    if (auto *TD = FD->getPrimaryTemplate())
11654
0
      checkTemplate(TD);
11655
0
  }
11656
11657
0
  void checkInstantiated(CXXRecordDecl *RD) {
11658
0
    auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11659
0
    if (!SD)
11660
0
      return;
11661
11662
0
    auto From = SD->getSpecializedTemplateOrPartial();
11663
0
    if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11664
0
      checkTemplate(TD);
11665
0
    else if (auto *TD =
11666
0
                 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11667
0
      if (!CheckDeclaration(TD))
11668
0
        diagnose(TD, true);
11669
0
      checkTemplate(TD);
11670
0
    }
11671
0
  }
11672
11673
0
  void checkInstantiated(VarDecl *RD) {
11674
0
    auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11675
0
    if (!SD)
11676
0
      return;
11677
11678
0
    auto From = SD->getSpecializedTemplateOrPartial();
11679
0
    if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11680
0
      checkTemplate(TD);
11681
0
    else if (auto *TD =
11682
0
                 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11683
0
      if (!CheckDeclaration(TD))
11684
0
        diagnose(TD, true);
11685
0
      checkTemplate(TD);
11686
0
    }
11687
0
  }
11688
11689
0
  void checkInstantiated(EnumDecl *FD) {}
11690
11691
  template<typename TemplDecl>
11692
0
  void checkTemplate(TemplDecl *TD) {
11693
0
    if (TD->isMemberSpecialization()) {
11694
0
      if (!CheckMemberSpecialization(TD))
11695
0
        diagnose(TD->getMostRecentDecl(), false);
11696
0
    }
11697
0
  }
Unexecuted instantiation: SemaTemplate.cpp:void (anonymous namespace)::ExplicitSpecializationVisibilityChecker::checkTemplate<clang::FunctionTemplateDecl>(clang::FunctionTemplateDecl*)
Unexecuted instantiation: SemaTemplate.cpp:void (anonymous namespace)::ExplicitSpecializationVisibilityChecker::checkTemplate<clang::ClassTemplateDecl>(clang::ClassTemplateDecl*)
Unexecuted instantiation: SemaTemplate.cpp:void (anonymous namespace)::ExplicitSpecializationVisibilityChecker::checkTemplate<clang::ClassTemplatePartialSpecializationDecl>(clang::ClassTemplatePartialSpecializationDecl*)
Unexecuted instantiation: SemaTemplate.cpp:void (anonymous namespace)::ExplicitSpecializationVisibilityChecker::checkTemplate<clang::VarTemplateDecl>(clang::VarTemplateDecl*)
Unexecuted instantiation: SemaTemplate.cpp:void (anonymous namespace)::ExplicitSpecializationVisibilityChecker::checkTemplate<clang::VarTemplatePartialSpecializationDecl>(clang::VarTemplatePartialSpecializationDecl*)
11698
};
11699
} // end anonymous namespace
11700
11701
0
void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11702
0
  if (!getLangOpts().Modules)
11703
0
    return;
11704
11705
0
  ExplicitSpecializationVisibilityChecker(*this, Loc,
11706
0
                                          Sema::AcceptableKind::Visible)
11707
0
      .check(Spec);
11708
0
}
11709
11710
void Sema::checkSpecializationReachability(SourceLocation Loc,
11711
0
                                           NamedDecl *Spec) {
11712
0
  if (!getLangOpts().CPlusPlusModules)
11713
0
    return checkSpecializationVisibility(Loc, Spec);
11714
11715
0
  ExplicitSpecializationVisibilityChecker(*this, Loc,
11716
0
                                          Sema::AcceptableKind::Reachable)
11717
0
      .check(Spec);
11718
0
}
11719
11720
/// Returns the top most location responsible for the definition of \p N.
11721
/// If \p N is a a template specialization, this is the location
11722
/// of the top of the instantiation stack.
11723
/// Otherwise, the location of \p N is returned.
11724
0
SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11725
0
  if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11726
0
    return N->getLocation();
11727
0
  if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11728
0
    if (!FD->isFunctionTemplateSpecialization())
11729
0
      return FD->getLocation();
11730
0
  } else if (!isa<ClassTemplateSpecializationDecl,
11731
0
                  VarTemplateSpecializationDecl>(N)) {
11732
0
    return N->getLocation();
11733
0
  }
11734
0
  for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11735
0
    if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11736
0
      continue;
11737
0
    return CSC.PointOfInstantiation;
11738
0
  }
11739
0
  return N->getLocation();
11740
0
}