Coverage Report

Created: 2020-11-24 06:42

/Users/buildslave/jenkins/workspace/coverage/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/DeclFriend.h"
15
#include "clang/AST/DeclTemplate.h"
16
#include "clang/AST/Expr.h"
17
#include "clang/AST/ExprCXX.h"
18
#include "clang/AST/RecursiveASTVisitor.h"
19
#include "clang/AST/TypeVisitor.h"
20
#include "clang/Basic/Builtins.h"
21
#include "clang/Basic/LangOptions.h"
22
#include "clang/Basic/PartialDiagnostic.h"
23
#include "clang/Basic/Stack.h"
24
#include "clang/Basic/TargetInfo.h"
25
#include "clang/Sema/DeclSpec.h"
26
#include "clang/Sema/Initialization.h"
27
#include "clang/Sema/Lookup.h"
28
#include "clang/Sema/Overload.h"
29
#include "clang/Sema/ParsedTemplate.h"
30
#include "clang/Sema/Scope.h"
31
#include "clang/Sema/SemaInternal.h"
32
#include "clang/Sema/Template.h"
33
#include "clang/Sema/TemplateDeduction.h"
34
#include "llvm/ADT/SmallBitVector.h"
35
#include "llvm/ADT/SmallString.h"
36
#include "llvm/ADT/StringExtras.h"
37
38
#include <iterator>
39
using namespace clang;
40
using namespace sema;
41
42
// Exported for use by Parser.
43
SourceRange
44
clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
45
8
                              unsigned N) {
46
8
  if (!N) 
return SourceRange()0
;
47
8
  return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
48
8
}
49
50
346k
unsigned Sema::getTemplateDepth(Scope *S) const {
51
346k
  unsigned Depth = 0;
52
53
  // Each template parameter scope represents one level of template parameter
54
  // depth.
55
837k
  for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
56
491k
       TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
57
491k
    ++Depth;
58
491k
  }
59
60
  // Note that there are template parameters with the given depth.
61
0
  auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
62
63
  // Look for parameters of an enclosing generic lambda. We don't create a
64
  // template parameter scope for these.
65
1
  for (FunctionScopeInfo *FSI : getFunctionScopes()) {
66
1
    if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
67
0
      if (!LSI->TemplateParams.empty()) {
68
0
        ParamsAtDepth(LSI->AutoTemplateParameterDepth);
69
0
        break;
70
0
      }
71
0
      if (LSI->GLTemplateParameterList) {
72
0
        ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
73
0
        break;
74
0
      }
75
0
    }
76
1
  }
77
78
  // Look for parameters of an enclosing terse function template. We don't
79
  // create a template parameter scope for these either.
80
346k
  for (const InventedTemplateParameterInfo &Info :
81
0
       getInventedParameterInfos()) {
82
0
    if (!Info.TemplateParams.empty()) {
83
0
      ParamsAtDepth(Info.AutoTemplateParameterDepth);
84
0
      break;
85
0
    }
86
0
  }
87
88
346k
  return Depth;
89
346k
}
90
91
/// \brief Determine whether the declaration found is acceptable as the name
92
/// of a template and, if so, return that template declaration. Otherwise,
93
/// returns null.
94
///
95
/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
96
/// is true. In all other cases it will return a TemplateDecl (or null).
97
NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
98
                                       bool AllowFunctionTemplates,
99
6.59M
                                       bool AllowDependent) {
100
6.59M
  D = D->getUnderlyingDecl();
101
102
6.59M
  if (isa<TemplateDecl>(D)) {
103
5.68M
    if (!AllowFunctionTemplates && 
isa<FunctionTemplateDecl>(D)2.08k
)
104
1.59k
      return nullptr;
105
106
5.68M
    return D;
107
5.68M
  }
108
109
907k
  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
110
    // C++ [temp.local]p1:
111
    //   Like normal (non-template) classes, class templates have an
112
    //   injected-class-name (Clause 9). The injected-class-name
113
    //   can be used with or without a template-argument-list. When
114
    //   it is used without a template-argument-list, it is
115
    //   equivalent to the injected-class-name followed by the
116
    //   template-parameters of the class template enclosed in
117
    //   <>. When it is used with a template-argument-list, it
118
    //   refers to the specified class template specialization,
119
    //   which could be the current specialization or another
120
    //   specialization.
121
167k
    if (Record->isInjectedClassName()) {
122
163k
      Record = cast<CXXRecordDecl>(Record->getDeclContext());
123
163k
      if (Record->getDescribedClassTemplate())
124
123k
        return Record->getDescribedClassTemplate();
125
126
39.5k
      if (ClassTemplateSpecializationDecl *Spec
127
38.5k
            = dyn_cast<ClassTemplateSpecializationDecl>(Record))
128
38.5k
        return Spec->getSpecializedTemplate();
129
5.50k
    }
130
131
5.50k
    return nullptr;
132
5.50k
  }
133
134
  // 'using Dependent::foo;' can resolve to a template name.
135
  // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
136
  // injected-class-name).
137
739k
  if (AllowDependent && 
isa<UnresolvedUsingValueDecl>(D)739k
)
138
35
    return D;
139
140
739k
  return nullptr;
141
739k
}
142
143
void Sema::FilterAcceptableTemplateNames(LookupResult &R,
144
                                         bool AllowFunctionTemplates,
145
3.82M
                                         bool AllowDependent) {
146
3.82M
  LookupResult::Filter filter = R.makeFilter();
147
7.93M
  while (filter.hasNext()) {
148
4.10M
    NamedDecl *Orig = filter.next();
149
4.10M
    if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
150
746k
      filter.erase();
151
4.10M
  }
152
3.82M
  filter.done();
153
3.82M
}
154
155
bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
156
                                         bool AllowFunctionTemplates,
157
                                         bool AllowDependent,
158
149
                                         bool AllowNonTemplateFunctions) {
159
299
  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; 
++I150
) {
160
150
    if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
161
0
      return true;
162
150
    if (AllowNonTemplateFunctions &&
163
3
        isa<FunctionDecl>((*I)->getUnderlyingDecl()))
164
0
      return true;
165
150
  }
166
167
149
  return false;
168
149
}
169
170
TemplateNameKind Sema::isTemplateName(Scope *S,
171
                                      CXXScopeSpec &SS,
172
                                      bool hasTemplateKeyword,
173
                                      const UnqualifiedId &Name,
174
                                      ParsedType ObjectTypePtr,
175
                                      bool EnteringContext,
176
                                      TemplateTy &TemplateResult,
177
                                      bool &MemberOfUnknownSpecialization,
178
3.50M
                                      bool Disambiguation) {
179
3.50M
  assert(getLangOpts().CPlusPlus && "No template names in C!");
180
181
3.50M
  DeclarationName TName;
182
3.50M
  MemberOfUnknownSpecialization = false;
183
184
3.50M
  switch (Name.getKind()) {
185
3.50M
  case UnqualifiedIdKind::IK_Identifier:
186
3.50M
    TName = DeclarationName(Name.Identifier);
187
3.50M
    break;
188
189
1.97k
  case UnqualifiedIdKind::IK_OperatorFunctionId:
190
1.97k
    TName = Context.DeclarationNames.getCXXOperatorName(
191
1.97k
                                              Name.OperatorFunctionId.Operator);
192
1.97k
    break;
193
194
4
  case UnqualifiedIdKind::IK_LiteralOperatorId:
195
4
    TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
196
4
    break;
197
198
0
  default:
199
0
    return TNK_Non_template;
200
3.50M
  }
201
202
3.50M
  QualType ObjectType = ObjectTypePtr.get();
203
204
3.50M
  AssumedTemplateKind AssumedTemplate;
205
3.50M
  LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
206
3.50M
  if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
207
3.50M
                         MemberOfUnknownSpecialization, SourceLocation(),
208
3.50M
                         &AssumedTemplate,
209
3.50M
                         /*AllowTypoCorrection=*/!Disambiguation))
210
160
    return TNK_Non_template;
211
212
3.50M
  if (AssumedTemplate != AssumedTemplateKind::None) {
213
669
    TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
214
    // Let the parser know whether we found nothing or found functions; if we
215
    // found nothing, we want to more carefully check whether this is actually
216
    // a function template name versus some other kind of undeclared identifier.
217
669
    return AssumedTemplate == AssumedTemplateKind::FoundNothing
218
661
               ? TNK_Undeclared_template
219
8
               : TNK_Function_template;
220
669
  }
221
222
3.50M
  if (R.empty())
223
892k
    return TNK_Non_template;
224
225
2.61M
  NamedDecl *D = nullptr;
226
2.61M
  if (R.isAmbiguous()) {
227
    // If we got an ambiguity involving a non-function template, treat this
228
    // as a template name, and pick an arbitrary template for error recovery.
229
9
    bool AnyFunctionTemplates = false;
230
17
    for (NamedDecl *FoundD : R) {
231
17
      if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
232
10
        if (isa<FunctionTemplateDecl>(FoundTemplate))
233
5
          AnyFunctionTemplates = true;
234
5
        else {
235
5
          D = FoundTemplate;
236
5
          break;
237
5
        }
238
10
      }
239
17
    }
240
241
    // If we didn't find any templates at all, this isn't a template name.
242
    // Leave the ambiguity for a later lookup to diagnose.
243
9
    if (!D && 
!AnyFunctionTemplates4
) {
244
2
      R.suppressDiagnostics();
245
2
      return TNK_Non_template;
246
2
    }
247
248
    // If the only templates were function templates, filter out the rest.
249
    // We'll diagnose the ambiguity later.
250
7
    if (!D)
251
2
      FilterAcceptableTemplateNames(R);
252
7
  }
253
254
  // At this point, we have either picked a single template name declaration D
255
  // or we have a non-empty set of results R containing either one template name
256
  // declaration or a set of function templates.
257
258
2.61M
  TemplateName Template;
259
2.61M
  TemplateNameKind TemplateKind;
260
261
2.61M
  unsigned ResultCount = R.end() - R.begin();
262
2.61M
  if (!D && 
ResultCount > 12.61M
) {
263
    // We assume that we'll preserve the qualifier from a function
264
    // template name in other ways.
265
119k
    Template = Context.getOverloadedTemplateName(R.begin(), R.end());
266
119k
    TemplateKind = TNK_Function_template;
267
268
    // We'll do this lookup again later.
269
119k
    R.suppressDiagnostics();
270
2.49M
  } else {
271
2.49M
    if (!D) {
272
2.49M
      D = getAsTemplateNameDecl(*R.begin());
273
2.49M
      assert(D && "unambiguous result is not a template name");
274
2.49M
    }
275
276
2.49M
    if (isa<UnresolvedUsingValueDecl>(D)) {
277
      // We don't yet know whether this is a template-name or not.
278
16
      MemberOfUnknownSpecialization = true;
279
16
      return TNK_Non_template;
280
16
    }
281
282
2.49M
    TemplateDecl *TD = cast<TemplateDecl>(D);
283
284
2.49M
    if (SS.isSet() && 
!SS.isInvalid()141k
) {
285
141k
      NestedNameSpecifier *Qualifier = SS.getScopeRep();
286
141k
      Template = Context.getQualifiedTemplateName(Qualifier,
287
141k
                                                  hasTemplateKeyword, TD);
288
2.35M
    } else {
289
2.35M
      Template = TemplateName(TD);
290
2.35M
    }
291
292
2.49M
    if (isa<FunctionTemplateDecl>(TD)) {
293
107k
      TemplateKind = TNK_Function_template;
294
295
      // We'll do this lookup again later.
296
107k
      R.suppressDiagnostics();
297
2.38M
    } else {
298
2.38M
      assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
299
2.38M
             isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
300
2.38M
             isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
301
2.38M
      TemplateKind =
302
3.01k
          isa<VarTemplateDecl>(TD) ? TNK_Var_template :
303
2.38M
          isa<ConceptDecl>(TD) ? 
TNK_Concept_template421
:
304
2.38M
          TNK_Type_template;
305
2.38M
    }
306
2.49M
  }
307
308
2.61M
  TemplateResult = TemplateTy::make(Template);
309
2.61M
  return TemplateKind;
310
2.61M
}
311
312
bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
313
                                SourceLocation NameLoc,
314
76.0k
                                ParsedTemplateTy *Template) {
315
76.0k
  CXXScopeSpec SS;
316
76.0k
  bool MemberOfUnknownSpecialization = false;
317
318
  // We could use redeclaration lookup here, but we don't need to: the
319
  // syntactic form of a deduction guide is enough to identify it even
320
  // if we can't look up the template name at all.
321
76.0k
  LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
322
76.0k
  if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
323
76.0k
                         /*EnteringContext*/ false,
324
76.0k
                         MemberOfUnknownSpecialization))
325
0
    return false;
326
327
76.0k
  if (R.empty()) 
return false72.4k
;
328
3.59k
  if (R.isAmbiguous()) {
329
    // FIXME: Diagnose an ambiguity if we find at least one template.
330
1
    R.suppressDiagnostics();
331
1
    return false;
332
1
  }
333
334
  // We only treat template-names that name type templates as valid deduction
335
  // guide names.
336
3.59k
  TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
337
3.59k
  if (!TD || 
!getAsTypeTemplateDecl(TD)999
)
338
2.59k
    return false;
339
340
998
  if (Template)
341
421
    *Template = TemplateTy::make(TemplateName(TD));
342
998
  return true;
343
998
}
344
345
bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
346
                                       SourceLocation IILoc,
347
                                       Scope *S,
348
                                       const CXXScopeSpec *SS,
349
                                       TemplateTy &SuggestedTemplate,
350
4
                                       TemplateNameKind &SuggestedKind) {
351
  // We can't recover unless there's a dependent scope specifier preceding the
352
  // template name.
353
  // FIXME: Typo correction?
354
4
  if (!SS || !SS->isSet() || 
!isDependentScopeSpecifier(*SS)0
||
355
0
      computeDeclContext(*SS))
356
4
    return false;
357
358
  // The code is missing a 'template' keyword prior to the dependent template
359
  // name.
360
0
  NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
361
0
  Diag(IILoc, diag::err_template_kw_missing)
362
0
    << Qualifier << II.getName()
363
0
    << FixItHint::CreateInsertion(IILoc, "template ");
364
0
  SuggestedTemplate
365
0
    = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
366
0
  SuggestedKind = TNK_Dependent_template_name;
367
0
  return true;
368
0
}
369
370
bool Sema::LookupTemplateName(LookupResult &Found,
371
                              Scope *S, CXXScopeSpec &SS,
372
                              QualType ObjectType,
373
                              bool EnteringContext,
374
                              bool &MemberOfUnknownSpecialization,
375
                              RequiredTemplateKind RequiredTemplate,
376
                              AssumedTemplateKind *ATK,
377
3.82M
                              bool AllowTypoCorrection) {
378
3.82M
  if (ATK)
379
3.71M
    *ATK = AssumedTemplateKind::None;
380
381
3.82M
  if (SS.isInvalid())
382
157
    return true;
383
384
3.82M
  Found.setTemplateNameLookup(true);
385
386
  // Determine where to perform name lookup
387
3.82M
  MemberOfUnknownSpecialization = false;
388
3.82M
  DeclContext *LookupCtx = nullptr;
389
3.82M
  bool IsDependent = false;
390
3.82M
  if (!ObjectType.isNull()) {
391
    // This nested-name-specifier occurs in a member access expression, e.g.,
392
    // x->B::f, and we are looking into the type of the object.
393
11.7k
    assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
394
11.7k
    LookupCtx = computeDeclContext(ObjectType);
395
11.7k
    IsDependent = !LookupCtx && 
ObjectType->isDependentType()4.68k
;
396
11.7k
    assert((IsDependent || !ObjectType->isIncompleteType() ||
397
11.7k
            ObjectType->castAs<TagType>()->isBeingDefined()) &&
398
11.7k
           "Caller should have completed object type");
399
400
    // Template names cannot appear inside an Objective-C class or object type
401
    // or a vector type.
402
    //
403
    // FIXME: This is wrong. For example:
404
    //
405
    //   template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
406
    //   Vec<int> vi;
407
    //   vi.Vec<int>::~Vec<int>();
408
    //
409
    // ... should be accepted but we will not treat 'Vec' as a template name
410
    // here. The right thing to do would be to check if the name is a valid
411
    // vector component name, and look up a template name if not. And similarly
412
    // for lookups into Objective-C class and object types, where the same
413
    // problem can arise.
414
11.7k
    if (ObjectType->isObjCObjectOrInterfaceType() ||
415
11.7k
        ObjectType->isVectorType()) {
416
26
      Found.clear();
417
26
      return false;
418
26
    }
419
3.81M
  } else if (SS.isNotEmpty()) {
420
    // This nested-name-specifier occurs after another nested-name-specifier,
421
    // so long into the context associated with the prior nested-name-specifier.
422
609k
    LookupCtx = computeDeclContext(SS, EnteringContext);
423
609k
    IsDependent = !LookupCtx && 
isDependentScopeSpecifier(SS)203k
;
424
425
    // The declaration context must be complete.
426
609k
    if (LookupCtx && 
RequireCompleteDeclContext(SS, LookupCtx)406k
)
427
6
      return true;
428
3.82M
  }
429
430
3.82M
  bool ObjectTypeSearchedInScope = false;
431
3.82M
  bool AllowFunctionTemplatesInLookup = true;
432
3.82M
  if (LookupCtx) {
433
    // Perform "qualified" name lookup into the declaration context we
434
    // computed, which is either the type of the base of a member access
435
    // expression or the declaration context associated with a prior
436
    // nested-name-specifier.
437
413k
    LookupQualifiedName(Found, LookupCtx);
438
439
    // FIXME: The C++ standard does not clearly specify what happens in the
440
    // case where the object type is dependent, and implementations vary. In
441
    // Clang, we treat a name after a . or -> as a template-name if lookup
442
    // finds a non-dependent member or member of the current instantiation that
443
    // is a type template, or finds no such members and lookup in the context
444
    // of the postfix-expression finds a type template. In the latter case, the
445
    // name is nonetheless dependent, and we may resolve it to a member of an
446
    // unknown specialization when we come to instantiate the template.
447
413k
    IsDependent |= Found.wasNotFoundInCurrentInstantiation();
448
413k
  }
449
450
3.82M
  if (SS.isEmpty() && 
(3.21M
ObjectType.isNull()3.21M
||
Found.empty()11.7k
)) {
451
    // C++ [basic.lookup.classref]p1:
452
    //   In a class member access expression (5.2.5), if the . or -> token is
453
    //   immediately followed by an identifier followed by a <, the
454
    //   identifier must be looked up to determine whether the < is the
455
    //   beginning of a template argument list (14.2) or a less-than operator.
456
    //   The identifier is first looked up in the class of the object
457
    //   expression. If the identifier is not found, it is then looked up in
458
    //   the context of the entire postfix-expression and shall name a class
459
    //   template.
460
3.21M
    if (S)
461
3.21M
      LookupName(Found, S);
462
463
3.21M
    if (!ObjectType.isNull()) {
464
      //  FIXME: We should filter out all non-type templates here, particularly
465
      //  variable templates and concepts. But the exclusion of alias templates
466
      //  and template template parameters is a wording defect.
467
6.53k
      AllowFunctionTemplatesInLookup = false;
468
6.53k
      ObjectTypeSearchedInScope = true;
469
6.53k
    }
470
471
3.21M
    IsDependent |= Found.wasNotFoundInCurrentInstantiation();
472
3.21M
  }
473
474
3.82M
  if (Found.isAmbiguous())
475
12
    return false;
476
477
3.82M
  if (ATK && 
SS.isEmpty()3.71M
&&
ObjectType.isNull()3.14M
&&
478
3.13M
      !RequiredTemplate.hasTemplateKeyword()) {
479
    // C++2a [temp.names]p2:
480
    //   A name is also considered to refer to a template if it is an
481
    //   unqualified-id followed by a < and name lookup finds either one or more
482
    //   functions or finds nothing.
483
    //
484
    // To keep our behavior consistent, we apply the "finds nothing" part in
485
    // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
486
    // successfully form a call to an undeclared template-id.
487
3.13M
    bool AllFunctions =
488
3.13M
        getLangOpts().CPlusPlus20 &&
489
4.58k
        std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
490
4.51k
          return isa<FunctionDecl>(ND->getUnderlyingDecl());
491
4.51k
        });
492
3.13M
    if (AllFunctions || 
(3.13M
Found.empty()3.13M
&&
!IsDependent615
)) {
493
      // If lookup found any functions, or if this is a name that can only be
494
      // used for a function, then strongly assume this is a function
495
      // template-id.
496
717
      *ATK = (Found.empty() && 
Found.getLookupName().isIdentifier()706
)
497
706
                 ? AssumedTemplateKind::FoundNothing
498
11
                 : AssumedTemplateKind::FoundFunctions;
499
717
      Found.clear();
500
717
      return false;
501
717
    }
502
3.82M
  }
503
504
3.82M
  if (Found.empty() && 
!IsDependent235k
&&
AllowTypoCorrection27.0k
) {
505
    // If we did not find any names, and this is not a disambiguation, attempt
506
    // to correct any typos.
507
13.5k
    DeclarationName Name = Found.getLookupName();
508
13.5k
    Found.clear();
509
    // Simple filter callback that, for keywords, only accepts the C++ *_cast
510
13.5k
    DefaultFilterCCC FilterCCC{};
511
13.5k
    FilterCCC.WantTypeSpecifiers = false;
512
13.5k
    FilterCCC.WantExpressionKeywords = false;
513
13.5k
    FilterCCC.WantRemainingKeywords = false;
514
13.5k
    FilterCCC.WantCXXNamedCasts = true;
515
13.5k
    if (TypoCorrection Corrected =
516
9
            CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
517
9
                        &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
518
9
      if (auto *ND = Corrected.getFoundDecl())
519
9
        Found.addDecl(ND);
520
9
      FilterAcceptableTemplateNames(Found);
521
9
      if (Found.isAmbiguous()) {
522
0
        Found.clear();
523
9
      } else if (!Found.empty()) {
524
8
        Found.setLookupName(Corrected.getCorrection());
525
8
        if (LookupCtx) {
526
8
          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
527
8
          bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
528
4
                                  Name.getAsString() == CorrectedStr;
529
8
          diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
530
8
                                    << Name << LookupCtx << DroppedSpecifier
531
8
                                    << SS.getRange());
532
0
        } else {
533
0
          diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
534
0
        }
535
8
      }
536
9
    }
537
13.5k
  }
538
539
3.82M
  NamedDecl *ExampleLookupResult =
540
3.59M
      Found.empty() ? 
nullptr235k
: Found.getRepresentativeDecl();
541
3.82M
  FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
542
3.82M
  if (Found.empty()) {
543
978k
    if (IsDependent) {
544
209k
      MemberOfUnknownSpecialization = true;
545
209k
      return false;
546
209k
    }
547
548
    // If a 'template' keyword was used, a lookup that finds only non-template
549
    // names is an error.
550
769k
    if (ExampleLookupResult && 
RequiredTemplate742k
) {
551
38
      Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
552
38
          << Found.getLookupName() << SS.getRange()
553
38
          << RequiredTemplate.hasTemplateKeyword()
554
38
          << RequiredTemplate.getTemplateKeywordLoc();
555
38
      Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
556
38
           diag::note_template_kw_refers_to_non_template)
557
38
          << Found.getLookupName();
558
38
      return true;
559
38
    }
560
561
769k
    return false;
562
769k
  }
563
564
2.84M
  if (S && 
!ObjectType.isNull()2.77M
&&
!ObjectTypeSearchedInScope2.28k
&&
565
1.79k
      !getLangOpts().CPlusPlus11) {
566
    // C++03 [basic.lookup.classref]p1:
567
    //   [...] If the lookup in the class of the object expression finds a
568
    //   template, the name is also looked up in the context of the entire
569
    //   postfix-expression and [...]
570
    //
571
    // Note: C++11 does not perform this second lookup.
572
86
    LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
573
86
                            LookupOrdinaryName);
574
86
    FoundOuter.setTemplateNameLookup(true);
575
86
    LookupName(FoundOuter, S);
576
    // FIXME: We silently accept an ambiguous lookup here, in violation of
577
    // [basic.lookup]/1.
578
86
    FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
579
580
86
    NamedDecl *OuterTemplate;
581
86
    if (FoundOuter.empty()) {
582
      //   - if the name is not found, the name found in the class of the
583
      //     object expression is used, otherwise
584
10
    } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
585
8
               !(OuterTemplate =
586
2
                     getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
587
      //   - if the name is found in the context of the entire
588
      //     postfix-expression and does not name a class template, the name
589
      //     found in the class of the object expression is used, otherwise
590
2
      FoundOuter.clear();
591
8
    } else if (!Found.isSuppressingDiagnostics()) {
592
      //   - if the name found is a class template, it must refer to the same
593
      //     entity as the one found in the class of the object expression,
594
      //     otherwise the program is ill-formed.
595
8
      if (!Found.isSingleResult() ||
596
7
          getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
597
2
              OuterTemplate->getCanonicalDecl()) {
598
2
        Diag(Found.getNameLoc(),
599
2
             diag::ext_nested_name_member_ref_lookup_ambiguous)
600
2
          << Found.getLookupName()
601
2
          << ObjectType;
602
2
        Diag(Found.getRepresentativeDecl()->getLocation(),
603
2
             diag::note_ambig_member_ref_object_type)
604
2
          << ObjectType;
605
2
        Diag(FoundOuter.getFoundDecl()->getLocation(),
606
2
             diag::note_ambig_member_ref_scope);
607
608
        // Recover by taking the template that we found in the object
609
        // expression's type.
610
2
      }
611
8
    }
612
86
  }
613
614
2.84M
  return false;
615
2.84M
}
616
617
void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
618
                                              SourceLocation Less,
619
33
                                              SourceLocation Greater) {
620
33
  if (TemplateName.isInvalid())
621
0
    return;
622
623
33
  DeclarationNameInfo NameInfo;
624
33
  CXXScopeSpec SS;
625
33
  LookupNameKind LookupKind;
626
627
33
  DeclContext *LookupCtx = nullptr;
628
33
  NamedDecl *Found = nullptr;
629
33
  bool MissingTemplateKeyword = false;
630
631
  // Figure out what name we looked up.
632
33
  if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
633
13
    NameInfo = DRE->getNameInfo();
634
13
    SS.Adopt(DRE->getQualifierLoc());
635
13
    LookupKind = LookupOrdinaryName;
636
13
    Found = DRE->getFoundDecl();
637
20
  } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
638
2
    NameInfo = ME->getMemberNameInfo();
639
2
    SS.Adopt(ME->getQualifierLoc());
640
2
    LookupKind = LookupMemberName;
641
2
    LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
642
2
    Found = ME->getMemberDecl();
643
18
  } else if (auto *DSDRE =
644
3
                 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
645
3
    NameInfo = DSDRE->getNameInfo();
646
3
    SS.Adopt(DSDRE->getQualifierLoc());
647
3
    MissingTemplateKeyword = true;
648
15
  } else if (auto *DSME =
649
15
                 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
650
15
    NameInfo = DSME->getMemberNameInfo();
651
15
    SS.Adopt(DSME->getQualifierLoc());
652
15
    MissingTemplateKeyword = true;
653
0
  } else {
654
0
    llvm_unreachable("unexpected kind of potential template name");
655
0
  }
656
657
  // If this is a dependent-scope lookup, diagnose that the 'template' keyword
658
  // was missing.
659
33
  if (MissingTemplateKeyword) {
660
18
    Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
661
18
        << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
662
18
    return;
663
18
  }
664
665
  // Try to correct the name by looking for templates and C++ named casts.
666
15
  struct TemplateCandidateFilter : CorrectionCandidateCallback {
667
15
    Sema &S;
668
15
    TemplateCandidateFilter(Sema &S) : S(S) {
669
15
      WantTypeSpecifiers = false;
670
15
      WantExpressionKeywords = false;
671
15
      WantRemainingKeywords = false;
672
15
      WantCXXNamedCasts = true;
673
15
    };
674
43
    bool ValidateCandidate(const TypoCorrection &Candidate) override {
675
43
      if (auto *ND = Candidate.getCorrectionDecl())
676
43
        return S.getAsTemplateNameDecl(ND);
677
0
      return Candidate.isKeyword();
678
0
    }
679
680
15
    std::unique_ptr<CorrectionCandidateCallback> clone() override {
681
15
      return std::make_unique<TemplateCandidateFilter>(*this);
682
15
    }
683
15
  };
684
685
15
  DeclarationName Name = NameInfo.getName();
686
15
  TemplateCandidateFilter CCC(*this);
687
15
  if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
688
14
                                             CTK_ErrorRecovery, LookupCtx)) {
689
14
    auto *ND = Corrected.getFoundDecl();
690
14
    if (ND)
691
14
      ND = getAsTemplateNameDecl(ND);
692
14
    if (ND || 
Corrected.isKeyword()0
) {
693
14
      if (LookupCtx) {
694
1
        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
695
1
        bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
696
0
                                Name.getAsString() == CorrectedStr;
697
1
        diagnoseTypo(Corrected,
698
1
                     PDiag(diag::err_non_template_in_member_template_id_suggest)
699
1
                         << Name << LookupCtx << DroppedSpecifier
700
1
                         << SS.getRange(), false);
701
13
      } else {
702
13
        diagnoseTypo(Corrected,
703
13
                     PDiag(diag::err_non_template_in_template_id_suggest)
704
13
                         << Name, false);
705
13
      }
706
14
      if (Found)
707
14
        Diag(Found->getLocation(),
708
14
             diag::note_non_template_in_template_id_found);
709
14
      return;
710
14
    }
711
1
  }
712
713
1
  Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
714
1
    << Name << SourceRange(Less, Greater);
715
1
  if (Found)
716
1
    Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
717
1
}
718
719
/// ActOnDependentIdExpression - Handle a dependent id-expression that
720
/// was just parsed.  This is only possible with an explicit scope
721
/// specifier naming a dependent type.
722
ExprResult
723
Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
724
                                 SourceLocation TemplateKWLoc,
725
                                 const DeclarationNameInfo &NameInfo,
726
                                 bool isAddressOfOperand,
727
599k
                           const TemplateArgumentListInfo *TemplateArgs) {
728
599k
  DeclContext *DC = getFunctionLevelDeclContext();
729
730
  // C++11 [expr.prim.general]p12:
731
  //   An id-expression that denotes a non-static data member or non-static
732
  //   member function of a class can only be used:
733
  //   (...)
734
  //   - if that id-expression denotes a non-static data member and it
735
  //     appears in an unevaluated operand.
736
  //
737
  // If this might be the case, form a DependentScopeDeclRefExpr instead of a
738
  // CXXDependentScopeMemberExpr. The former can instantiate to either
739
  // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
740
  // always a MemberExpr.
741
599k
  bool MightBeCxx11UnevalField =
742
599k
      getLangOpts().CPlusPlus11 && 
isUnevaluatedContext()599k
;
743
744
  // Check if the nested name specifier is an enum type.
745
599k
  bool IsEnum = false;
746
599k
  if (NestedNameSpecifier *NNS = SS.getScopeRep())
747
599k
    IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
748
749
599k
  if (!MightBeCxx11UnevalField && 
!isAddressOfOperand598k
&&
!IsEnum598k
&&
750
598k
      isa<CXXMethodDecl>(DC) && 
cast<CXXMethodDecl>(DC)->isInstance()148k
) {
751
115k
    QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
752
753
    // Since the 'this' expression is synthesized, we don't need to
754
    // perform the double-lookup check.
755
115k
    NamedDecl *FirstQualifierInScope = nullptr;
756
757
115k
    return CXXDependentScopeMemberExpr::Create(
758
115k
        Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
759
115k
        /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
760
115k
        FirstQualifierInScope, NameInfo, TemplateArgs);
761
115k
  }
762
763
484k
  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
764
484k
}
765
766
ExprResult
767
Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
768
                                SourceLocation TemplateKWLoc,
769
                                const DeclarationNameInfo &NameInfo,
770
941k
                                const TemplateArgumentListInfo *TemplateArgs) {
771
  // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
772
941k
  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
773
941k
  if (!QualifierLoc)
774
1
    return ExprError();
775
776
941k
  return DependentScopeDeclRefExpr::Create(
777
941k
      Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
778
941k
}
779
780
781
/// Determine whether we would be unable to instantiate this template (because
782
/// it either has no definition, or is in the process of being instantiated).
783
bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
784
                                          NamedDecl *Instantiation,
785
                                          bool InstantiatedFromMember,
786
                                          const NamedDecl *Pattern,
787
                                          const NamedDecl *PatternDef,
788
                                          TemplateSpecializationKind TSK,
789
1.57M
                                          bool Complain /*= true*/) {
790
1.57M
  assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
791
1.57M
         isa<VarDecl>(Instantiation));
792
793
1.57M
  bool IsEntityBeingDefined = false;
794
1.57M
  if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
795
742k
    IsEntityBeingDefined = TD->isBeingDefined();
796
797
1.57M
  if (PatternDef && 
!IsEntityBeingDefined1.52M
) {
798
1.52M
    NamedDecl *SuggestedDef = nullptr;
799
1.52M
    if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
800
23
                              /*OnlyNeedComplete*/false)) {
801
      // If we're allowed to diagnose this and recover, do so.
802
23
      bool Recover = Complain && 
!isSFINAEContext()16
;
803
23
      if (Complain)
804
16
        diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
805
16
                              Sema::MissingImportKind::Definition, Recover);
806
23
      return !Recover;
807
23
    }
808
1.52M
    return false;
809
1.52M
  }
810
811
43.5k
  if (!Complain || 
(602
PatternDef602
&&
PatternDef->isInvalidDecl()3
))
812
42.9k
    return true;
813
814
602
  llvm::Optional<unsigned> Note;
815
602
  QualType InstantiationTy;
816
602
  if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
817
561
    InstantiationTy = Context.getTypeDeclType(TD);
818
602
  if (PatternDef) {
819
3
    Diag(PointOfInstantiation,
820
3
         diag::err_template_instantiate_within_definition)
821
3
      << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
822
3
      << InstantiationTy;
823
    // Not much point in noting the template declaration here, since
824
    // we're lexically inside it.
825
3
    Instantiation->setInvalidDecl();
826
599
  } else if (InstantiatedFromMember) {
827
9
    if (isa<FunctionDecl>(Instantiation)) {
828
2
      Diag(PointOfInstantiation,
829
2
           diag::err_explicit_instantiation_undefined_member)
830
2
        << /*member function*/ 1 << Instantiation->getDeclName()
831
2
        << Instantiation->getDeclContext();
832
2
      Note = diag::note_explicit_instantiation_here;
833
7
    } else {
834
7
      assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
835
7
      Diag(PointOfInstantiation,
836
7
           diag::err_implicit_instantiate_member_undefined)
837
7
        << InstantiationTy;
838
7
      Note = diag::note_member_declared_at;
839
7
    }
840
590
  } else {
841
590
    if (isa<FunctionDecl>(Instantiation)) {
842
5
      Diag(PointOfInstantiation,
843
5
           diag::err_explicit_instantiation_undefined_func_template)
844
5
        << Pattern;
845
5
      Note = diag::note_explicit_instantiation_here;
846
585
    } else if (isa<TagDecl>(Instantiation)) {
847
551
      Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
848
551
        << (TSK != TSK_ImplicitInstantiation)
849
551
        << InstantiationTy;
850
551
      Note = diag::note_template_decl_here;
851
34
    } else {
852
34
      assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
853
34
      if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
854
30
        Diag(PointOfInstantiation,
855
30
             diag::err_explicit_instantiation_undefined_var_template)
856
30
          << Instantiation;
857
30
        Instantiation->setInvalidDecl();
858
30
      } else
859
4
        Diag(PointOfInstantiation,
860
4
             diag::err_explicit_instantiation_undefined_member)
861
4
          << /*static data member*/ 2 << Instantiation->getDeclName()
862
4
          << Instantiation->getDeclContext();
863
34
      Note = diag::note_explicit_instantiation_here;
864
34
    }
865
590
  }
866
602
  if (Note) // Diagnostics were emitted.
867
599
    Diag(Pattern->getLocation(), Note.getValue());
868
869
  // In general, Instantiation isn't marked invalid to get more than one
870
  // error for multiple undefined instantiations. But the code that does
871
  // explicit declaration -> explicit definition conversion can't handle
872
  // invalid declarations, so mark as invalid in that case.
873
602
  if (TSK == TSK_ExplicitInstantiationDeclaration)
874
3
    Instantiation->setInvalidDecl();
875
602
  return true;
876
602
}
877
878
/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
879
/// that the template parameter 'PrevDecl' is being shadowed by a new
880
/// declaration at location Loc. Returns true to indicate that this is
881
/// an error, and false otherwise.
882
87
void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
883
87
  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
884
885
  // C++ [temp.local]p4:
886
  //   A template-parameter shall not be redeclared within its
887
  //   scope (including nested scopes).
888
  //
889
  // Make this a warning when MSVC compatibility is requested.
890
5
  unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
891
82
                                             : diag::err_template_param_shadow;
892
87
  Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
893
87
  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
894
87
}
895
896
/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
897
/// the parameter D to reference the templated declaration and return a pointer
898
/// to the template declaration. Otherwise, do nothing to D and return null.
899
6.37M
TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
900
6.37M
  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
901
1.19M
    D = Temp->getTemplatedDecl();
902
1.19M
    return Temp;
903
1.19M
  }
904
5.18M
  return nullptr;
905
5.18M
}
906
907
ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
908
24
                                             SourceLocation EllipsisLoc) const {
909
24
  assert(Kind == Template &&
910
24
         "Only template template arguments can be pack expansions here");
911
24
  assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
912
24
         "Template template argument pack expansion without packs");
913
24
  ParsedTemplateArgument Result(*this);
914
24
  Result.EllipsisLoc = EllipsisLoc;
915
24
  return Result;
916
24
}
917
918
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
919
4.04M
                                            const ParsedTemplateArgument &Arg) {
920
921
4.04M
  switch (Arg.getKind()) {
922
3.38M
  case ParsedTemplateArgument::Type: {
923
3.38M
    TypeSourceInfo *DI;
924
3.38M
    QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
925
3.38M
    if (!DI)
926
0
      DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
927
3.38M
    return TemplateArgumentLoc(TemplateArgument(T), DI);
928
0
  }
929
930
657k
  case ParsedTemplateArgument::NonType: {
931
657k
    Expr *E = static_cast<Expr *>(Arg.getAsExpr());
932
657k
    return TemplateArgumentLoc(TemplateArgument(E), E);
933
0
  }
934
935
4.73k
  case ParsedTemplateArgument::Template: {
936
4.73k
    TemplateName Template = Arg.getAsTemplate().get();
937
4.73k
    TemplateArgument TArg;
938
4.73k
    if (Arg.getEllipsisLoc().isValid())
939
24
      TArg = TemplateArgument(Template, Optional<unsigned int>());
940
4.70k
    else
941
4.70k
      TArg = Template;
942
4.73k
    return TemplateArgumentLoc(
943
4.73k
        SemaRef.Context, TArg,
944
4.73k
        Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
945
4.73k
        Arg.getLocation(), Arg.getEllipsisLoc());
946
0
  }
947
0
  }
948
949
0
  llvm_unreachable("Unhandled parsed template argument");
950
0
}
951
952
/// Translates template arguments as provided by the parser
953
/// into template arguments used by semantic analysis.
954
void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
955
2.58M
                                      TemplateArgumentListInfo &TemplateArgs) {
956
6.63M
 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; 
++I4.04M
)
957
4.04M
   TemplateArgs.addArgument(translateTemplateArgument(*this,
958
4.04M
                                                      TemplateArgsIn[I]));
959
2.58M
}
960
961
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
962
                                                 SourceLocation Loc,
963
1.93M
                                                 IdentifierInfo *Name) {
964
1.93M
  NamedDecl *PrevDecl = SemaRef.LookupSingleName(
965
1.93M
      S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
966
1.93M
  if (PrevDecl && 
PrevDecl->isTemplateParameter()1.96k
)
967
21
    SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
968
1.93M
}
969
970
/// Convert a parsed type into a parsed template argument. This is mostly
971
/// trivial, except that we may have parsed a C++17 deduced class template
972
/// specialization type, in which case we should form a template template
973
/// argument instead of a type template argument.
974
3.38M
ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
975
3.38M
  TypeSourceInfo *TInfo;
976
3.38M
  QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
977
3.38M
  if (T.isNull())
978
61
    return ParsedTemplateArgument();
979
3.38M
  assert(TInfo && "template argument with no location");
980
981
  // If we might have formed a deduced template specialization type, convert
982
  // it to a template template argument.
983
3.38M
  if (getLangOpts().CPlusPlus17) {
984
96.5k
    TypeLoc TL = TInfo->getTypeLoc();
985
96.5k
    SourceLocation EllipsisLoc;
986
96.5k
    if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
987
0
      EllipsisLoc = PET.getEllipsisLoc();
988
0
      TL = PET.getPatternLoc();
989
0
    }
990
991
96.5k
    CXXScopeSpec SS;
992
96.5k
    if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
993
306
      SS.Adopt(ET.getQualifierLoc());
994
306
      TL = ET.getNamedTypeLoc();
995
306
    }
996
997
96.5k
    if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
998
300
      TemplateName Name = DTST.getTypePtr()->getTemplateName();
999
300
      if (SS.isSet())
1000
15
        Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
1001
15
                                                /*HasTemplateKeyword*/ false,
1002
15
                                                Name.getAsTemplateDecl());
1003
300
      ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
1004
300
                                    DTST.getTemplateNameLoc());
1005
300
      if (EllipsisLoc.isValid())
1006
0
        Result = Result.getTemplatePackExpansion(EllipsisLoc);
1007
300
      return Result;
1008
300
    }
1009
3.38M
  }
1010
1011
  // This is a normal type template argument. Note, if the type template
1012
  // argument is an injected-class-name for a template, it has a dual nature
1013
  // and can be used as either a type or a template. We handle that in
1014
  // convertTypeTemplateArgumentToTemplate.
1015
3.38M
  return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1016
3.38M
                                ParsedType.get().getAsOpaquePtr(),
1017
3.38M
                                TInfo->getTypeLoc().getBeginLoc());
1018
3.38M
}
1019
1020
/// ActOnTypeParameter - Called when a C++ template type parameter
1021
/// (e.g., "typename T") has been parsed. Typename specifies whether
1022
/// the keyword "typename" was used to declare the type parameter
1023
/// (otherwise, "class" was used), and KeyLoc is the location of the
1024
/// "class" or "typename" keyword. ParamName is the name of the
1025
/// parameter (NULL indicates an unnamed template parameter) and
1026
/// ParamNameLoc is the location of the parameter name (if any).
1027
/// If the type parameter has a default argument, it will be added
1028
/// later via ActOnTypeParameterDefault.
1029
NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1030
                                    SourceLocation EllipsisLoc,
1031
                                    SourceLocation KeyLoc,
1032
                                    IdentifierInfo *ParamName,
1033
                                    SourceLocation ParamNameLoc,
1034
                                    unsigned Depth, unsigned Position,
1035
                                    SourceLocation EqualLoc,
1036
                                    ParsedType DefaultArg,
1037
1.83M
                                    bool HasTypeConstraint) {
1038
1.83M
  assert(S->isTemplateParamScope() &&
1039
1.83M
         "Template type parameter not in template parameter scope!");
1040
1041
1.83M
  bool IsParameterPack = EllipsisLoc.isValid();
1042
1.83M
  TemplateTypeParmDecl *Param
1043
1.83M
    = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1044
1.83M
                                   KeyLoc, ParamNameLoc, Depth, Position,
1045
1.83M
                                   ParamName, Typename, IsParameterPack,
1046
1.83M
                                   HasTypeConstraint);
1047
1.83M
  Param->setAccess(AS_public);
1048
1049
1.83M
  if (Param->isParameterPack())
1050
122k
    if (auto *LSI = getEnclosingLambda())
1051
10
      LSI->LocalPacks.push_back(Param);
1052
1053
1.83M
  if (ParamName) {
1054
1.77M
    maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1055
1056
    // Add the template parameter into the current scope.
1057
1.77M
    S->AddDecl(Param);
1058
1.77M
    IdResolver.AddDecl(Param);
1059
1.77M
  }
1060
1061
  // C++0x [temp.param]p9:
1062
  //   A default template-argument may be specified for any kind of
1063
  //   template-parameter that is not a template parameter pack.
1064
1.83M
  if (DefaultArg && 
IsParameterPack72.9k
) {
1065
1
    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1066
1
    DefaultArg = nullptr;
1067
1
  }
1068
1069
  // Handle the default argument, if provided.
1070
1.83M
  if (DefaultArg) {
1071
72.9k
    TypeSourceInfo *DefaultTInfo;
1072
72.9k
    GetTypeFromParser(DefaultArg, &DefaultTInfo);
1073
1074
72.9k
    assert(DefaultTInfo && "expected source information for type");
1075
1076
    // Check for unexpanded parameter packs.
1077
72.9k
    if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1078
72.9k
                                        UPPC_DefaultArgument))
1079
2
      return Param;
1080
1081
    // Check the template argument itself.
1082
72.9k
    if (CheckTemplateArgument(Param, DefaultTInfo)) {
1083
0
      Param->setInvalidDecl();
1084
0
      return Param;
1085
0
    }
1086
1087
72.9k
    Param->setDefaultArgument(DefaultTInfo);
1088
72.9k
  }
1089
1090
1.83M
  return Param;
1091
1.83M
}
1092
1093
/// Convert the parser's template argument list representation into our form.
1094
static TemplateArgumentListInfo
1095
204k
makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1096
204k
  TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1097
204k
                                        TemplateId.RAngleLoc);
1098
204k
  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1099
204k
                                     TemplateId.NumArgs);
1100
204k
  S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1101
204k
  return TemplateArgs;
1102
204k
}
1103
1104
bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1105
                               TemplateIdAnnotation *TypeConstr,
1106
                               TemplateTypeParmDecl *ConstrainedParameter,
1107
108
                               SourceLocation EllipsisLoc) {
1108
108
  ConceptDecl *CD =
1109
108
      cast<ConceptDecl>(TypeConstr->Template.get().getAsTemplateDecl());
1110
1111
  // C++2a [temp.param]p4:
1112
  //     [...] The concept designated by a type-constraint shall be a type
1113
  //     concept ([temp.concept]).
1114
108
  if (!CD->isTypeConcept()) {
1115
5
    Diag(TypeConstr->TemplateNameLoc,
1116
5
         diag::err_type_constraint_non_type_concept);
1117
5
    return true;
1118
5
  }
1119
1120
103
  bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1121
1122
103
  if (!WereArgsSpecified &&
1123
56
      CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1124
4
    Diag(TypeConstr->TemplateNameLoc,
1125
4
         diag::err_type_constraint_missing_arguments) << CD;
1126
4
    return true;
1127
4
  }
1128
1129
99
  TemplateArgumentListInfo TemplateArgs;
1130
99
  if (TypeConstr->LAngleLoc.isValid()) {
1131
47
    TemplateArgs =
1132
47
        makeTemplateArgumentListInfo(*this, *TypeConstr);
1133
47
  }
1134
99
  return AttachTypeConstraint(
1135
92
      SS.isSet() ? 
SS.getWithLocInContext(Context)7
: NestedNameSpecifierLoc(),
1136
99
      DeclarationNameInfo(DeclarationName(TypeConstr->Name),
1137
99
                          TypeConstr->TemplateNameLoc), CD,
1138
52
      TypeConstr->LAngleLoc.isValid() ? 
&TemplateArgs47
: nullptr,
1139
99
      ConstrainedParameter, EllipsisLoc);
1140
99
}
1141
1142
template<typename ArgumentLocAppender>
1143
static ExprResult formImmediatelyDeclaredConstraint(
1144
    Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1145
    ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
1146
    SourceLocation RAngleLoc, QualType ConstrainedType,
1147
    SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1148
196
    SourceLocation EllipsisLoc) {
1149
1150
196
  TemplateArgumentListInfo ConstraintArgs;
1151
196
  ConstraintArgs.addArgument(
1152
196
    S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1153
196
                                    /*NTTPType=*/QualType(), ParamNameLoc));
1154
1155
196
  ConstraintArgs.setRAngleLoc(RAngleLoc);
1156
196
  ConstraintArgs.setLAngleLoc(LAngleLoc);
1157
196
  Appender(ConstraintArgs);
1158
1159
  // C++2a [temp.param]p4:
1160
  //     [...] This constraint-expression E is called the immediately-declared
1161
  //     constraint of T. [...]
1162
196
  CXXScopeSpec SS;
1163
196
  SS.Adopt(NS);
1164
196
  ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1165
196
      SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1166
196
      /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1167
196
  if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1168
170
    return ImmediatelyDeclaredConstraint;
1169
1170
  // C++2a [temp.param]p4:
1171
  //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1172
  //
1173
  // We have the following case:
1174
  //
1175
  // template<typename T> concept C1 = true;
1176
  // template<C1... T> struct s1;
1177
  //
1178
  // The constraint: (C1<T> && ...)
1179
  //
1180
  // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1181
  // any unqualified lookups for 'operator&&' here.
1182
26
  return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1183
26
                            /*LParenLoc=*/SourceLocation(),
1184
26
                            ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1185
26
                            EllipsisLoc, /*RHS=*/nullptr,
1186
26
                            /*RParenLoc=*/SourceLocation(),
1187
26
                            /*NumExpansions=*/None);
1188
26
}
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)
Line
Count
Source
1148
194
    SourceLocation EllipsisLoc) {
1149
1150
194
  TemplateArgumentListInfo ConstraintArgs;
1151
194
  ConstraintArgs.addArgument(
1152
194
    S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1153
194
                                    /*NTTPType=*/QualType(), ParamNameLoc));
1154
1155
194
  ConstraintArgs.setRAngleLoc(RAngleLoc);
1156
194
  ConstraintArgs.setLAngleLoc(LAngleLoc);
1157
194
  Appender(ConstraintArgs);
1158
1159
  // C++2a [temp.param]p4:
1160
  //     [...] This constraint-expression E is called the immediately-declared
1161
  //     constraint of T. [...]
1162
194
  CXXScopeSpec SS;
1163
194
  SS.Adopt(NS);
1164
194
  ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1165
194
      SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1166
194
      /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1167
194
  if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1168
169
    return ImmediatelyDeclaredConstraint;
1169
1170
  // C++2a [temp.param]p4:
1171
  //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1172
  //
1173
  // We have the following case:
1174
  //
1175
  // template<typename T> concept C1 = true;
1176
  // template<C1... T> struct s1;
1177
  //
1178
  // The constraint: (C1<T> && ...)
1179
  //
1180
  // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1181
  // any unqualified lookups for 'operator&&' here.
1182
25
  return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1183
25
                            /*LParenLoc=*/SourceLocation(),
1184
25
                            ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1185
25
                            EllipsisLoc, /*RHS=*/nullptr,
1186
25
                            /*RParenLoc=*/SourceLocation(),
1187
25
                            /*NumExpansions=*/None);
1188
25
}
SemaTemplate.cpp:clang::ActionResult<clang::Expr*, true> formImmediatelyDeclaredConstraint<clang::Sema::AttachTypeConstraint(clang::AutoTypeLoc, 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::SourceLocation)::$_3, clang::SourceLocation)
Line
Count
Source
1148
2
    SourceLocation EllipsisLoc) {
1149
1150
2
  TemplateArgumentListInfo ConstraintArgs;
1151
2
  ConstraintArgs.addArgument(
1152
2
    S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1153
2
                                    /*NTTPType=*/QualType(), ParamNameLoc));
1154
1155
2
  ConstraintArgs.setRAngleLoc(RAngleLoc);
1156
2
  ConstraintArgs.setLAngleLoc(LAngleLoc);
1157
2
  Appender(ConstraintArgs);
1158
1159
  // C++2a [temp.param]p4:
1160
  //     [...] This constraint-expression E is called the immediately-declared
1161
  //     constraint of T. [...]
1162
2
  CXXScopeSpec SS;
1163
2
  SS.Adopt(NS);
1164
2
  ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1165
2
      SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1166
2
      /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1167
2
  if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1168
1
    return ImmediatelyDeclaredConstraint;
1169
1170
  // C++2a [temp.param]p4:
1171
  //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1172
  //
1173
  // We have the following case:
1174
  //
1175
  // template<typename T> concept C1 = true;
1176
  // template<C1... T> struct s1;
1177
  //
1178
  // The constraint: (C1<T> && ...)
1179
  //
1180
  // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1181
  // any unqualified lookups for 'operator&&' here.
1182
1
  return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1183
1
                            /*LParenLoc=*/SourceLocation(),
1184
1
                            ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1185
1
                            EllipsisLoc, /*RHS=*/nullptr,
1186
1
                            /*RParenLoc=*/SourceLocation(),
1187
1
                            /*NumExpansions=*/None);
1188
1
}
1189
1190
/// Attach a type-constraint to a template parameter.
1191
/// \returns true if an error occured. This can happen if the
1192
/// immediately-declared constraint could not be formed (e.g. incorrect number
1193
/// of arguments for the named concept).
1194
bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1195
                                DeclarationNameInfo NameInfo,
1196
                                ConceptDecl *NamedConcept,
1197
                                const TemplateArgumentListInfo *TemplateArgs,
1198
                                TemplateTypeParmDecl *ConstrainedParameter,
1199
194
                                SourceLocation EllipsisLoc) {
1200
  // C++2a [temp.param]p4:
1201
  //     [...] If Q is of the form C<A1, ..., An>, then let E' be
1202
  //     C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1203
194
  const ASTTemplateArgumentListInfo *ArgsAsWritten =
1204
108
    TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1205
86
                                                       *TemplateArgs) : nullptr;
1206
1207
194
  QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1208
1209
194
  ExprResult ImmediatelyDeclaredConstraint =
1210
194
      formImmediatelyDeclaredConstraint(
1211
194
          *this, NS, NameInfo, NamedConcept,
1212
108
          TemplateArgs ? TemplateArgs->getLAngleLoc() : 
SourceLocation()86
,
1213
108
          TemplateArgs ? TemplateArgs->getRAngleLoc() : 
SourceLocation()86
,
1214
194
          ParamAsArgument, ConstrainedParameter->getLocation(),
1215
194
          [&] (TemplateArgumentListInfo &ConstraintArgs) {
1216
194
            if (TemplateArgs)
1217
108
              for (const auto &ArgLoc : TemplateArgs->arguments())
1218
110
                ConstraintArgs.addArgument(ArgLoc);
1219
194
          }, EllipsisLoc);
1220
194
  if (ImmediatelyDeclaredConstraint.isInvalid())
1221
0
    return true;
1222
1223
194
  ConstrainedParameter->setTypeConstraint(NS, NameInfo,
1224
194
                                          /*FoundDecl=*/NamedConcept,
1225
194
                                          NamedConcept, ArgsAsWritten,
1226
194
                                          ImmediatelyDeclaredConstraint.get());
1227
194
  return false;
1228
194
}
1229
1230
bool Sema::AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *NTTP,
1231
3
                                SourceLocation EllipsisLoc) {
1232
3
  if (NTTP->getType() != TL.getType() ||
1233
2
      TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1234
1
    Diag(NTTP->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1235
1
         diag::err_unsupported_placeholder_constraint)
1236
1
       << NTTP->getTypeSourceInfo()->getTypeLoc().getSourceRange();
1237
1
    return true;
1238
1
  }
1239
  // FIXME: Concepts: This should be the type of the placeholder, but this is
1240
  // unclear in the wording right now.
1241
2
  DeclRefExpr *Ref = BuildDeclRefExpr(NTTP, NTTP->getType(), VK_RValue,
1242
2
                                      NTTP->getLocation());
1243
2
  if (!Ref)
1244
0
    return true;
1245
2
  ExprResult ImmediatelyDeclaredConstraint =
1246
2
      formImmediatelyDeclaredConstraint(
1247
2
          *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1248
2
          TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1249
2
          BuildDecltypeType(Ref, NTTP->getLocation()), NTTP->getLocation(),
1250
2
          [&] (TemplateArgumentListInfo &ConstraintArgs) {
1251
6
            for (unsigned I = 0, C = TL.getNumArgs(); I != C; 
++I4
)
1252
4
              ConstraintArgs.addArgument(TL.getArgLoc(I));
1253
2
          }, EllipsisLoc);
1254
2
  if (ImmediatelyDeclaredConstraint.isInvalid() ||
1255
2
     !ImmediatelyDeclaredConstraint.isUsable())
1256
0
    return true;
1257
1258
2
  NTTP->setPlaceholderTypeConstraint(ImmediatelyDeclaredConstraint.get());
1259
2
  return false;
1260
2
}
1261
1262
/// Check that the type of a non-type template parameter is
1263
/// well-formed.
1264
///
1265
/// \returns the (possibly-promoted) parameter type if valid;
1266
/// otherwise, produces a diagnostic and returns a NULL type.
1267
QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1268
322k
                                                 SourceLocation Loc) {
1269
322k
  if (TSI->getType()->isUndeducedType()) {
1270
    // C++17 [temp.dep.expr]p3:
1271
    //   An id-expression is type-dependent if it contains
1272
    //    - an identifier associated by name lookup with a non-type
1273
    //      template-parameter declared with a type that contains a
1274
    //      placeholder type (7.1.7.4),
1275
158
    TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1276
158
  }
1277
1278
322k
  return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1279
322k
}
1280
1281
/// Require the given type to be a structural type, and diagnose if it is not.
1282
///
1283
/// \return \c true if an error was produced.
1284
269
bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1285
269
  if (T->isDependentType())
1286
0
    return false;
1287
1288
269
  if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1289
7
    return true;
1290
1291
262
  if (T->isStructuralType())
1292
213
    return false;
1293
1294
  // Structural types are required to be object types or lvalue references.
1295
49
  if (T->isRValueReferenceType()) {
1296
3
    Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1297
3
    return true;
1298
3
  }
1299
1300
  // Don't mention structural types in our diagnostic prior to C++20. Also,
1301
  // there's not much more we can say about non-scalar non-class types --
1302
  // because we can't see functions or arrays here, those can only be language
1303
  // extensions.
1304
46
  if (!getLangOpts().CPlusPlus20 ||
1305
33
      
(15
!T->isScalarType()15
&&
!T->isRecordType()15
)) {
1306
33
    Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1307
33
    return true;
1308
33
  }
1309
1310
  // Structural types are required to be literal types.
1311
13
  if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1312
0
    return true;
1313
1314
13
  Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1315
1316
  // Drill down into the reason why the class is non-structural.
1317
18
  while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1318
    // All members are required to be public and non-mutable, and can't be of
1319
    // rvalue reference type. Check these conditions first to prefer a "local"
1320
    // reason over a more distant one.
1321
12
    for (const FieldDecl *FD : RD->fields()) {
1322
12
      if (FD->getAccess() != AS_public) {
1323
3
        Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1324
3
        return true;
1325
3
      }
1326
9
      if (FD->isMutable()) {
1327
1
        Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1328
1
        return true;
1329
1
      }
1330
8
      if (FD->getType()->isRValueReferenceType()) {
1331
4
        Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1332
4
            << T;
1333
4
        return true;
1334
4
      }
1335
8
    }
1336
1337
    // All bases are required to be public.
1338
8
    for (const auto &BaseSpec : RD->bases()) {
1339
4
      if (BaseSpec.getAccessSpecifier() != AS_public) {
1340
3
        Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1341
3
            << T << 1;
1342
3
        return true;
1343
3
      }
1344
4
    }
1345
1346
    // All subobjects are required to be of structural types.
1347
5
    SourceLocation SubLoc;
1348
5
    QualType SubType;
1349
5
    int Kind = -1;
1350
1351
4
    for (const FieldDecl *FD : RD->fields()) {
1352
4
      QualType T = Context.getBaseElementType(FD->getType());
1353
4
      if (!T->isStructuralType()) {
1354
4
        SubLoc = FD->getLocation();
1355
4
        SubType = T;
1356
4
        Kind = 0;
1357
4
        break;
1358
4
      }
1359
4
    }
1360
1361
5
    if (Kind == -1) {
1362
1
      for (const auto &BaseSpec : RD->bases()) {
1363
1
        QualType T = BaseSpec.getType();
1364
1
        if (!T->isStructuralType()) {
1365
1
          SubLoc = BaseSpec.getBaseTypeLoc();
1366
1
          SubType = T;
1367
1
          Kind = 1;
1368
1
          break;
1369
1
        }
1370
1
      }
1371
1
    }
1372
1373
5
    assert(Kind != -1 && "couldn't find reason why type is not structural");
1374
5
    Diag(SubLoc, diag::note_not_structural_subobject)
1375
5
        << T << Kind << SubType;
1376
5
    T = SubType;
1377
5
    RD = T->getAsCXXRecordDecl();
1378
5
  }
1379
1380
2
  return true;
1381
13
}
1382
1383
QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1384
753k
                                                 SourceLocation Loc) {
1385
  // We don't allow variably-modified types as the type of non-type template
1386
  // parameters.
1387
753k
  if (T->isVariablyModifiedType()) {
1388
1
    Diag(Loc, diag::err_variably_modified_nontype_template_param)
1389
1
      << T;
1390
1
    return QualType();
1391
1
  }
1392
1393
  // C++ [temp.param]p4:
1394
  //
1395
  // A non-type template-parameter shall have one of the following
1396
  // (optionally cv-qualified) types:
1397
  //
1398
  //       -- integral or enumeration type,
1399
753k
  if (T->isIntegralOrEnumerationType() ||
1400
      //   -- pointer to object or pointer to function,
1401
126k
      T->isPointerType() ||
1402
      //   -- lvalue reference to object or lvalue reference to function,
1403
124k
      T->isLValueReferenceType() ||
1404
      //   -- pointer to member,
1405
120k
      T->isMemberPointerType() ||
1406
      //   -- std::nullptr_t, or
1407
120k
      T->isNullPtrType() ||
1408
      //   -- a type that contains a placeholder type.
1409
634k
      
T->isUndeducedType()120k
) {
1410
    // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1411
    // are ignored when determining its type.
1412
634k
    return T.getUnqualifiedType();
1413
634k
  }
1414
1415
  // C++ [temp.param]p8:
1416
  //
1417
  //   A non-type template-parameter of type "array of T" or
1418
  //   "function returning T" is adjusted to be of type "pointer to
1419
  //   T" or "pointer to function returning T", respectively.
1420
119k
  if (T->isArrayType() || 
T->isFunctionType()119k
)
1421
84
    return Context.getDecayedType(T);
1422
1423
  // If T is a dependent type, we can't do the check now, so we
1424
  // assume that it is well-formed. Note that stripping off the
1425
  // qualifiers here is not really correct if T turns out to be
1426
  // an array type, but we'll recompute the type everywhere it's
1427
  // used during instantiation, so that should be OK. (Using the
1428
  // qualified type is equally wrong.)
1429
119k
  if (T->isDependentType())
1430
119k
    return T.getUnqualifiedType();
1431
1432
  // C++20 [temp.param]p6:
1433
  //   -- a structural type
1434
269
  if (RequireStructuralType(T, Loc))
1435
56
    return QualType();
1436
1437
213
  if (!getLangOpts().CPlusPlus20) {
1438
    // FIXME: Consider allowing structural types as an extension in C++17. (In
1439
    // earlier language modes, the template argument evaluation rules are too
1440
    // inflexible.)
1441
30
    Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1442
30
    return QualType();
1443
30
  }
1444
1445
183
  Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1446
183
  return T.getUnqualifiedType();
1447
183
}
1448
1449
NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1450
                                          unsigned Depth,
1451
                                          unsigned Position,
1452
                                          SourceLocation EqualLoc,
1453
203k
                                          Expr *Default) {
1454
203k
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1455
1456
  // Check that we have valid decl-specifiers specified.
1457
203k
  auto CheckValidDeclSpecifiers = [this, &D] {
1458
    // C++ [temp.param]
1459
    // p1
1460
    //   template-parameter:
1461
    //     ...
1462
    //     parameter-declaration
1463
    // p2
1464
    //   ... A storage class shall not be specified in a template-parameter
1465
    //   declaration.
1466
    // [dcl.typedef]p1:
1467
    //   The typedef specifier [...] shall not be used in the decl-specifier-seq
1468
    //   of a parameter-declaration
1469
203k
    const DeclSpec &DS = D.getDeclSpec();
1470
35
    auto EmitDiag = [this](SourceLocation Loc) {
1471
35
      Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1472
35
          << FixItHint::CreateRemoval(Loc);
1473
35
    };
1474
203k
    if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1475
18
      EmitDiag(DS.getStorageClassSpecLoc());
1476
1477
203k
    if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1478
1
      EmitDiag(DS.getThreadStorageClassSpecLoc());
1479
1480
    // [dcl.inline]p1:
1481
    //   The inline specifier can be applied only to the declaration or
1482
    //   definition of a variable or function.
1483
1484
203k
    if (DS.isInlineSpecified())
1485
6
      EmitDiag(DS.getInlineSpecLoc());
1486
1487
    // [dcl.constexpr]p1:
1488
    //   The constexpr specifier shall be applied only to the definition of a
1489
    //   variable or variable template or the declaration of a function or
1490
    //   function template.
1491
1492
203k
    if (DS.hasConstexprSpecifier())
1493
1
      EmitDiag(DS.getConstexprSpecLoc());
1494
1495
    // [dcl.fct.spec]p1:
1496
    //   Function-specifiers can be used only in function declarations.
1497
1498
203k
    if (DS.isVirtualSpecified())
1499
3
      EmitDiag(DS.getVirtualSpecLoc());
1500
1501
203k
    if (DS.hasExplicitSpecifier())
1502
6
      EmitDiag(DS.getExplicitSpecLoc());
1503
1504
203k
    if (DS.isNoreturnSpecified())
1505
0
      EmitDiag(DS.getNoreturnSpecLoc());
1506
203k
  };
1507
1508
203k
  CheckValidDeclSpecifiers();
1509
1510
203k
  if (TInfo->getType()->isUndeducedType()) {
1511
138
    Diag(D.getIdentifierLoc(),
1512
138
         diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1513
138
      << QualType(TInfo->getType()->getContainedAutoType(), 0);
1514
138
  }
1515
1516
203k
  assert(S->isTemplateParamScope() &&
1517
203k
         "Non-type template parameter not in template parameter scope!");
1518
203k
  bool Invalid = false;
1519
1520
203k
  QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1521
203k
  if (T.isNull()) {
1522
71
    T = Context.IntTy; // Recover with an 'int' type.
1523
71
    Invalid = true;
1524
71
  }
1525
1526
203k
  CheckFunctionOrTemplateParamDeclarator(S, D);
1527
1528
203k
  IdentifierInfo *ParamName = D.getIdentifier();
1529
203k
  bool IsParameterPack = D.hasEllipsis();
1530
203k
  NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1531
203k
      Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1532
203k
      D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1533
203k
      TInfo);
1534
203k
  Param->setAccess(AS_public);
1535
1536
203k
  if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1537
126
    if (TL.isConstrained())
1538
3
      if (AttachTypeConstraint(TL, Param, D.getEllipsisLoc()))
1539
1
        Invalid = true;
1540
1541
203k
  if (Invalid)
1542
72
    Param->setInvalidDecl();
1543
1544
203k
  if (Param->isParameterPack())
1545
12.9k
    if (auto *LSI = getEnclosingLambda())
1546
12
      LSI->LocalPacks.push_back(Param);
1547
1548
203k
  if (ParamName) {
1549
156k
    maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1550
156k
                                         ParamName);
1551
1552
    // Add the template parameter into the current scope.
1553
156k
    S->AddDecl(Param);
1554
156k
    IdResolver.AddDecl(Param);
1555
156k
  }
1556
1557
  // C++0x [temp.param]p9:
1558
  //   A default template-argument may be specified for any kind of
1559
  //   template-parameter that is not a template parameter pack.
1560
203k
  if (Default && 
IsParameterPack54.1k
) {
1561
1
    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1562
1
    Default = nullptr;
1563
1
  }
1564
1565
  // Check the well-formedness of the default template argument, if provided.
1566
203k
  if (Default) {
1567
    // Check for unexpanded parameter packs.
1568
54.1k
    if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1569
1
      return Param;
1570
1571
54.1k
    TemplateArgument Converted;
1572
54.1k
    ExprResult DefaultRes =
1573
54.1k
        CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1574
54.1k
    if (DefaultRes.isInvalid()) {
1575
2
      Param->setInvalidDecl();
1576
2
      return Param;
1577
2
    }
1578
54.1k
    Default = DefaultRes.get();
1579
1580
54.1k
    Param->setDefaultArgument(Default);
1581
54.1k
  }
1582
1583
203k
  return Param;
1584
203k
}
1585
1586
/// ActOnTemplateTemplateParameter - Called when a C++ template template
1587
/// parameter (e.g. T in template <template \<typename> class T> class array)
1588
/// has been parsed. S is the current scope.
1589
NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1590
                                           SourceLocation TmpLoc,
1591
                                           TemplateParameterList *Params,
1592
                                           SourceLocation EllipsisLoc,
1593
                                           IdentifierInfo *Name,
1594
                                           SourceLocation NameLoc,
1595
                                           unsigned Depth,
1596
                                           unsigned Position,
1597
                                           SourceLocation EqualLoc,
1598
8.71k
                                           ParsedTemplateArgument Default) {
1599
8.71k
  assert(S->isTemplateParamScope() &&
1600
8.71k
         "Template template parameter not in template parameter scope!");
1601
1602
  // Construct the parameter object.
1603
8.71k
  bool IsParameterPack = EllipsisLoc.isValid();
1604
8.71k
  TemplateTemplateParmDecl *Param =
1605
8.71k
    TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1606
8.71k
                                     NameLoc.isInvalid()? 
TmpLoc0
: NameLoc,
1607
8.71k
                                     Depth, Position, IsParameterPack,
1608
8.71k
                                     Name, Params);
1609
8.71k
  Param->setAccess(AS_public);
1610
1611
8.71k
  if (Param->isParameterPack())
1612
106
    if (auto *LSI = getEnclosingLambda())
1613
10
      LSI->LocalPacks.push_back(Param);
1614
1615
  // If the template template parameter has a name, then link the identifier
1616
  // into the scope and lookup mechanisms.
1617
8.71k
  if (Name) {
1618
6.67k
    maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1619
1620
6.67k
    S->AddDecl(Param);
1621
6.67k
    IdResolver.AddDecl(Param);
1622
6.67k
  }
1623
1624
8.71k
  if (Params->size() == 0) {
1625
1
    Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1626
1
    << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1627
1
    Param->setInvalidDecl();
1628
1
  }
1629
1630
  // C++0x [temp.param]p9:
1631
  //   A default template-argument may be specified for any kind of
1632
  //   template-parameter that is not a template parameter pack.
1633
8.71k
  if (IsParameterPack && 
!Default.isInvalid()106
) {
1634
1
    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1635
1
    Default = ParsedTemplateArgument();
1636
1
  }
1637
1638
8.71k
  if (!Default.isInvalid()) {
1639
    // Check only that we have a template template argument. We don't want to
1640
    // try to check well-formedness now, because our template template parameter
1641
    // might have dependent types in its template parameters, which we wouldn't
1642
    // be able to match now.
1643
    //
1644
    // If none of the template template parameter's template arguments mention
1645
    // other template parameters, we could actually perform more checking here.
1646
    // However, it isn't worth doing.
1647
174
    TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1648
174
    if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1649
0
      Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1650
0
        << DefaultArg.getSourceRange();
1651
0
      return Param;
1652
0
    }
1653
1654
    // Check for unexpanded parameter packs.
1655
174
    if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1656
174
                                        DefaultArg.getArgument().getAsTemplate(),
1657
174
                                        UPPC_DefaultArgument))
1658
1
      return Param;
1659
1660
173
    Param->setDefaultArgument(Context, DefaultArg);
1661
173
  }
1662
1663
8.70k
  return Param;
1664
8.71k
}
1665
1666
/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1667
/// constrained by RequiresClause, that contains the template parameters in
1668
/// Params.
1669
TemplateParameterList *
1670
Sema::ActOnTemplateParameterList(unsigned Depth,
1671
                                 SourceLocation ExportLoc,
1672
                                 SourceLocation TemplateLoc,
1673
                                 SourceLocation LAngleLoc,
1674
                                 ArrayRef<NamedDecl *> Params,
1675
                                 SourceLocation RAngleLoc,
1676
1.18M
                                 Expr *RequiresClause) {
1677
1.18M
  if (ExportLoc.isValid())
1678
3
    Diag(ExportLoc, diag::warn_template_export_unsupported);
1679
1680
1.18M
  return TemplateParameterList::Create(
1681
1.18M
      Context, TemplateLoc, LAngleLoc,
1682
1.18M
      llvm::makeArrayRef(Params.data(), Params.size()),
1683
1.18M
      RAngleLoc, RequiresClause);
1684
1.18M
}
1685
1686
static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1687
427k
                                   const CXXScopeSpec &SS) {
1688
427k
  if (SS.isSet())
1689
471
    T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1690
427k
}
1691
1692
DeclResult Sema::CheckClassTemplate(
1693
    Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1694
    CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1695
    const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1696
    AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1697
    SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1698
231k
    TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1699
231k
  assert(TemplateParams && TemplateParams->size() > 0 &&
1700
231k
         "No template parameters");
1701
231k
  assert(TUK != TUK_Reference && "Can only declare or define class templates");
1702
231k
  bool Invalid = false;
1703
1704
  // Check that we can declare a template here.
1705
231k
  if (CheckTemplateDeclScope(S, TemplateParams))
1706
7
    return true;
1707
1708
231k
  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1709
231k
  assert(Kind != TTK_Enum && "can't build template of enumerated type");
1710
1711
  // There is no such thing as an unnamed class template.
1712
231k
  if (!Name) {
1713
0
    Diag(KWLoc, diag::err_template_unnamed_class);
1714
0
    return true;
1715
0
  }
1716
1717
  // Find any previous declaration with this name. For a friend with no
1718
  // scope explicitly specified, we only look for tag declarations (per
1719
  // C++11 [basic.lookup.elab]p2).
1720
231k
  DeclContext *SemanticContext;
1721
231k
  LookupResult Previous(*this, Name, NameLoc,
1722
231k
                        (SS.isEmpty() && 
TUK == TUK_Friend231k
)
1723
225k
                          ? 
LookupTagName6.17k
: LookupOrdinaryName,
1724
231k
                        forRedeclarationInCurContext());
1725
231k
  if (SS.isNotEmpty() && 
!SS.isInvalid()117
) {
1726
117
    SemanticContext = computeDeclContext(SS, true);
1727
117
    if (!SemanticContext) {
1728
      // FIXME: Horrible, horrible hack! We can't currently represent this
1729
      // in the AST, and historically we have just ignored such friend
1730
      // class templates, so don't complain here.
1731
2
      Diag(NameLoc, TUK == TUK_Friend
1732
1
                        ? diag::warn_template_qualified_friend_ignored
1733
1
                        : diag::err_template_qualified_declarator_no_match)
1734
2
          << SS.getScopeRep() << SS.getRange();
1735
2
      return TUK != TUK_Friend;
1736
2
    }
1737
1738
115
    if (RequireCompleteDeclContext(SS, SemanticContext))
1739
0
      return true;
1740
1741
    // If we're adding a template to a dependent context, we may need to
1742
    // rebuilding some of the types used within the template parameter list,
1743
    // now that we know what the current instantiation is.
1744
115
    if (SemanticContext->isDependentContext()) {
1745
23
      ContextRAII SavedContext(*this, SemanticContext);
1746
23
      if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1747
0
        Invalid = true;
1748
92
    } else if (TUK != TUK_Friend && 
TUK != TUK_Reference77
)
1749
77
      diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1750
1751
115
    LookupQualifiedName(Previous, SemanticContext);
1752
231k
  } else {
1753
231k
    SemanticContext = CurContext;
1754
1755
    // C++14 [class.mem]p14:
1756
    //   If T is the name of a class, then each of the following shall have a
1757
    //   name different from T:
1758
    //    -- every member template of class T
1759
231k
    if (TUK != TUK_Friend &&
1760
225k
        DiagnoseClassNameShadow(SemanticContext,
1761
225k
                                DeclarationNameInfo(Name, NameLoc)))
1762
6
      return true;
1763
1764
231k
    LookupName(Previous, S);
1765
231k
  }
1766
1767
231k
  if (Previous.isAmbiguous())
1768
0
    return true;
1769
1770
231k
  NamedDecl *PrevDecl = nullptr;
1771
231k
  if (Previous.begin() != Previous.end())
1772
16.0k
    PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1773
1774
231k
  if (PrevDecl && 
PrevDecl->isTemplateParameter()16.0k
) {
1775
    // Maybe we will complain about the shadowed template parameter.
1776
7
    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1777
    // Just pretend that we didn't see the previous declaration.
1778
7
    PrevDecl = nullptr;
1779
7
  }
1780
1781
  // If there is a previous declaration with the same name, check
1782
  // whether this is a valid redeclaration.
1783
231k
  ClassTemplateDecl *PrevClassTemplate =
1784
231k
      dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1785
1786
  // We may have found the injected-class-name of a class template,
1787
  // class template partial specialization, or class template specialization.
1788
  // In these cases, grab the template that is being defined or specialized.
1789
231k
  if (!PrevClassTemplate && 
PrevDecl217k
&&
isa<CXXRecordDecl>(PrevDecl)1.69k
&&
1790
1.68k
      cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1791
1.67k
    PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1792
1.67k
    PrevClassTemplate
1793
1.67k
      = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1794
1.67k
    if (!PrevClassTemplate && 
isa<ClassTemplateSpecializationDecl>(PrevDecl)24
) {
1795
24
      PrevClassTemplate
1796
24
        = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1797
24
            ->getSpecializedTemplate();
1798
24
    }
1799
1.67k
  }
1800
1801
231k
  if (TUK == TUK_Friend) {
1802
    // C++ [namespace.memdef]p3:
1803
    //   [...] When looking for a prior declaration of a class or a function
1804
    //   declared as a friend, and when the name of the friend class or
1805
    //   function is neither a qualified name nor a template-id, scopes outside
1806
    //   the innermost enclosing namespace scope are not considered.
1807
6.19k
    if (!SS.isSet()) {
1808
6.17k
      DeclContext *OutermostContext = CurContext;
1809
12.3k
      while (!OutermostContext->isFileContext())
1810
6.20k
        OutermostContext = OutermostContext->getLookupParent();
1811
1812
6.17k
      if (PrevDecl &&
1813
5.23k
          (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1814
5.23k
           
OutermostContext->Encloses(PrevDecl->getDeclContext())12
)) {
1815
5.23k
        SemanticContext = PrevDecl->getDeclContext();
1816
944
      } else {
1817
        // Declarations in outer scopes don't matter. However, the outermost
1818
        // context we computed is the semantic context for our new
1819
        // declaration.
1820
944
        PrevDecl = PrevClassTemplate = nullptr;
1821
944
        SemanticContext = OutermostContext;
1822
1823
        // Check that the chosen semantic context doesn't already contain a
1824
        // declaration of this name as a non-tag type.
1825
944
        Previous.clear(LookupOrdinaryName);
1826
944
        DeclContext *LookupContext = SemanticContext;
1827
944
        while (LookupContext->isTransparentContext())
1828
0
          LookupContext = LookupContext->getLookupParent();
1829
944
        LookupQualifiedName(Previous, LookupContext);
1830
1831
944
        if (Previous.isAmbiguous())
1832
0
          return true;
1833
1834
944
        if (Previous.begin() != Previous.end())
1835
1
          PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1836
944
      }
1837
6.17k
    }
1838
225k
  } else if (PrevDecl &&
1839
10.7k
             !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1840
10.7k
                            S, SS.isValid()))
1841
49
    PrevDecl = PrevClassTemplate = nullptr;
1842
1843
231k
  if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1844
3
          PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1845
3
    if (SS.isEmpty() &&
1846
3
        !(PrevClassTemplate &&
1847
3
          PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1848
2
              SemanticContext->getRedeclContext()))) {
1849
2
      Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1850
2
      Diag(Shadow->getTargetDecl()->getLocation(),
1851
2
           diag::note_using_decl_target);
1852
2
      Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1853
      // Recover by ignoring the old declaration.
1854
2
      PrevDecl = PrevClassTemplate = nullptr;
1855
2
    }
1856
3
  }
1857
1858
231k
  if (PrevClassTemplate) {
1859
    // Ensure that the template parameter lists are compatible. Skip this check
1860
    // for a friend in a dependent context: the template parameter list itself
1861
    // could be dependent.
1862
15.9k
    if (!(TUK == TUK_Friend && 
CurContext->isDependentContext()5.24k
) &&
1863
10.8k
        !TemplateParameterListsAreEqual(TemplateParams,
1864
10.8k
                                   PrevClassTemplate->getTemplateParameters(),
1865
10.8k
                                        /*Complain=*/true,
1866
10.8k
                                        TPL_TemplateMatch))
1867
34
      return true;
1868
1869
    // C++ [temp.class]p4:
1870
    //   In a redeclaration, partial specialization, explicit
1871
    //   specialization or explicit instantiation of a class template,
1872
    //   the class-key shall agree in kind with the original class
1873
    //   template declaration (7.1.5.3).
1874
15.9k
    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1875
15.9k
    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1876
0
                                      TUK == TUK_Definition,  KWLoc, Name)) {
1877
0
      Diag(KWLoc, diag::err_use_with_wrong_tag)
1878
0
        << Name
1879
0
        << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1880
0
      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1881
0
      Kind = PrevRecordDecl->getTagKind();
1882
0
    }
1883
1884
    // Check for redefinition of this class template.
1885
15.9k
    if (TUK == TUK_Definition) {
1886
10.0k
      if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1887
        // If we have a prior definition that is not visible, treat this as
1888
        // simply making that previous definition visible.
1889
112
        NamedDecl *Hidden = nullptr;
1890
112
        if (SkipBody && 
!hasVisibleDefinition(Def, &Hidden)111
) {
1891
110
          SkipBody->ShouldSkip = true;
1892
110
          SkipBody->Previous = Def;
1893
110
          auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1894
110
          assert(Tmpl && "original definition of a class template is not a "
1895
110
                         "class template?");
1896
110
          makeMergedDefinitionVisible(Hidden);
1897
110
          makeMergedDefinitionVisible(Tmpl);
1898
2
        } else {
1899
2
          Diag(NameLoc, diag::err_redefinition) << Name;
1900
2
          Diag(Def->getLocation(), diag::note_previous_definition);
1901
          // FIXME: Would it make sense to try to "forget" the previous
1902
          // definition, as part of error recovery?
1903
2
          return true;
1904
2
        }
1905
215k
      }
1906
10.0k
    }
1907
215k
  } else if (PrevDecl) {
1908
    // C++ [temp]p5:
1909
    //   A class template shall not have the same name as any other
1910
    //   template, class, function, object, enumeration, enumerator,
1911
    //   namespace, or type in the same scope (3.3), except as specified
1912
    //   in (14.5.4).
1913
6
    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1914
6
    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1915
6
    return true;
1916
6
  }
1917
1918
  // Check the template parameter list of this declaration, possibly
1919
  // merging in the template parameter list from the previous class
1920
  // template declaration. Skip this check for a friend in a dependent
1921
  // context, because the template parameter list might be dependent.
1922
231k
  if (!(TUK == TUK_Friend && 
CurContext->isDependentContext()6.19k
) &&
1923
225k
      CheckTemplateParameterList(
1924
225k
          TemplateParams,
1925
225k
          PrevClassTemplate
1926
10.7k
              ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1927
215k
              : nullptr,
1928
225k
          (SS.isSet() && 
SemanticContext103
&&
SemanticContext->isRecord()103
&&
1929
89
           SemanticContext->isDependentContext())
1930
20
              ? TPC_ClassTemplateMember
1931
225k
              : TUK == TUK_Friend ? 
TPC_FriendClassTemplate148
:
TPC_ClassTemplate225k
,
1932
225k
          SkipBody))
1933
20
    Invalid = true;
1934
1935
231k
  if (SS.isSet()) {
1936
    // If the name of the template was qualified, we must be defining the
1937
    // template out-of-line.
1938
112
    if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1939
1
      Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1940
2
                                      : diag::err_member_decl_does_not_match)
1941
3
        << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1942
3
      Invalid = true;
1943
3
    }
1944
112
  }
1945
1946
  // If this is a templated friend in a dependent context we should not put it
1947
  // on the redecl chain. In some cases, the templated friend can be the most
1948
  // recent declaration tricking the template instantiator to make substitutions
1949
  // there.
1950
  // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1951
231k
  bool ShouldAddRedecl
1952
231k
    = !(TUK == TUK_Friend && 
CurContext->isDependentContext()6.19k
);
1953
1954
231k
  CXXRecordDecl *NewClass =
1955
231k
    CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1956
231k
                          PrevClassTemplate && 
ShouldAddRedecl15.9k
?
1957
221k
                            
PrevClassTemplate->getTemplatedDecl()10.7k
: nullptr,
1958
231k
                          /*DelayTypeCreation=*/true);
1959
231k
  SetNestedNameSpecifier(*this, NewClass, SS);
1960
231k
  if (NumOuterTemplateParamLists > 0)
1961
54
    NewClass->setTemplateParameterListsInfo(
1962
54
        Context, llvm::makeArrayRef(OuterTemplateParamLists,
1963
54
                                    NumOuterTemplateParamLists));
1964
1965
  // Add alignment attributes if necessary; these attributes are checked when
1966
  // the ASTContext lays out the structure.
1967
231k
  if (TUK == TUK_Definition && 
(186k
!SkipBody186k
||
!SkipBody->ShouldSkip186k
)) {
1968
186k
    AddAlignmentAttributesForRecord(NewClass);
1969
186k
    AddMsStructLayoutForRecord(NewClass);
1970
186k
  }
1971
1972
231k
  ClassTemplateDecl *NewTemplate
1973
231k
    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1974
231k
                                DeclarationName(Name), TemplateParams,
1975
231k
                                NewClass);
1976
1977
231k
  if (ShouldAddRedecl)
1978
225k
    NewTemplate->setPreviousDecl(PrevClassTemplate);
1979
1980
231k
  NewClass->setDescribedClassTemplate(NewTemplate);
1981
1982
231k
  if (ModulePrivateLoc.isValid())
1983
3
    NewTemplate->setModulePrivate();
1984
1985
  // Build the type for the class template declaration now.
1986
231k
  QualType T = NewTemplate->getInjectedClassNameSpecialization();
1987
231k
  T = Context.getInjectedClassNameType(NewClass, T);
1988
231k
  assert(T->isDependentType() && "Class template type is not dependent?");
1989
231k
  (void)T;
1990
1991
  // If we are providing an explicit specialization of a member that is a
1992
  // class template, make a note of that.
1993
231k
  if (PrevClassTemplate &&
1994
15.9k
      PrevClassTemplate->getInstantiatedFromMemberTemplate())
1995
30
    PrevClassTemplate->setMemberSpecialization();
1996
1997
  // Set the access specifier.
1998
231k
  if (!Invalid && 
TUK != TUK_Friend231k
&&
NewTemplate->getDeclContext()->isRecord()225k
)
1999
6.81k
    SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2000
2001
  // Set the lexical context of these templates
2002
231k
  NewClass->setLexicalDeclContext(CurContext);
2003
231k
  NewTemplate->setLexicalDeclContext(CurContext);
2004
2005
231k
  if (TUK == TUK_Definition && 
(186k
!SkipBody186k
||
!SkipBody->ShouldSkip186k
))
2006
186k
    NewClass->startDefinition();
2007
2008
231k
  ProcessDeclAttributeList(S, NewClass, Attr);
2009
2010
231k
  if (PrevClassTemplate)
2011
15.9k
    mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2012
2013
231k
  AddPushedVisibilityAttribute(NewClass);
2014
231k
  inferGslOwnerPointerAttribute(NewClass);
2015
2016
231k
  if (TUK != TUK_Friend) {
2017
    // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2018
225k
    Scope *Outer = S;
2019
451k
    while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2020
225k
      Outer = Outer->getParent();
2021
225k
    PushOnScopeChains(NewTemplate, Outer);
2022
6.19k
  } else {
2023
6.19k
    if (PrevClassTemplate && 
PrevClassTemplate->getAccess() != AS_none5.24k
) {
2024
19
      NewTemplate->setAccess(PrevClassTemplate->getAccess());
2025
19
      NewClass->setAccess(PrevClassTemplate->getAccess());
2026
19
    }
2027
2028
6.19k
    NewTemplate->setObjectOfFriendDecl();
2029
2030
    // Friend templates are visible in fairly strange ways.
2031
6.19k
    if (!CurContext->isDependentContext()) {
2032
148
      DeclContext *DC = SemanticContext->getRedeclContext();
2033
148
      DC->makeDeclVisibleInContext(NewTemplate);
2034
148
      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2035
141
        PushOnScopeChains(NewTemplate, EnclosingScope,
2036
141
                          /* AddToContext = */ false);
2037
148
    }
2038
2039
6.19k
    FriendDecl *Friend = FriendDecl::Create(
2040
6.19k
        Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2041
6.19k
    Friend->setAccess(AS_public);
2042
6.19k
    CurContext->addDecl(Friend);
2043
6.19k
  }
2044
2045
231k
  if (PrevClassTemplate)
2046
15.9k
    CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
2047
2048
231k
  if (Invalid) {
2049
23
    NewTemplate->setInvalidDecl();
2050
23
    NewClass->setInvalidDecl();
2051
23
  }
2052
2053
231k
  ActOnDocumentableDecl(NewTemplate);
2054
2055
231k
  if (SkipBody && 
SkipBody->ShouldSkip225k
)
2056
110
    return SkipBody->Previous;
2057
2058
231k
  return NewTemplate;
2059
231k
}
2060
2061
namespace {
2062
/// Tree transform to "extract" a transformed type from a class template's
2063
/// constructor to a deduction guide.
2064
class ExtractTypeForDeductionGuide
2065
  : public TreeTransform<ExtractTypeForDeductionGuide> {
2066
  llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2067
2068
public:
2069
  typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
2070
  ExtractTypeForDeductionGuide(
2071
      Sema &SemaRef,
2072
      llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2073
2.21k
      : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2074
2075
2.21k
  TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2076
2077
13.0k
  QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2078
13.0k
    ASTContext &Context = SemaRef.getASTContext();
2079
13.0k
    TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2080
13.0k
    TypeLocBuilder InnerTLB;
2081
13.0k
    QualType Transformed =
2082
13.0k
        TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2083
13.0k
    TypeSourceInfo *TSI =
2084
13.0k
        TransformType(InnerTLB.getTypeSourceInfo(Context, Transformed));
2085
2086
13.0k
    TypedefNameDecl *Decl = nullptr;
2087
2088
13.0k
    if (isa<TypeAliasDecl>(OrigDecl))
2089
3
      Decl = TypeAliasDecl::Create(
2090
3
          Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2091
3
          OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2092
13.0k
    else {
2093
13.0k
      assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2094
13.0k
      Decl = TypedefDecl::Create(
2095
13.0k
          Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2096
13.0k
          OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2097
13.0k
    }
2098
2099
13.0k
    MaterializedTypedefs.push_back(Decl);
2100
2101
13.0k
    QualType TDTy = Context.getTypedefType(Decl);
2102
13.0k
    TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2103
13.0k
    TypedefTL.setNameLoc(TL.getNameLoc());
2104
2105
13.0k
    return TDTy;
2106
13.0k
  }
2107
};
2108
2109
/// Transform to convert portions of a constructor declaration into the
2110
/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2111
struct ConvertConstructorToDeductionGuideTransform {
2112
  ConvertConstructorToDeductionGuideTransform(Sema &S,
2113
                                              ClassTemplateDecl *Template)
2114
972
      : SemaRef(S), Template(Template) {}
2115
2116
  Sema &SemaRef;
2117
  ClassTemplateDecl *Template;
2118
2119
  DeclContext *DC = Template->getDeclContext();
2120
  CXXRecordDecl *Primary = Template->getTemplatedDecl();
2121
  DeclarationName DeductionGuideName =
2122
      SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
2123
2124
  QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2125
2126
  // Index adjustment to apply to convert depth-1 template parameters into
2127
  // depth-0 template parameters.
2128
  unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2129
2130
  /// Transform a constructor declaration into a deduction guide.
2131
  NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2132
1.18k
                                  CXXConstructorDecl *CD) {
2133
1.18k
    SmallVector<TemplateArgument, 16> SubstArgs;
2134
2135
1.18k
    LocalInstantiationScope Scope(SemaRef);
2136
2137
    // C++ [over.match.class.deduct]p1:
2138
    // -- For each constructor of the class template designated by the
2139
    //    template-name, a function template with the following properties:
2140
2141
    //    -- The template parameters are the template parameters of the class
2142
    //       template followed by the template parameters (including default
2143
    //       template arguments) of the constructor, if any.
2144
1.18k
    TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2145
1.18k
    if (FTD) {
2146
529
      TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2147
529
      SmallVector<NamedDecl *, 16> AllParams;
2148
529
      AllParams.reserve(TemplateParams->size() + InnerParams->size());
2149
529
      AllParams.insert(AllParams.begin(),
2150
529
                       TemplateParams->begin(), TemplateParams->end());
2151
529
      SubstArgs.reserve(InnerParams->size());
2152
2153
      // Later template parameters could refer to earlier ones, so build up
2154
      // a list of substituted template arguments as we go.
2155
945
      for (NamedDecl *Param : *InnerParams) {
2156
945
        MultiLevelTemplateArgumentList Args;
2157
945
        Args.setKind(TemplateSubstitutionKind::Rewrite);
2158
945
        Args.addOuterTemplateArguments(SubstArgs);
2159
945
        Args.addOuterRetainedLevel();
2160
945
        NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2161
945
        if (!NewParam)
2162
0
          return nullptr;
2163
945
        AllParams.push_back(NewParam);
2164
945
        SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2165
945
            SemaRef.Context.getInjectedTemplateArg(NewParam)));
2166
945
      }
2167
529
      TemplateParams = TemplateParameterList::Create(
2168
529
          SemaRef.Context, InnerParams->getTemplateLoc(),
2169
529
          InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2170
529
          /*FIXME: RequiresClause*/ nullptr);
2171
529
    }
2172
2173
    // If we built a new template-parameter-list, track that we need to
2174
    // substitute references to the old parameters into references to the
2175
    // new ones.
2176
1.18k
    MultiLevelTemplateArgumentList Args;
2177
1.18k
    Args.setKind(TemplateSubstitutionKind::Rewrite);
2178
1.18k
    if (FTD) {
2179
529
      Args.addOuterTemplateArguments(SubstArgs);
2180
529
      Args.addOuterRetainedLevel();
2181
529
    }
2182
2183
1.18k
    FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
2184
1.18k
                                   .getAsAdjusted<FunctionProtoTypeLoc>();
2185
1.18k
    assert(FPTL && "no prototype for constructor declaration");
2186
2187
    // Transform the type of the function, adjusting the return type and
2188
    // replacing references to the old parameters with references to the
2189
    // new ones.
2190
1.18k
    TypeLocBuilder TLB;
2191
1.18k
    SmallVector<ParmVarDecl*, 8> Params;
2192
1.18k
    SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2193
1.18k
    QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2194
1.18k
                                                  MaterializedTypedefs);
2195
1.18k
    if (NewType.isNull())
2196
0
      return nullptr;
2197
1.18k
    TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2198
2199
1.18k
    return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
2200
1.18k
                               NewTInfo, CD->getBeginLoc(), CD->getLocation(),
2201
1.18k
                               CD->getEndLoc(), MaterializedTypedefs);
2202
1.18k
  }
2203
2204
  /// Build a deduction guide with the specified parameter types.
2205
297
  NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2206
297
    SourceLocation Loc = Template->getLocation();
2207
2208
    // Build the requested type.
2209
297
    FunctionProtoType::ExtProtoInfo EPI;
2210
297
    EPI.HasTrailingReturn = true;
2211
297
    QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2212
297
                                                DeductionGuideName, EPI);
2213
297
    TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2214
2215
297
    FunctionProtoTypeLoc FPTL =
2216
297
        TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
2217
2218
    // Build the parameters, needed during deduction / substitution.
2219
297
    SmallVector<ParmVarDecl*, 4> Params;
2220
244
    for (auto T : ParamTypes) {
2221
244
      ParmVarDecl *NewParam = ParmVarDecl::Create(
2222
244
          SemaRef.Context, DC, Loc, Loc, nullptr, T,
2223
244
          SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
2224
244
      NewParam->setScopeInfo(0, Params.size());
2225
244
      FPTL.setParam(Params.size(), NewParam);
2226
244
      Params.push_back(NewParam);
2227
244
    }
2228
2229
297
    return buildDeductionGuide(Template->getTemplateParameters(),
2230
297
                               ExplicitSpecifier(), TSI, Loc, Loc, Loc);
2231
297
  }
2232
2233
private:
2234
  /// Transform a constructor template parameter into a deduction guide template
2235
  /// parameter, rebuilding any internal references to earlier parameters and
2236
  /// renumbering as we go.
2237
  NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2238
945
                                        MultiLevelTemplateArgumentList &Args) {
2239
945
    if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
2240
      // TemplateTypeParmDecl's index cannot be changed after creation, so
2241
      // substitute it directly.
2242
645
      auto *NewTTP = TemplateTypeParmDecl::Create(
2243
645
          SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
2244
645
          /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
2245
645
          TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2246
645
          TTP->isParameterPack(), TTP->hasTypeConstraint(),
2247
645
          TTP->isExpandedParameterPack() ?
2248
645
          
llvm::Optional<unsigned>(TTP->getNumExpansionParameters())0
: None);
2249
645
      if (const auto *TC = TTP->getTypeConstraint()) {
2250
2
        TemplateArgumentListInfo TransformedArgs;
2251
2
        const auto *ArgsAsWritten = TC->getTemplateArgsAsWritten();
2252
2
        if (!ArgsAsWritten ||
2253
2
            SemaRef.Subst(ArgsAsWritten->getTemplateArgs(),
2254
2
                          ArgsAsWritten->NumTemplateArgs, TransformedArgs,
2255
2
                          Args))
2256
0
          SemaRef.AttachTypeConstraint(
2257
0
              TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2258
0
              TC->getNamedConcept(), ArgsAsWritten ? &TransformedArgs : nullptr,
2259
0
              NewTTP,
2260
0
              NewTTP->isParameterPack()
2261
0
                 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2262
0
                     ->getEllipsisLoc()
2263
0
                 : SourceLocation());
2264
2
      }
2265
645
      if (TTP->hasDefaultArgument()) {
2266
61
        TypeSourceInfo *InstantiatedDefaultArg =
2267
61
            SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2268
61
                              TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2269
61
        if (InstantiatedDefaultArg)
2270
61
          NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2271
61
      }
2272
645
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2273
645
                                                           NewTTP);
2274
645
      return NewTTP;
2275
645
    }
2276
2277
300
    if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2278
4
      return transformTemplateParameterImpl(TTP, Args);
2279
2280
296
    return transformTemplateParameterImpl(
2281
296
        cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2282
296
  }
2283
  template<typename TemplateParmDecl>
2284
  TemplateParmDecl *
2285
  transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2286
300
                                 MultiLevelTemplateArgumentList &Args) {
2287
    // Ask the template instantiator to do the heavy lifting for us, then adjust
2288
    // the index of the parameter once it's done.
2289
300
    auto *NewParam =
2290
300
        cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2291
300
    assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2292
300
    NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2293
300
    return NewParam;
2294
300
  }
SemaTemplate.cpp:clang::TemplateTemplateParmDecl* (anonymous namespace)::ConvertConstructorToDeductionGuideTransform::transformTemplateParameterImpl<clang::TemplateTemplateParmDecl>(clang::TemplateTemplateParmDecl*, clang::MultiLevelTemplateArgumentList&)
Line
Count
Source
2286
4
                                 MultiLevelTemplateArgumentList &Args) {
2287
    // Ask the template instantiator to do the heavy lifting for us, then adjust
2288
    // the index of the parameter once it's done.
2289
4
    auto *NewParam =
2290
4
        cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2291
4
    assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2292
4
    NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2293
4
    return NewParam;
2294
4
  }
SemaTemplate.cpp:clang::NonTypeTemplateParmDecl* (anonymous namespace)::ConvertConstructorToDeductionGuideTransform::transformTemplateParameterImpl<clang::NonTypeTemplateParmDecl>(clang::NonTypeTemplateParmDecl*, clang::MultiLevelTemplateArgumentList&)
Line
Count
Source
2286
296
                                 MultiLevelTemplateArgumentList &Args) {
2287
    // Ask the template instantiator to do the heavy lifting for us, then adjust
2288
    // the index of the parameter once it's done.
2289
296
    auto *NewParam =
2290
296
        cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2291
296
    assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2292
296
    NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2293
296
    return NewParam;
2294
296
  }
2295
2296
  QualType transformFunctionProtoType(
2297
      TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
2298
      SmallVectorImpl<ParmVarDecl *> &Params,
2299
      MultiLevelTemplateArgumentList &Args,
2300
1.18k
      SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2301
1.18k
    SmallVector<QualType, 4> ParamTypes;
2302
1.18k
    const FunctionProtoType *T = TL.getTypePtr();
2303
2304
    //    -- The types of the function parameters are those of the constructor.
2305
2.21k
    for (auto *OldParam : TL.getParams()) {
2306
2.21k
      ParmVarDecl *NewParam =
2307
2.21k
          transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2308
2.21k
      if (!NewParam)
2309
0
        return QualType();
2310
2.21k
      ParamTypes.push_back(NewParam->getType());
2311
2.21k
      Params.push_back(NewParam);
2312
2.21k
    }
2313
2314
    //    -- The return type is the class template specialization designated by
2315
    //       the template-name and template arguments corresponding to the
2316
    //       template parameters obtained from the class template.
2317
    //
2318
    // We use the injected-class-name type of the primary template instead.
2319
    // This has the convenient property that it is different from any type that
2320
    // the user can write in a deduction-guide (because they cannot enter the
2321
    // context of the template), so implicit deduction guides can never collide
2322
    // with explicit ones.
2323
1.18k
    QualType ReturnType = DeducedType;
2324
1.18k
    TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2325
2326
    // Resolving a wording defect, we also inherit the variadicness of the
2327
    // constructor.
2328
1.18k
    FunctionProtoType::ExtProtoInfo EPI;
2329
1.18k
    EPI.Variadic = T->isVariadic();
2330
1.18k
    EPI.HasTrailingReturn = true;
2331
2332
1.18k
    QualType Result = SemaRef.BuildFunctionType(
2333
1.18k
        ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2334
1.18k
    if (Result.isNull())
2335
0
      return QualType();
2336
2337
1.18k
    FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2338
1.18k
    NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2339
1.18k
    NewTL.setLParenLoc(TL.getLParenLoc());
2340
1.18k
    NewTL.setRParenLoc(TL.getRParenLoc());
2341
1.18k
    NewTL.setExceptionSpecRange(SourceRange());
2342
1.18k
    NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2343
3.40k
    for (unsigned I = 0, E = NewTL.getNumParams(); I != E; 
++I2.21k
)
2344
2.21k
      NewTL.setParam(I, Params[I]);
2345
2346
1.18k
    return Result;
2347
1.18k
  }
2348
2349
  ParmVarDecl *transformFunctionTypeParam(
2350
      ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
2351
2.21k
      llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2352
2.21k
    TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2353
2.21k
    TypeSourceInfo *NewDI;
2354
2.21k
    if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2355
      // Expand out the one and only element in each inner pack.
2356
69
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2357
69
      NewDI =
2358
69
          SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2359
69
                            OldParam->getLocation(), OldParam->getDeclName());
2360
69
      if (!NewDI) 
return nullptr0
;
2361
69
      NewDI =
2362
69
          SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2363
69
                                     PackTL.getTypePtr()->getNumExpansions());
2364
69
    } else
2365
2.15k
      NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2366
2.15k
                                OldParam->getDeclName());
2367
2.21k
    if (!NewDI)
2368
0
      return nullptr;
2369
2370
    // Extract the type. This (for instance) replaces references to typedef
2371
    // members of the current instantiations with the definitions of those
2372
    // typedefs, avoiding triggering instantiation of the deduced type during
2373
    // deduction.
2374
2.21k
    NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2375
2.21k
                .transform(NewDI);
2376
2377
    // Resolving a wording defect, we also inherit default arguments from the
2378
    // constructor.
2379
2.21k
    ExprResult NewDefArg;
2380
2.21k
    if (OldParam->hasDefaultArg()) {
2381
      // We don't care what the value is (we won't use it); just create a
2382
      // placeholder to indicate there is a default argument.
2383
230
      QualType ParamTy = NewDI->getType();
2384
230
      NewDefArg = new (SemaRef.Context)
2385
230
          OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
2386
230
                          ParamTy.getNonLValueExprType(SemaRef.Context),
2387
84
                          ParamTy->isLValueReferenceType() ? VK_LValue :
2388
146
                          ParamTy->isRValueReferenceType() ? 
VK_XValue0
:
2389
146
                          VK_RValue);
2390
230
    }
2391
2392
2.21k
    ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2393
2.21k
                                                OldParam->getInnerLocStart(),
2394
2.21k
                                                OldParam->getLocation(),
2395
2.21k
                                                OldParam->getIdentifier(),
2396
2.21k
                                                NewDI->getType(),
2397
2.21k
                                                NewDI,
2398
2.21k
                                                OldParam->getStorageClass(),
2399
2.21k
                                                NewDefArg.get());
2400
2.21k
    NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2401
2.21k
                           OldParam->getFunctionScopeIndex());
2402
2.21k
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2403
2.21k
    return NewParam;
2404
2.21k
  }
2405
2406
  FunctionTemplateDecl *buildDeductionGuide(
2407
      TemplateParameterList *TemplateParams, ExplicitSpecifier ES,
2408
      TypeSourceInfo *TInfo, SourceLocation LocStart, SourceLocation Loc,
2409
      SourceLocation LocEnd,
2410
1.48k
      llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2411
1.48k
    DeclarationNameInfo Name(DeductionGuideName, Loc);
2412
1.48k
    ArrayRef<ParmVarDecl *> Params =
2413
1.48k
        TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2414
2415
    // Build the implicit deduction guide template.
2416
1.48k
    auto *Guide =
2417
1.48k
        CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2418
1.48k
                                      TInfo->getType(), TInfo, LocEnd);
2419
1.48k
    Guide->setImplicit();
2420
1.48k
    Guide->setParams(Params);
2421
2422
1.48k
    for (auto *Param : Params)
2423
2.46k
      Param->setDeclContext(Guide);
2424
1.48k
    for (auto *TD : MaterializedTypedefs)
2425
13.0k
      TD->setDeclContext(Guide);
2426
2427
1.48k
    auto *GuideTemplate = FunctionTemplateDecl::Create(
2428
1.48k
        SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2429
1.48k
    GuideTemplate->setImplicit();
2430
1.48k
    Guide->setDescribedFunctionTemplate(GuideTemplate);
2431
2432
1.48k
    if (isa<CXXRecordDecl>(DC)) {
2433
26
      Guide->setAccess(AS_public);
2434
26
      GuideTemplate->setAccess(AS_public);
2435
26
    }
2436
2437
1.48k
    DC->addDecl(GuideTemplate);
2438
1.48k
    return GuideTemplate;
2439
1.48k
  }
2440
};
2441
}
2442
2443
void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2444
976
                                          SourceLocation Loc) {
2445
976
  if (CXXRecordDecl *DefRecord =
2446
945
          cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2447
945
    TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2448
945
    Template = DescribedTemplate ? DescribedTemplate : 
Template0
;
2449
945
  }
2450
2451
976
  DeclContext *DC = Template->getDeclContext();
2452
976
  if (DC->isDependentContext())
2453
4
    return;
2454
2455
972
  ConvertConstructorToDeductionGuideTransform Transform(
2456
972
      *this, cast<ClassTemplateDecl>(Template));
2457
972
  if (!isCompleteType(Loc, Transform.DeducedType))
2458
0
    return;
2459
2460
  // Check whether we've already declared deduction guides for this template.
2461
  // FIXME: Consider storing a flag on the template to indicate this.
2462
972
  auto Existing = DC->lookup(Transform.DeductionGuideName);
2463
972
  for (auto *D : Existing)
2464
727
    if (D->isImplicit())
2465
727
      return;
2466
2467
  // In case we were expanding a pack when we attempted to declare deduction
2468
  // guides, turn off pack expansion for everything we're about to do.
2469
245
  ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2470
  // Create a template instantiation record to track the "instantiation" of
2471
  // constructors into deduction guides.
2472
  // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2473
  // this substitution process actually fail?
2474
245
  InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2475
245
  if (BuildingDeductionGuides.isInvalid())
2476
1
    return;
2477
2478
  // Convert declared constructors into deduction guide templates.
2479
  // FIXME: Skip constructors for which deduction must necessarily fail (those
2480
  // for which some class template parameter without a default argument never
2481
  // appears in a deduced context).
2482
244
  bool AddedAny = false;
2483
1.18k
  for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2484
1.18k
    D = D->getUnderlyingDecl();
2485
1.18k
    if (D->isInvalidDecl() || D->isImplicit())
2486
0
      continue;
2487
1.18k
    D = cast<NamedDecl>(D->getCanonicalDecl());
2488
2489
1.18k
    auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2490
1.18k
    auto *CD =
2491
657
        dyn_cast_or_null<CXXConstructorDecl>(FTD ? 
FTD->getTemplatedDecl()529
: D);
2492
    // Class-scope explicit specializations (MS extension) do not result in
2493
    // deduction guides.
2494
1.18k
    if (!CD || (!FTD && 
CD->isFunctionTemplateSpecialization()657
))
2495
0
      continue;
2496
2497
1.18k
    Transform.transformConstructor(FTD, CD);
2498
1.18k
    AddedAny = true;
2499
1.18k
  }
2500
2501
  // C++17 [over.match.class.deduct]
2502
  //    --  If C is not defined or does not declare any constructors, an
2503
  //    additional function template derived as above from a hypothetical
2504
  //    constructor C().
2505
244
  if (!AddedAny)
2506
53
    Transform.buildSimpleDeductionGuide(None);
2507
2508
  //    -- An additional function template derived as above from a hypothetical
2509
  //    constructor C(C), called the copy deduction candidate.
2510
244
  cast<CXXDeductionGuideDecl>(
2511
244
      cast<FunctionTemplateDecl>(
2512
244
          Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2513
244
          ->getTemplatedDecl())
2514
244
      ->setIsCopyDeductionCandidate();
2515
244
}
2516
2517
/// Diagnose the presence of a default template argument on a
2518
/// template parameter, which is ill-formed in certain contexts.
2519
///
2520
/// \returns true if the default template argument should be dropped.
2521
static bool DiagnoseDefaultTemplateArgument(Sema &S,
2522
                                            Sema::TemplateParamListContext TPC,
2523
                                            SourceLocation ParamLoc,
2524
127k
                                            SourceRange DefArgRange) {
2525
127k
  switch (TPC) {
2526
75.2k
  case Sema::TPC_ClassTemplate:
2527
75.2k
  case Sema::TPC_VarTemplate:
2528
75.2k
  case Sema::TPC_TypeAliasTemplate:
2529
75.2k
    return false;
2530
2531
51.9k
  case Sema::TPC_FunctionTemplate:
2532
51.9k
  case Sema::TPC_FriendFunctionTemplateDefinition:
2533
    // C++ [temp.param]p9:
2534
    //   A default template-argument shall not be specified in a
2535
    //   function template declaration or a function template
2536
    //   definition [...]
2537
    //   If a friend function template declaration specifies a default
2538
    //   template-argument, that declaration shall be a definition and shall be
2539
    //   the only declaration of the function template in the translation unit.
2540
    // (C++98/03 doesn't have this wording; see DR226).
2541
51.9k
    S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2542
51.9k
         diag::warn_cxx98_compat_template_parameter_default_in_function_template
2543
39
           : diag::ext_template_parameter_default_in_function_template)
2544
51.9k
      << DefArgRange;
2545
51.9k
    return false;
2546
2547
14
  case Sema::TPC_ClassTemplateMember:
2548
    // C++0x [temp.param]p9:
2549
    //   A default template-argument shall not be specified in the
2550
    //   template-parameter-lists of the definition of a member of a
2551
    //   class template that appears outside of the member's class.
2552
14
    S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2553
14
      << DefArgRange;
2554
14
    return true;
2555
2556
10
  case Sema::TPC_FriendClassTemplate:
2557
10
  case Sema::TPC_FriendFunctionTemplate:
2558
    // C++ [temp.param]p9:
2559
    //   A default template-argument shall not be specified in a
2560
    //   friend template declaration.
2561
10
    S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2562
10
      << DefArgRange;
2563
10
    return true;
2564
2565
    // FIXME: C++0x [temp.param]p9 allows default template-arguments
2566
    // for friend function templates if there is only a single
2567
    // declaration (and it is a definition). Strange!
2568
0
  }
2569
2570
0
  llvm_unreachable("Invalid TemplateParamListContext!");
2571
0
}
2572
2573
/// Check for unexpanded parameter packs within the template parameters
2574
/// of a template template parameter, recursively.
2575
static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2576
5.90k
                                             TemplateTemplateParmDecl *TTP) {
2577
  // A template template parameter which is a parameter pack is also a pack
2578
  // expansion.
2579
5.90k
  if (TTP->isParameterPack())
2580
89
    return false;
2581
2582
5.81k
  TemplateParameterList *Params = TTP->getTemplateParameters();
2583
12.5k
  for (unsigned I = 0, N = Params->size(); I != N; 
++I6.75k
) {
2584
6.75k
    NamedDecl *P = Params->getParam(I);
2585
6.75k
    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2586
6.07k
      if (!TTP->isParameterPack())
2587
1.63k
        if (const TypeConstraint *TC = TTP->getTypeConstraint())
2588
1
          if (TC->hasExplicitTemplateArgs())
2589
0
            for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2590
0
              if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2591
0
                                                    Sema::UPPC_TypeConstraint))
2592
0
                return true;
2593
6.07k
      continue;
2594
681
    }
2595
2596
681
    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2597
654
      if (!NTTP->isParameterPack() &&
2598
239
          S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2599
239
                                            NTTP->getTypeSourceInfo(),
2600
239
                                      Sema::UPPC_NonTypeTemplateParameterType))
2601
0
        return true;
2602
2603
654
      continue;
2604
654
    }
2605
2606
27
    if (TemplateTemplateParmDecl *InnerTTP
2607
27
                                        = dyn_cast<TemplateTemplateParmDecl>(P))
2608
27
      if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2609
0
        return true;
2610
27
  }
2611
2612
5.81k
  return false;
2613
5.81k
}
2614
2615
/// Checks the validity of a template parameter list, possibly
2616
/// considering the template parameter list from a previous
2617
/// declaration.
2618
///
2619
/// If an "old" template parameter list is provided, it must be
2620
/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2621
/// template parameter list.
2622
///
2623
/// \param NewParams Template parameter list for a new template
2624
/// declaration. This template parameter list will be updated with any
2625
/// default arguments that are carried through from the previous
2626
/// template parameter list.
2627
///
2628
/// \param OldParams If provided, template parameter list from a
2629
/// previous declaration of the same template. Default template
2630
/// arguments will be merged from the old template parameter list to
2631
/// the new template parameter list.
2632
///
2633
/// \param TPC Describes the context in which we are checking the given
2634
/// template parameter list.
2635
///
2636
/// \param SkipBody If we might have already made a prior merged definition
2637
/// of this template visible, the corresponding body-skipping information.
2638
/// Default argument redefinition is not an error when skipping such a body,
2639
/// because (under the ODR) we can assume the default arguments are the same
2640
/// as the prior merged definition.
2641
///
2642
/// \returns true if an error occurred, false otherwise.
2643
bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2644
                                      TemplateParameterList *OldParams,
2645
                                      TemplateParamListContext TPC,
2646
1.13M
                                      SkipBodyInfo *SkipBody) {
2647
1.13M
  bool Invalid = false;
2648
2649
  // C++ [temp.param]p10:
2650
  //   The set of default template-arguments available for use with a
2651
  //   template declaration or definition is obtained by merging the
2652
  //   default arguments from the definition (if in scope) and all
2653
  //   declarations in scope in the same way default function
2654
  //   arguments are (8.3.6).
2655
1.13M
  bool SawDefaultArgument = false;
2656
1.13M
  SourceLocation PreviousDefaultArgLoc;
2657
2658
  // Dummy initialization to avoid warnings.
2659
1.13M
  TemplateParameterList::iterator OldParam = NewParams->end();
2660
1.13M
  if (OldParams)
2661
76.0k
    OldParam = OldParams->begin();
2662
2663
1.13M
  bool RemoveDefaultArguments = false;
2664
1.13M
  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2665
1.13M
                                    NewParamEnd = NewParams->end();
2666
3.21M
       NewParam != NewParamEnd; 
++NewParam2.08M
) {
2667
    // Variables used to diagnose redundant default arguments
2668
2.08M
    bool RedundantDefaultArg = false;
2669
2.08M
    SourceLocation OldDefaultLoc;
2670
2.08M
    SourceLocation NewDefaultLoc;
2671
2672
    // Variable used to diagnose missing default arguments
2673
2.08M
    bool MissingDefaultArg = false;
2674
2675
    // Variable used to diagnose non-final parameter packs
2676
2.08M
    bool SawParameterPack = false;
2677
2678
2.08M
    if (TemplateTypeParmDecl *NewTypeParm
2679
1.90M
          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2680
      // Check the presence of a default argument here.
2681
1.90M
      if (NewTypeParm->hasDefaultArgument() &&
2682
72.8k
          DiagnoseDefaultTemplateArgument(*this, TPC,
2683
72.8k
                                          NewTypeParm->getLocation(),
2684
72.8k
               NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2685
72.8k
                                                       .getSourceRange()))
2686
22
        NewTypeParm->removeDefaultArgument();
2687
2688
      // Merge default arguments for template type parameters.
2689
1.90M
      TemplateTypeParmDecl *OldTypeParm
2690
1.78M
          = OldParams? 
cast<TemplateTypeParmDecl>(*OldParam)120k
: nullptr;
2691
1.90M
      if (NewTypeParm->isParameterPack()) {
2692
91.7k
        assert(!NewTypeParm->hasDefaultArgument() &&
2693
91.7k
               "Parameter packs can't have a default argument!");
2694
91.7k
        SawParameterPack = true;
2695
1.80M
      } else if (OldTypeParm && 
hasVisibleDefaultArgument(OldTypeParm)113k
&&
2696
8.35k
                 NewTypeParm->hasDefaultArgument() &&
2697
3
                 (!SkipBody || !SkipBody->ShouldSkip)) {
2698
1
        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2699
1
        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2700
1
        SawDefaultArgument = true;
2701
1
        RedundantDefaultArg = true;
2702
1
        PreviousDefaultArgLoc = NewDefaultLoc;
2703
1.80M
      } else if (OldTypeParm && 
OldTypeParm->hasDefaultArgument()113k
) {
2704
        // Merge the default argument from the old declaration to the
2705
        // new declaration.
2706
8.53k
        NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2707
8.53k
        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2708
1.80M
      } else if (NewTypeParm->hasDefaultArgument()) {
2709
72.8k
        SawDefaultArgument = true;
2710
72.8k
        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2711
1.72M
      } else if (SawDefaultArgument)
2712
57
        MissingDefaultArg = true;
2713
186k
    } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2714
180k
               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2715
      // Check for unexpanded parameter packs.
2716
180k
      if (!NewNonTypeParm->isParameterPack() &&
2717
171k
          DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2718
171k
                                          NewNonTypeParm->getTypeSourceInfo(),
2719
1
                                          UPPC_NonTypeTemplateParameterType)) {
2720
1
        Invalid = true;
2721
1
        continue;
2722
1
      }
2723
2724
      // Check the presence of a default argument here.
2725
180k
      if (NewNonTypeParm->hasDefaultArgument() &&
2726
54.1k
          DiagnoseDefaultTemplateArgument(*this, TPC,
2727
54.1k
                                          NewNonTypeParm->getLocation(),
2728
1
                    NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2729
1
        NewNonTypeParm->removeDefaultArgument();
2730
1
      }
2731
2732
      // Merge default arguments for non-type template parameters
2733
180k
      NonTypeTemplateParmDecl *OldNonTypeParm
2734
164k
        = OldParams? 
cast<NonTypeTemplateParmDecl>(*OldParam)15.8k
: nullptr;
2735
180k
      if (NewNonTypeParm->isParameterPack()) {
2736
9.26k
        assert(!NewNonTypeParm->hasDefaultArgument() &&
2737
9.26k
               "Parameter packs can't have a default argument!");
2738
9.26k
        if (!NewNonTypeParm->isPackExpansion())
2739
9.22k
          SawParameterPack = true;
2740
171k
      } else if (OldNonTypeParm && 
hasVisibleDefaultArgument(OldNonTypeParm)15.0k
&&
2741
749
                 NewNonTypeParm->hasDefaultArgument() &&
2742
1
                 (!SkipBody || !SkipBody->ShouldSkip)) {
2743
1
        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2744
1
        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2745
1
        SawDefaultArgument = true;
2746
1
        RedundantDefaultArg = true;
2747
1
        PreviousDefaultArgLoc = NewDefaultLoc;
2748
171k
      } else if (OldNonTypeParm && 
OldNonTypeParm->hasDefaultArgument()15.0k
) {
2749
        // Merge the default argument from the old declaration to the
2750
        // new declaration.
2751
775
        NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2752
775
        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2753
170k
      } else if (NewNonTypeParm->hasDefaultArgument()) {
2754
54.1k
        SawDefaultArgument = true;
2755
54.1k
        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2756
116k
      } else if (SawDefaultArgument)
2757
5
        MissingDefaultArg = true;
2758
5.88k
    } else {
2759
5.88k
      TemplateTemplateParmDecl *NewTemplateParm
2760
5.88k
        = cast<TemplateTemplateParmDecl>(*NewParam);
2761
2762
      // Check for unexpanded parameter packs, recursively.
2763
5.88k
      if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2764
0
        Invalid = true;
2765
0
        continue;
2766
0
      }
2767
2768
      // Check the presence of a default argument here.
2769
5.88k
      if (NewTemplateParm->hasDefaultArgument() &&
2770
166
          DiagnoseDefaultTemplateArgument(*this, TPC,
2771
166
                                          NewTemplateParm->getLocation(),
2772
166
                     NewTemplateParm->getDefaultArgument().getSourceRange()))
2773
1
        NewTemplateParm->removeDefaultArgument();
2774
2775
      // Merge default arguments for template template parameters
2776
5.88k
      TemplateTemplateParmDecl *OldTemplateParm
2777
5.80k
        = OldParams? 
cast<TemplateTemplateParmDecl>(*OldParam)75
: nullptr;
2778
5.88k
      if (NewTemplateParm->isParameterPack()) {
2779
89
        assert(!NewTemplateParm->hasDefaultArgument() &&
2780
89
               "Parameter packs can't have a default argument!");
2781
89
        if (!NewTemplateParm->isPackExpansion())
2782
80
          SawParameterPack = true;
2783
5.79k
      } else if (OldTemplateParm &&
2784
75
                 hasVisibleDefaultArgument(OldTemplateParm) &&
2785
30
                 NewTemplateParm->hasDefaultArgument() &&
2786
1
                 (!SkipBody || !SkipBody->ShouldSkip)) {
2787
1
        OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2788
1
        NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2789
1
        SawDefaultArgument = true;
2790
1
        RedundantDefaultArg = true;
2791
1
        PreviousDefaultArgLoc = NewDefaultLoc;
2792
5.79k
      } else if (OldTemplateParm && 
OldTemplateParm->hasDefaultArgument()74
) {
2793
        // Merge the default argument from the old declaration to the
2794
        // new declaration.
2795
56
        NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2796
56
        PreviousDefaultArgLoc
2797
56
          = OldTemplateParm->getDefaultArgument().getLocation();
2798
5.73k
      } else if (NewTemplateParm->hasDefaultArgument()) {
2799
137
        SawDefaultArgument = true;
2800
137
        PreviousDefaultArgLoc
2801
137
          = NewTemplateParm->getDefaultArgument().getLocation();
2802
5.59k
      } else if (SawDefaultArgument)
2803
5
        MissingDefaultArg = true;
2804
5.88k
    }
2805
2806
    // C++11 [temp.param]p11:
2807
    //   If a template parameter of a primary class template or alias template
2808
    //   is a template parameter pack, it shall be the last template parameter.
2809
2.08M
    if (SawParameterPack && 
(NewParam + 1) != NewParamEnd101k
&&
2810
17.4k
        (TPC == TPC_ClassTemplate || 
TPC == TPC_VarTemplate17.4k
||
2811
17.4k
         TPC == TPC_TypeAliasTemplate)) {
2812
7
      Diag((*NewParam)->getLocation(),
2813
7
           diag::err_template_param_pack_must_be_last_template_parameter);
2814
7
      Invalid = true;
2815
7
    }
2816
2817
2.08M
    if (RedundantDefaultArg) {
2818
      // C++ [temp.param]p12:
2819
      //   A template-parameter shall not be given default arguments
2820
      //   by two different declarations in the same scope.
2821
3
      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2822
3
      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2823
3
      Invalid = true;
2824
2.08M
    } else if (MissingDefaultArg && 
TPC != TPC_FunctionTemplate67
) {
2825
      // C++ [temp.param]p11:
2826
      //   If a template-parameter of a class template has a default
2827
      //   template-argument, each subsequent template-parameter shall either
2828
      //   have a default template-argument supplied or be a template parameter
2829
      //   pack.
2830
15
      Diag((*NewParam)->getLocation(),
2831
15
           diag::err_template_param_default_arg_missing);
2832
15
      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2833
15
      Invalid = true;
2834
15
      RemoveDefaultArguments = true;
2835
15
    }
2836
2837
    // If we have an old template parameter list that we're merging
2838
    // in, move on to the next parameter.
2839
2.08M
    if (OldParams)
2840
136k
      ++OldParam;
2841
2.08M
  }
2842
2843
  // We were missing some default arguments at the end of the list, so remove
2844
  // all of the default arguments.
2845
1.13M
  if (RemoveDefaultArguments) {
2846
15
    for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2847
15
                                      NewParamEnd = NewParams->end();
2848
46
         NewParam != NewParamEnd; 
++NewParam31
) {
2849
31
      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2850
19
        TTP->removeDefaultArgument();
2851
12
      else if (NonTypeTemplateParmDecl *NTTP
2852
6
                                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2853
6
        NTTP->removeDefaultArgument();
2854
6
      else
2855
6
        cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2856
31
    }
2857
15
  }
2858
2859
1.13M
  return Invalid;
2860
1.13M
}
2861
2862
namespace {
2863
2864
/// A class which looks for a use of a certain level of template
2865
/// parameter.
2866
struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2867
  typedef RecursiveASTVisitor<DependencyChecker> super;
2868
2869
  unsigned Depth;
2870
2871
  // Whether we're looking for a use of a template parameter that makes the
2872
  // overall construct type-dependent / a dependent type. This is strictly
2873
  // best-effort for now; we may fail to match at all for a dependent type
2874
  // in some cases if this is set.
2875
  bool IgnoreNonTypeDependent;
2876
2877
  bool Match;
2878
  SourceLocation MatchLoc;
2879
2880
  DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2881
      : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2882
18
        Match(false) {}
2883
2884
  DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2885
42
      : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2886
42
    NamedDecl *ND = Params->getParam(0);
2887
42
    if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2888
40
      Depth = PD->getDepth();
2889
2
    } else if (NonTypeTemplateParmDecl *PD =
2890
0
                 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2891
0
      Depth = PD->getDepth();
2892
2
    } else {
2893
2
      Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2894
2
    }
2895
42
  }
2896
2897
54
  bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2898
54
    if (ParmDepth >= Depth) {
2899
51
      Match = true;
2900
51
      MatchLoc = Loc;
2901
51
      return true;
2902
51
    }
2903
3
    return false;
2904
3
  }
2905
2906
35
  bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2907
    // Prune out non-type-dependent expressions if requested. This can
2908
    // sometimes result in us failing to find a template parameter reference
2909
    // (if a value-dependent expression creates a dependent type), but this
2910
    // mode is best-effort only.
2911
35
    if (auto *E = dyn_cast_or_null<Expr>(S))
2912
35
      if (IgnoreNonTypeDependent && 
!E->isTypeDependent()34
)
2913
16
        return true;
2914
19
    return super::TraverseStmt(S, Q);
2915
19
  }
2916
2917
36
  bool TraverseTypeLoc(TypeLoc TL) {
2918
36
    if (IgnoreNonTypeDependent && !TL.isNull() &&
2919
36
        !TL.getType()->isDependentType())
2920
6
      return true;
2921
30
    return super::TraverseTypeLoc(TL);
2922
30
  }
2923
2924
11
  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2925
11
    return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2926
11
  }
2927
2928
40
  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2929
    // For a best-effort search, keep looking until we find a location.
2930
40
    return IgnoreNonTypeDependent || !Matches(T->getDepth());
2931
40
  }
2932
2933
44
  bool TraverseTemplateName(TemplateName N) {
2934
44
    if (TemplateTemplateParmDecl *PD =
2935
1
          dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2936
1
      if (Matches(PD->getDepth()))
2937
1
        return false;
2938
43
    return super::TraverseTemplateName(N);
2939
43
  }
2940
2941
2
  bool VisitDeclRefExpr(DeclRefExpr *E) {
2942
2
    if (NonTypeTemplateParmDecl *PD =
2943
2
          dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2944
2
      if (Matches(PD->getDepth(), E->getExprLoc()))
2945
1
        return false;
2946
1
    return super::VisitDeclRefExpr(E);
2947
1
  }
2948
2949
0
  bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2950
0
    return TraverseType(T->getReplacementType());
2951
0
  }
2952
2953
  bool
2954
0
  VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2955
0
    return TraverseTemplateArgument(T->getArgumentPack());
2956
0
  }
2957
2958
37
  bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2959
37
    return TraverseType(T->getInjectedSpecializationType());
2960
37
  }
2961
};
2962
} // end anonymous namespace
2963
2964
/// Determines whether a given type depends on the given parameter
2965
/// list.
2966
static bool
2967
42
DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2968
42
  if (!Params->size())
2969
0
    return false;
2970
2971
42
  DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2972
42
  Checker.TraverseType(T);
2973
42
  return Checker.Match;
2974
42
}
2975
2976
// Find the source range corresponding to the named type in the given
2977
// nested-name-specifier, if any.
2978
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2979
                                                       QualType T,
2980
56
                                                       const CXXScopeSpec &SS) {
2981
56
  NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2982
66
  while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2983
65
    if (const Type *CurType = NNS->getAsType()) {
2984
65
      if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2985
55
        return NNSLoc.getTypeLoc().getSourceRange();
2986
0
    } else
2987
0
      break;
2988
2989
10
    NNSLoc = NNSLoc.getPrefix();
2990
10
  }
2991
2992
1
  return SourceRange();
2993
56
}
2994
2995
/// Match the given template parameter lists to the given scope
2996
/// specifier, returning the template parameter list that applies to the
2997
/// name.
2998
///
2999
/// \param DeclStartLoc the start of the declaration that has a scope
3000
/// specifier or a template parameter list.
3001
///
3002
/// \param DeclLoc The location of the declaration itself.
3003
///
3004
/// \param SS the scope specifier that will be matched to the given template
3005
/// parameter lists. This scope specifier precedes a qualified name that is
3006
/// being declared.
3007
///
3008
/// \param TemplateId The template-id following the scope specifier, if there
3009
/// is one. Used to check for a missing 'template<>'.
3010
///
3011
/// \param ParamLists the template parameter lists, from the outermost to the
3012
/// innermost template parameter lists.
3013
///
3014
/// \param IsFriend Whether to apply the slightly different rules for
3015
/// matching template parameters to scope specifiers in friend
3016
/// declarations.
3017
///
3018
/// \param IsMemberSpecialization will be set true if the scope specifier
3019
/// denotes a fully-specialized type, and therefore this is a declaration of
3020
/// a member specialization.
3021
///
3022
/// \returns the template parameter list, if any, that corresponds to the
3023
/// name that is preceded by the scope specifier @p SS. This template
3024
/// parameter list may have template parameters (if we're declaring a
3025
/// template) or may have no template parameters (if we're declaring a
3026
/// template specialization), or may be NULL (if what we're declaring isn't
3027
/// itself a template).
3028
TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
3029
    SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3030
    TemplateIdAnnotation *TemplateId,
3031
    ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3032
4.80M
    bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3033
4.80M
  IsMemberSpecialization = false;
3034
4.80M
  Invalid = false;
3035
3036
  // The sequence of nested types to which we will match up the template
3037
  // parameter lists. We first build this list by starting with the type named
3038
  // by the nested-name-specifier and walking out until we run out of types.
3039
4.80M
  SmallVector<QualType, 4> NestedTypes;
3040
4.80M
  QualType T;
3041
4.80M
  if (SS.getScopeRep()) {
3042
347k
    if (CXXRecordDecl *Record
3043
346k
              = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3044
346k
      T = Context.getTypeDeclType(Record);
3045
1.34k
    else
3046
1.34k
      T = QualType(SS.getScopeRep()->getAsType(), 0);
3047
347k
  }
3048
3049
  // If we found an explicit specialization that prevents us from needing
3050
  // 'template<>' headers, this will be set to the location of that
3051
  // explicit specialization.
3052
4.80M
  SourceLocation ExplicitSpecLoc;
3053
3054
5.14M
  while (!T.isNull()) {
3055
348k
    NestedTypes.push_back(T);
3056
3057
    // Retrieve the parent of a record type.
3058
348k
    if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3059
      // If this type is an explicit specialization, we're done.
3060
348k
      if (ClassTemplateSpecializationDecl *Spec
3061
79.7k
          = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3062
79.7k
        if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3063
11.7k
            Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3064
5.46k
          ExplicitSpecLoc = Spec->getLocation();
3065
5.46k
          break;
3066
5.46k
        }
3067
268k
      } else if (Record->getTemplateSpecializationKind()
3068
8
                                                == TSK_ExplicitSpecialization) {
3069
8
        ExplicitSpecLoc = Record->getLocation();
3070
8
        break;
3071
8
      }
3072
3073
342k
      if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3074
1.89k
        T = Context.getTypeDeclType(Parent);
3075
340k
      else
3076
340k
        T = QualType();
3077
342k
      continue;
3078
342k
    }
3079
3080
49
    if (const TemplateSpecializationType *TST
3081
25
                                     = T->getAs<TemplateSpecializationType>()) {
3082
25
      if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3083
25
        if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3084
12
          T = Context.getTypeDeclType(Parent);
3085
13
        else
3086
13
          T = QualType();
3087
25
        continue;
3088
25
      }
3089
24
    }
3090
3091
    // Look one step prior in a dependent template specialization type.
3092
24
    if (const DependentTemplateSpecializationType *DependentTST
3093
0
                          = T->getAs<DependentTemplateSpecializationType>()) {
3094
0
      if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3095
0
        T = QualType(NNS->getAsType(), 0);
3096
0
      else
3097
0
        T = QualType();
3098
0
      continue;
3099
0
    }
3100
3101
    // Look one step prior in a dependent name type.
3102
24
    if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3103
0
      if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3104
0
        T = QualType(NNS->getAsType(), 0);
3105
0
      else
3106
0
        T = QualType();
3107
0
      continue;
3108
0
    }
3109
3110
    // Retrieve the parent of an enumeration type.
3111
24
    if (const EnumType *EnumT = T->getAs<EnumType>()) {
3112
      // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3113
      // check here.
3114
4
      EnumDecl *Enum = EnumT->getDecl();
3115
3116
      // Get to the parent type.
3117
4
      if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3118
0
        T = Context.getTypeDeclType(Parent);
3119
4
      else
3120
4
        T = QualType();
3121
4
      continue;
3122
4
    }
3123
3124
20
    T = QualType();
3125
20
  }
3126
  // Reverse the nested types list, since we want to traverse from the outermost
3127
  // to the innermost while checking template-parameter-lists.
3128
4.80M
  std::reverse(NestedTypes.begin(), NestedTypes.end());
3129
3130
  // C++0x [temp.expl.spec]p17:
3131
  //   A member or a member template may be nested within many
3132
  //   enclosing class templates. In an explicit specialization for
3133
  //   such a member, the member declaration shall be preceded by a
3134
  //   template<> for each enclosing class template that is
3135
  //   explicitly specialized.
3136
4.80M
  bool SawNonEmptyTemplateParameterList = false;
3137
3138
61.5k
  auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3139
61.5k
    if (SawNonEmptyTemplateParameterList) {
3140
15
      if (!SuppressDiagnostic)
3141
4
        Diag(DeclLoc, diag::err_specialize_member_of_template)
3142
4
          << !Recovery << Range;
3143
15
      Invalid = true;
3144
15
      IsMemberSpecialization = false;
3145
15
      return true;
3146
15
    }
3147
3148
61.5k
    return false;
3149
61.5k
  };
3150
3151
60
  auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3152
    // Check that we can have an explicit specialization here.
3153
60
    if (CheckExplicitSpecialization(Range, true))
3154
3
      return true;
3155
3156
    // We don't have a template header, but we should.
3157
57
    SourceLocation ExpectedTemplateLoc;
3158
57
    if (!ParamLists.empty())
3159
10
      ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3160
47
    else
3161
47
      ExpectedTemplateLoc = DeclStartLoc;
3162
3163
57
    if (!SuppressDiagnostic)
3164
52
      Diag(DeclLoc, diag::err_template_spec_needs_header)
3165
52
        << Range
3166
52
        << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3167
57
    return false;
3168
57
  };
3169
3170
4.80M
  unsigned ParamIdx = 0;
3171
5.15M
  for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3172
348k
       
++TypeIdx348k
) {
3173
348k
    T = NestedTypes[TypeIdx];
3174
3175
    // Whether we expect a 'template<>' header.
3176
348k
    bool NeedEmptyTemplateHeader = false;
3177
3178
    // Whether we expect a template header with parameters.
3179
348k
    bool NeedNonemptyTemplateHeader = false;
3180
3181
    // For a dependent type, the set of template parameters that we
3182
    // expect to see.
3183
348k
    TemplateParameterList *ExpectedTemplateParams = nullptr;
3184
3185
    // C++0x [temp.expl.spec]p15:
3186
    //   A member or a member template may be nested within many enclosing
3187
    //   class templates. In an explicit specialization for such a member, the
3188
    //   member declaration shall be preceded by a template<> for each
3189
    //   enclosing class template that is explicitly specialized.
3190
348k
    if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3191
348k
      if (ClassTemplatePartialSpecializationDecl *Partial
3192
68.0k
            = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3193
68.0k
        ExpectedTemplateParams = Partial->getTemplateParameters();
3194
68.0k
        NeedNonemptyTemplateHeader = true;
3195
280k
      } else if (Record->isDependentType()) {
3196
252k
        if (Record->getDescribedClassTemplate()) {
3197
251k
          ExpectedTemplateParams = Record->getDescribedClassTemplate()
3198
251k
                                                      ->getTemplateParameters();
3199
251k
          NeedNonemptyTemplateHeader = true;
3200
251k
        }
3201
27.5k
      } else if (ClassTemplateSpecializationDecl *Spec
3202
11.7k
                     = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3203
        // C++0x [temp.expl.spec]p4:
3204
        //   Members of an explicitly specialized class template are defined
3205
        //   in the same manner as members of normal classes, and not using
3206
        //   the template<> syntax.
3207
11.7k
        if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3208
6.24k
          NeedEmptyTemplateHeader = true;
3209
5.46k
        else
3210
5.46k
          continue;
3211
15.8k
      } else if (Record->getTemplateSpecializationKind()) {
3212
9
        if (Record->getTemplateSpecializationKind()
3213
9
                                                != TSK_ExplicitSpecialization &&
3214
1
            TypeIdx == NumTypes - 1)
3215
1
          IsMemberSpecialization = true;
3216
3217
9
        continue;
3218
9
      }
3219
49
    } else if (const TemplateSpecializationType *TST
3220
25
                                     = T->getAs<TemplateSpecializationType>()) {
3221
25
      if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3222
25
        ExpectedTemplateParams = Template->getTemplateParameters();
3223
25
        NeedNonemptyTemplateHeader = true;
3224
25
      }
3225
24
    } else if (T->getAs<DependentTemplateSpecializationType>()) {
3226
      // FIXME:  We actually could/should check the template arguments here
3227
      // against the corresponding template parameter list.
3228
0
      NeedNonemptyTemplateHeader = false;
3229
0
    }
3230
3231
    // C++ [temp.expl.spec]p16:
3232
    //   In an explicit specialization declaration for a member of a class
3233
    //   template or a member template that ap- pears in namespace scope, the
3234
    //   member template and some of its enclosing class templates may remain
3235
    //   unspecialized, except that the declaration shall not explicitly
3236
    //   specialize a class member template if its en- closing class templates
3237
    //   are not explicitly specialized as well.
3238
342k
    if (ParamIdx < ParamLists.size()) {
3239
332k
      if (ParamLists[ParamIdx]->size() == 0) {
3240
7.05k
        if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3241
7.05k
                                        false))
3242
10
          return nullptr;
3243
325k
      } else
3244
325k
        SawNonEmptyTemplateParameterList = true;
3245
332k
    }
3246
3247
342k
    if (NeedEmptyTemplateHeader) {
3248
      // If we're on the last of the types, and we need a 'template<>' header
3249
      // here, then it's a member specialization.
3250
6.24k
      if (TypeIdx == NumTypes - 1)
3251
6.13k
        IsMemberSpecialization = true;
3252
3253
6.24k
      if (ParamIdx < ParamLists.size()) {
3254
6.17k
        if (ParamLists[ParamIdx]->size() > 0) {
3255
          // The header has template parameters when it shouldn't. Complain.
3256
39
          if (!SuppressDiagnostic)
3257
22
            Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3258
22
                 diag::err_template_param_list_matches_nontemplate)
3259
22
              << T
3260
22
              << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3261
22
                             ParamLists[ParamIdx]->getRAngleLoc())
3262
22
              << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3263
39
          Invalid = true;
3264
39
          return nullptr;
3265
39
        }
3266
3267
        // Consume this template header.
3268
6.13k
        ++ParamIdx;
3269
6.13k
        continue;
3270
6.13k
      }
3271
3272
75
      if (!IsFriend)
3273
33
        if (DiagnoseMissingExplicitSpecialization(
3274
33
                getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3275
0
          return nullptr;
3276
3277
75
      continue;
3278
75
    }
3279
3280
336k
    if (NeedNonemptyTemplateHeader) {
3281
      // In friend declarations we can have template-ids which don't
3282
      // depend on the corresponding template parameter lists.  But
3283
      // assume that empty parameter lists are supposed to match this
3284
      // template-id.
3285
319k
      if (IsFriend && 
T->isDependentType()54
) {
3286
54
        if (ParamIdx < ParamLists.size() &&
3287
42
            DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3288
39
          ExpectedTemplateParams = nullptr;
3289
15
        else
3290
15
          continue;
3291
319k
      }
3292
3293
319k
      if (ParamIdx < ParamLists.size()) {
3294
        // Check the template parameter list, if we can.
3295
319k
        if (ExpectedTemplateParams &&
3296
319k
            !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3297
319k
                                            ExpectedTemplateParams,
3298
319k
                                            !SuppressDiagnostic, TPL_TemplateMatch))
3299
4
          Invalid = true;
3300
3301
319k
        if (!Invalid &&
3302
319k
            CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3303
319k
                                       TPC_ClassTemplateMember))
3304
0
          Invalid = true;
3305
3306
319k
        ++ParamIdx;
3307
319k
        continue;
3308
319k
      }
3309
3310
3
      if (!SuppressDiagnostic)
3311
1
        Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3312
1
          << T
3313
1
          << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3314
3
      Invalid = true;
3315
3
      continue;
3316
3
    }
3317
336k
  }
3318
3319
  // If there were at least as many template-ids as there were template
3320
  // parameter lists, then there are no template parameter lists remaining for
3321
  // the declaration itself.
3322
4.80M
  if (ParamIdx >= ParamLists.size()) {
3323
3.32M
    if (TemplateId && 
!IsFriend1.55k
) {
3324
      // We don't have a template header for the declaration itself, but we
3325
      // should.
3326
27
      DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3327
27
                                                        TemplateId->RAngleLoc));
3328
3329
      // Fabricate an empty template parameter list for the invented header.
3330
27
      return TemplateParameterList::Create(Context, SourceLocation(),
3331
27
                                           SourceLocation(), None,
3332
27
                                           SourceLocation(), nullptr);
3333
27
    }
3334
3335
3.32M
    return nullptr;
3336
3.32M
  }
3337
3338
  // If there were too many template parameter lists, complain about that now.
3339
1.47M
  if (ParamIdx < ParamLists.size() - 1) {
3340
20
    bool HasAnyExplicitSpecHeader = false;
3341
20
    bool AllExplicitSpecHeaders = true;
3342
40
    for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; 
++I20
) {
3343
20
      if (ParamLists[I]->size() == 0)
3344
15
        HasAnyExplicitSpecHeader = true;
3345
5
      else
3346
5
        AllExplicitSpecHeaders = false;
3347
20
    }
3348
3349
20
    if (!SuppressDiagnostic)
3350
14
      Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3351
11
           AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
3352
3
                                  : diag::err_template_spec_extra_headers)
3353
14
          << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3354
14
                         ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3355
3356
    // If there was a specialization somewhere, such that 'template<>' is
3357
    // not required, and there were any 'template<>' headers, note where the
3358
    // specialization occurred.
3359
20
    if (ExplicitSpecLoc.isValid() && 
HasAnyExplicitSpecHeader15
&&
3360
15
        !SuppressDiagnostic)
3361
11
      Diag(ExplicitSpecLoc,
3362
11
           diag::note_explicit_template_spec_does_not_need_header)
3363
11
        << NestedTypes.back();
3364
3365
    // We have a template parameter list with no corresponding scope, which
3366
    // means that the resulting template declaration can't be instantiated
3367
    // properly (we'll end up with dependent nodes when we shouldn't).
3368
20
    if (!AllExplicitSpecHeaders)
3369
5
      Invalid = true;
3370
20
  }
3371
3372
  // C++ [temp.expl.spec]p16:
3373
  //   In an explicit specialization declaration for a member of a class
3374
  //   template or a member template that ap- pears in namespace scope, the
3375
  //   member template and some of its enclosing class templates may remain
3376
  //   unspecialized, except that the declaration shall not explicitly
3377
  //   specialize a class member template if its en- closing class templates
3378
  //   are not explicitly specialized as well.
3379
1.47M
  if (ParamLists.back()->size() == 0 &&
3380
54.4k
      CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3381
54.4k
                                  false))
3382
2
    return nullptr;
3383
3384
  // Return the last template parameter list, which corresponds to the
3385
  // entity being declared.
3386
1.47M
  return ParamLists.back();
3387
1.47M
}
3388
3389
39
void Sema::NoteAllFoundTemplates(TemplateName Name) {
3390
39
  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3391
28
    Diag(Template->getLocation(), diag::note_template_declared_here)
3392
28
        << (isa<FunctionTemplateDecl>(Template)
3393
6
                ? 0
3394
22
                : isa<ClassTemplateDecl>(Template)
3395
0
                      ? 1
3396
22
                      : isa<VarTemplateDecl>(Template)
3397
20
                            ? 2
3398
2
                            : isa<TypeAliasTemplateDecl>(Template) ? 3 : 
40
)
3399
28
        << Template->getDeclName();
3400
28
    return;
3401
28
  }
3402
3403
11
  if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3404
3
    for (OverloadedTemplateStorage::iterator I = OST->begin(),
3405
3
                                          IEnd = OST->end();
3406
9
         I != IEnd; 
++I6
)
3407
6
      Diag((*I)->getLocation(), diag::note_template_declared_here)
3408
6
        << 0 << (*I)->getDeclName();
3409
3410
3
    return;
3411
3
  }
3412
11
}
3413
3414
static QualType
3415
checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3416
                           const SmallVectorImpl<TemplateArgument> &Converted,
3417
                           SourceLocation TemplateLoc,
3418
2.01k
                           TemplateArgumentListInfo &TemplateArgs) {
3419
2.01k
  ASTContext &Context = SemaRef.getASTContext();
3420
2.01k
  switch (BTD->getBuiltinTemplateKind()) {
3421
1.05k
  case BTK__make_integer_seq: {
3422
    // Specializations of __make_integer_seq<S, T, N> are treated like
3423
    // S<T, 0, ..., N-1>.
3424
3425
    // C++14 [inteseq.intseq]p1:
3426
    //   T shall be an integer type.
3427
1.05k
    if (!Converted[1].getAsType()->isIntegralType(Context)) {
3428
1
      SemaRef.Diag(TemplateArgs[1].getLocation(),
3429
1
                   diag::err_integer_sequence_integral_element_type);
3430
1
      return QualType();
3431
1
    }
3432
3433
    // C++14 [inteseq.make]p1:
3434
    //   If N is negative the program is ill-formed.
3435
1.05k
    TemplateArgument NumArgsArg = Converted[2];
3436
1.05k
    llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3437
1.05k
    if (NumArgs < 0) {
3438
1
      SemaRef.Diag(TemplateArgs[2].getLocation(),
3439
1
                   diag::err_integer_sequence_negative_length);
3440
1
      return QualType();
3441
1
    }
3442
3443
1.05k
    QualType ArgTy = NumArgsArg.getIntegralType();
3444
1.05k
    TemplateArgumentListInfo SyntheticTemplateArgs;
3445
    // The type argument gets reused as the first template argument in the
3446
    // synthetic template argument list.
3447
1.05k
    SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3448
    // Expand N into 0 ... N-1.
3449
1.05k
    for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3450
18.3k
         I < NumArgs; 
++I17.2k
) {
3451
17.2k
      TemplateArgument TA(Context, I, ArgTy);
3452
17.2k
      SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3453
17.2k
          TA, ArgTy, TemplateArgs[2].getLocation()));
3454
17.2k
    }
3455
    // The first template argument will be reused as the template decl that
3456
    // our synthetic template arguments will be applied to.
3457
1.05k
    return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3458
1.05k
                                       TemplateLoc, SyntheticTemplateArgs);
3459
1.05k
  }
3460
3461
959
  case BTK__type_pack_element:
3462
    // Specializations of
3463
    //    __type_pack_element<Index, T_1, ..., T_N>
3464
    // are treated like T_Index.
3465
959
    assert(Converted.size() == 2 &&
3466
959
      "__type_pack_element should be given an index and a parameter pack");
3467
3468
    // If the Index is out of bounds, the program is ill-formed.
3469
959
    TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3470
959
    llvm::APSInt Index = IndexArg.getAsIntegral();
3471
959
    assert(Index >= 0 && "the index used with __type_pack_element should be of "
3472
959
                         "type std::size_t, and hence be non-negative");
3473
959
    if (Index >= Ts.pack_size()) {
3474
1
      SemaRef.Diag(TemplateArgs[0].getLocation(),
3475
1
                   diag::err_type_pack_element_out_of_bounds);
3476
1
      return QualType();
3477
1
    }
3478
3479
    // We simply return the type at index `Index`.
3480
958
    auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3481
958
    return Nth->getAsType();
3482
0
  }
3483
0
  llvm_unreachable("unexpected BuiltinTemplateDecl!");
3484
0
}
3485
3486
/// Determine whether this alias template is "enable_if_t".
3487
27.4k
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3488
27.4k
  return AliasTemplate->getName().equals("enable_if_t");
3489
27.4k
}
3490
3491
/// Collect all of the separable terms in the given condition, which
3492
/// might be a conjunction.
3493
///
3494
/// FIXME: The right answer is to convert the logical expression into
3495
/// disjunctive normal form, so we can find the first failed term
3496
/// within each possible clause.
3497
static void collectConjunctionTerms(Expr *Clause,
3498
68.5k
                                    SmallVectorImpl<Expr *> &Terms) {
3499
68.5k
  if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3500
19.7k
    if (BinOp->getOpcode() == BO_LAnd) {
3501
10.3k
      collectConjunctionTerms(BinOp->getLHS(), Terms);
3502
10.3k
      collectConjunctionTerms(BinOp->getRHS(), Terms);
3503
10.3k
    }
3504
3505
19.7k
    return;
3506
19.7k
  }
3507
3508
48.7k
  Terms.push_back(Clause);
3509
48.7k
}
3510
3511
// The ranges-v3 library uses an odd pattern of a top-level "||" with
3512
// a left-hand side that is value-dependent but never true. Identify
3513
// the idiom and ignore that term.
3514
47.7k
static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3515
  // Top-level '||'.
3516
47.7k
  auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3517
47.7k
  if (!BinOp) 
return Cond35.7k
;
3518
3519
12.0k
  if (BinOp->getOpcode() != BO_LOr) 
return Cond10.3k
;
3520
3521
  // With an inner '==' that has a literal on the right-hand side.
3522
1.63k
  Expr *LHS = BinOp->getLHS();
3523
1.63k
  auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3524
1.63k
  if (!InnerBinOp) 
return Cond1.63k
;
3525
3526
6
  if (InnerBinOp->getOpcode() != BO_EQ ||
3527
6
      !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3528
0
    return Cond;
3529
3530
  // If the inner binary operation came from a macro expansion named
3531
  // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3532
  // of the '||', which is the real, user-provided condition.
3533
6
  SourceLocation Loc = InnerBinOp->getExprLoc();
3534
6
  if (!Loc.isMacroID()) 
return Cond3
;
3535
3536
3
  StringRef MacroName = PP.getImmediateMacroName(Loc);
3537
3
  if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3538
3
    return BinOp->getRHS();
3539
3540
0
  return Cond;
3541
0
}
3542
3543
namespace {
3544
3545
// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3546
// within failing boolean expression, such as substituting template parameters
3547
// for actual types.
3548
class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3549
public:
3550
  explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3551
47.7k
      : Policy(P) {}
3552
3553
92.1k
  bool handledStmt(Stmt *E, raw_ostream &OS) override {
3554
92.1k
    const auto *DR = dyn_cast<DeclRefExpr>(E);
3555
92.1k
    if (DR && 
DR->getQualifier()49.6k
) {
3556
      // If this is a qualified name, expand the template arguments in nested
3557
      // qualifiers.
3558
49.4k
      DR->getQualifier()->print(OS, Policy, true);
3559
      // Then print the decl itself.
3560
49.4k
      const ValueDecl *VD = DR->getDecl();
3561
49.4k
      OS << VD->getName();
3562
49.4k
      if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3563
        // This is a template variable, print the expanded template arguments.
3564
2
        printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3565
2
      }
3566
49.4k
      return true;
3567
49.4k
    }
3568
42.6k
    return false;
3569
42.6k
  }
3570
3571
private:
3572
  const PrintingPolicy Policy;
3573
};
3574
3575
} // end anonymous namespace
3576
3577
std::pair<Expr *, std::string>
3578
47.7k
Sema::findFailedBooleanCondition(Expr *Cond) {
3579
47.7k
  Cond = lookThroughRangesV3Condition(PP, Cond);
3580
3581
  // Separate out all of the terms in a conjunction.
3582
47.7k
  SmallVector<Expr *, 4> Terms;
3583
47.7k
  collectConjunctionTerms(Cond, Terms);
3584
3585
  // Determine which term failed.
3586
47.7k
  Expr *FailedCond = nullptr;
3587
46.9k
  for (Expr *Term : Terms) {
3588
46.9k
    Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3589
3590
    // Literals are uninteresting.
3591
46.9k
    if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3592
46.8k
        isa<IntegerLiteral>(TermAsWritten))
3593
51
      continue;
3594
3595
    // The initialization of the parameter from the argument is
3596
    // a constant-evaluated context.
3597
46.8k
    EnterExpressionEvaluationContext ConstantEvaluated(
3598
46.8k
      *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3599
3600
46.8k
    bool Succeeded;
3601
46.8k
    if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3602
46.8k
        !Succeeded) {
3603
45.9k
      FailedCond = TermAsWritten;
3604
45.9k
      break;
3605
45.9k
    }
3606
46.8k
  }
3607
47.7k
  if (!FailedCond)
3608
1.74k
    FailedCond = Cond->IgnoreParenImpCasts();
3609
3610
47.7k
  std::string Description;
3611
47.7k
  {
3612
47.7k
    llvm::raw_string_ostream Out(Description);
3613
47.7k
    PrintingPolicy Policy = getPrintingPolicy();
3614
47.7k
    Policy.PrintCanonicalTypes = true;
3615
47.7k
    FailedBooleanConditionPrinterHelper Helper(Policy);
3616
47.7k
    FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3617
47.7k
  }
3618
47.7k
  return { FailedCond, Description };
3619
47.7k
}
3620
3621
QualType Sema::CheckTemplateIdType(TemplateName Name,
3622
                                   SourceLocation TemplateLoc,
3623
5.92M
                                   TemplateArgumentListInfo &TemplateArgs) {
3624
5.92M
  DependentTemplateName *DTN
3625
5.92M
    = Name.getUnderlying().getAsDependentTemplateName();
3626
5.92M
  if (DTN && 
DTN->isIdentifier()10
)
3627
    // When building a template-id where the template-name is dependent,
3628
    // assume the template is a type template. Either our assumption is
3629
    // correct, or the code is ill-formed and will be diagnosed when the
3630
    // dependent name is substituted.
3631
10
    return Context.getDependentTemplateSpecializationType(ETK_None,
3632
10
                                                          DTN->getQualifier(),
3633
10
                                                          DTN->getIdentifier(),
3634
10
                                                          TemplateArgs);
3635
3636
5.92M
  if (Name.getAsAssumedTemplateName() &&
3637
0
      resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3638
0
    return QualType();
3639
3640
5.92M
  TemplateDecl *Template = Name.getAsTemplateDecl();
3641
5.92M
  if (!Template || 
isa<FunctionTemplateDecl>(Template)5.92M
||
3642
5.92M
      isa<VarTemplateDecl>(Template) || 
isa<ConceptDecl>(Template)5.92M
) {
3643
    // We might have a substituted template template parameter pack. If so,
3644
    // build a template specialization type for it.
3645
22
    if (Name.getAsSubstTemplateTemplateParmPack())
3646
2
      return Context.getTemplateSpecializationType(Name, TemplateArgs);
3647
3648
20
    Diag(TemplateLoc, diag::err_template_id_not_a_type)
3649
20
      << Name;
3650
20
    NoteAllFoundTemplates(Name);
3651
20
    return QualType();
3652
20
  }
3653
3654
  // Check that the template argument list is well-formed for this
3655
  // template.
3656
5.92M
  SmallVector<TemplateArgument, 4> Converted;
3657
5.92M
  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3658
5.92M
                                false, Converted,
3659
5.92M
                                /*UpdateArgsWithConversion=*/true))
3660
1.40k
    return QualType();
3661
3662
5.92M
  QualType CanonType;
3663
3664
5.92M
  bool InstantiationDependent = false;
3665
5.92M
  if (TypeAliasTemplateDecl *AliasTemplate =
3666
653k
          dyn_cast<TypeAliasTemplateDecl>(Template)) {
3667
3668
    // Find the canonical type for this type alias template specialization.
3669
653k
    TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3670
653k
    if (Pattern->isInvalidDecl())
3671
1
      return QualType();
3672
3673
653k
    TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3674
653k
                                           Converted);
3675
3676
    // Only substitute for the innermost template argument list.
3677
653k
    MultiLevelTemplateArgumentList TemplateArgLists;
3678
653k
    TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3679
653k
    TemplateArgLists.addOuterRetainedLevels(
3680
653k
        AliasTemplate->getTemplateParameters()->getDepth());
3681
3682
653k
    LocalInstantiationScope Scope(*this);
3683
653k
    InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3684
653k
    if (Inst.isInvalid())
3685
0
      return QualType();
3686
3687
653k
    CanonType = SubstType(Pattern->getUnderlyingType(),
3688
653k
                          TemplateArgLists, AliasTemplate->getLocation(),
3689
653k
                          AliasTemplate->getDeclName());
3690
653k
    if (CanonType.isNull()) {
3691
      // If this was enable_if and we failed to find the nested type
3692
      // within enable_if in a SFINAE context, dig out the specific
3693
      // enable_if condition that failed and present that instead.
3694
27.4k
      if (isEnableIfAliasTemplate(AliasTemplate)) {
3695
73
        if (auto DeductionInfo = isSFINAEContext()) {
3696
73
          if (*DeductionInfo &&
3697
73
              (*DeductionInfo)->hasSFINAEDiagnostic() &&
3698
73
              (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3699
73
                diag::err_typename_nested_not_found_enable_if &&
3700
73
              TemplateArgs[0].getArgument().getKind()
3701
73
                == TemplateArgument::Expression) {
3702
73
            Expr *FailedCond;
3703
73
            std::string FailedDescription;
3704
73
            std::tie(FailedCond, FailedDescription) =
3705
73
              findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3706
3707
            // Remove the old SFINAE diagnostic.
3708
73
            PartialDiagnosticAt OldDiag =
3709
73
              {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3710
73
            (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3711
3712
            // Add a new SFINAE diagnostic specifying which condition
3713
            // failed.
3714
73
            (*DeductionInfo)->addSFINAEDiagnostic(
3715
73
              OldDiag.first,
3716
73
              PDiag(diag::err_typename_nested_not_found_requirement)
3717
73
                << FailedDescription
3718
73
                << FailedCond->getSourceRange());
3719
73
          }
3720
73
        }
3721
73
      }
3722
3723
27.4k
      return QualType();
3724
27.4k
    }
3725
5.26M
  } else if (Name.isDependent() ||
3726
5.22M
             TemplateSpecializationType::anyDependentTemplateArguments(
3727
3.08M
               TemplateArgs, InstantiationDependent)) {
3728
    // This class template specialization is a dependent
3729
    // type. Therefore, its canonical type is another class template
3730
    // specialization type that contains all of the converted
3731
    // arguments in canonical form. This ensures that, e.g., A<T> and
3732
    // A<T, T> have identical types when A is declared as:
3733
    //
3734
    //   template<typename T, typename U = T> struct A;
3735
3.08M
    CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3736
3737
    // This might work out to be a current instantiation, in which
3738
    // case the canonical type needs to be the InjectedClassNameType.
3739
    //
3740
    // TODO: in theory this could be a simple hashtable lookup; most
3741
    // changes to CurContext don't change the set of current
3742
    // instantiations.
3743
3.08M
    if (isa<ClassTemplateDecl>(Template)) {
3744
5.02M
      for (DeclContext *Ctx = CurContext; Ctx; 
Ctx = Ctx->getLookupParent()1.95M
) {
3745
        // If we get out to a namespace, we're done.
3746
5.02M
        if (Ctx->isFileContext()) 
break2.80M
;
3747
3748
        // If this isn't a record, keep looking.
3749
2.22M
        CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3750
2.22M
        if (!Record) 
continue438k
;
3751
3752
        // Look for one of the two cases with InjectedClassNameTypes
3753
        // and check whether it's the same template.
3754
1.78M
        if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3755
1.44M
            !Record->getDescribedClassTemplate())
3756
515k
          continue;
3757
3758
        // Fetch the injected class name type and check whether its
3759
        // injected type is equal to the type we just built.
3760
1.27M
        QualType ICNT = Context.getTypeDeclType(Record);
3761
1.27M
        QualType Injected = cast<InjectedClassNameType>(ICNT)
3762
1.27M
          ->getInjectedSpecializationType();
3763
3764
1.27M
        if (CanonType != Injected->getCanonicalTypeInternal())
3765
1.00M
          continue;
3766
3767
        // If so, the canonical type of this TST is the injected
3768
        // class name type of the record we just found.
3769
268k
        assert(ICNT.isCanonical());
3770
268k
        CanonType = ICNT;
3771
268k
        break;
3772
268k
      }
3773
3.07M
    }
3774
2.18M
  } else if (ClassTemplateDecl *ClassTemplate
3775
2.18M
               = dyn_cast<ClassTemplateDecl>(Template)) {
3776
    // Find the class template specialization declaration that
3777
    // corresponds to these arguments.
3778
2.18M
    void *InsertPos = nullptr;
3779
2.18M
    ClassTemplateSpecializationDecl *Decl
3780
2.18M
      = ClassTemplate->findSpecialization(Converted, InsertPos);
3781
2.18M
    if (!Decl) {
3782
      // This is the first time we have referenced this class template
3783
      // specialization. Create the canonical declaration and add it to
3784
      // the set of specializations.
3785
795k
      Decl = ClassTemplateSpecializationDecl::Create(
3786
795k
          Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3787
795k
          ClassTemplate->getDeclContext(),
3788
795k
          ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3789
795k
          ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
3790
795k
      ClassTemplate->AddSpecialization(Decl, InsertPos);
3791
795k
      if (ClassTemplate->isOutOfLine())
3792
42
        Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3793
795k
    }
3794
3795
2.18M
    if (Decl->getSpecializationKind() == TSK_Undeclared) {
3796
893k
      MultiLevelTemplateArgumentList TemplateArgLists;
3797
893k
      TemplateArgLists.addOuterTemplateArguments(Converted);
3798
893k
      InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3799
893k
                              Decl);
3800
893k
    }
3801
3802
    // Diagnose uses of this specialization.
3803
2.18M
    (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3804
3805
2.18M
    CanonType = Context.getTypeDeclType(Decl);
3806
2.18M
    assert(isa<RecordType>(CanonType) &&
3807
2.18M
           "type of non-dependent specialization is not a RecordType");
3808
2.01k
  } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3809
2.01k
    CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3810
2.01k
                                           TemplateArgs);
3811
2.01k
  }
3812
3813
  // Build the fully-sugared type for this class template
3814
  // specialization, which refers back to the class template
3815
  // specialization we created or found.
3816
5.89M
  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3817
5.92M
}
3818
3819
void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3820
                                           TemplateNameKind &TNK,
3821
                                           SourceLocation NameLoc,
3822
16
                                           IdentifierInfo *&II) {
3823
16
  assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3824
3825
16
  TemplateName Name = ParsedName.get();
3826
16
  auto *ATN = Name.getAsAssumedTemplateName();
3827
16
  assert(ATN && "not an assumed template name");
3828
16
  II = ATN->getDeclName().getAsIdentifierInfo();
3829
3830
16
  if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3831
    // Resolved to a type template name.
3832
3
    ParsedName = TemplateTy::make(Name);
3833
3
    TNK = TNK_Type_template;
3834
3
  }
3835
16
}
3836
3837
bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3838
                                            SourceLocation NameLoc,
3839
141
                                            bool Diagnose) {
3840
  // We assumed this undeclared identifier to be an (ADL-only) function
3841
  // template name, but it was used in a context where a type was required.
3842
  // Try to typo-correct it now.
3843
141
  AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3844
141
  assert(ATN && "not an assumed template name");
3845
3846
141
  LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3847
141
  struct CandidateCallback : CorrectionCandidateCallback {
3848
46
    bool ValidateCandidate(const TypoCorrection &TC) override {
3849
46
      return TC.getCorrectionDecl() &&
3850
45
             getAsTypeTemplateDecl(TC.getCorrectionDecl());
3851
46
    }
3852
137
    std::unique_ptr<CorrectionCandidateCallback> clone() override {
3853
137
      return std::make_unique<CandidateCallback>(*this);
3854
137
    }
3855
141
  } FilterCCC;
3856
3857
141
  TypoCorrection Corrected =
3858
141
      CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3859
141
                  FilterCCC, CTK_ErrorRecovery);
3860
141
  if (Corrected && 
Corrected.getFoundDecl()34
) {
3861
34
    diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3862
34
                                << ATN->getDeclName());
3863
34
    Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3864
34
    return false;
3865
34
  }
3866
3867
107
  if (Diagnose)
3868
94
    Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3869
107
  return true;
3870
107
}
3871
3872
TypeResult Sema::ActOnTemplateIdType(
3873
    Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3874
    TemplateTy TemplateD, IdentifierInfo *TemplateII,
3875
    SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3876
    ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3877
1.05M
    bool IsCtorOrDtorName, bool IsClassName) {
3878
1.05M
  if (SS.isInvalid())
3879
0
    return true;
3880
3881
1.05M
  if (!IsCtorOrDtorName && 
!IsClassName1.05M
&&
SS.isSet()932k
) {
3882
31.9k
    DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3883
3884
    // C++ [temp.res]p3:
3885
    //   A qualified-id that refers to a type and in which the
3886
    //   nested-name-specifier depends on a template-parameter (14.6.2)
3887
    //   shall be prefixed by the keyword typename to indicate that the
3888
    //   qualified-id denotes a type, forming an
3889
    //   elaborated-type-specifier (7.1.5.3).
3890
31.9k
    if (!LookupCtx && 
isDependentScopeSpecifier(SS)7
) {
3891
7
      Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3892
7
        << SS.getScopeRep() << TemplateII->getName();
3893
      // Recover as if 'typename' were specified.
3894
      // FIXME: This is not quite correct recovery as we don't transform SS
3895
      // into the corresponding dependent form (and we don't diagnose missing
3896
      // 'template' keywords within SS as a result).
3897
7
      return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3898
7
                               TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3899
7
                               TemplateArgsIn, RAngleLoc);
3900
7
    }
3901
3902
    // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3903
    // it's not actually allowed to be used as a type in most cases. Because
3904
    // we annotate it before we know whether it's valid, we have to check for
3905
    // this case here.
3906
31.9k
    auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3907
31.9k
    if (LookupRD && 
LookupRD->getIdentifier() == TemplateII356
) {
3908
16
      Diag(TemplateIILoc,
3909
16
           TemplateKWLoc.isInvalid()
3910
12
               ? diag::err_out_of_line_qualified_id_type_names_constructor
3911
4
               : diag::ext_out_of_line_qualified_id_type_names_constructor)
3912
16
        << TemplateII << 0 /*injected-class-name used as template name*/
3913
16
        << 1 /*if any keyword was present, it was 'template'*/;
3914
16
    }
3915
31.9k
  }
3916
3917
1.05M
  TemplateName Template = TemplateD.get();
3918
1.05M
  if (Template.getAsAssumedTemplateName() &&
3919
114
      resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3920
86
    return true;
3921
3922
  // Translate the parser's template argument list in our AST format.
3923
1.05M
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3924
1.05M
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3925
3926
1.05M
  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3927
47
    QualType T
3928
47
      = Context.getDependentTemplateSpecializationType(ETK_None,
3929
47
                                                       DTN->getQualifier(),
3930
47
                                                       DTN->getIdentifier(),
3931
47
                                                       TemplateArgs);
3932
    // Build type-source information.
3933
47
    TypeLocBuilder TLB;
3934
47
    DependentTemplateSpecializationTypeLoc SpecTL
3935
47
      = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3936
47
    SpecTL.setElaboratedKeywordLoc(SourceLocation());
3937
47
    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3938
47
    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3939
47
    SpecTL.setTemplateNameLoc(TemplateIILoc);
3940
47
    SpecTL.setLAngleLoc(LAngleLoc);
3941
47
    SpecTL.setRAngleLoc(RAngleLoc);
3942
94
    for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; 
++I47
)
3943
47
      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3944
47
    return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3945
47
  }
3946
3947
1.05M
  QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3948
1.05M
  if (Result.isNull())
3949
593
    return true;
3950
3951
  // Build type-source information.
3952
1.05M
  TypeLocBuilder TLB;
3953
1.05M
  TemplateSpecializationTypeLoc SpecTL
3954
1.05M
    = TLB.push<TemplateSpecializationTypeLoc>(Result);
3955
1.05M
  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3956
1.05M
  SpecTL.setTemplateNameLoc(TemplateIILoc);
3957
1.05M
  SpecTL.setLAngleLoc(LAngleLoc);
3958
1.05M
  SpecTL.setRAngleLoc(RAngleLoc);
3959
2.74M
  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; 
++i1.69M
)
3960
1.69M
    SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3961
3962
  // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3963
  // constructor or destructor name (in such a case, the scope specifier
3964
  // will be attached to the enclosing Decl or Expr node).
3965
1.05M
  if (SS.isNotEmpty() && 
!IsCtorOrDtorName35.1k
) {
3966
    // Create an elaborated-type-specifier containing the nested-name-specifier.
3967
35.1k
    Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3968
35.1k
    ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3969
35.1k
    ElabTL.setElaboratedKeywordLoc(SourceLocation());
3970
35.1k
    ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3971
35.1k
  }
3972
3973
1.05M
  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3974
1.05M
}
3975
3976
TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3977
                                        TypeSpecifierType TagSpec,
3978
                                        SourceLocation TagLoc,
3979
                                        CXXScopeSpec &SS,
3980
                                        SourceLocation TemplateKWLoc,
3981
                                        TemplateTy TemplateD,
3982
                                        SourceLocation TemplateLoc,
3983
                                        SourceLocation LAngleLoc,
3984
                                        ASTTemplateArgsPtr TemplateArgsIn,
3985
4.45k
                                        SourceLocation RAngleLoc) {
3986
4.45k
  if (SS.isInvalid())
3987
0
    return TypeResult(true);
3988
3989
4.45k
  TemplateName Template = TemplateD.get();
3990
3991
  // Translate the parser's template argument list in our AST format.
3992
4.45k
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3993
4.45k
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3994
3995
  // Determine the tag kind
3996
4.45k
  TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3997
4.45k
  ElaboratedTypeKeyword Keyword
3998
4.45k
    = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3999
4000
4.45k
  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4001
5
    QualType T = Context.getDependentTemplateSpecializationType(Keyword,
4002
5
                                                          DTN->getQualifier(),
4003
5
                                                          DTN->getIdentifier(),
4004
5
                                                                TemplateArgs);
4005
4006
    // Build type-source information.
4007
5
    TypeLocBuilder TLB;
4008
5
    DependentTemplateSpecializationTypeLoc SpecTL
4009
5
      = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4010
5
    SpecTL.setElaboratedKeywordLoc(TagLoc);
4011
5
    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4012
5
    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4013
5
    SpecTL.setTemplateNameLoc(TemplateLoc);
4014
5
    SpecTL.setLAngleLoc(LAngleLoc);
4015
5
    SpecTL.setRAngleLoc(RAngleLoc);
4016
10
    for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; 
++I5
)
4017
5
      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4018
5
    return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4019
5
  }
4020
4021
4.45k
  if (TypeAliasTemplateDecl *TAT =
4022
2
        dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4023
    // C++0x [dcl.type.elab]p2:
4024
    //   If the identifier resolves to a typedef-name or the simple-template-id
4025
    //   resolves to an alias template specialization, the
4026
    //   elaborated-type-specifier is ill-formed.
4027
2
    Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4028
2
        << TAT << NTK_TypeAliasTemplate << TagKind;
4029
2
    Diag(TAT->getLocation(), diag::note_declared_at);
4030
2
  }
4031
4032
4.45k
  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4033
4.45k
  if (Result.isNull())
4034
8
    return TypeResult(true);
4035
4036
  // Check the tag kind
4037
4.44k
  if (const RecordType *RT = Result->getAs<RecordType>()) {
4038
916
    RecordDecl *D = RT->getDecl();
4039
4040
916
    IdentifierInfo *Id = D->getIdentifier();
4041
916
    assert(Id && "templated class must have an identifier");
4042
4043
916
    if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4044
4
                                      TagLoc, Id)) {
4045
4
      Diag(TagLoc, diag::err_use_with_wrong_tag)
4046
4
        << Result
4047
4
        << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
4048
4
      Diag(D->getLocation(), diag::note_previous_use);
4049
4
    }
4050
916
  }
4051
4052
  // Provide source-location information for the template specialization.
4053
4.44k
  TypeLocBuilder TLB;
4054
4.44k
  TemplateSpecializationTypeLoc SpecTL
4055
4.44k
    = TLB.push<TemplateSpecializationTypeLoc>(Result);
4056
4.44k
  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4057
4.44k
  SpecTL.setTemplateNameLoc(TemplateLoc);
4058
4.44k
  SpecTL.setLAngleLoc(LAngleLoc);
4059
4.44k
  SpecTL.setRAngleLoc(RAngleLoc);
4060
10.5k
  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; 
++i6.06k
)
4061
6.06k
    SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4062
4063
  // Construct an elaborated type containing the nested-name-specifier (if any)
4064
  // and tag keyword.
4065
4.44k
  Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
4066
4.44k
  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
4067
4.44k
  ElabTL.setElaboratedKeywordLoc(TagLoc);
4068
4.44k
  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4069
4.44k
  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
4070
4.44k
}
4071
4072
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4073
                                             NamedDecl *PrevDecl,
4074
                                             SourceLocation Loc,
4075
                                             bool IsPartialSpecialization);
4076
4077
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4078
4079
static bool isTemplateArgumentTemplateParameter(
4080
448
    const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4081
448
  switch (Arg.getKind()) {
4082
10
  case TemplateArgument::Null:
4083
10
  case TemplateArgument::NullPtr:
4084
10
  case TemplateArgument::Integral:
4085
10
  case TemplateArgument::Declaration:
4086
10
  case TemplateArgument::Pack:
4087
10
  case TemplateArgument::TemplateExpansion:
4088
10
    return false;
4089
4090
428
  case TemplateArgument::Type: {
4091
428
    QualType Type = Arg.getAsType();
4092
428
    const TemplateTypeParmType *TPT =
4093
428
        Arg.getAsType()->getAs<TemplateTypeParmType>();
4094
428
    return TPT && 
!Type.hasQualifiers()137
&&
4095
137
           TPT->getDepth() == Depth && 
TPT->getIndex() == Index135
;
4096
10
  }
4097
4098
8
  case TemplateArgument::Expression: {
4099
8
    DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4100
8
    if (!DRE || !DRE->getDecl())
4101
0
      return false;
4102
8
    const NonTypeTemplateParmDecl *NTTP =
4103
8
        dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4104
8
    return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4105
8
  }
4106
4107
2
  case TemplateArgument::Template:
4108
2
    const TemplateTemplateParmDecl *TTP =
4109
2
        dyn_cast_or_null<TemplateTemplateParmDecl>(
4110
2
            Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4111
2
    return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4112
0
  }
4113
0
  llvm_unreachable("unexpected kind of template argument");
4114
0
}
4115
4116
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4117
357
                                    ArrayRef<TemplateArgument> Args) {
4118
357
  if (Params->size() != Args.size())
4119
6
    return false;
4120
4121
351
  unsigned Depth = Params->getDepth();
4122
4123
468
  for (unsigned I = 0, N = Args.size(); I != N; 
++I117
) {
4124
450
    TemplateArgument Arg = Args[I];
4125
4126
    // If the parameter is a pack expansion, the argument must be a pack
4127
    // whose only element is a pack expansion.
4128
450
    if (Params->getParam(I)->isParameterPack()) {
4129
5
      if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4130
5
          !Arg.pack_begin()->isPackExpansion())
4131
2
        return false;
4132
3
      Arg = Arg.pack_begin()->getPackExpansionPattern();
4133
3
    }
4134
4135
448
    if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4136
331
      return false;
4137
448
  }
4138
4139
18
  return true;
4140
351
}
4141
4142
template<typename PartialSpecDecl>
4143
148k
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4144
148k
  if (Partial->getDeclContext()->isDependentContext())
4145
4.45k
    return;
4146
4147
  // FIXME: Get the TDK from deduction in order to provide better diagnostics
4148
  // for non-substitution-failure issues?
4149
144k
  TemplateDeductionInfo Info(Partial->getLocation());
4150
144k
  if (S.isMoreSpecializedThanPrimary(Partial, Info))
4151
144k
    return;
4152
4153
30
  auto *Template = Partial->getSpecializedTemplate();
4154
30
  S.Diag(Partial->getLocation(),
4155
30
         diag::ext_partial_spec_not_more_specialized_than_primary)
4156
30
      << isa<VarTemplateDecl>(Template);
4157
4158
30
  if (Info.hasSFINAEDiagnostic()) {
4159
3
    PartialDiagnosticAt Diag = {SourceLocation(),
4160
3
                                PartialDiagnostic::NullDiagnostic()};
4161
3
    Info.takeSFINAEDiagnostic(Diag);
4162
3
    SmallString<128> SFINAEArgString;
4163
3
    Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4164
3
    S.Diag(Diag.first,
4165
3
           diag::note_partial_spec_not_more_specialized_than_primary)
4166
3
      << SFINAEArgString;
4167
3
  }
4168
4169
30
  S.Diag(Template->getLocation(), diag::note_template_decl_here);
4170
30
  SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4171
30
  Template->getAssociatedConstraints(TemplateAC);
4172
30
  Partial->getAssociatedConstraints(PartialAC);
4173
30
  S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4174
30
                                                  TemplateAC);
4175
30
}
SemaTemplate.cpp:void checkMoreSpecializedThanPrimary<clang::ClassTemplatePartialSpecializationDecl>(clang::Sema&, clang::ClassTemplatePartialSpecializationDecl*)
Line
Count
Source
4143
148k
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4144
148k
  if (Partial->getDeclContext()->isDependentContext())
4145
4.38k
    return;
4146
4147
  // FIXME: Get the TDK from deduction in order to provide better diagnostics
4148
  // for non-substitution-failure issues?
4149
143k
  TemplateDeductionInfo Info(Partial->getLocation());
4150
143k
  if (S.isMoreSpecializedThanPrimary(Partial, Info))
4151
143k
    return;
4152
4153
20
  auto *Template = Partial->getSpecializedTemplate();
4154
20
  S.Diag(Partial->getLocation(),
4155
20
         diag::ext_partial_spec_not_more_specialized_than_primary)
4156
20
      << isa<VarTemplateDecl>(Template);
4157
4158
20
  if (Info.hasSFINAEDiagnostic()) {
4159
3
    PartialDiagnosticAt Diag = {SourceLocation(),
4160
3
                                PartialDiagnostic::NullDiagnostic()};
4161
3
    Info.takeSFINAEDiagnostic(Diag);
4162
3
    SmallString<128> SFINAEArgString;
4163
3
    Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4164
3
    S.Diag(Diag.first,
4165
3
           diag::note_partial_spec_not_more_specialized_than_primary)
4166
3
      << SFINAEArgString;
4167
3
  }
4168
4169
20
  S.Diag(Template->getLocation(), diag::note_template_decl_here);
4170
20
  SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4171
20
  Template->getAssociatedConstraints(TemplateAC);
4172
20
  Partial->getAssociatedConstraints(PartialAC);
4173
20
  S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4174
20
                                                  TemplateAC);
4175
20
}
SemaTemplate.cpp:void checkMoreSpecializedThanPrimary<clang::VarTemplatePartialSpecializationDecl>(clang::Sema&, clang::VarTemplatePartialSpecializationDecl*)
Line
Count
Source
4143
387
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4144
387
  if (Partial->getDeclContext()->isDependentContext())
4145
69
    return;
4146
4147
  // FIXME: Get the TDK from deduction in order to provide better diagnostics
4148
  // for non-substitution-failure issues?
4149
318
  TemplateDeductionInfo Info(Partial->getLocation());
4150
318
  if (S.isMoreSpecializedThanPrimary(Partial, Info))
4151
308
    return;
4152
4153
10
  auto *Template = Partial->getSpecializedTemplate();
4154
10
  S.Diag(Partial->getLocation(),
4155
10
         diag::ext_partial_spec_not_more_specialized_than_primary)
4156
10
      << isa<VarTemplateDecl>(Template);
4157
4158
10
  if (Info.hasSFINAEDiagnostic()) {
4159
0
    PartialDiagnosticAt Diag = {SourceLocation(),
4160
0
                                PartialDiagnostic::NullDiagnostic()};
4161
0
    Info.takeSFINAEDiagnostic(Diag);
4162
0
    SmallString<128> SFINAEArgString;
4163
0
    Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4164
0
    S.Diag(Diag.first,
4165
0
           diag::note_partial_spec_not_more_specialized_than_primary)
4166
0
      << SFINAEArgString;
4167
0
  }
4168
4169
10
  S.Diag(Template->getLocation(), diag::note_template_decl_here);
4170
10
  SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4171
10
  Template->getAssociatedConstraints(TemplateAC);
4172
10
  Partial->getAssociatedConstraints(PartialAC);
4173
10
  S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4174
10
                                                  TemplateAC);
4175
10
}
4176
4177
static void
4178
noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4179
25
                           const llvm::SmallBitVector &DeducibleParams) {
4180
58
  for (unsigned I = 0, N = DeducibleParams.size(); I != N; 
++I33
) {
4181
33
    if (!DeducibleParams[I]) {
4182
27
      NamedDecl *Param = TemplateParams->getParam(I);
4183
27
      if (Param->getDeclName())
4184
26
        S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4185
26
            << Param->getDeclName();
4186
1
      else
4187
1
        S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4188
1
            << "(anonymous)";
4189
27
    }
4190
33
  }
4191
25
}
4192
4193
4194
template<typename PartialSpecDecl>
4195
static void checkTemplatePartialSpecialization(Sema &S,
4196
148k
                                               PartialSpecDecl *Partial) {
4197
  // C++1z [temp.class.spec]p8: (DR1495)
4198
  //   - The specialization shall be more specialized than the primary
4199
  //     template (14.5.5.2).
4200
148k
  checkMoreSpecializedThanPrimary(S, Partial);
4201
4202
  // C++ [temp.class.spec]p8: (DR1315)
4203
  //   - Each template-parameter shall appear at least once in the
4204
  //     template-id outside a non-deduced context.
4205
  // C++1z [temp.class.spec.match]p3 (P0127R2)
4206
  //   If the template arguments of a partial specialization cannot be
4207
  //   deduced because of the structure of its template-parameter-list
4208
  //   and the template-id, the program is ill-formed.
4209
148k
  auto *TemplateParams = Partial->getTemplateParameters();
4210
148k
  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4211
148k
  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4212
148k
                               TemplateParams->getDepth(), DeducibleParams);
4213
4214
148k
  if (!DeducibleParams.all()) {
4215
21
    unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4216
21
    S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4217
21
      << isa<VarTemplatePartialSpecializationDecl>(Partial)
4218
21
      << (NumNonDeducible > 1)
4219
21
      << SourceRange(Partial->getLocation(),
4220
21
                     Partial->getTemplateArgsAsWritten()->RAngleLoc);
4221
21
    noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4222
21
  }
4223
148k
}
SemaTemplate.cpp:void checkTemplatePartialSpecialization<clang::ClassTemplatePartialSpecializationDecl>(clang::Sema&, clang::ClassTemplatePartialSpecializationDecl*)
Line
Count
Source
4196
148k
                                               PartialSpecDecl *Partial) {
4197
  // C++1z [temp.class.spec]p8: (DR1495)
4198
  //   - The specialization shall be more specialized than the primary
4199
  //     template (14.5.5.2).
4200
148k
  checkMoreSpecializedThanPrimary(S, Partial);
4201
4202
  // C++ [temp.class.spec]p8: (DR1315)
4203
  //   - Each template-parameter shall appear at least once in the
4204
  //     template-id outside a non-deduced context.
4205
  // C++1z [temp.class.spec.match]p3 (P0127R2)
4206
  //   If the template arguments of a partial specialization cannot be
4207
  //   deduced because of the structure of its template-parameter-list
4208
  //   and the template-id, the program is ill-formed.
4209
148k
  auto *TemplateParams = Partial->getTemplateParameters();
4210
148k
  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4211
148k
  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4212
148k
                               TemplateParams->getDepth(), DeducibleParams);
4213
4214
148k
  if (!DeducibleParams.all()) {
4215
16
    unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4216
16
    S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4217
16
      << isa<VarTemplatePartialSpecializationDecl>(Partial)
4218
16
      << (NumNonDeducible > 1)
4219
16
      << SourceRange(Partial->getLocation(),
4220
16
                     Partial->getTemplateArgsAsWritten()->RAngleLoc);
4221
16
    noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4222
16
  }
4223
148k
}
SemaTemplate.cpp:void checkTemplatePartialSpecialization<clang::VarTemplatePartialSpecializationDecl>(clang::Sema&, clang::VarTemplatePartialSpecializationDecl*)
Line
Count
Source
4196
387
                                               PartialSpecDecl *Partial) {
4197
  // C++1z [temp.class.spec]p8: (DR1495)
4198
  //   - The specialization shall be more specialized than the primary
4199
  //     template (14.5.5.2).
4200
387
  checkMoreSpecializedThanPrimary(S, Partial);
4201
4202
  // C++ [temp.class.spec]p8: (DR1315)
4203
  //   - Each template-parameter shall appear at least once in the
4204
  //     template-id outside a non-deduced context.
4205
  // C++1z [temp.class.spec.match]p3 (P0127R2)
4206
  //   If the template arguments of a partial specialization cannot be
4207
  //   deduced because of the structure of its template-parameter-list
4208
  //   and the template-id, the program is ill-formed.
4209
387
  auto *TemplateParams = Partial->getTemplateParameters();
4210
387
  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4211
387
  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4212
387
                               TemplateParams->getDepth(), DeducibleParams);
4213
4214
387
  if (!DeducibleParams.all()) {
4215
5
    unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4216
5
    S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4217
5
      << isa<VarTemplatePartialSpecializationDecl>(Partial)
4218
5
      << (NumNonDeducible > 1)
4219
5
      << SourceRange(Partial->getLocation(),
4220
5
                     Partial->getTemplateArgsAsWritten()->RAngleLoc);
4221
5
    noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4222
5
  }
4223
387
}
4224
4225
void Sema::CheckTemplatePartialSpecialization(
4226
148k
    ClassTemplatePartialSpecializationDecl *Partial) {
4227
148k
  checkTemplatePartialSpecialization(*this, Partial);
4228
148k
}
4229
4230
void Sema::CheckTemplatePartialSpecialization(
4231
387
    VarTemplatePartialSpecializationDecl *Partial) {
4232
387
  checkTemplatePartialSpecialization(*this, Partial);
4233
387
}
4234
4235
285
void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4236
  // C++1z [temp.param]p11:
4237
  //   A template parameter of a deduction guide template that does not have a
4238
  //   default-argument shall be deducible from the parameter-type-list of the
4239
  //   deduction guide template.
4240
285
  auto *TemplateParams = TD->getTemplateParameters();
4241
285
  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4242
285
  MarkDeducedTemplateParameters(TD, DeducibleParams);
4243
1.16k
  for (unsigned I = 0; I != TemplateParams->size(); 
++I878
) {
4244
    // A parameter pack is deducible (to an empty pack).
4245
878
    auto *Param = TemplateParams->getParam(I);
4246
878
    if (Param->isParameterPack() || 
hasVisibleDefaultArgument(Param)847
)
4247
436
      DeducibleParams[I] = true;
4248
878
  }
4249
4250
285
  if (!DeducibleParams.all()) {
4251
4
    unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4252
4
    Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4253
4
      << (NumNonDeducible > 1);
4254
4
    noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4255
4
  }
4256
285
}
4257
4258
DeclResult Sema::ActOnVarTemplateSpecialization(
4259
    Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
4260
    TemplateParameterList *TemplateParams, StorageClass SC,
4261
880
    bool IsPartialSpecialization) {
4262
  // D must be variable template id.
4263
880
  assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4264
880
         "Variable template specialization is declared with a template it.");
4265
4266
880
  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4267
880
  TemplateArgumentListInfo TemplateArgs =
4268
880
      makeTemplateArgumentListInfo(*this, *TemplateId);
4269
880
  SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4270
880
  SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4271
880
  SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4272
4273
880
  TemplateName Name = TemplateId->Template.get();
4274
4275
  // The template-id must name a variable template.
4276
880
  VarTemplateDecl *VarTemplate =
4277
880
      dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4278
880
  if (!VarTemplate) {
4279
8
    NamedDecl *FnTemplate;
4280
8
    if (auto *OTS = Name.getAsOverloadedTemplate())
4281
3
      FnTemplate = *OTS->begin();
4282
5
    else
4283
5
      FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4284
8
    if (FnTemplate)
4285
6
      return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4286
6
               << FnTemplate->getDeclName();
4287
2
    return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4288
2
             << IsPartialSpecialization;
4289
2
  }
4290
4291
  // Check for unexpanded parameter packs in any of the template arguments.
4292
1.89k
  
for (unsigned I = 0, N = TemplateArgs.size(); 872
I != N;
++I1.02k
)
4293
1.02k
    if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4294
1.02k
                                        UPPC_PartialSpecialization))
4295
0
      return true;
4296
4297
  // Check that the template argument list is well-formed for this
4298
  // template.
4299
872
  SmallVector<TemplateArgument, 4> Converted;
4300
872
  if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4301
872
                                false, Converted,
4302
872
                                /*UpdateArgsWithConversion=*/true))
4303
0
    return true;
4304
4305
  // Find the variable template (partial) specialization declaration that
4306
  // corresponds to these arguments.
4307
872
  if (IsPartialSpecialization) {
4308
357
    if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4309
357
                                               TemplateArgs.size(), Converted))
4310
0
      return true;
4311
4312
    // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4313
    // also do them during instantiation.
4314
357
    bool InstantiationDependent;
4315
357
    if (!Name.isDependent() &&
4316
286
        !TemplateSpecializationType::anyDependentTemplateArguments(
4317
286
            TemplateArgs.arguments(),
4318
0
            InstantiationDependent)) {
4319
0
      Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4320
0
          << VarTemplate->getDeclName();
4321
0
      IsPartialSpecialization = false;
4322
0
    }
4323
4324
357
    if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4325
357
                                Converted) &&
4326
18
        (!Context.getLangOpts().CPlusPlus20 ||
4327
11
         !TemplateParams->hasAssociatedConstraints())) {
4328
      // C++ [temp.class.spec]p9b3:
4329
      //
4330
      //   -- The argument list of the specialization shall not be identical
4331
      //      to the implicit argument list of the primary template.
4332
9
      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4333
9
        << /*variable template*/ 1
4334
9
        << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4335
9
        << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4336
      // FIXME: Recover from this by treating the declaration as a redeclaration
4337
      // of the primary template.
4338
9
      return true;
4339
9
    }
4340
863
  }
4341
4342
863
  void *InsertPos = nullptr;
4343
863
  VarTemplateSpecializationDecl *PrevDecl = nullptr;
4344
4345
863
  if (IsPartialSpecialization)
4346
348
    PrevDecl = VarTemplate->findPartialSpecialization(Converted, TemplateParams,
4347
348
                                                      InsertPos);
4348
515
  else
4349
515
    PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
4350
4351
863
  VarTemplateSpecializationDecl *Specialization = nullptr;
4352
4353
  // Check whether we can declare a variable template specialization in
4354
  // the current scope.
4355
863
  if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4356
863
                                       TemplateNameLoc,
4357
863
                                       IsPartialSpecialization))
4358
20
    return true;
4359
4360
843
  if (PrevDecl && 
PrevDecl->getSpecializationKind() == TSK_Undeclared118
) {
4361
    // Since the only prior variable template specialization with these
4362
    // arguments was referenced but not declared,  reuse that
4363
    // declaration node as our own, updating its source location and
4364
    // the list of outer template parameters to reflect our new declaration.
4365
0
    Specialization = PrevDecl;
4366
0
    Specialization->setLocation(TemplateNameLoc);
4367
0
    PrevDecl = nullptr;
4368
843
  } else if (IsPartialSpecialization) {
4369
    // Create a new class template partial specialization declaration node.
4370
338
    VarTemplatePartialSpecializationDecl *PrevPartial =
4371
338
        cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4372
338
    VarTemplatePartialSpecializationDecl *Partial =
4373
338
        VarTemplatePartialSpecializationDecl::Create(
4374
338
            Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4375
338
            TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4376
338
            Converted, TemplateArgs);
4377
4378
338
    if (!PrevPartial)
4379
273
      VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4380
338
    Specialization = Partial;
4381
4382
    // If we are providing an explicit specialization of a member variable
4383
    // template specialization, make a note of that.
4384
338
    if (PrevPartial && 
PrevPartial->getInstantiatedFromMember()65
)
4385
21
      PrevPartial->setMemberSpecialization();
4386
4387
338
    CheckTemplatePartialSpecialization(Partial);
4388
505
  } else {
4389
    // Create a new class template specialization declaration node for
4390
    // this explicit specialization or friend declaration.
4391
505
    Specialization = VarTemplateSpecializationDecl::Create(
4392
505
        Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4393
505
        VarTemplate, DI->getType(), DI, SC, Converted);
4394
505
    Specialization->setTemplateArgsInfo(TemplateArgs);
4395
4396
505
    if (!PrevDecl)
4397
452
      VarTemplate->AddSpecialization(Specialization, InsertPos);
4398
505
  }
4399
4400
  // C++ [temp.expl.spec]p6:
4401
  //   If a template, a member template or the member of a class template is
4402
  //   explicitly specialized then that specialization shall be declared
4403
  //   before the first use of that specialization that would cause an implicit
4404
  //   instantiation to take place, in every translation unit in which such a
4405
  //   use occurs; no diagnostic is required.
4406
843
  if (PrevDecl && 
PrevDecl->getPointOfInstantiation().isValid()118
) {
4407
6
    bool Okay = false;
4408
12
    for (Decl *Prev = PrevDecl; Prev; 
Prev = Prev->getPreviousDecl()6
) {
4409
      // Is there any previous explicit specialization declaration?
4410
6
      if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4411
0
        Okay = true;
4412
0
        break;
4413
0
      }
4414
6
    }
4415
4416
6
    if (!Okay) {
4417
6
      SourceRange Range(TemplateNameLoc, RAngleLoc);
4418
6
      Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4419
6
          << Name << Range;
4420
4421
6
      Diag(PrevDecl->getPointOfInstantiation(),
4422
6
           diag::note_instantiation_required_here)
4423
6
          << (PrevDecl->getTemplateSpecializationKind() !=
4424
6
              TSK_ImplicitInstantiation);
4425
6
      return true;
4426
6
    }
4427
837
  }
4428
4429
837
  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4430
837
  Specialization->setLexicalDeclContext(CurContext);
4431
4432
  // Add the specialization into its lexical context, so that it can
4433
  // be seen when iterating through the list of declarations in that
4434
  // context. However, specializations are not found by name lookup.
4435
837
  CurContext->addDecl(Specialization);
4436
4437
  // Note that this is an explicit specialization.
4438
837
  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4439
4440
837
  if (PrevDecl) {
4441
    // Check that this isn't a redefinition of this specialization,
4442
    // merging with previous declarations.
4443
112
    LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4444
112
                          forRedeclarationInCurContext());
4445
112
    PrevSpec.addDecl(PrevDecl);
4446
112
    D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4447
725
  } else if (Specialization->isStaticDataMember() &&
4448
313
             Specialization->isOutOfLine()) {
4449
148
    Specialization->setAccess(VarTemplate->getAccess());
4450
148
  }
4451
4452
837
  return Specialization;
4453
837
}
4454
4455
namespace {
4456
/// A partial specialization whose template arguments have matched
4457
/// a given template-id.
4458
struct PartialSpecMatchResult {
4459
  VarTemplatePartialSpecializationDecl *Partial;
4460
  TemplateArgumentList *Args;
4461
};
4462
} // end anonymous namespace
4463
4464
DeclResult
4465
Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4466
                         SourceLocation TemplateNameLoc,
4467
3.46k
                         const TemplateArgumentListInfo &TemplateArgs) {
4468
3.46k
  assert(Template && "A variable template id without template?");
4469
4470
  // Check that the template argument list is well-formed for this template.
4471
3.46k
  SmallVector<TemplateArgument, 4> Converted;
4472
3.46k
  if (CheckTemplateArgumentList(
4473
3.46k
          Template, TemplateNameLoc,
4474
3.46k
          const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4475
3.46k
          Converted, /*UpdateArgsWithConversion=*/true))
4476
14
    return true;
4477
4478
  // Produce a placeholder value if the specialization is dependent.
4479
3.45k
  bool InstantiationDependent = false;
4480
3.45k
  if (Template->getDeclContext()->isDependentContext() ||
4481
3.44k
      TemplateSpecializationType::anyDependentTemplateArguments(
4482
3.44k
          TemplateArgs, InstantiationDependent))
4483
734
    return DeclResult();
4484
4485
  // Find the variable template specialization declaration that
4486
  // corresponds to these arguments.
4487
2.72k
  void *InsertPos = nullptr;
4488
2.72k
  if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
4489
776
          Converted, InsertPos)) {
4490
776
    checkSpecializationVisibility(TemplateNameLoc, Spec);
4491
    // If we already have a variable template specialization, return it.
4492
776
    return Spec;
4493
776
  }
4494
4495
  // This is the first time we have referenced this variable template
4496
  // specialization. Create the canonical declaration and add it to
4497
  // the set of specializations, based on the closest partial specialization
4498
  // that it represents. That is,
4499
1.94k
  VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4500
1.94k
  TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4501
1.94k
                                       Converted);
4502
1.94k
  TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4503
1.94k
  bool AmbiguousPartialSpec = false;
4504
1.94k
  typedef PartialSpecMatchResult MatchResult;
4505
1.94k
  SmallVector<MatchResult, 4> Matched;
4506
1.94k
  SourceLocation PointOfInstantiation = TemplateNameLoc;
4507
1.94k
  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4508
1.94k
                                            /*ForTakingAddress=*/false);
4509
4510
  // 1. Attempt to find the closest partial specialization that this
4511
  // specializes, if any.
4512
  // TODO: Unify with InstantiateClassTemplateSpecialization()?
4513
  //       Perhaps better after unification of DeduceTemplateArguments() and
4514
  //       getMoreSpecializedPartialSpecialization().
4515
1.94k
  SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4516
1.94k
  Template->getPartialSpecializations(PartialSpecs);
4517
4518
2.82k
  for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I882
) {
4519
882
    VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4520
882
    TemplateDeductionInfo Info(FailedCandidates.getLocation());
4521
4522
882
    if (TemplateDeductionResult Result =
4523
149
            DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4524
      // Store the failed-deduction information for use in diagnostics, later.
4525
      // TODO: Actually use the failed-deduction info?
4526
149
      FailedCandidates.addCandidate().set(
4527
149
          DeclAccessPair::make(Template, AS_public), Partial,
4528
149
          MakeDeductionFailureInfo(Context, Result, Info));
4529
149
      (void)Result;
4530
733
    } else {
4531
733
      Matched.push_back(PartialSpecMatchResult());
4532
733
      Matched.back().Partial = Partial;
4533
733
      Matched.back().Args = Info.take();
4534
733
    }
4535
882
  }
4536
4537
1.94k
  if (Matched.size() >= 1) {
4538
721
    SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4539
721
    if (Matched.size() == 1) {
4540
      //   -- If exactly one matching specialization is found, the
4541
      //      instantiation is generated from that specialization.
4542
      // We don't need to do anything for this.
4543
12
    } else {
4544
      //   -- If more than one matching specialization is found, the
4545
      //      partial order rules (14.5.4.2) are used to determine
4546
      //      whether one of the specializations is more specialized
4547
      //      than the others. If none of the specializations is more
4548
      //      specialized than all of the other matching
4549
      //      specializations, then the use of the variable template is
4550
      //      ambiguous and the program is ill-formed.
4551
12
      for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4552
12
                                                 PEnd = Matched.end();
4553
24
           P != PEnd; 
++P12
) {
4554
12
        if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4555
12
                                                    PointOfInstantiation) ==
4556
12
            P->Partial)
4557
8
          Best = P;
4558
12
      }
4559
4560
      // Determine if the best partial specialization is more specialized than
4561
      // the others.
4562
12
      for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4563
12
                                                 PEnd = Matched.end();
4564
33
           P != PEnd; 
++P21
) {
4565
24
        if (P != Best && getMoreSpecializedPartialSpecialization(
4566
12
                             P->Partial, Best->Partial,
4567
3
                             PointOfInstantiation) != Best->Partial) {
4568
3
          AmbiguousPartialSpec = true;
4569
3
          break;
4570
3
        }
4571
24
      }
4572
12
    }
4573
4574
    // Instantiate using the best variable template partial specialization.
4575
721
    InstantiationPattern = Best->Partial;
4576
721
    InstantiationArgs = Best->Args;
4577
1.22k
  } else {
4578
    //   -- If no match is found, the instantiation is generated
4579
    //      from the primary template.
4580
    // InstantiationPattern = Template->getTemplatedDecl();
4581
1.22k
  }
4582
4583
  // 2. Create the canonical declaration.
4584
  // Note that we do not instantiate a definition until we see an odr-use
4585
  // in DoMarkVarDeclReferenced().
4586
  // FIXME: LateAttrs et al.?
4587
1.94k
  VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4588
1.94k
      Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4589
1.94k
      Converted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4590
1.94k
  if (!Decl)
4591
0
    return true;
4592
4593
1.94k
  if (AmbiguousPartialSpec) {
4594
    // Partial ordering did not produce a clear winner. Complain.
4595
3
    Decl->setInvalidDecl();
4596
3
    Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4597
3
        << Decl;
4598
4599
    // Print the matching partial specializations.
4600
3
    for (MatchResult P : Matched)
4601
6
      Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4602
6
          << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4603
6
                                             *P.Args);
4604
3
    return true;
4605
3
  }
4606
4607
1.94k
  if (VarTemplatePartialSpecializationDecl *D =
4608
718
          dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4609
718
    Decl->setInstantiationOf(D, InstantiationArgs);
4610
4611
1.94k
  checkSpecializationVisibility(TemplateNameLoc, Decl);
4612
4613
1.94k
  assert(Decl && "No variable template specialization?");
4614
1.94k
  return Decl;
4615
1.94k
}
4616
4617
ExprResult
4618
Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4619
                         const DeclarationNameInfo &NameInfo,
4620
                         VarTemplateDecl *Template, SourceLocation TemplateLoc,
4621
2.92k
                         const TemplateArgumentListInfo *TemplateArgs) {
4622
4623
2.92k
  DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4624
2.92k
                                       *TemplateArgs);
4625
2.92k
  if (Decl.isInvalid())
4626
16
    return ExprError();
4627
4628
2.90k
  if (!Decl.get())
4629
734
    return ExprResult();
4630
4631
2.17k
  VarDecl *Var = cast<VarDecl>(Decl.get());
4632
2.17k
  if (!Var->getTemplateSpecializationKind())
4633
1.49k
    Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4634
1.49k
                                       NameInfo.getLoc());
4635
4636
  // Build an ordinary singleton decl ref.
4637
2.17k
  return BuildDeclarationNameExpr(SS, NameInfo, Var,
4638
2.17k
                                  /*FoundD=*/nullptr, TemplateArgs);
4639
2.17k
}
4640
4641
void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4642
87
                                            SourceLocation Loc) {
4643
87
  Diag(Loc, diag::err_template_missing_args)
4644
87
    << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4645
87
  if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4646
87
    Diag(TD->getLocation(), diag::note_template_decl_here)
4647
87
      << TD->getTemplateParameters()->getSourceRange();
4648
87
  }
4649
87
}
4650
4651
ExprResult
4652
Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4653
                             SourceLocation TemplateKWLoc,
4654
                             const DeclarationNameInfo &ConceptNameInfo,
4655
                             NamedDecl *FoundDecl,
4656
                             ConceptDecl *NamedConcept,
4657
817
                             const TemplateArgumentListInfo *TemplateArgs) {
4658
817
  assert(NamedConcept && "A concept template id without a template?");
4659
4660
817
  llvm::SmallVector<TemplateArgument, 4> Converted;
4661
817
  if (CheckTemplateArgumentList(NamedConcept, ConceptNameInfo.getLoc(),
4662
817
                           const_cast<TemplateArgumentListInfo&>(*TemplateArgs),
4663
817
                                /*PartialTemplateArgs=*/false, Converted,
4664
817
                                /*UpdateArgsWithConversion=*/false))
4665
1
    return ExprError();
4666
4667
816
  ConstraintSatisfaction Satisfaction;
4668
816
  bool AreArgsDependent = false;
4669
988
  for (TemplateArgument &Arg : Converted) {
4670
988
    if (Arg.isDependent()) {
4671
305
      AreArgsDependent = true;
4672
305
      break;
4673
305
    }
4674
988
  }
4675
816
  if (!AreArgsDependent &&
4676
511
      CheckConstraintSatisfaction(NamedConcept,
4677
511
                                  {NamedConcept->getConstraintExpr()},
4678
511
                                  Converted,
4679
23
                                  SourceRange(SS.isSet() ? SS.getBeginLoc() :
4680
488
                                                       ConceptNameInfo.getLoc(),
4681
511
                                                TemplateArgs->getRAngleLoc()),
4682
511
                                    Satisfaction))
4683
4
      return ExprError();
4684
4685
812
  return ConceptSpecializationExpr::Create(Context,
4686
766
      SS.isSet() ? 
SS.getWithLocInContext(Context)46
: NestedNameSpecifierLoc{},
4687
812
      TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4688
812
      ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), Converted,
4689
507
      AreArgsDependent ? 
nullptr305
: &Satisfaction);
4690
812
}
4691
4692
ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4693
                                     SourceLocation TemplateKWLoc,
4694
                                     LookupResult &R,
4695
                                     bool RequiresADL,
4696
350k
                                 const TemplateArgumentListInfo *TemplateArgs) {
4697
  // FIXME: Can we do any checking at this point? I guess we could check the
4698
  // template arguments that we have against the template name, if the template
4699
  // name refers to a single template. That's not a terribly common case,
4700
  // though.
4701
  // foo<int> could identify a single function unambiguously
4702
  // This approach does NOT work, since f<int>(1);
4703
  // gets resolved prior to resorting to overload resolution
4704
  // i.e., template<class T> void f(double);
4705
  //       vs template<class T, class U> void f(U);
4706
4707
  // These should be filtered out by our callers.
4708
350k
  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4709
4710
  // Non-function templates require a template argument list.
4711
350k
  if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4712
3.16k
    if (!TemplateArgs && 
!isa<FunctionTemplateDecl>(TD)9
) {
4713
9
      diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4714
9
      return ExprError();
4715
9
    }
4716
350k
  }
4717
4718
  // In C++1y, check variable template ids.
4719
350k
  if (R.getAsSingle<VarTemplateDecl>()) {
4720
2.92k
    ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
4721
2.92k
                                        R.getAsSingle<VarTemplateDecl>(),
4722
2.92k
                                        TemplateKWLoc, TemplateArgs);
4723
2.92k
    if (Res.isInvalid() || 
Res.isUsable()2.90k
)
4724
2.19k
      return Res;
4725
    // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
4726
2.92k
  }
4727
4728
348k
  if (R.getAsSingle<ConceptDecl>()) {
4729
229
    return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4730
229
                                  R.getFoundDecl(),
4731
229
                                  R.getAsSingle<ConceptDecl>(), TemplateArgs);
4732
229
  }
4733
4734
  // We don't want lookup warnings at this point.
4735
348k
  R.suppressDiagnostics();
4736
4737
348k
  UnresolvedLookupExpr *ULE
4738
348k
    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4739
348k
                                   SS.getWithLocInContext(Context),
4740
348k
                                   TemplateKWLoc,
4741
348k
                                   R.getLookupNameInfo(),
4742
348k
                                   RequiresADL, TemplateArgs,
4743
348k
                                   R.begin(), R.end());
4744
4745
348k
  return ULE;
4746
348k
}
4747
4748
// We actually only call this from template instantiation.
4749
ExprResult
4750
Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4751
                                   SourceLocation TemplateKWLoc,
4752
                                   const DeclarationNameInfo &NameInfo,
4753
43.4k
                             const TemplateArgumentListInfo *TemplateArgs) {
4754
4755
43.4k
  assert(TemplateArgs || TemplateKWLoc.isValid());
4756
43.4k
  DeclContext *DC;
4757
43.4k
  if (!(DC = computeDeclContext(SS, false)) ||
4758
19.3k
      DC->isDependentContext() ||
4759
19.3k
      RequireCompleteDeclContext(SS, DC))
4760
24.0k
    return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4761
4762
19.3k
  bool MemberOfUnknownSpecialization;
4763
19.3k
  LookupResult R(*this, NameInfo, LookupOrdinaryName);
4764
19.3k
  if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4765
19.3k
                         /*Entering*/false, MemberOfUnknownSpecialization,
4766
19.3k
                         TemplateKWLoc))
4767
3
    return ExprError();
4768
4769
19.3k
  if (R.isAmbiguous())
4770
0
    return ExprError();
4771
4772
19.3k
  if (R.empty()) {
4773
0
    Diag(NameInfo.getLoc(), diag::err_no_member)
4774
0
      << NameInfo.getName() << DC << SS.getRange();
4775
0
    return ExprError();
4776
0
  }
4777
4778
19.3k
  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4779
1
    Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4780
1
      << SS.getScopeRep()
4781
1
      << NameInfo.getName().getAsString() << SS.getRange();
4782
1
    Diag(Temp->getLocation(), diag::note_referenced_class_template);
4783
1
    return ExprError();
4784
1
  }
4785
4786
19.3k
  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4787
19.3k
}
4788
4789
/// Form a template name from a name that is syntactically required to name a
4790
/// template, either due to use of the 'template' keyword or because a name in
4791
/// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
4792
///
4793
/// This action forms a template name given the name of the template and its
4794
/// optional scope specifier. This is used when the 'template' keyword is used
4795
/// or when the parsing context unambiguously treats a following '<' as
4796
/// introducing a template argument list. Note that this may produce a
4797
/// non-dependent template name if we can perform the lookup now and identify
4798
/// the named template.
4799
///
4800
/// For example, given "x.MetaFun::template apply", the scope specifier
4801
/// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
4802
/// of the "template" keyword, and "apply" is the \p Name.
4803
TemplateNameKind Sema::ActOnTemplateName(Scope *S,
4804
                                         CXXScopeSpec &SS,
4805
                                         SourceLocation TemplateKWLoc,
4806
                                         const UnqualifiedId &Name,
4807
                                         ParsedType ObjectType,
4808
                                         bool EnteringContext,
4809
                                         TemplateTy &Result,
4810
160k
                                         bool AllowInjectedClassName) {
4811
160k
  if (TemplateKWLoc.isValid() && 
S160k
&&
!S->getTemplateParamParent()24.1k
)
4812
200
    Diag(TemplateKWLoc,
4813
200
         getLangOpts().CPlusPlus11 ?
4814
165
           diag::warn_cxx98_compat_template_outside_of_template :
4815
35
           diag::ext_template_outside_of_template)
4816
200
      << FixItHint::CreateRemoval(TemplateKWLoc);
4817
4818
160k
  if (SS.isInvalid())
4819
9
    return TNK_Non_template;
4820
4821
  // Figure out where isTemplateName is going to look.
4822
160k
  DeclContext *LookupCtx = nullptr;
4823
160k
  if (SS.isNotEmpty())
4824
158k
    LookupCtx = computeDeclContext(SS, EnteringContext);
4825
2.02k
  else if (ObjectType)
4826
2.02k
    LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4827
4828
  // C++0x [temp.names]p5:
4829
  //   If a name prefixed by the keyword template is not the name of
4830
  //   a template, the program is ill-formed. [Note: the keyword
4831
  //   template may not be applied to non-template members of class
4832
  //   templates. -end note ] [ Note: as is the case with the
4833
  //   typename prefix, the template prefix is allowed in cases
4834
  //   where it is not strictly necessary; i.e., when the
4835
  //   nested-name-specifier or the expression on the left of the ->
4836
  //   or . is not dependent on a template-parameter, or the use
4837
  //   does not appear in the scope of a template. -end note]
4838
  //
4839
  // Note: C++03 was more strict here, because it banned the use of
4840
  // the "template" keyword prior to a template-name that was not a
4841
  // dependent name. C++ DR468 relaxed this requirement (the
4842
  // "template" keyword is now permitted). We follow the C++0x
4843
  // rules, even in C++03 mode with a warning, retroactively applying the DR.
4844
160k
  bool MemberOfUnknownSpecialization;
4845
160k
  TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4846
160k
                                        ObjectType, EnteringContext, Result,
4847
160k
                                        MemberOfUnknownSpecialization);
4848
160k
  if (TNK != TNK_Non_template) {
4849
    // We resolved this to a (non-dependent) template name. Return it.
4850
50.9k
    auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4851
50.9k
    if (!AllowInjectedClassName && 
SS.isNotEmpty()46.8k
&&
LookupRD46.8k
&&
4852
46.8k
        Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4853
46.8k
        Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4854
      // C++14 [class.qual]p2:
4855
      //   In a lookup in which function names are not ignored and the
4856
      //   nested-name-specifier nominates a class C, if the name specified
4857
      //   [...] is the injected-class-name of C, [...] the name is instead
4858
      //   considered to name the constructor
4859
      //
4860
      // We don't get here if naming the constructor would be valid, so we
4861
      // just reject immediately and recover by treating the
4862
      // injected-class-name as naming the template.
4863
22
      Diag(Name.getBeginLoc(),
4864
22
           diag::ext_out_of_line_qualified_id_type_names_constructor)
4865
22
          << Name.Identifier
4866
22
          << 0 /*injected-class-name used as template name*/
4867
22
          << TemplateKWLoc.isValid();
4868
22
    }
4869
50.9k
    return TNK;
4870
50.9k
  }
4871
4872
109k
  if (!MemberOfUnknownSpecialization) {
4873
    // Didn't find a template name, and the lookup wasn't dependent.
4874
    // Do the lookup again to determine if this is a "nothing found" case or
4875
    // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4876
    // need to do this.
4877
13.5k
    DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4878
13.5k
    LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4879
13.5k
                   LookupOrdinaryName);
4880
13.5k
    bool MOUS;
4881
    // Tell LookupTemplateName that we require a template so that it diagnoses
4882
    // cases where it finds a non-template.
4883
13.5k
    RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4884
13.5k
                                   ? RequiredTemplateKind(TemplateKWLoc)
4885
9
                                   : TemplateNameIsRequired;
4886
13.5k
    if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
4887
13.5k
                            RTK, nullptr, /*AllowTypoCorrection=*/false) &&
4888
13.5k
        !R.isAmbiguous()) {
4889
13.5k
      if (LookupCtx)
4890
13.5k
        Diag(Name.getBeginLoc(), diag::err_no_member)
4891
13.5k
            << DNI.getName() << LookupCtx << SS.getRange();
4892
1
      else
4893
1
        Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4894