Coverage Report

Created: 2022-05-14 11:35

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