Coverage Report

Created: 2019-07-24 05:18

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