Coverage Report

Created: 2022-01-22 13:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaTemplateInstantiate.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
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 C++ template instantiation.
9
//
10
//===----------------------------------------------------------------------===/
11
12
#include "TreeTransform.h"
13
#include "clang/AST/ASTConsumer.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTLambda.h"
16
#include "clang/AST/ASTMutationListener.h"
17
#include "clang/AST/DeclTemplate.h"
18
#include "clang/AST/Expr.h"
19
#include "clang/AST/PrettyDeclStackTrace.h"
20
#include "clang/AST/TypeVisitor.h"
21
#include "clang/Basic/LangOptions.h"
22
#include "clang/Basic/Stack.h"
23
#include "clang/Basic/TargetInfo.h"
24
#include "clang/Sema/DeclSpec.h"
25
#include "clang/Sema/Initialization.h"
26
#include "clang/Sema/Lookup.h"
27
#include "clang/Sema/SemaConcept.h"
28
#include "clang/Sema/SemaInternal.h"
29
#include "clang/Sema/Template.h"
30
#include "clang/Sema/TemplateDeduction.h"
31
#include "clang/Sema/TemplateInstCallback.h"
32
#include "llvm/Support/TimeProfiler.h"
33
34
using namespace clang;
35
using namespace sema;
36
37
//===----------------------------------------------------------------------===/
38
// Template Instantiation Support
39
//===----------------------------------------------------------------------===/
40
41
/// Retrieve the template argument list(s) that should be used to
42
/// instantiate the definition of the given declaration.
43
///
44
/// \param D the declaration for which we are computing template instantiation
45
/// arguments.
46
///
47
/// \param Innermost if non-NULL, the innermost template argument list.
48
///
49
/// \param RelativeToPrimary true if we should get the template
50
/// arguments relative to the primary template, even when we're
51
/// dealing with a specialization. This is only relevant for function
52
/// template specializations.
53
///
54
/// \param Pattern If non-NULL, indicates the pattern from which we will be
55
/// instantiating the definition of the given declaration, \p D. This is
56
/// used to determine the proper set of template instantiation arguments for
57
/// friend function template specializations.
58
MultiLevelTemplateArgumentList
59
Sema::getTemplateInstantiationArgs(NamedDecl *D,
60
                                   const TemplateArgumentList *Innermost,
61
                                   bool RelativeToPrimary,
62
1.89M
                                   const FunctionDecl *Pattern) {
63
  // Accumulate the set of template argument lists in this structure.
64
1.89M
  MultiLevelTemplateArgumentList Result;
65
66
1.89M
  if (Innermost)
67
0
    Result.addOuterTemplateArguments(Innermost);
68
69
1.89M
  DeclContext *Ctx = dyn_cast<DeclContext>(D);
70
1.89M
  if (!Ctx) {
71
890k
    Ctx = D->getDeclContext();
72
73
    // Add template arguments from a variable template instantiation. For a
74
    // class-scope explicit specialization, there are no template arguments
75
    // at this level, but there may be enclosing template arguments.
76
890k
    VarTemplateSpecializationDecl *Spec =
77
890k
        dyn_cast<VarTemplateSpecializationDecl>(D);
78
890k
    if (Spec && 
!Spec->isClassScopeExplicitSpecialization()2.41k
) {
79
      // We're done when we hit an explicit specialization.
80
2.39k
      if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
81
2.39k
          
!isa<VarTemplatePartialSpecializationDecl>(Spec)0
)
82
0
        return Result;
83
84
2.39k
      Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
85
86
      // If this variable template specialization was instantiated from a
87
      // specialized member that is a variable template, we're done.
88
2.39k
      assert(Spec->getSpecializedTemplate() && "No variable template?");
89
0
      llvm::PointerUnion<VarTemplateDecl*,
90
2.39k
                         VarTemplatePartialSpecializationDecl*> Specialized
91
2.39k
                             = Spec->getSpecializedTemplateOrPartial();
92
2.39k
      if (VarTemplatePartialSpecializationDecl *Partial =
93
2.39k
              Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
94
551
        if (Partial->isMemberSpecialization())
95
3
          return Result;
96
1.84k
      } else {
97
1.84k
        VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
98
1.84k
        if (Tmpl->isMemberSpecialization())
99
11
          return Result;
100
1.84k
      }
101
2.39k
    }
102
103
    // If we have a template template parameter with translation unit context,
104
    // then we're performing substitution into a default template argument of
105
    // this template template parameter before we've constructed the template
106
    // that will own this template template parameter. In this case, we
107
    // use empty template parameter lists for all of the outer templates
108
    // to avoid performing any substitutions.
109
890k
    if (Ctx->isTranslationUnit()) {
110
739
      if (TemplateTemplateParmDecl *TTP
111
739
                                      = dyn_cast<TemplateTemplateParmDecl>(D)) {
112
0
        for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
113
0
          Result.addOuterTemplateArguments(None);
114
0
        return Result;
115
0
      }
116
739
    }
117
890k
  }
118
119
4.00M
  
while (1.89M
!Ctx->isFileContext()) {
120
    // Add template arguments from a class template instantiation.
121
2.11M
    ClassTemplateSpecializationDecl *Spec
122
2.11M
          = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
123
2.11M
    if (Spec && 
!Spec->isClassScopeExplicitSpecialization()1.89M
) {
124
      // We're done when we hit an explicit specialization.
125
1.89M
      if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
126
1.89M
          
!isa<ClassTemplatePartialSpecializationDecl>(Spec)177
)
127
177
        break;
128
129
1.89M
      Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
130
131
      // If this class template specialization was instantiated from a
132
      // specialized member that is a class template, we're done.
133
1.89M
      assert(Spec->getSpecializedTemplate() && "No class template?");
134
1.89M
      if (Spec->getSpecializedTemplate()->isMemberSpecialization())
135
48
        break;
136
1.89M
    }
137
    // Add template arguments from a function template specialization.
138
219k
    else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
139
200k
      if (!RelativeToPrimary &&
140
200k
          Function->getTemplateSpecializationKindForInstantiation() ==
141
185k
              TSK_ExplicitSpecialization)
142
0
        break;
143
144
200k
      if (!RelativeToPrimary && Function->getTemplateSpecializationKind() ==
145
185k
                                    TSK_ExplicitSpecialization) {
146
        // This is an implicit instantiation of an explicit specialization. We
147
        // don't get any template arguments from this function but might get
148
        // some from an enclosing template.
149
200k
      } else if (const TemplateArgumentList *TemplateArgs
150
200k
            = Function->getTemplateSpecializationArgs()) {
151
        // Add the template arguments for this specialization.
152
96.3k
        Result.addOuterTemplateArguments(TemplateArgs);
153
154
        // If this function was instantiated from a specialized member that is
155
        // a function template, we're done.
156
96.3k
        assert(Function->getPrimaryTemplate() && "No function template?");
157
96.3k
        if (Function->getPrimaryTemplate()->isMemberSpecialization())
158
36
          break;
159
160
        // If this function is a generic lambda specialization, we are done.
161
96.3k
        if (isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
162
2.57k
          break;
163
164
103k
      } else if (Function->getDescribedFunctionTemplate()) {
165
13
        assert(Result.getNumSubstitutedLevels() == 0 &&
166
13
               "Outer template not instantiated?");
167
13
      }
168
169
      // If this is a friend declaration and it declares an entity at
170
      // namespace scope, take arguments from its lexical parent
171
      // instead of its semantic parent, unless of course the pattern we're
172
      // instantiating actually comes from the file's context!
173
197k
      if (Function->getFriendObjectKind() &&
174
197k
          
Function->getDeclContext()->isFileContext()395
&&
175
197k
          
(378
!Pattern378
||
!Pattern->getLexicalDeclContext()->isFileContext()376
)) {
176
349
        Ctx = Function->getLexicalDeclContext();
177
349
        RelativeToPrimary = false;
178
349
        continue;
179
349
      }
180
197k
    } else 
if (CXXRecordDecl *19.7k
Rec19.7k
= dyn_cast<CXXRecordDecl>(Ctx)) {
181
16.9k
      if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
182
0
        assert(Result.getNumSubstitutedLevels() == 0 &&
183
0
               "Outer template not instantiated?");
184
0
        if (ClassTemplate->isMemberSpecialization())
185
0
          break;
186
0
      }
187
16.9k
    }
188
189
2.11M
    Ctx = Ctx->getParent();
190
2.11M
    RelativeToPrimary = false;
191
2.11M
  }
192
193
1.89M
  return Result;
194
1.89M
}
195
196
14.2M
bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
197
14.2M
  switch (Kind) {
198
6.37M
  case TemplateInstantiation:
199
6.38M
  case ExceptionSpecInstantiation:
200
7.64M
  case DefaultTemplateArgumentInstantiation:
201
7.66M
  case DefaultFunctionArgumentInstantiation:
202
8.17M
  case ExplicitTemplateArgumentSubstitution:
203
9.81M
  case DeducedTemplateArgumentSubstitution:
204
10.8M
  case PriorTemplateArgumentSubstitution:
205
10.8M
  case ConstraintsCheck:
206
10.8M
  case NestedRequirementConstraintsCheck:
207
10.8M
    return true;
208
209
332
  case RequirementInstantiation:
210
1.96M
  case DefaultTemplateArgumentChecking:
211
2.82M
  case DeclaringSpecialMember:
212
2.82M
  case DeclaringImplicitEqualityComparison:
213
2.98M
  case DefiningSynthesizedFunction:
214
3.35M
  case ExceptionSpecEvaluation:
215
3.36M
  case ConstraintSubstitution:
216
3.36M
  case ParameterMappingSubstitution:
217
3.36M
  case ConstraintNormalization:
218
3.36M
  case RewritingOperatorAsSpaceship:
219
3.36M
  case InitializingStructuredBinding:
220
3.36M
  case MarkingClassDllexported:
221
3.36M
    return false;
222
223
  // This function should never be called when Kind's value is Memoization.
224
0
  case Memoization:
225
0
    break;
226
14.2M
  }
227
228
0
  llvm_unreachable("Invalid SynthesisKind!");
229
0
}
230
231
Sema::InstantiatingTemplate::InstantiatingTemplate(
232
    Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
233
    SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
234
    Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
235
    sema::TemplateDeductionInfo *DeductionInfo)
236
6.41M
    : SemaRef(SemaRef) {
237
  // Don't allow further instantiation if a fatal error and an uncompilable
238
  // error have occurred. Any diagnostics we might have raised will not be
239
  // visible, and we do not need to construct a correct AST.
240
6.41M
  if (SemaRef.Diags.hasFatalErrorOccurred() &&
241
6.41M
      
SemaRef.hasUncompilableErrorOccurred()3.85k
) {
242
3.85k
    Invalid = true;
243
3.85k
    return;
244
3.85k
  }
245
6.40M
  Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
246
6.40M
  if (!Invalid) {
247
6.40M
    CodeSynthesisContext Inst;
248
6.40M
    Inst.Kind = Kind;
249
6.40M
    Inst.PointOfInstantiation = PointOfInstantiation;
250
6.40M
    Inst.Entity = Entity;
251
6.40M
    Inst.Template = Template;
252
6.40M
    Inst.TemplateArgs = TemplateArgs.data();
253
6.40M
    Inst.NumTemplateArgs = TemplateArgs.size();
254
6.40M
    Inst.DeductionInfo = DeductionInfo;
255
6.40M
    Inst.InstantiationRange = InstantiationRange;
256
6.40M
    SemaRef.pushCodeSynthesisContext(Inst);
257
258
6.40M
    AlreadyInstantiating = !Inst.Entity ? 
false346
:
259
6.40M
        !SemaRef.InstantiatingSpecializations
260
6.40M
             .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
261
6.40M
             .second;
262
6.40M
    atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
263
6.40M
  }
264
6.40M
}
265
266
Sema::InstantiatingTemplate::InstantiatingTemplate(
267
    Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
268
    SourceRange InstantiationRange)
269
    : InstantiatingTemplate(SemaRef,
270
                            CodeSynthesisContext::TemplateInstantiation,
271
3.07M
                            PointOfInstantiation, InstantiationRange, Entity) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Decl*, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Decl*, clang::SourceRange)
Line
Count
Source
271
3.07M
                            PointOfInstantiation, InstantiationRange, Entity) {}
272
273
Sema::InstantiatingTemplate::InstantiatingTemplate(
274
    Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
275
    ExceptionSpecification, SourceRange InstantiationRange)
276
    : InstantiatingTemplate(
277
          SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
278
6.09k
          PointOfInstantiation, InstantiationRange, Entity) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::FunctionDecl*, clang::Sema::InstantiatingTemplate::ExceptionSpecification, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::FunctionDecl*, clang::Sema::InstantiatingTemplate::ExceptionSpecification, clang::SourceRange)
Line
Count
Source
278
6.09k
          PointOfInstantiation, InstantiationRange, Entity) {}
279
280
Sema::InstantiatingTemplate::InstantiatingTemplate(
281
    Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
282
    TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
283
    SourceRange InstantiationRange)
284
    : InstantiatingTemplate(
285
          SemaRef,
286
          CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
287
          PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
288
629k
          Template, TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, llvm::PointerUnion<clang::TemplateTypeParmDecl*, clang::NonTypeTemplateParmDecl*, clang::TemplateTemplateParmDecl*>, clang::TemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, llvm::PointerUnion<clang::TemplateTypeParmDecl*, clang::NonTypeTemplateParmDecl*, clang::TemplateTemplateParmDecl*>, clang::TemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
288
629k
          Template, TemplateArgs) {}
289
290
Sema::InstantiatingTemplate::InstantiatingTemplate(
291
    Sema &SemaRef, SourceLocation PointOfInstantiation,
292
    FunctionTemplateDecl *FunctionTemplate,
293
    ArrayRef<TemplateArgument> TemplateArgs,
294
    CodeSynthesisContext::SynthesisKind Kind,
295
    sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
296
    : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
297
                            InstantiationRange, FunctionTemplate, nullptr,
298
793k
                            TemplateArgs, &DeductionInfo) {
299
793k
  assert(
300
793k
    Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
301
793k
    Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
302
793k
}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::FunctionTemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::Sema::CodeSynthesisContext::SynthesisKind, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::FunctionTemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::Sema::CodeSynthesisContext::SynthesisKind, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
298
793k
                            TemplateArgs, &DeductionInfo) {
299
793k
  assert(
300
793k
    Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
301
793k
    Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
302
793k
}
303
304
Sema::InstantiatingTemplate::InstantiatingTemplate(
305
    Sema &SemaRef, SourceLocation PointOfInstantiation,
306
    TemplateDecl *Template,
307
    ArrayRef<TemplateArgument> TemplateArgs,
308
    sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
309
    : InstantiatingTemplate(
310
          SemaRef,
311
          CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
312
          PointOfInstantiation, InstantiationRange, Template, nullptr,
313
156k
          TemplateArgs, &DeductionInfo) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::TemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::TemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
313
156k
          TemplateArgs, &DeductionInfo) {}
314
315
Sema::InstantiatingTemplate::InstantiatingTemplate(
316
    Sema &SemaRef, SourceLocation PointOfInstantiation,
317
    ClassTemplatePartialSpecializationDecl *PartialSpec,
318
    ArrayRef<TemplateArgument> TemplateArgs,
319
    sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
320
    : InstantiatingTemplate(
321
          SemaRef,
322
          CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
323
          PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
324
239k
          TemplateArgs, &DeductionInfo) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::ClassTemplatePartialSpecializationDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::ClassTemplatePartialSpecializationDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
324
239k
          TemplateArgs, &DeductionInfo) {}
325
326
Sema::InstantiatingTemplate::InstantiatingTemplate(
327
    Sema &SemaRef, SourceLocation PointOfInstantiation,
328
    VarTemplatePartialSpecializationDecl *PartialSpec,
329
    ArrayRef<TemplateArgument> TemplateArgs,
330
    sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
331
    : InstantiatingTemplate(
332
          SemaRef,
333
          CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
334
          PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
335
894
          TemplateArgs, &DeductionInfo) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::VarTemplatePartialSpecializationDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::VarTemplatePartialSpecializationDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
335
894
          TemplateArgs, &DeductionInfo) {}
336
337
Sema::InstantiatingTemplate::InstantiatingTemplate(
338
    Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
339
    ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
340
    : InstantiatingTemplate(
341
          SemaRef,
342
          CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
343
          PointOfInstantiation, InstantiationRange, Param, nullptr,
344
8.18k
          TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::ParmVarDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::ParmVarDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
344
8.18k
          TemplateArgs) {}
345
346
Sema::InstantiatingTemplate::InstantiatingTemplate(
347
    Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
348
    NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
349
    SourceRange InstantiationRange)
350
    : InstantiatingTemplate(
351
          SemaRef,
352
          CodeSynthesisContext::PriorTemplateArgumentSubstitution,
353
          PointOfInstantiation, InstantiationRange, Param, Template,
354
472k
          TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::NamedDecl*, clang::NonTypeTemplateParmDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::NamedDecl*, clang::NonTypeTemplateParmDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
354
472k
          TemplateArgs) {}
355
356
Sema::InstantiatingTemplate::InstantiatingTemplate(
357
    Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
358
    TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
359
    SourceRange InstantiationRange)
360
    : InstantiatingTemplate(
361
          SemaRef,
362
          CodeSynthesisContext::PriorTemplateArgumentSubstitution,
363
          PointOfInstantiation, InstantiationRange, Param, Template,
364
43.5k
          TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::NamedDecl*, clang::TemplateTemplateParmDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::NamedDecl*, clang::TemplateTemplateParmDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
364
43.5k
          TemplateArgs) {}
365
366
Sema::InstantiatingTemplate::InstantiatingTemplate(
367
    Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
368
    NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
369
    SourceRange InstantiationRange)
370
    : InstantiatingTemplate(
371
          SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
372
          PointOfInstantiation, InstantiationRange, Param, Template,
373
981k
          TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::TemplateDecl*, clang::NamedDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::TemplateDecl*, clang::NamedDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
373
981k
          TemplateArgs) {}
374
375
Sema::InstantiatingTemplate::InstantiatingTemplate(
376
    Sema &SemaRef, SourceLocation PointOfInstantiation,
377
    concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo,
378
    SourceRange InstantiationRange)
379
    : InstantiatingTemplate(
380
          SemaRef, CodeSynthesisContext::RequirementInstantiation,
381
          PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
382
166
          /*Template=*/nullptr, /*TemplateArgs=*/None, &DeductionInfo) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::concepts::Requirement*, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::concepts::Requirement*, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
382
166
          /*Template=*/nullptr, /*TemplateArgs=*/None, &DeductionInfo) {}
383
384
385
Sema::InstantiatingTemplate::InstantiatingTemplate(
386
    Sema &SemaRef, SourceLocation PointOfInstantiation,
387
    concepts::NestedRequirement *Req, ConstraintsCheck,
388
    SourceRange InstantiationRange)
389
    : InstantiatingTemplate(
390
          SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
391
          PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
392
24
          /*Template=*/nullptr, /*TemplateArgs=*/None) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::concepts::NestedRequirement*, clang::Sema::InstantiatingTemplate::ConstraintsCheck, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::concepts::NestedRequirement*, clang::Sema::InstantiatingTemplate::ConstraintsCheck, clang::SourceRange)
Line
Count
Source
392
24
          /*Template=*/nullptr, /*TemplateArgs=*/None) {}
393
394
395
Sema::InstantiatingTemplate::InstantiatingTemplate(
396
    Sema &SemaRef, SourceLocation PointOfInstantiation,
397
    ConstraintsCheck, NamedDecl *Template,
398
    ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
399
    : InstantiatingTemplate(
400
          SemaRef, CodeSynthesisContext::ConstraintsCheck,
401
          PointOfInstantiation, InstantiationRange, Template, nullptr,
402
1.12k
          TemplateArgs) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintsCheck, clang::NamedDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintsCheck, clang::NamedDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::SourceRange)
Line
Count
Source
402
1.12k
          TemplateArgs) {}
403
404
Sema::InstantiatingTemplate::InstantiatingTemplate(
405
    Sema &SemaRef, SourceLocation PointOfInstantiation,
406
    ConstraintSubstitution, NamedDecl *Template,
407
    sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
408
    : InstantiatingTemplate(
409
          SemaRef, CodeSynthesisContext::ConstraintSubstitution,
410
          PointOfInstantiation, InstantiationRange, Template, nullptr,
411
1.01k
          {}, &DeductionInfo) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintSubstitution, clang::NamedDecl*, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintSubstitution, clang::NamedDecl*, clang::sema::TemplateDeductionInfo&, clang::SourceRange)
Line
Count
Source
411
1.01k
          {}, &DeductionInfo) {}
412
413
Sema::InstantiatingTemplate::InstantiatingTemplate(
414
    Sema &SemaRef, SourceLocation PointOfInstantiation,
415
    ConstraintNormalization, NamedDecl *Template,
416
    SourceRange InstantiationRange)
417
    : InstantiatingTemplate(
418
          SemaRef, CodeSynthesisContext::ConstraintNormalization,
419
126
          PointOfInstantiation, InstantiationRange, Template) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintNormalization, clang::NamedDecl*, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ConstraintNormalization, clang::NamedDecl*, clang::SourceRange)
Line
Count
Source
419
126
          PointOfInstantiation, InstantiationRange, Template) {}
420
421
Sema::InstantiatingTemplate::InstantiatingTemplate(
422
    Sema &SemaRef, SourceLocation PointOfInstantiation,
423
    ParameterMappingSubstitution, NamedDecl *Template,
424
    SourceRange InstantiationRange)
425
    : InstantiatingTemplate(
426
          SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
427
139
          PointOfInstantiation, InstantiationRange, Template) {}
Unexecuted instantiation: clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ParameterMappingSubstitution, clang::NamedDecl*, clang::SourceRange)
clang::Sema::InstantiatingTemplate::InstantiatingTemplate(clang::Sema&, clang::SourceLocation, clang::Sema::InstantiatingTemplate::ParameterMappingSubstitution, clang::NamedDecl*, clang::SourceRange)
Line
Count
Source
427
139
          PointOfInstantiation, InstantiationRange, Template) {}
428
429
7.10M
void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
430
7.10M
  Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
431
7.10M
  InNonInstantiationSFINAEContext = false;
432
433
7.10M
  CodeSynthesisContexts.push_back(Ctx);
434
435
7.10M
  if (!Ctx.isInstantiationRecord())
436
1.68M
    ++NonInstantiationEntries;
437
438
  // Check to see if we're low on stack space. We can't do anything about this
439
  // from here, but we can at least warn the user.
440
7.10M
  if (isStackNearlyExhausted())
441
4
    warnStackExhausted(Ctx.PointOfInstantiation);
442
7.10M
}
443
444
7.10M
void Sema::popCodeSynthesisContext() {
445
7.10M
  auto &Active = CodeSynthesisContexts.back();
446
7.10M
  if (!Active.isInstantiationRecord()) {
447
1.68M
    assert(NonInstantiationEntries > 0);
448
0
    --NonInstantiationEntries;
449
1.68M
  }
450
451
0
  InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
452
453
  // Name lookup no longer looks in this template's defining module.
454
7.10M
  assert(CodeSynthesisContexts.size() >=
455
7.10M
             CodeSynthesisContextLookupModules.size() &&
456
7.10M
         "forgot to remove a lookup module for a template instantiation");
457
7.10M
  if (CodeSynthesisContexts.size() ==
458
7.10M
      CodeSynthesisContextLookupModules.size()) {
459
1.20k
    if (Module *M = CodeSynthesisContextLookupModules.back())
460
714
      LookupModulesCache.erase(M);
461
1.20k
    CodeSynthesisContextLookupModules.pop_back();
462
1.20k
  }
463
464
  // If we've left the code synthesis context for the current context stack,
465
  // stop remembering that we've emitted that stack.
466
7.10M
  if (CodeSynthesisContexts.size() ==
467
7.10M
      LastEmittedCodeSynthesisContextDepth)
468
5.94k
    LastEmittedCodeSynthesisContextDepth = 0;
469
470
7.10M
  CodeSynthesisContexts.pop_back();
471
7.10M
}
472
473
6.41M
void Sema::InstantiatingTemplate::Clear() {
474
6.41M
  if (!Invalid) {
475
6.40M
    if (!AlreadyInstantiating) {
476
6.39M
      auto &Active = SemaRef.CodeSynthesisContexts.back();
477
6.39M
      if (Active.Entity)
478
6.39M
        SemaRef.InstantiatingSpecializations.erase(
479
6.39M
            {Active.Entity->getCanonicalDecl(), Active.Kind});
480
6.39M
    }
481
482
6.40M
    atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
483
6.40M
                  SemaRef.CodeSynthesisContexts.back());
484
485
6.40M
    SemaRef.popCodeSynthesisContext();
486
6.40M
    Invalid = true;
487
6.40M
  }
488
6.41M
}
489
490
bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
491
                                        SourceLocation PointOfInstantiation,
492
6.40M
                                           SourceRange InstantiationRange) {
493
6.40M
  assert(SemaRef.NonInstantiationEntries <=
494
6.40M
         SemaRef.CodeSynthesisContexts.size());
495
6.40M
  if ((SemaRef.CodeSynthesisContexts.size() -
496
6.40M
          SemaRef.NonInstantiationEntries)
497
6.40M
        <= SemaRef.getLangOpts().InstantiationDepth)
498
6.40M
    return false;
499
500
12
  SemaRef.Diag(PointOfInstantiation,
501
12
               diag::err_template_recursion_depth_exceeded)
502
12
    << SemaRef.getLangOpts().InstantiationDepth
503
12
    << InstantiationRange;
504
12
  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
505
12
    << SemaRef.getLangOpts().InstantiationDepth;
506
12
  return true;
507
6.40M
}
508
509
/// Prints the current instantiation stack through a series of
510
/// notes.
511
5.97k
void Sema::PrintInstantiationStack() {
512
  // Determine which template instantiations to skip, if any.
513
5.97k
  unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
514
5.97k
  unsigned Limit = Diags.getTemplateBacktraceLimit();
515
5.97k
  if (Limit && Limit < CodeSynthesisContexts.size()) {
516
12
    SkipStart = Limit / 2 + Limit % 2;
517
12
    SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
518
12
  }
519
520
  // FIXME: In all of these cases, we need to show the template arguments
521
5.97k
  unsigned InstantiationIdx = 0;
522
5.97k
  for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
523
5.97k
         Active = CodeSynthesisContexts.rbegin(),
524
5.97k
         ActiveEnd = CodeSynthesisContexts.rend();
525
18.6k
       Active != ActiveEnd;
526
12.6k
       ++Active, ++InstantiationIdx) {
527
    // Skip this instantiation?
528
12.6k
    if (InstantiationIdx >= SkipStart && 
InstantiationIdx < SkipEnd6.21k
) {
529
6.17k
      if (InstantiationIdx == SkipStart) {
530
        // Note that we're skipping instantiations.
531
12
        Diags.Report(Active->PointOfInstantiation,
532
12
                     diag::note_instantiation_contexts_suppressed)
533
12
          << unsigned(CodeSynthesisContexts.size() - Limit);
534
12
      }
535
6.17k
      continue;
536
6.17k
    }
537
538
6.49k
    switch (Active->Kind) {
539
5.88k
    case CodeSynthesisContext::TemplateInstantiation: {
540
5.88k
      Decl *D = Active->Entity;
541
5.88k
      if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
542
746
        unsigned DiagID = diag::note_template_member_class_here;
543
746
        if (isa<ClassTemplateSpecializationDecl>(Record))
544
691
          DiagID = diag::note_template_class_instantiation_here;
545
746
        Diags.Report(Active->PointOfInstantiation, DiagID)
546
746
          << Record << Active->InstantiationRange;
547
5.14k
      } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
548
4.99k
        unsigned DiagID;
549
4.99k
        if (Function->getPrimaryTemplate())
550
4.03k
          DiagID = diag::note_function_template_spec_here;
551
960
        else
552
960
          DiagID = diag::note_template_member_function_here;
553
4.99k
        Diags.Report(Active->PointOfInstantiation, DiagID)
554
4.99k
          << Function
555
4.99k
          << Active->InstantiationRange;
556
4.99k
      } else 
if (VarDecl *147
VD147
= dyn_cast<VarDecl>(D)) {
557
92
        Diags.Report(Active->PointOfInstantiation,
558
92
                     VD->isStaticDataMember()?
559
71
                       diag::note_template_static_data_member_def_here
560
92
                     : 
diag::note_template_variable_def_here21
)
561
92
          << VD
562
92
          << Active->InstantiationRange;
563
92
      } else 
if (EnumDecl *55
ED55
= dyn_cast<EnumDecl>(D)) {
564
6
        Diags.Report(Active->PointOfInstantiation,
565
6
                     diag::note_template_enum_def_here)
566
6
          << ED
567
6
          << Active->InstantiationRange;
568
49
      } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
569
35
        Diags.Report(Active->PointOfInstantiation,
570
35
                     diag::note_template_nsdmi_here)
571
35
            << FD << Active->InstantiationRange;
572
35
      } else {
573
14
        Diags.Report(Active->PointOfInstantiation,
574
14
                     diag::note_template_type_alias_instantiation_here)
575
14
          << cast<TypeAliasTemplateDecl>(D)
576
14
          << Active->InstantiationRange;
577
14
      }
578
5.88k
      break;
579
0
    }
580
581
55
    case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
582
55
      TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
583
55
      SmallString<128> TemplateArgsStr;
584
55
      llvm::raw_svector_ostream OS(TemplateArgsStr);
585
55
      Template->printName(OS);
586
55
      printTemplateArgumentList(OS, Active->template_arguments(),
587
55
                                getPrintingPolicy());
588
55
      Diags.Report(Active->PointOfInstantiation,
589
55
                   diag::note_default_arg_instantiation_here)
590
55
        << OS.str()
591
55
        << Active->InstantiationRange;
592
55
      break;
593
0
    }
594
595
2
    case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
596
2
      FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
597
2
      Diags.Report(Active->PointOfInstantiation,
598
2
                   diag::note_explicit_template_arg_substitution_here)
599
2
        << FnTmpl
600
2
        << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
601
2
                                           Active->TemplateArgs,
602
2
                                           Active->NumTemplateArgs)
603
2
        << Active->InstantiationRange;
604
2
      break;
605
0
    }
606
607
91
    case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
608
91
      if (FunctionTemplateDecl *FnTmpl =
609
91
              dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
610
79
        Diags.Report(Active->PointOfInstantiation,
611
79
                     diag::note_function_template_deduction_instantiation_here)
612
79
          << FnTmpl
613
79
          << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
614
79
                                             Active->TemplateArgs,
615
79
                                             Active->NumTemplateArgs)
616
79
          << Active->InstantiationRange;
617
79
      } else {
618
12
        bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
619
12
                     isa<VarTemplateSpecializationDecl>(Active->Entity);
620
12
        bool IsTemplate = false;
621
12
        TemplateParameterList *Params;
622
12
        if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
623
0
          IsTemplate = true;
624
0
          Params = D->getTemplateParameters();
625
12
        } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
626
12
                       Active->Entity)) {
627
4
          Params = D->getTemplateParameters();
628
8
        } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
629
8
                       Active->Entity)) {
630
8
          Params = D->getTemplateParameters();
631
8
        } else {
632
0
          llvm_unreachable("unexpected template kind");
633
0
        }
634
635
12
        Diags.Report(Active->PointOfInstantiation,
636
12
                     diag::note_deduced_template_arg_substitution_here)
637
12
          << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
638
12
          << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
639
12
                                             Active->NumTemplateArgs)
640
12
          << Active->InstantiationRange;
641
12
      }
642
91
      break;
643
0
    }
644
645
76
    case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
646
76
      ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
647
76
      FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
648
649
76
      SmallString<128> TemplateArgsStr;
650
76
      llvm::raw_svector_ostream OS(TemplateArgsStr);
651
76
      FD->printName(OS);
652
76
      printTemplateArgumentList(OS, Active->template_arguments(),
653
76
                                getPrintingPolicy());
654
76
      Diags.Report(Active->PointOfInstantiation,
655
76
                   diag::note_default_function_arg_instantiation_here)
656
76
        << OS.str()
657
76
        << Active->InstantiationRange;
658
76
      break;
659
0
    }
660
661
12
    case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
662
12
      NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
663
12
      std::string Name;
664
12
      if (!Parm->getName().empty())
665
2
        Name = std::string(" '") + Parm->getName().str() + "'";
666
667
12
      TemplateParameterList *TemplateParams = nullptr;
668
12
      if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
669
12
        TemplateParams = Template->getTemplateParameters();
670
0
      else
671
0
        TemplateParams =
672
0
          cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
673
0
                                                      ->getTemplateParameters();
674
12
      Diags.Report(Active->PointOfInstantiation,
675
12
                   diag::note_prior_template_arg_substitution)
676
12
        << isa<TemplateTemplateParmDecl>(Parm)
677
12
        << Name
678
12
        << getTemplateArgumentBindingsText(TemplateParams,
679
12
                                           Active->TemplateArgs,
680
12
                                           Active->NumTemplateArgs)
681
12
        << Active->InstantiationRange;
682
12
      break;
683
0
    }
684
685
5
    case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
686
5
      TemplateParameterList *TemplateParams = nullptr;
687
5
      if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
688
5
        TemplateParams = Template->getTemplateParameters();
689
0
      else
690
0
        TemplateParams =
691
0
          cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
692
0
                                                      ->getTemplateParameters();
693
694
5
      Diags.Report(Active->PointOfInstantiation,
695
5
                   diag::note_template_default_arg_checking)
696
5
        << getTemplateArgumentBindingsText(TemplateParams,
697
5
                                           Active->TemplateArgs,
698
5
                                           Active->NumTemplateArgs)
699
5
        << Active->InstantiationRange;
700
5
      break;
701
0
    }
702
703
34
    case CodeSynthesisContext::ExceptionSpecEvaluation:
704
34
      Diags.Report(Active->PointOfInstantiation,
705
34
                   diag::note_evaluating_exception_spec_here)
706
34
          << cast<FunctionDecl>(Active->Entity);
707
34
      break;
708
709
80
    case CodeSynthesisContext::ExceptionSpecInstantiation:
710
80
      Diags.Report(Active->PointOfInstantiation,
711
80
                   diag::note_template_exception_spec_instantiation_here)
712
80
        << cast<FunctionDecl>(Active->Entity)
713
80
        << Active->InstantiationRange;
714
80
      break;
715
716
1
    case CodeSynthesisContext::RequirementInstantiation:
717
1
      Diags.Report(Active->PointOfInstantiation,
718
1
                   diag::note_template_requirement_instantiation_here)
719
1
        << Active->InstantiationRange;
720
1
      break;
721
722
0
    case CodeSynthesisContext::NestedRequirementConstraintsCheck:
723
0
      Diags.Report(Active->PointOfInstantiation,
724
0
                   diag::note_nested_requirement_here)
725
0
        << Active->InstantiationRange;
726
0
      break;
727
728
11
    case CodeSynthesisContext::DeclaringSpecialMember:
729
11
      Diags.Report(Active->PointOfInstantiation,
730
11
                   diag::note_in_declaration_of_implicit_special_member)
731
11
        << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
732
11
      break;
733
734
1
    case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
735
1
      Diags.Report(Active->Entity->getLocation(),
736
1
                   diag::note_in_declaration_of_implicit_equality_comparison);
737
1
      break;
738
739
184
    case CodeSynthesisContext::DefiningSynthesizedFunction: {
740
      // FIXME: For synthesized functions that are not defaulted,
741
      // produce a note.
742
184
      auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
743
184
      DefaultedFunctionKind DFK =
744
184
          FD ? getDefaultedFunctionKind(FD) : 
DefaultedFunctionKind()0
;
745
184
      if (DFK.isSpecialMember()) {
746
163
        auto *MD = cast<CXXMethodDecl>(FD);
747
163
        Diags.Report(Active->PointOfInstantiation,
748
163
                     diag::note_member_synthesized_at)
749
163
            << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
750
163
            << Context.getTagDeclType(MD->getParent());
751
163
      } else 
if (21
DFK.isComparison()21
) {
752
21
        Diags.Report(Active->PointOfInstantiation,
753
21
                     diag::note_comparison_synthesized_at)
754
21
            << (int)DFK.asComparison()
755
21
            << Context.getTagDeclType(
756
21
                   cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
757
21
      }
758
184
      break;
759
0
    }
760
761
3
    case CodeSynthesisContext::RewritingOperatorAsSpaceship:
762
3
      Diags.Report(Active->Entity->getLocation(),
763
3
                   diag::note_rewriting_operator_as_spaceship);
764
3
      break;
765
766
10
    case CodeSynthesisContext::InitializingStructuredBinding:
767
10
      Diags.Report(Active->PointOfInstantiation,
768
10
                   diag::note_in_binding_decl_init)
769
10
          << cast<BindingDecl>(Active->Entity);
770
10
      break;
771
772
2
    case CodeSynthesisContext::MarkingClassDllexported:
773
2
      Diags.Report(Active->PointOfInstantiation,
774
2
                   diag::note_due_to_dllexported_class)
775
2
          << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
776
2
      break;
777
778
0
    case CodeSynthesisContext::Memoization:
779
0
      break;
780
781
24
    case CodeSynthesisContext::ConstraintsCheck: {
782
24
      unsigned DiagID = 0;
783
24
      if (!Active->Entity) {
784
2
        Diags.Report(Active->PointOfInstantiation,
785
2
                     diag::note_nested_requirement_here)
786
2
          << Active->InstantiationRange;
787
2
        break;
788
2
      }
789
22
      if (isa<ConceptDecl>(Active->Entity))
790
5
        DiagID = diag::note_concept_specialization_here;
791
17
      else if (isa<TemplateDecl>(Active->Entity))
792
7
        DiagID = diag::note_checking_constraints_for_template_id_here;
793
10
      else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
794
6
        DiagID = diag::note_checking_constraints_for_var_spec_id_here;
795
4
      else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
796
2
        DiagID = diag::note_checking_constraints_for_class_spec_id_here;
797
2
      else {
798
2
        assert(isa<FunctionDecl>(Active->Entity));
799
0
        DiagID = diag::note_checking_constraints_for_function_here;
800
2
      }
801
0
      SmallString<128> TemplateArgsStr;
802
22
      llvm::raw_svector_ostream OS(TemplateArgsStr);
803
22
      cast<NamedDecl>(Active->Entity)->printName(OS);
804
22
      if (!isa<FunctionDecl>(Active->Entity)) {
805
20
        printTemplateArgumentList(OS, Active->template_arguments(),
806
20
                                  getPrintingPolicy());
807
20
      }
808
22
      Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
809
22
        << Active->InstantiationRange;
810
22
      break;
811
24
    }
812
12
    case CodeSynthesisContext::ConstraintSubstitution:
813
12
      Diags.Report(Active->PointOfInstantiation,
814
12
                   diag::note_constraint_substitution_here)
815
12
          << Active->InstantiationRange;
816
12
      break;
817
1
    case CodeSynthesisContext::ConstraintNormalization:
818
1
      Diags.Report(Active->PointOfInstantiation,
819
1
                   diag::note_constraint_normalization_here)
820
1
          << cast<NamedDecl>(Active->Entity)->getName()
821
1
          << Active->InstantiationRange;
822
1
      break;
823
1
    case CodeSynthesisContext::ParameterMappingSubstitution:
824
1
      Diags.Report(Active->PointOfInstantiation,
825
1
                   diag::note_parameter_mapping_substitution_here)
826
1
          << Active->InstantiationRange;
827
1
      break;
828
6.49k
    }
829
6.49k
  }
830
5.97k
}
831
832
5.46M
Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
833
5.46M
  if (InNonInstantiationSFINAEContext)
834
85.2k
    return Optional<TemplateDeductionInfo *>(nullptr);
835
836
5.37M
  for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
837
5.37M
         Active = CodeSynthesisContexts.rbegin(),
838
5.37M
         ActiveEnd = CodeSynthesisContexts.rend();
839
5.59M
       Active != ActiveEnd;
840
5.37M
       
++Active221k
)
841
2.19M
  {
842
2.19M
    switch (Active->Kind) {
843
1.29M
    case CodeSynthesisContext::TemplateInstantiation:
844
      // An instantiation of an alias template may or may not be a SFINAE
845
      // context, depending on what else is on the stack.
846
1.29M
      if (isa<TypeAliasTemplateDecl>(Active->Entity))
847
100k
        break;
848
1.29M
      
LLVM_FALLTHROUGH1.19M
;1.19M
849
1.19M
    case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
850
1.19M
    case CodeSynthesisContext::ExceptionSpecInstantiation:
851
1.19M
    case CodeSynthesisContext::ConstraintsCheck:
852
1.19M
    case CodeSynthesisContext::ParameterMappingSubstitution:
853
1.19M
    case CodeSynthesisContext::ConstraintNormalization:
854
1.19M
    case CodeSynthesisContext::NestedRequirementConstraintsCheck:
855
      // This is a template instantiation, so there is no SFINAE.
856
1.19M
      return None;
857
858
66.1k
    case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
859
120k
    case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
860
121k
    case CodeSynthesisContext::DefaultTemplateArgumentChecking:
861
121k
    case CodeSynthesisContext::RewritingOperatorAsSpaceship:
862
      // A default template argument instantiation and substitution into
863
      // template parameters with arguments for prior parameters may or may
864
      // not be a SFINAE context; look further up the stack.
865
121k
      break;
866
867
92.5k
    case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
868
750k
    case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
869
752k
    case CodeSynthesisContext::ConstraintSubstitution:
870
752k
    case CodeSynthesisContext::RequirementInstantiation:
871
      // We're either substituting explicitly-specified template arguments,
872
      // deduced template arguments, a constraint expression or a requirement
873
      // in a requires expression, so SFINAE applies.
874
752k
      assert(Active->DeductionInfo && "Missing deduction info pointer");
875
0
      return Active->DeductionInfo;
876
877
20.1k
    case CodeSynthesisContext::DeclaringSpecialMember:
878
20.2k
    case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
879
29.3k
    case CodeSynthesisContext::DefiningSynthesizedFunction:
880
29.5k
    case CodeSynthesisContext::InitializingStructuredBinding:
881
29.5k
    case CodeSynthesisContext::MarkingClassDllexported:
882
      // This happens in a context unrelated to template instantiation, so
883
      // there is no SFINAE.
884
29.5k
      return None;
885
886
69
    case CodeSynthesisContext::ExceptionSpecEvaluation:
887
      // FIXME: This should not be treated as a SFINAE context, because
888
      // we will cache an incorrect exception specification. However, clang
889
      // bootstrap relies this! See PR31692.
890
69
      break;
891
892
0
    case CodeSynthesisContext::Memoization:
893
0
      break;
894
2.19M
    }
895
896
    // The inner context was transparent for SFINAE. If it occurred within a
897
    // non-instantiation SFINAE context, then SFINAE applies.
898
221k
    if (Active->SavedInNonInstantiationSFINAEContext)
899
3
      return Optional<TemplateDeductionInfo *>(nullptr);
900
221k
  }
901
902
3.39M
  return None;
903
5.37M
}
904
905
//===----------------------------------------------------------------------===/
906
// Template Instantiation for Types
907
//===----------------------------------------------------------------------===/
908
namespace {
909
  class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
910
    const MultiLevelTemplateArgumentList &TemplateArgs;
911
    SourceLocation Loc;
912
    DeclarationName Entity;
913
914
  public:
915
    typedef TreeTransform<TemplateInstantiator> inherited;
916
917
    TemplateInstantiator(Sema &SemaRef,
918
                         const MultiLevelTemplateArgumentList &TemplateArgs,
919
                         SourceLocation Loc,
920
                         DeclarationName Entity)
921
      : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
922
9.56M
        Entity(Entity) { }
923
924
    /// Determine whether the given type \p T has already been
925
    /// transformed.
926
    ///
927
    /// For the purposes of template instantiation, a type has already been
928
    /// transformed if it is NULL or if it is not dependent.
929
    bool AlreadyTransformed(QualType T);
930
931
    /// Returns the location of the entity being instantiated, if known.
932
11.9M
    SourceLocation getBaseLocation() { return Loc; }
933
934
    /// Returns the name of the entity being instantiated, if any.
935
20.6M
    DeclarationName getBaseEntity() { return Entity; }
936
937
    /// Sets the "base" location and entity when that
938
    /// information is known based on another transformation.
939
18.6M
    void setBase(SourceLocation Loc, DeclarationName Entity) {
940
18.6M
      this->Loc = Loc;
941
18.6M
      this->Entity = Entity;
942
18.6M
    }
943
944
28
    unsigned TransformTemplateDepth(unsigned Depth) {
945
28
      return TemplateArgs.getNewDepth(Depth);
946
28
    }
947
948
    bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
949
                                 SourceRange PatternRange,
950
                                 ArrayRef<UnexpandedParameterPack> Unexpanded,
951
                                 bool &ShouldExpand, bool &RetainExpansion,
952
310k
                                 Optional<unsigned> &NumExpansions) {
953
310k
      return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
954
310k
                                                       PatternRange, Unexpanded,
955
310k
                                                       TemplateArgs,
956
310k
                                                       ShouldExpand,
957
310k
                                                       RetainExpansion,
958
310k
                                                       NumExpansions);
959
310k
    }
960
961
11.1k
    void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
962
11.1k
      SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
963
11.1k
    }
964
965
4.34k
    TemplateArgument ForgetPartiallySubstitutedPack() {
966
4.34k
      TemplateArgument Result;
967
4.34k
      if (NamedDecl *PartialPack
968
4.34k
            = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
969
4.34k
        MultiLevelTemplateArgumentList &TemplateArgs
970
4.34k
          = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
971
4.34k
        unsigned Depth, Index;
972
4.34k
        std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
973
4.34k
        if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
974
4.34k
          Result = TemplateArgs(Depth, Index);
975
4.34k
          TemplateArgs.setArgument(Depth, Index, TemplateArgument());
976
4.34k
        }
977
4.34k
      }
978
979
4.34k
      return Result;
980
4.34k
    }
981
982
4.34k
    void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
983
4.34k
      if (Arg.isNull())
984
0
        return;
985
986
4.34k
      if (NamedDecl *PartialPack
987
4.34k
            = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
988
4.34k
        MultiLevelTemplateArgumentList &TemplateArgs
989
4.34k
        = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
990
4.34k
        unsigned Depth, Index;
991
4.34k
        std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
992
4.34k
        TemplateArgs.setArgument(Depth, Index, Arg);
993
4.34k
      }
994
4.34k
    }
995
996
    /// Transform the given declaration by instantiating a reference to
997
    /// this declaration.
998
    Decl *TransformDecl(SourceLocation Loc, Decl *D);
999
1000
2.53k
    void transformAttrs(Decl *Old, Decl *New) {
1001
2.53k
      SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1002
2.53k
    }
1003
1004
5.44k
    void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1005
5.44k
      if (Old->isParameterPack()) {
1006
8
        SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
1007
8
        for (auto *New : NewDecls)
1008
13
          SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
1009
13
              Old, cast<VarDecl>(New));
1010
8
        return;
1011
8
      }
1012
1013
5.43k
      assert(NewDecls.size() == 1 &&
1014
5.43k
             "should only have multiple expansions for a pack");
1015
0
      Decl *New = NewDecls.front();
1016
1017
      // If we've instantiated the call operator of a lambda or the call
1018
      // operator template of a generic lambda, update the "instantiation of"
1019
      // information.
1020
5.43k
      auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1021
5.43k
      if (NewMD && 
isLambdaCallOperator(NewMD)2.53k
) {
1022
2.53k
        auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1023
2.53k
        if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1024
1.40k
          NewTD->setInstantiatedFromMemberTemplate(
1025
1.40k
              OldMD->getDescribedFunctionTemplate());
1026
1.13k
        else
1027
1.13k
          NewMD->setInstantiationOfMemberFunction(OldMD,
1028
1.13k
                                                  TSK_ImplicitInstantiation);
1029
2.53k
      }
1030
1031
5.43k
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
1032
1033
      // We recreated a local declaration, but not by instantiating it. There
1034
      // may be pending dependent diagnostics to produce.
1035
5.43k
      if (auto *DC = dyn_cast<DeclContext>(Old))
1036
5.07k
        SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1037
5.43k
    }
1038
1039
    /// Transform the definition of the given declaration by
1040
    /// instantiating it.
1041
    Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1042
1043
    /// Transform the first qualifier within a scope by instantiating the
1044
    /// declaration.
1045
    NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1046
1047
    /// Rebuild the exception declaration and register the declaration
1048
    /// as an instantiated local.
1049
    VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1050
                                  TypeSourceInfo *Declarator,
1051
                                  SourceLocation StartLoc,
1052
                                  SourceLocation NameLoc,
1053
                                  IdentifierInfo *Name);
1054
1055
    /// Rebuild the Objective-C exception declaration and register the
1056
    /// declaration as an instantiated local.
1057
    VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1058
                                      TypeSourceInfo *TSInfo, QualType T);
1059
1060
    /// Check for tag mismatches when instantiating an
1061
    /// elaborated type.
1062
    QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1063
                                   ElaboratedTypeKeyword Keyword,
1064
                                   NestedNameSpecifierLoc QualifierLoc,
1065
                                   QualType T);
1066
1067
    TemplateName
1068
    TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1069
                          SourceLocation NameLoc,
1070
                          QualType ObjectType = QualType(),
1071
                          NamedDecl *FirstQualifierInScope = nullptr,
1072
                          bool AllowInjectedClassName = false);
1073
1074
    const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1075
1076
    ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1077
    ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1078
    ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1079
1080
    ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1081
                                            NonTypeTemplateParmDecl *D);
1082
    ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1083
                                           SubstNonTypeTemplateParmPackExpr *E);
1084
    ExprResult TransformSubstNonTypeTemplateParmExpr(
1085
                                           SubstNonTypeTemplateParmExpr *E);
1086
1087
    /// Rebuild a DeclRefExpr for a VarDecl reference.
1088
    ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1089
1090
    /// Transform a reference to a function or init-capture parameter pack.
1091
    ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1092
1093
    /// Transform a FunctionParmPackExpr which was built when we couldn't
1094
    /// expand a function parameter pack reference which refers to an expanded
1095
    /// pack.
1096
    ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1097
1098
    QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1099
6.70k
                                        FunctionProtoTypeLoc TL) {
1100
      // Call the base version; it will forward to our overridden version below.
1101
6.70k
      return inherited::TransformFunctionProtoType(TLB, TL);
1102
6.70k
    }
1103
1104
    template<typename Fn>
1105
    QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1106
                                        FunctionProtoTypeLoc TL,
1107
                                        CXXRecordDecl *ThisContext,
1108
                                        Qualifiers ThisTypeQuals,
1109
                                        Fn TransformExceptionSpec);
1110
1111
    ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1112
                                            int indexAdjustment,
1113
                                            Optional<unsigned> NumExpansions,
1114
                                            bool ExpectParameterPack);
1115
1116
    /// Transforms a template type parameter type by performing
1117
    /// substitution of the corresponding template type argument.
1118
    QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1119
                                           TemplateTypeParmTypeLoc TL);
1120
1121
    /// Transforms an already-substituted template type parameter pack
1122
    /// into either itself (if we aren't substituting into its pack expansion)
1123
    /// or the appropriate substituted argument.
1124
    QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1125
                                           SubstTemplateTypeParmPackTypeLoc TL);
1126
1127
2.54k
    ExprResult TransformLambdaExpr(LambdaExpr *E) {
1128
2.54k
      LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1129
2.54k
      return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
1130
2.54k
    }
1131
1132
167
    ExprResult TransformRequiresExpr(RequiresExpr *E) {
1133
167
      LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1134
167
      return TreeTransform<TemplateInstantiator>::TransformRequiresExpr(E);
1135
167
    }
1136
1137
    bool TransformRequiresExprRequirements(
1138
        ArrayRef<concepts::Requirement *> Reqs,
1139
164
        SmallVectorImpl<concepts::Requirement *> &Transformed) {
1140
164
      bool SatisfactionDetermined = false;
1141
192
      for (concepts::Requirement *Req : Reqs) {
1142
192
        concepts::Requirement *TransReq = nullptr;
1143
192
        if (!SatisfactionDetermined) {
1144
184
          if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1145
35
            TransReq = TransformTypeRequirement(TypeReq);
1146
149
          else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1147
111
            TransReq = TransformExprRequirement(ExprReq);
1148
38
          else
1149
38
            TransReq = TransformNestedRequirement(
1150
38
                cast<concepts::NestedRequirement>(Req));
1151
184
          if (!TransReq)
1152
0
            return true;
1153
184
          if (!TransReq->isDependent() && !TransReq->isSatisfied())
1154
            // [expr.prim.req]p6
1155
            //   [...]  The substitution and semantic constraint checking
1156
            //   proceeds in lexical order and stops when a condition that
1157
            //   determines the result of the requires-expression is
1158
            //   encountered. [..]
1159
92
            SatisfactionDetermined = true;
1160
184
        } else
1161
8
          TransReq = Req;
1162
192
        Transformed.push_back(TransReq);
1163
192
      }
1164
164
      return false;
1165
164
    }
1166
1167
    TemplateParameterList *TransformTemplateParameterList(
1168
2.56k
                              TemplateParameterList *OrigTPL)  {
1169
2.56k
      if (!OrigTPL || 
!OrigTPL->size()1.42k
)
return OrigTPL1.14k
;
1170
1171
1.42k
      DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1172
1.42k
      TemplateDeclInstantiator  DeclInstantiator(getSema(),
1173
1.42k
                        /* DeclContext *Owner */ Owner, TemplateArgs);
1174
1.42k
      return DeclInstantiator.SubstTemplateParams(OrigTPL);
1175
2.56k
    }
1176
1177
    concepts::TypeRequirement *
1178
    TransformTypeRequirement(concepts::TypeRequirement *Req);
1179
    concepts::ExprRequirement *
1180
    TransformExprRequirement(concepts::ExprRequirement *Req);
1181
    concepts::NestedRequirement *
1182
    TransformNestedRequirement(concepts::NestedRequirement *Req);
1183
1184
  private:
1185
    ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1186
                                               SourceLocation loc,
1187
                                               TemplateArgument arg);
1188
  };
1189
}
1190
1191
15.8M
bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1192
15.8M
  if (T.isNull())
1193
0
    return true;
1194
1195
15.8M
  if (T->isInstantiationDependentType() || 
T->isVariablyModifiedType()764k
)
1196
15.1M
    return false;
1197
1198
764k
  getSema().MarkDeclarationsReferencedInType(Loc, T);
1199
764k
  return true;
1200
15.8M
}
1201
1202
static TemplateArgument
1203
534k
getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
1204
534k
  assert(S.ArgumentPackSubstitutionIndex >= 0);
1205
0
  assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1206
0
  Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1207
534k
  if (Arg.isPackExpansion())
1208
57.8k
    Arg = Arg.getPackExpansionPattern();
1209
534k
  return Arg;
1210
534k
}
1211
1212
8.06M
Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1213
8.06M
  if (!D)
1214
124k
    return nullptr;
1215
1216
7.94M
  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1217
10.6k
    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1218
      // If the corresponding template argument is NULL or non-existent, it's
1219
      // because we are performing instantiation from explicitly-specified
1220
      // template arguments in a function template, but there were some
1221
      // arguments left unspecified.
1222
0
      if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1223
0
                                            TTP->getPosition()))
1224
0
        return D;
1225
1226
0
      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1227
1228
0
      if (TTP->isParameterPack()) {
1229
0
        assert(Arg.getKind() == TemplateArgument::Pack &&
1230
0
               "Missing argument pack");
1231
0
        Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1232
0
      }
1233
1234
0
      TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1235
0
      assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1236
0
             "Wrong kind of template template argument");
1237
0
      return Template.getAsTemplateDecl();
1238
0
    }
1239
1240
    // Fall through to find the instantiated declaration for this template
1241
    // template parameter.
1242
10.6k
  }
1243
1244
7.94M
  return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1245
7.94M
}
1246
1247
146k
Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1248
146k
  Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1249
146k
  if (!Inst)
1250
135
    return nullptr;
1251
1252
146k
  getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1253
146k
  return Inst;
1254
146k
}
1255
1256
NamedDecl *
1257
TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1258
124k
                                                     SourceLocation Loc) {
1259
  // If the first part of the nested-name-specifier was a template type
1260
  // parameter, instantiate that type parameter down to a tag type.
1261
124k
  if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1262
13
    const TemplateTypeParmType *TTP
1263
13
      = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1264
1265
13
    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1266
      // FIXME: This needs testing w/ member access expressions.
1267
12
      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1268
1269
12
      if (TTP->isParameterPack()) {
1270
0
        assert(Arg.getKind() == TemplateArgument::Pack &&
1271
0
               "Missing argument pack");
1272
1273
0
        if (getSema().ArgumentPackSubstitutionIndex == -1)
1274
0
          return nullptr;
1275
1276
0
        Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1277
0
      }
1278
1279
12
      QualType T = Arg.getAsType();
1280
12
      if (T.isNull())
1281
0
        return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1282
1283
12
      if (const TagType *Tag = T->getAs<TagType>())
1284
12
        return Tag->getDecl();
1285
1286
      // The resulting type is not a tag; complain.
1287
0
      getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1288
0
      return nullptr;
1289
12
    }
1290
13
  }
1291
1292
124k
  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1293
124k
}
1294
1295
VarDecl *
1296
TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1297
                                           TypeSourceInfo *Declarator,
1298
                                           SourceLocation StartLoc,
1299
                                           SourceLocation NameLoc,
1300
12
                                           IdentifierInfo *Name) {
1301
12
  VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1302
12
                                                 StartLoc, NameLoc, Name);
1303
12
  if (Var)
1304
12
    getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1305
12
  return Var;
1306
12
}
1307
1308
VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1309
                                                        TypeSourceInfo *TSInfo,
1310
2
                                                        QualType T) {
1311
2
  VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1312
2
  if (Var)
1313
2
    getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1314
2
  return Var;
1315
2
}
1316
1317
QualType
1318
TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1319
                                            ElaboratedTypeKeyword Keyword,
1320
                                            NestedNameSpecifierLoc QualifierLoc,
1321
24.7k
                                            QualType T) {
1322
24.7k
  if (const TagType *TT = T->getAs<TagType>()) {
1323
23.3k
    TagDecl* TD = TT->getDecl();
1324
1325
23.3k
    SourceLocation TagLocation = KeywordLoc;
1326
1327
23.3k
    IdentifierInfo *Id = TD->getIdentifier();
1328
1329
    // TODO: should we even warn on struct/class mismatches for this?  Seems
1330
    // like it's likely to produce a lot of spurious errors.
1331
23.3k
    if (Id && 
Keyword != ETK_None19.8k
&&
Keyword != ETK_Typename2.15k
) {
1332
1.42k
      TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1333
1.42k
      if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1334
1.42k
                                                TagLocation, Id)) {
1335
0
        SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1336
0
          << Id
1337
0
          << FixItHint::CreateReplacement(SourceRange(TagLocation),
1338
0
                                          TD->getKindName());
1339
0
        SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1340
0
      }
1341
1.42k
    }
1342
23.3k
  }
1343
1344
24.7k
  return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1345
24.7k
                                                                    Keyword,
1346
24.7k
                                                                  QualifierLoc,
1347
24.7k
                                                                    T);
1348
24.7k
}
1349
1350
TemplateName TemplateInstantiator::TransformTemplateName(
1351
    CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1352
    QualType ObjectType, NamedDecl *FirstQualifierInScope,
1353
3.58M
    bool AllowInjectedClassName) {
1354
3.58M
  if (TemplateTemplateParmDecl *TTP
1355
3.58M
       = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1356
38.1k
    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1357
      // If the corresponding template argument is NULL or non-existent, it's
1358
      // because we are performing instantiation from explicitly-specified
1359
      // template arguments in a function template, but there were some
1360
      // arguments left unspecified.
1361
27.5k
      if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1362
27.5k
                                            TTP->getPosition()))
1363
7
        return Name;
1364
1365
27.4k
      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1366
1367
27.4k
      if (TemplateArgs.isRewrite()) {
1368
        // We're rewriting the template parameter as a reference to another
1369
        // template parameter.
1370
136
        if (Arg.getKind() == TemplateArgument::Pack) {
1371
1
          assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1372
1
                 "unexpected pack arguments in template rewrite");
1373
0
          Arg = Arg.pack_begin()->getPackExpansionPattern();
1374
1
        }
1375
0
        assert(Arg.getKind() == TemplateArgument::Template &&
1376
136
               "unexpected nontype template argument kind in template rewrite");
1377
0
        return Arg.getAsTemplate();
1378
136
      }
1379
1380
27.3k
      if (TTP->isParameterPack()) {
1381
16.4k
        assert(Arg.getKind() == TemplateArgument::Pack &&
1382
16.4k
               "Missing argument pack");
1383
1384
16.4k
        if (getSema().ArgumentPackSubstitutionIndex == -1) {
1385
          // We have the template argument pack to substitute, but we're not
1386
          // actually expanding the enclosing pack expansion yet. So, just
1387
          // keep the entire argument pack.
1388
6
          return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1389
6
        }
1390
1391
16.4k
        Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1392
16.4k
      }
1393
1394
27.3k
      TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1395
27.3k
      assert(!Template.isNull() && "Null template template argument");
1396
0
      assert(!Template.getAsQualifiedTemplateName() &&
1397
27.3k
             "template decl to substitute is qualified?");
1398
1399
0
      Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1400
27.3k
      return Template;
1401
27.3k
    }
1402
38.1k
  }
1403
1404
3.55M
  if (SubstTemplateTemplateParmPackStorage *SubstPack
1405
3.55M
      = Name.getAsSubstTemplateTemplateParmPack()) {
1406
3
    if (getSema().ArgumentPackSubstitutionIndex == -1)
1407
0
      return Name;
1408
1409
3
    TemplateArgument Arg = SubstPack->getArgumentPack();
1410
3
    Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1411
3
    return Arg.getAsTemplate().getNameToSubstitute();
1412
3
  }
1413
1414
3.55M
  return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1415
3.55M
                                          FirstQualifierInScope,
1416
3.55M
                                          AllowInjectedClassName);
1417
3.55M
}
1418
1419
ExprResult
1420
84
TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1421
84
  if (!E->isTypeDependent())
1422
0
    return E;
1423
1424
84
  return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1425
84
}
1426
1427
ExprResult
1428
TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1429
845k
                                               NonTypeTemplateParmDecl *NTTP) {
1430
  // If the corresponding template argument is NULL or non-existent, it's
1431
  // because we are performing instantiation from explicitly-specified
1432
  // template arguments in a function template, but there were some
1433
  // arguments left unspecified.
1434
845k
  if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1435
845k
                                        NTTP->getPosition()))
1436
2.61k
    return E;
1437
1438
842k
  TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1439
1440
842k
  if (TemplateArgs.isRewrite()) {
1441
    // We're rewriting the template parameter as a reference to another
1442
    // template parameter.
1443
48
    if (Arg.getKind() == TemplateArgument::Pack) {
1444
18
      assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1445
18
             "unexpected pack arguments in template rewrite");
1446
0
      Arg = Arg.pack_begin()->getPackExpansionPattern();
1447
18
    }
1448
0
    assert(Arg.getKind() == TemplateArgument::Expression &&
1449
48
           "unexpected nontype template argument kind in template rewrite");
1450
    // FIXME: This can lead to the same subexpression appearing multiple times
1451
    // in a complete expression.
1452
0
    return Arg.getAsExpr();
1453
48
  }
1454
1455
842k
  if (NTTP->isParameterPack()) {
1456
23.2k
    assert(Arg.getKind() == TemplateArgument::Pack &&
1457
23.2k
           "Missing argument pack");
1458
1459
23.2k
    if (getSema().ArgumentPackSubstitutionIndex == -1) {
1460
      // We have an argument pack, but we can't select a particular argument
1461
      // out of it yet. Therefore, we'll build an expression to hold on to that
1462
      // argument pack.
1463
53
      QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1464
53
                                              E->getLocation(),
1465
53
                                              NTTP->getDeclName());
1466
53
      if (TargetType.isNull())
1467
0
        return ExprError();
1468
1469
53
      QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
1470
53
      if (TargetType->isRecordType())
1471
0
        ExprType.addConst();
1472
1473
53
      return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1474
53
          ExprType, TargetType->isReferenceType() ? 
VK_LValue2
:
VK_PRValue51
,
1475
53
          NTTP, E->getLocation(), Arg);
1476
53
    }
1477
1478
23.1k
    Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1479
23.1k
  }
1480
1481
842k
  return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1482
842k
}
1483
1484
const LoopHintAttr *
1485
46
TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1486
46
  Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1487
1488
46
  if (TransformedExpr == LH->getValue())
1489
11
    return LH;
1490
1491
  // Generate error if there is a problem with the value.
1492
35
  if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1493
8
    return LH;
1494
1495
  // Create new LoopHintValueAttr with integral expression in place of the
1496
  // non-type template parameter.
1497
27
  return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1498
27
                                      LH->getState(), TransformedExpr, *LH);
1499
35
}
1500
1501
ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1502
                                                 NonTypeTemplateParmDecl *parm,
1503
                                                 SourceLocation loc,
1504
843k
                                                 TemplateArgument arg) {
1505
843k
  ExprResult result;
1506
1507
  // Determine the substituted parameter type. We can usually infer this from
1508
  // the template argument, but not always.
1509
843k
  auto SubstParamType = [&] {
1510
2
    QualType T;
1511
2
    if (parm->isExpandedParameterPack())
1512
0
      T = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1513
2
    else
1514
2
      T = parm->getType();
1515
2
    if (parm->isParameterPack() && 
isa<PackExpansionType>(T)0
)
1516
0
      T = cast<PackExpansionType>(T)->getPattern();
1517
2
    return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
1518
2
  };
1519
1520
843k
  bool refParam = false;
1521
1522
  // The template argument itself might be an expression, in which case we just
1523
  // return that expression. This happens when substituting into an alias
1524
  // template.
1525
843k
  if (arg.getKind() == TemplateArgument::Expression) {
1526
287k
    Expr *argExpr = arg.getAsExpr();
1527
287k
    result = argExpr;
1528
287k
    if (argExpr->isLValue()) {
1529
6
      if (argExpr->getType()->isRecordType()) {
1530
        // Check whether the parameter was actually a reference.
1531
2
        QualType paramType = SubstParamType();
1532
2
        if (paramType.isNull())
1533
0
          return ExprError();
1534
2
        refParam = paramType->isReferenceType();
1535
4
      } else {
1536
4
        refParam = true;
1537
4
      }
1538
6
    }
1539
556k
  } else if (arg.getKind() == TemplateArgument::Declaration ||
1540
556k
             
arg.getKind() == TemplateArgument::NullPtr555k
) {
1541
1.51k
    ValueDecl *VD;
1542
1.51k
    if (arg.getKind() == TemplateArgument::Declaration) {
1543
1.44k
      VD = arg.getAsDecl();
1544
1545
      // Find the instantiation of the template argument.  This is
1546
      // required for nested templates.
1547
1.44k
      VD = cast_or_null<ValueDecl>(
1548
1.44k
             getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1549
1.44k
      if (!VD)
1550
0
        return ExprError();
1551
1.44k
    } else {
1552
      // Propagate NULL template argument.
1553
70
      VD = nullptr;
1554
70
    }
1555
1556
1.51k
    QualType paramType = VD ? 
arg.getParamTypeForDecl()1.44k
:
arg.getNullPtrType()70
;
1557
1.51k
    assert(!paramType.isNull() && "type substitution failed for param type");
1558
0
    assert(!paramType->isDependentType() && "param type still dependent");
1559
0
    result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
1560
1.51k
    refParam = paramType->isReferenceType();
1561
555k
  } else {
1562
555k
    result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1563
555k
    assert(result.isInvalid() ||
1564
555k
           SemaRef.Context.hasSameType(result.get()->getType(),
1565
555k
                                       arg.getIntegralType()));
1566
555k
  }
1567
1568
843k
  if (result.isInvalid())
1569
2
    return ExprError();
1570
1571
843k
  Expr *resultExpr = result.get();
1572
843k
  return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1573
843k
      resultExpr->getType(), resultExpr->getValueKind(), loc, parm, refParam,
1574
843k
      resultExpr);
1575
843k
}
1576
1577
ExprResult
1578
TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1579
145
                                          SubstNonTypeTemplateParmPackExpr *E) {
1580
145
  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1581
    // We aren't expanding the parameter pack, so just return ourselves.
1582
0
    return E;
1583
0
  }
1584
1585
145
  TemplateArgument Arg = E->getArgumentPack();
1586
145
  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1587
145
  return transformNonTypeTemplateParmRef(E->getParameterPack(),
1588
145
                                         E->getParameterPackLocation(),
1589
145
                                         Arg);
1590
145
}
1591
1592
ExprResult
1593
TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
1594
1.09k
                                          SubstNonTypeTemplateParmExpr *E) {
1595
1.09k
  ExprResult SubstReplacement = E->getReplacement();
1596
1.09k
  if (!isa<ConstantExpr>(SubstReplacement.get()))
1597
1.09k
    SubstReplacement = TransformExpr(E->getReplacement());
1598
1.09k
  if (SubstReplacement.isInvalid())
1599
0
    return true;
1600
1.09k
  QualType SubstType = TransformType(E->getParameterType(getSema().Context));
1601
1.09k
  if (SubstType.isNull())
1602
0
    return true;
1603
  // The type may have been previously dependent and not now, which means we
1604
  // might have to implicit cast the argument to the new type, for example:
1605
  // template<auto T, decltype(T) U>
1606
  // concept C = sizeof(U) == 4;
1607
  // void foo() requires C<2, 'a'> { }
1608
  // When normalizing foo(), we first form the normalized constraints of C:
1609
  // AtomicExpr(sizeof(U) == 4,
1610
  //            U=SubstNonTypeTemplateParmExpr(Param=U,
1611
  //                                           Expr=DeclRef(U),
1612
  //                                           Type=decltype(T)))
1613
  // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
1614
  // produce:
1615
  // AtomicExpr(sizeof(U) == 4,
1616
  //            U=SubstNonTypeTemplateParmExpr(Param=U,
1617
  //                                           Expr=ImpCast(
1618
  //                                               decltype(2),
1619
  //                                               SubstNTTPE(Param=U, Expr='a',
1620
  //                                                          Type=char)),
1621
  //                                           Type=decltype(2)))
1622
  // The call to CheckTemplateArgument here produces the ImpCast.
1623
1.09k
  TemplateArgument Converted;
1624
1.09k
  if (SemaRef.CheckTemplateArgument(E->getParameter(), SubstType,
1625
1.09k
                                    SubstReplacement.get(),
1626
1.09k
                                    Converted).isInvalid())
1627
0
    return true;
1628
1.09k
  return transformNonTypeTemplateParmRef(E->getParameter(),
1629
1.09k
                                         E->getExprLoc(), Converted);
1630
1.09k
}
1631
1632
ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1633
11.2k
                                                       SourceLocation Loc) {
1634
11.2k
  DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1635
11.2k
  return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1636
11.2k
}
1637
1638
ExprResult
1639
55
TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1640
55
  if (getSema().ArgumentPackSubstitutionIndex != -1) {
1641
    // We can expand this parameter pack now.
1642
54
    VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1643
54
    VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1644
54
    if (!VD)
1645
0
      return ExprError();
1646
54
    return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1647
54
  }
1648
1649
1
  QualType T = TransformType(E->getType());
1650
1
  if (T.isNull())
1651
0
    return ExprError();
1652
1653
  // Transform each of the parameter expansions into the corresponding
1654
  // parameters in the instantiation of the function decl.
1655
1
  SmallVector<VarDecl *, 8> Vars;
1656
1
  Vars.reserve(E->getNumExpansions());
1657
1
  for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1658
3
       I != End; 
++I2
) {
1659
2
    VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1660
2
    if (!D)
1661
0
      return ExprError();
1662
2
    Vars.push_back(D);
1663
2
  }
1664
1665
1
  auto *PackExpr =
1666
1
      FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1667
1
                                   E->getParameterPackLocation(), Vars);
1668
1
  getSema().MarkFunctionParmPackReferenced(PackExpr);
1669
1
  return PackExpr;
1670
1
}
1671
1672
ExprResult
1673
TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1674
11.4k
                                                       VarDecl *PD) {
1675
11.4k
  typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1676
11.4k
  llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1677
11.4k
    = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1678
11.4k
  assert(Found && "no instantiation for parameter pack");
1679
1680
0
  Decl *TransformedDecl;
1681
11.4k
  if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1682
    // If this is a reference to a function parameter pack which we can
1683
    // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1684
11.1k
    if (getSema().ArgumentPackSubstitutionIndex == -1) {
1685
228
      QualType T = TransformType(E->getType());
1686
228
      if (T.isNull())
1687
0
        return ExprError();
1688
228
      auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1689
228
                                                    E->getExprLoc(), *Pack);
1690
228
      getSema().MarkFunctionParmPackReferenced(PackExpr);
1691
228
      return PackExpr;
1692
228
    }
1693
1694
10.8k
    TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1695
10.8k
  } else {
1696
367
    TransformedDecl = Found->get<Decl*>();
1697
367
  }
1698
1699
  // We have either an unexpanded pack or a specific expansion.
1700
11.2k
  return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1701
11.4k
}
1702
1703
ExprResult
1704
1.84M
TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1705
1.84M
  NamedDecl *D = E->getDecl();
1706
1707
  // Handle references to non-type template parameters and non-type template
1708
  // parameter packs.
1709
1.84M
  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1710
911k
    if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1711
845k
      return TransformTemplateParmRefExpr(E, NTTP);
1712
1713
    // We have a non-type template parameter that isn't fully substituted;
1714
    // FindInstantiatedDecl will find it in the local instantiation scope.
1715
911k
  }
1716
1717
  // Handle references to function parameter packs.
1718
1.00M
  if (VarDecl *PD = dyn_cast<VarDecl>(D))
1719
834k
    if (PD->isParameterPack())
1720
11.4k
      return TransformFunctionParmPackRefExpr(E, PD);
1721
1722
989k
  return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1723
1.00M
}
1724
1725
ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1726
0
    CXXDefaultArgExpr *E) {
1727
0
  assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1728
0
             getDescribedFunctionTemplate() &&
1729
0
         "Default arg expressions are never formed in dependent cases.");
1730
0
  return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1731
0
                           cast<FunctionDecl>(E->getParam()->getDeclContext()),
1732
0
                                        E->getParam());
1733
0
}
1734
1735
template<typename Fn>
1736
QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1737
                                 FunctionProtoTypeLoc TL,
1738
                                 CXXRecordDecl *ThisContext,
1739
                                 Qualifiers ThisTypeQuals,
1740
1.03M
                                 Fn TransformExceptionSpec) {
1741
  // We need a local instantiation scope for this function prototype.
1742
1.03M
  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1743
1.03M
  return inherited::TransformFunctionProtoType(
1744
1.03M
      TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1745
1.03M
}
SemaTemplateInstantiate.cpp:clang::QualType (anonymous namespace)::TemplateInstantiator::TransformFunctionProtoType<clang::TreeTransform<(anonymous namespace)::TemplateInstantiator>::TransformFunctionProtoType(clang::TypeLocBuilder&, clang::FunctionProtoTypeLoc)::'lambda'(clang::FunctionProtoType::ExceptionSpecInfo&, bool&)>(clang::TypeLocBuilder&, clang::FunctionProtoTypeLoc, clang::CXXRecordDecl*, clang::Qualifiers, (anonymous namespace)::TemplateInstantiator)
Line
Count
Source
1740
6.70k
                                 Fn TransformExceptionSpec) {
1741
  // We need a local instantiation scope for this function prototype.
1742
6.70k
  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1743
6.70k
  return inherited::TransformFunctionProtoType(
1744
6.70k
      TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1745
6.70k
}
SemaTemplateInstantiate.cpp:clang::QualType (anonymous namespace)::TemplateInstantiator::TransformFunctionProtoType<clang::Sema::SubstFunctionDeclType(clang::TypeSourceInfo*, clang::MultiLevelTemplateArgumentList const&, clang::SourceLocation, clang::DeclarationName, clang::CXXRecordDecl*, clang::Qualifiers)::$_0>(clang::TypeLocBuilder&, clang::FunctionProtoTypeLoc, clang::CXXRecordDecl*, clang::Qualifiers, clang::Sema::SubstFunctionDeclType(clang::TypeSourceInfo*, clang::MultiLevelTemplateArgumentList const&, clang::SourceLocation, clang::DeclarationName, clang::CXXRecordDecl*, clang::Qualifiers)::$_0)
Line
Count
Source
1740
1.02M
                                 Fn TransformExceptionSpec) {
1741
  // We need a local instantiation scope for this function prototype.
1742
1.02M
  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1743
1.02M
  return inherited::TransformFunctionProtoType(
1744
1.02M
      TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1745
1.02M
}
1746
1747
ParmVarDecl *
1748
TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1749
                                                 int indexAdjustment,
1750
                                               Optional<unsigned> NumExpansions,
1751
1.58M
                                                 bool ExpectParameterPack) {
1752
1.58M
  auto NewParm =
1753
1.58M
      SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1754
1.58M
                               NumExpansions, ExpectParameterPack);
1755
1.58M
  if (NewParm && 
SemaRef.getLangOpts().OpenCL1.56M
)
1756
23
    SemaRef.deduceOpenCLAddressSpace(NewParm);
1757
1.58M
  return NewParm;
1758
1.58M
}
1759
1760
QualType
1761
TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1762
5.20M
                                                TemplateTypeParmTypeLoc TL) {
1763
5.20M
  const TemplateTypeParmType *T = TL.getTypePtr();
1764
5.20M
  if (T->getDepth() < TemplateArgs.getNumLevels()) {
1765
    // Replace the template type parameter with its corresponding
1766
    // template argument.
1767
1768
    // If the corresponding template argument is NULL or doesn't exist, it's
1769
    // because we are performing instantiation from explicitly-specified
1770
    // template arguments in a function template class, but there were some
1771
    // arguments left unspecified.
1772
4.74M
    if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1773
40.0k
      TemplateTypeParmTypeLoc NewTL
1774
40.0k
        = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1775
40.0k
      NewTL.setNameLoc(TL.getNameLoc());
1776
40.0k
      return TL.getType();
1777
40.0k
    }
1778
1779
4.70M
    TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1780
1781
4.70M
    if (TemplateArgs.isRewrite()) {
1782
      // We're rewriting the template parameter as a reference to another
1783
      // template parameter.
1784
1.75k
      if (Arg.getKind() == TemplateArgument::Pack) {
1785
405
        assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1786
405
               "unexpected pack arguments in template rewrite");
1787
0
        Arg = Arg.pack_begin()->getPackExpansionPattern();
1788
405
      }
1789
0
      assert(Arg.getKind() == TemplateArgument::Type &&
1790
1.75k
             "unexpected nontype template argument kind in template rewrite");
1791
0
      QualType NewT = Arg.getAsType();
1792
1.75k
      assert(isa<TemplateTypeParmType>(NewT) &&
1793
1.75k
             "type parm not rewritten to type parm");
1794
0
      auto NewTL = TLB.push<TemplateTypeParmTypeLoc>(NewT);
1795
1.75k
      NewTL.setNameLoc(TL.getNameLoc());
1796
1.75k
      return NewT;
1797
1.75k
    }
1798
1799
4.70M
    if (T->isParameterPack()) {
1800
533k
      assert(Arg.getKind() == TemplateArgument::Pack &&
1801
533k
             "Missing argument pack");
1802
1803
533k
      if (getSema().ArgumentPackSubstitutionIndex == -1) {
1804
        // We have the template argument pack, but we're not expanding the
1805
        // enclosing pack expansion yet. Just save the template argument
1806
        // pack for later substitution.
1807
42.5k
        QualType Result
1808
42.5k
          = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1809
42.5k
        SubstTemplateTypeParmPackTypeLoc NewTL
1810
42.5k
          = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1811
42.5k
        NewTL.setNameLoc(TL.getNameLoc());
1812
42.5k
        return Result;
1813
42.5k
      }
1814
1815
491k
      Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1816
491k
    }
1817
1818
4.65M
    assert(Arg.getKind() == TemplateArgument::Type &&
1819
4.65M
           "Template argument kind mismatch");
1820
1821
0
    QualType Replacement = Arg.getAsType();
1822
1823
    // TODO: only do this uniquing once, at the start of instantiation.
1824
4.65M
    QualType Result
1825
4.65M
      = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1826
4.65M
    SubstTemplateTypeParmTypeLoc NewTL
1827
4.65M
      = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1828
4.65M
    NewTL.setNameLoc(TL.getNameLoc());
1829
4.65M
    return Result;
1830
4.70M
  }
1831
1832
  // The template type parameter comes from an inner template (e.g.,
1833
  // the template parameter list of a member template inside the
1834
  // template we are instantiating). Create a new template type
1835
  // parameter with the template "level" reduced by one.
1836
462k
  TemplateTypeParmDecl *NewTTPDecl = nullptr;
1837
462k
  if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1838
462k
    NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1839
462k
                                  TransformDecl(TL.getNameLoc(), OldTTPDecl));
1840
1841
462k
  QualType Result = getSema().Context.getTemplateTypeParmType(
1842
462k
      T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1843
462k
      T->isParameterPack(), NewTTPDecl);
1844
462k
  TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1845
462k
  NewTL.setNameLoc(TL.getNameLoc());
1846
462k
  return Result;
1847
5.20M
}
1848
1849
QualType
1850
TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1851
                                                            TypeLocBuilder &TLB,
1852
3.98k
                                         SubstTemplateTypeParmPackTypeLoc TL) {
1853
3.98k
  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1854
    // We aren't expanding the parameter pack, so just return ourselves.
1855
7
    SubstTemplateTypeParmPackTypeLoc NewTL
1856
7
      = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1857
7
    NewTL.setNameLoc(TL.getNameLoc());
1858
7
    return TL.getType();
1859
7
  }
1860
1861
3.97k
  TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1862
3.97k
  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1863
3.97k
  QualType Result = Arg.getAsType();
1864
1865
3.97k
  Result = getSema().Context.getSubstTemplateTypeParmType(
1866
3.97k
                                      TL.getTypePtr()->getReplacedParameter(),
1867
3.97k
                                                          Result);
1868
3.97k
  SubstTemplateTypeParmTypeLoc NewTL
1869
3.97k
    = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1870
3.97k
  NewTL.setNameLoc(TL.getNameLoc());
1871
3.97k
  return Result;
1872
3.98k
}
1873
1874
template<typename EntityPrinter>
1875
static concepts::Requirement::SubstitutionDiagnostic *
1876
56
createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1877
56
  SmallString<128> Message;
1878
56
  SourceLocation ErrorLoc;
1879
56
  if (Info.hasSFINAEDiagnostic()) {
1880
55
    PartialDiagnosticAt PDA(SourceLocation(),
1881
55
                            PartialDiagnostic::NullDiagnostic{});
1882
55
    Info.takeSFINAEDiagnostic(PDA);
1883
55
    PDA.second.EmitToString(S.getDiagnostics(), Message);
1884
55
    ErrorLoc = PDA.first;
1885
55
  } else {
1886
1
    ErrorLoc = Info.getLocation();
1887
1
  }
1888
56
  char *MessageBuf = new (S.Context) char[Message.size()];
1889
56
  std::copy(Message.begin(), Message.end(), MessageBuf);
1890
56
  SmallString<128> Entity;
1891
56
  llvm::raw_svector_ostream OS(Entity);
1892
56
  Printer(OS);
1893
56
  char *EntityBuf = new (S.Context) char[Entity.size()];
1894
56
  std::copy(Entity.begin(), Entity.end(), EntityBuf);
1895
56
  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1896
56
      StringRef(EntityBuf, Entity.size()), ErrorLoc,
1897
56
      StringRef(MessageBuf, Message.size())};
1898
56
}
SemaTemplateInstantiate.cpp:clang::concepts::Requirement::SubstitutionDiagnostic* createSubstDiag<(anonymous namespace)::TemplateInstantiator::TransformTypeRequirement(clang::concepts::TypeRequirement*)::$_2>(clang::Sema&, clang::sema::TemplateDeductionInfo&, (anonymous namespace)::TemplateInstantiator::TransformTypeRequirement(clang::concepts::TypeRequirement*)::$_2)
Line
Count
Source
1876
19
createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1877
19
  SmallString<128> Message;
1878
19
  SourceLocation ErrorLoc;
1879
19
  if (Info.hasSFINAEDiagnostic()) {
1880
18
    PartialDiagnosticAt PDA(SourceLocation(),
1881
18
                            PartialDiagnostic::NullDiagnostic{});
1882
18
    Info.takeSFINAEDiagnostic(PDA);
1883
18
    PDA.second.EmitToString(S.getDiagnostics(), Message);
1884
18
    ErrorLoc = PDA.first;
1885
18
  } else {
1886
1
    ErrorLoc = Info.getLocation();
1887
1
  }
1888
19
  char *MessageBuf = new (S.Context) char[Message.size()];
1889
19
  std::copy(Message.begin(), Message.end(), MessageBuf);
1890
19
  SmallString<128> Entity;
1891
19
  llvm::raw_svector_ostream OS(Entity);
1892
19
  Printer(OS);
1893
19
  char *EntityBuf = new (S.Context) char[Entity.size()];
1894
19
  std::copy(Entity.begin(), Entity.end(), EntityBuf);
1895
19
  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1896
19
      StringRef(EntityBuf, Entity.size()), ErrorLoc,
1897
19
      StringRef(MessageBuf, Message.size())};
1898
19
}
SemaTemplateInstantiate.cpp:clang::concepts::Requirement::SubstitutionDiagnostic* createSubstDiag<(anonymous namespace)::TemplateInstantiator::TransformExprRequirement(clang::concepts::ExprRequirement*)::$_3>(clang::Sema&, clang::sema::TemplateDeductionInfo&, (anonymous namespace)::TemplateInstantiator::TransformExprRequirement(clang::concepts::ExprRequirement*)::$_3)
Line
Count
Source
1876
30
createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1877
30
  SmallString<128> Message;
1878
30
  SourceLocation ErrorLoc;
1879
30
  if (Info.hasSFINAEDiagnostic()) {
1880
30
    PartialDiagnosticAt PDA(SourceLocation(),
1881
30
                            PartialDiagnostic::NullDiagnostic{});
1882
30
    Info.takeSFINAEDiagnostic(PDA);
1883
30
    PDA.second.EmitToString(S.getDiagnostics(), Message);
1884
30
    ErrorLoc = PDA.first;
1885
30
  } else {
1886
0
    ErrorLoc = Info.getLocation();
1887
0
  }
1888
30
  char *MessageBuf = new (S.Context) char[Message.size()];
1889
30
  std::copy(Message.begin(), Message.end(), MessageBuf);
1890
30
  SmallString<128> Entity;
1891
30
  llvm::raw_svector_ostream OS(Entity);
1892
30
  Printer(OS);
1893
30
  char *EntityBuf = new (S.Context) char[Entity.size()];
1894
30
  std::copy(Entity.begin(), Entity.end(), EntityBuf);
1895
30
  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1896
30
      StringRef(EntityBuf, Entity.size()), ErrorLoc,
1897
30
      StringRef(MessageBuf, Message.size())};
1898
30
}
SemaTemplateInstantiate.cpp:clang::concepts::Requirement::SubstitutionDiagnostic* createSubstDiag<(anonymous namespace)::TemplateInstantiator::TransformExprRequirement(clang::concepts::ExprRequirement*)::$_4>(clang::Sema&, clang::sema::TemplateDeductionInfo&, (anonymous namespace)::TemplateInstantiator::TransformExprRequirement(clang::concepts::ExprRequirement*)::$_4)
Line
Count
Source
1876
4
createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1877
4
  SmallString<128> Message;
1878
4
  SourceLocation ErrorLoc;
1879
4
  if (Info.hasSFINAEDiagnostic()) {
1880
4
    PartialDiagnosticAt PDA(SourceLocation(),
1881
4
                            PartialDiagnostic::NullDiagnostic{});
1882
4
    Info.takeSFINAEDiagnostic(PDA);
1883
4
    PDA.second.EmitToString(S.getDiagnostics(), Message);
1884
4
    ErrorLoc = PDA.first;
1885
4
  } else {
1886
0
    ErrorLoc = Info.getLocation();
1887
0
  }
1888
4
  char *MessageBuf = new (S.Context) char[Message.size()];
1889
4
  std::copy(Message.begin(), Message.end(), MessageBuf);
1890
4
  SmallString<128> Entity;
1891
4
  llvm::raw_svector_ostream OS(Entity);
1892
4
  Printer(OS);
1893
4
  char *EntityBuf = new (S.Context) char[Entity.size()];
1894
4
  std::copy(Entity.begin(), Entity.end(), EntityBuf);
1895
4
  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1896
4
      StringRef(EntityBuf, Entity.size()), ErrorLoc,
1897
4
      StringRef(MessageBuf, Message.size())};
1898
4
}
SemaTemplateInstantiate.cpp:clang::concepts::Requirement::SubstitutionDiagnostic* createSubstDiag<(anonymous namespace)::TemplateInstantiator::TransformNestedRequirement(clang::concepts::NestedRequirement*)::$_5>(clang::Sema&, clang::sema::TemplateDeductionInfo&, (anonymous namespace)::TemplateInstantiator::TransformNestedRequirement(clang::concepts::NestedRequirement*)::$_5)
Line
Count
Source
1876
3
createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1877
3
  SmallString<128> Message;
1878
3
  SourceLocation ErrorLoc;
1879
3
  if (Info.hasSFINAEDiagnostic()) {
1880
3
    PartialDiagnosticAt PDA(SourceLocation(),
1881
3
                            PartialDiagnostic::NullDiagnostic{});
1882
3
    Info.takeSFINAEDiagnostic(PDA);
1883
3
    PDA.second.EmitToString(S.getDiagnostics(), Message);
1884
3
    ErrorLoc = PDA.first;
1885
3
  } else {
1886
0
    ErrorLoc = Info.getLocation();
1887
0
  }
1888
3
  char *MessageBuf = new (S.Context) char[Message.size()];
1889
3
  std::copy(Message.begin(), Message.end(), MessageBuf);
1890
3
  SmallString<128> Entity;
1891
3
  llvm::raw_svector_ostream OS(Entity);
1892
3
  Printer(OS);
1893
3
  char *EntityBuf = new (S.Context) char[Entity.size()];
1894
3
  std::copy(Entity.begin(), Entity.end(), EntityBuf);
1895
3
  return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1896
3
      StringRef(EntityBuf, Entity.size()), ErrorLoc,
1897
3
      StringRef(MessageBuf, Message.size())};
1898
3
}
1899
1900
concepts::TypeRequirement *
1901
35
TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
1902
35
  if (!Req->isDependent() && 
!AlwaysRebuild()1
)
1903
1
    return Req;
1904
34
  if (Req->isSubstitutionFailure()) {
1905
0
    if (AlwaysRebuild())
1906
0
      return RebuildTypeRequirement(
1907
0
              Req->getSubstitutionDiagnostic());
1908
0
    return Req;
1909
0
  }
1910
1911
34
  Sema::SFINAETrap Trap(SemaRef);
1912
34
  TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
1913
34
  Sema::InstantiatingTemplate TypeInst(SemaRef,
1914
34
      Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
1915
34
      Req->getType()->getTypeLoc().getSourceRange());
1916
34
  if (TypeInst.isInvalid())
1917
0
    return nullptr;
1918
34
  TypeSourceInfo *TransType = TransformType(Req->getType());
1919
34
  if (!TransType || 
Trap.hasErrorOccurred()15
)
1920
19
    return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
1921
19
        [&] (llvm::raw_ostream& OS) {
1922
19
            Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
1923
19
        }));
1924
15
  return RebuildTypeRequirement(TransType);
1925
34
}
1926
1927
concepts::ExprRequirement *
1928
111
TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
1929
111
  if (!Req->isDependent() && 
!AlwaysRebuild()26
)
1930
22
    return Req;
1931
1932
89
  Sema::SFINAETrap Trap(SemaRef);
1933
1934
89
  llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
1935
89
      TransExpr;
1936
89
  if (Req->isExprSubstitutionFailure())
1937
3
    TransExpr = Req->getExprSubstitutionDiagnostic();
1938
86
  else {
1939
86
    Expr *E = Req->getExpr();
1940
86
    TemplateDeductionInfo Info(E->getBeginLoc());
1941
86
    Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
1942
86
                                         E->getSourceRange());
1943
86
    if (ExprInst.isInvalid())
1944
0
      return nullptr;
1945
86
    ExprResult TransExprRes = TransformExpr(E);
1946
86
    if (TransExprRes.isInvalid() || 
Trap.hasErrorOccurred()57
)
1947
30
      TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
1948
30
        E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
1949
30
      });
1950
56
    else
1951
56
      TransExpr = TransExprRes.get();
1952
86
  }
1953
1954
89
  llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
1955
89
  const auto &RetReq = Req->getReturnTypeRequirement();
1956
89
  if (RetReq.isEmpty())
1957
67
    TransRetReq.emplace();
1958
22
  else if (RetReq.isSubstitutionFailure())
1959
0
    TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
1960
22
  else if (RetReq.isTypeConstraint()) {
1961
22
    TemplateParameterList *OrigTPL =
1962
22
        RetReq.getTypeConstraintTemplateParameterList();
1963
22
    TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
1964
22
    Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
1965
22
                                        Req, Info, OrigTPL->getSourceRange());
1966
22
    if (TPLInst.isInvalid())
1967
0
      return nullptr;
1968
22
    TemplateParameterList *TPL =
1969
22
        TransformTemplateParameterList(OrigTPL);
1970
22
    if (!TPL)
1971
4
      TransRetReq.emplace(createSubstDiag(SemaRef, Info,
1972
4
          [&] (llvm::raw_ostream& OS) {
1973
4
              RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
1974
4
                  ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
1975
4
          }));
1976
18
    else {
1977
18
      TPLInst.Clear();
1978
18
      TransRetReq.emplace(TPL);
1979
18
    }
1980
22
  }
1981
89
  assert(TransRetReq.hasValue() &&
1982
89
         "All code paths leading here must set TransRetReq");
1983
89
  if (Expr *E = TransExpr.dyn_cast<Expr *>())
1984
56
    return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
1985
56
                                  std::move(*TransRetReq));
1986
33
  return RebuildExprRequirement(
1987
33
      TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
1988
33
      Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
1989
89
}
1990
1991
concepts::NestedRequirement *
1992
TemplateInstantiator::TransformNestedRequirement(
1993
38
    concepts::NestedRequirement *Req) {
1994
38
  if (!Req->isDependent() && 
!AlwaysRebuild()14
)
1995
14
    return Req;
1996
24
  if (Req->isSubstitutionFailure()) {
1997
0
    if (AlwaysRebuild())
1998
0
      return RebuildNestedRequirement(
1999
0
          Req->getSubstitutionDiagnostic());
2000
0
    return Req;
2001
0
  }
2002
24
  Sema::InstantiatingTemplate ReqInst(SemaRef,
2003
24
      Req->getConstraintExpr()->getBeginLoc(), Req,
2004
24
      Sema::InstantiatingTemplate::ConstraintsCheck{},
2005
24
      Req->getConstraintExpr()->getSourceRange());
2006
2007
24
  ExprResult TransConstraint;
2008
24
  TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc());
2009
24
  {
2010
24
    EnterExpressionEvaluationContext ContextRAII(
2011
24
        SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2012
24
    Sema::SFINAETrap Trap(SemaRef);
2013
24
    Sema::InstantiatingTemplate ConstrInst(SemaRef,
2014
24
        Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2015
24
        Req->getConstraintExpr()->getSourceRange());
2016
24
    if (ConstrInst.isInvalid())
2017
0
      return nullptr;
2018
24
    TransConstraint = TransformExpr(Req->getConstraintExpr());
2019
24
    if (TransConstraint.isInvalid() || 
Trap.hasErrorOccurred()21
)
2020
3
      return RebuildNestedRequirement(createSubstDiag(SemaRef, Info,
2021
3
          [&] (llvm::raw_ostream& OS) {
2022
3
              Req->getConstraintExpr()->printPretty(OS, nullptr,
2023
3
                                                    SemaRef.getPrintingPolicy());
2024
3
          }));
2025
24
  }
2026
21
  return RebuildNestedRequirement(TransConstraint.get());
2027
24
}
2028
2029
2030
/// Perform substitution on the type T with a given set of template
2031
/// arguments.
2032
///
2033
/// This routine substitutes the given template arguments into the
2034
/// type T and produces the instantiated type.
2035
///
2036
/// \param T the type into which the template arguments will be
2037
/// substituted. If this type is not dependent, it will be returned
2038
/// immediately.
2039
///
2040
/// \param Args the template arguments that will be
2041
/// substituted for the top-level template parameters within T.
2042
///
2043
/// \param Loc the location in the source code where this substitution
2044
/// is being performed. It will typically be the location of the
2045
/// declarator (if we're instantiating the type of some declaration)
2046
/// or the location of the type in the source code (if, e.g., we're
2047
/// instantiating the type of a cast expression).
2048
///
2049
/// \param Entity the name of the entity associated with a declaration
2050
/// being instantiated (if any). May be empty to indicate that there
2051
/// is no such entity (if, e.g., this is a type that occurs as part of
2052
/// a cast expression) or that the entity has no name (e.g., an
2053
/// unnamed function parameter).
2054
///
2055
/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2056
/// acceptable as the top level type of the result.
2057
///
2058
/// \returns If the instantiation succeeds, the instantiated
2059
/// type. Otherwise, produces diagnostics and returns a NULL type.
2060
TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
2061
                                const MultiLevelTemplateArgumentList &Args,
2062
                                SourceLocation Loc,
2063
                                DeclarationName Entity,
2064
3.37M
                                bool AllowDeducedTST) {
2065
3.37M
  assert(!CodeSynthesisContexts.empty() &&
2066
3.37M
         "Cannot perform an instantiation without some context on the "
2067
3.37M
         "instantiation stack");
2068
2069
3.37M
  if (!T->getType()->isInstantiationDependentType() &&
2070
3.37M
      
!T->getType()->isVariablyModifiedType()743k
)
2071
743k
    return T;
2072
2073
2.62M
  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2074
2.62M
  return AllowDeducedTST ? 
Instantiator.TransformTypeWithDeducedTST(T)73.4k
2075
2.62M
                         : 
Instantiator.TransformType(T)2.55M
;
2076
3.37M
}
2077
2078
TypeSourceInfo *Sema::SubstType(TypeLoc TL,
2079
                                const MultiLevelTemplateArgumentList &Args,
2080
                                SourceLocation Loc,
2081
33.0k
                                DeclarationName Entity) {
2082
33.0k
  assert(!CodeSynthesisContexts.empty() &&
2083
33.0k
         "Cannot perform an instantiation without some context on the "
2084
33.0k
         "instantiation stack");
2085
2086
33.0k
  if (TL.getType().isNull())
2087
0
    return nullptr;
2088
2089
33.0k
  if (!TL.getType()->isInstantiationDependentType() &&
2090
33.0k
      
!TL.getType()->isVariablyModifiedType()0
) {
2091
    // FIXME: Make a copy of the TypeLoc data here, so that we can
2092
    // return a new TypeSourceInfo. Inefficient!
2093
0
    TypeLocBuilder TLB;
2094
0
    TLB.pushFullCopy(TL);
2095
0
    return TLB.getTypeSourceInfo(Context, TL.getType());
2096
0
  }
2097
2098
33.0k
  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2099
33.0k
  TypeLocBuilder TLB;
2100
33.0k
  TLB.reserve(TL.getFullDataSize());
2101
33.0k
  QualType Result = Instantiator.TransformType(TLB, TL);
2102
33.0k
  if (Result.isNull())
2103
0
    return nullptr;
2104
2105
33.0k
  return TLB.getTypeSourceInfo(Context, Result);
2106
33.0k
}
2107
2108
/// Deprecated form of the above.
2109
QualType Sema::SubstType(QualType T,
2110
                         const MultiLevelTemplateArgumentList &TemplateArgs,
2111
1.54M
                         SourceLocation Loc, DeclarationName Entity) {
2112
1.54M
  assert(!CodeSynthesisContexts.empty() &&
2113
1.54M
         "Cannot perform an instantiation without some context on the "
2114
1.54M
         "instantiation stack");
2115
2116
  // If T is not a dependent type or a variably-modified type, there
2117
  // is nothing to do.
2118
1.54M
  if (!T->isInstantiationDependentType() && 
!T->isVariablyModifiedType()130k
)
2119
130k
    return T;
2120
2121
1.41M
  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2122
1.41M
  return Instantiator.TransformType(T);
2123
1.54M
}
2124
2125
1.16M
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
2126
1.16M
  if (T->getType()->isInstantiationDependentType() ||
2127
1.16M
      
T->getType()->isVariablyModifiedType()188k
)
2128
979k
    return true;
2129
2130
188k
  TypeLoc TL = T->getTypeLoc().IgnoreParens();
2131
188k
  if (!TL.getAs<FunctionProtoTypeLoc>())
2132
23
    return false;
2133
2134
188k
  FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
2135
188k
  for (ParmVarDecl *P : FP.getParams()) {
2136
    // This must be synthesized from a typedef.
2137
46.0k
    if (!P) 
continue19
;
2138
2139
    // If there are any parameters, a new TypeSourceInfo that refers to the
2140
    // instantiated parameters must be built.
2141
46.0k
    return true;
2142
46.0k
  }
2143
2144
142k
  return false;
2145
188k
}
2146
2147
/// A form of SubstType intended specifically for instantiating the
2148
/// type of a FunctionDecl.  Its purpose is solely to force the
2149
/// instantiation of default-argument expressions and to avoid
2150
/// instantiating an exception-specification.
2151
TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
2152
                                const MultiLevelTemplateArgumentList &Args,
2153
                                SourceLocation Loc,
2154
                                DeclarationName Entity,
2155
                                CXXRecordDecl *ThisContext,
2156
1.16M
                                Qualifiers ThisTypeQuals) {
2157
1.16M
  assert(!CodeSynthesisContexts.empty() &&
2158
1.16M
         "Cannot perform an instantiation without some context on the "
2159
1.16M
         "instantiation stack");
2160
2161
1.16M
  if (!NeedsInstantiationAsFunctionType(T))
2162
142k
    return T;
2163
2164
1.02M
  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2165
2166
1.02M
  TypeLocBuilder TLB;
2167
2168
1.02M
  TypeLoc TL = T->getTypeLoc();
2169
1.02M
  TLB.reserve(TL.getFullDataSize());
2170
2171
1.02M
  QualType Result;
2172
2173
1.02M
  if (FunctionProtoTypeLoc Proto =
2174
1.02M
          TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
2175
    // Instantiate the type, other than its exception specification. The
2176
    // exception specification is instantiated in InitFunctionInstantiation
2177
    // once we've built the FunctionDecl.
2178
    // FIXME: Set the exception specification to EST_Uninstantiated here,
2179
    // instead of rebuilding the function type again later.
2180
1.02M
    Result = Instantiator.TransformFunctionProtoType(
2181
1.02M
        TLB, Proto, ThisContext, ThisTypeQuals,
2182
1.02M
        [](FunctionProtoType::ExceptionSpecInfo &ESI,
2183
1.02M
           bool &Changed) 
{ return false; }976k
);
2184
1.02M
  } else {
2185
65
    Result = Instantiator.TransformType(TLB, TL);
2186
65
  }
2187
1.02M
  if (Result.isNull())
2188
49.0k
    return nullptr;
2189
2190
976k
  return TLB.getTypeSourceInfo(Context, Result);
2191
1.02M
}
2192
2193
bool Sema::SubstExceptionSpec(SourceLocation Loc,
2194
                              FunctionProtoType::ExceptionSpecInfo &ESI,
2195
                              SmallVectorImpl<QualType> &ExceptionStorage,
2196
411k
                              const MultiLevelTemplateArgumentList &Args) {
2197
411k
  assert(ESI.Type != EST_Uninstantiated);
2198
2199
0
  bool Changed = false;
2200
411k
  TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2201
411k
  return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2202
411k
                                             Changed);
2203
411k
}
2204
2205
void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
2206
409k
                              const MultiLevelTemplateArgumentList &Args) {
2207
409k
  FunctionProtoType::ExceptionSpecInfo ESI =
2208
409k
      Proto->getExtProtoInfo().ExceptionSpec;
2209
2210
409k
  SmallVector<QualType, 4> ExceptionStorage;
2211
409k
  if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2212
409k
                         ESI, ExceptionStorage, Args))
2213
    // On error, recover by dropping the exception specification.
2214
38
    ESI.Type = EST_None;
2215
2216
409k
  UpdateExceptionSpec(New, ESI);
2217
409k
}
2218
2219
namespace {
2220
2221
  struct GetContainedInventedTypeParmVisitor :
2222
    public TypeVisitor<GetContainedInventedTypeParmVisitor,
2223
                       TemplateTypeParmDecl *> {
2224
    using TypeVisitor<GetContainedInventedTypeParmVisitor,
2225
                      TemplateTypeParmDecl *>::Visit;
2226
2227
2.33M
    TemplateTypeParmDecl *Visit(QualType T) {
2228
2.33M
      if (T.isNull())
2229
0
        return nullptr;
2230
2.33M
      return Visit(T.getTypePtr());
2231
2.33M
    }
2232
    // The deduced type itself.
2233
    TemplateTypeParmDecl *VisitTemplateTypeParmType(
2234
456k
        const TemplateTypeParmType *T) {
2235
456k
      if (!T->getDecl() || 
!T->getDecl()->isImplicit()456k
)
2236
447k
        return nullptr;
2237
9.03k
      return T->getDecl();
2238
456k
    }
2239
2240
    // Only these types can contain 'auto' types, and subsequently be replaced
2241
    // by references to invented parameters.
2242
2243
16.7k
    TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2244
16.7k
      return Visit(T->getNamedType());
2245
16.7k
    }
2246
2247
202k
    TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2248
202k
      return Visit(T->getPointeeType());
2249
202k
    }
2250
2251
1
    TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2252
1
      return Visit(T->getPointeeType());
2253
1
    }
2254
2255
516k
    TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2256
516k
      return Visit(T->getPointeeTypeAsWritten());
2257
516k
    }
2258
2259
66
    TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2260
66
      return Visit(T->getPointeeType());
2261
66
    }
2262
2263
632
    TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2264
632
      return Visit(T->getElementType());
2265
632
    }
2266
2267
    TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2268
0
      const DependentSizedExtVectorType *T) {
2269
0
      return Visit(T->getElementType());
2270
0
    }
2271
2272
0
    TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2273
0
      return Visit(T->getElementType());
2274
0
    }
2275
2276
1.54k
    TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2277
1.54k
      return VisitFunctionType(T);
2278
1.54k
    }
2279
2280
1.54k
    TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2281
1.54k
      return Visit(T->getReturnType());
2282
1.54k
    }
2283
2284
1.98k
    TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2285
1.98k
      return Visit(T->getInnerType());
2286
1.98k
    }
2287
2288
37
    TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2289
37
      return Visit(T->getModifiedType());
2290
37
    }
2291
2292
2
    TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2293
2
      return Visit(T->getUnderlyingType());
2294
2
    }
2295
2296
0
    TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2297
0
      return Visit(T->getOriginalType());
2298
0
    }
2299
2300
32.8k
    TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2301
32.8k
      return Visit(T->getPattern());
2302
32.8k
    }
2303
  };
2304
2305
} // namespace
2306
2307
bool Sema::SubstTypeConstraint(
2308
    TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
2309
48
    const MultiLevelTemplateArgumentList &TemplateArgs) {
2310
48
  const ASTTemplateArgumentListInfo *TemplArgInfo =
2311
48
      TC->getTemplateArgsAsWritten();
2312
48
  TemplateArgumentListInfo InstArgs;
2313
2314
48
  if (TemplArgInfo) {
2315
40
    InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2316
40
    InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2317
40
    if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
2318
40
                               InstArgs))
2319
4
      return true;
2320
40
  }
2321
44
  return AttachTypeConstraint(
2322
44
      TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2323
44
      TC->getNamedConcept(), &InstArgs, Inst,
2324
44
      Inst->isParameterPack()
2325
44
          ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2326
4
                ->getEllipsisLoc()
2327
44
          : 
SourceLocation()40
);
2328
48
}
2329
2330
ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
2331
                            const MultiLevelTemplateArgumentList &TemplateArgs,
2332
                                    int indexAdjustment,
2333
                                    Optional<unsigned> NumExpansions,
2334
1.58M
                                    bool ExpectParameterPack) {
2335
1.58M
  TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
2336
1.58M
  TypeSourceInfo *NewDI = nullptr;
2337
2338
1.58M
  TypeLoc OldTL = OldDI->getTypeLoc();
2339
1.58M
  if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
2340
2341
    // We have a function parameter pack. Substitute into the pattern of the
2342
    // expansion.
2343
32.8k
    NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
2344
32.8k
                      OldParm->getLocation(), OldParm->getDeclName());
2345
32.8k
    if (!NewDI)
2346
0
      return nullptr;
2347
2348
32.8k
    if (NewDI->getType()->containsUnexpandedParameterPack()) {
2349
      // We still have unexpanded parameter packs, which means that
2350
      // our function parameter is still a function parameter pack.
2351
      // Therefore, make its type a pack expansion type.
2352
15.5k
      NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
2353
15.5k
                                 NumExpansions);
2354
17.2k
    } else if (ExpectParameterPack) {
2355
      // We expected to get a parameter pack but didn't (because the type
2356
      // itself is not a pack expansion type), so complain. This can occur when
2357
      // the substitution goes through an alias template that "loses" the
2358
      // pack expansion.
2359
0
      Diag(OldParm->getLocation(),
2360
0
           diag::err_function_parameter_pack_without_parameter_packs)
2361
0
        << NewDI->getType();
2362
0
      return nullptr;
2363
0
    }
2364
1.55M
  } else {
2365
1.55M
    NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
2366
1.55M
                      OldParm->getDeclName());
2367
1.55M
  }
2368
2369
1.58M
  if (!NewDI)
2370
21.1k
    return nullptr;
2371
2372
1.56M
  if (NewDI->getType()->isVoidType()) {
2373
16
    Diag(OldParm->getLocation(), diag::err_param_with_void_type);
2374
16
    return nullptr;
2375
16
  }
2376
2377
  // In abbreviated templates, TemplateTypeParmDecls with possible
2378
  // TypeConstraints are created when the parameter list is originally parsed.
2379
  // The TypeConstraints can therefore reference other functions parameters in
2380
  // the abbreviated function template, which is why we must instantiate them
2381
  // here, when the instantiated versions of those referenced parameters are in
2382
  // scope.
2383
1.56M
  if (TemplateTypeParmDecl *TTP =
2384
1.56M
          GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
2385
9.03k
    if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
2386
109
      auto *Inst = cast_or_null<TemplateTypeParmDecl>(
2387
109
          FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
2388
      // We will first get here when instantiating the abbreviated function
2389
      // template's described function, but we might also get here later.
2390
      // Make sure we do not instantiate the TypeConstraint more than once.
2391
109
      if (Inst && !Inst->getTypeConstraint()) {
2392
        // TODO: Concepts: do not instantiate the constraint (delayed constraint
2393
        // substitution)
2394
12
        if (SubstTypeConstraint(Inst, TC, TemplateArgs))
2395
0
          return nullptr;
2396
12
      }
2397
109
    }
2398
9.03k
  }
2399
2400
1.56M
  ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
2401
1.56M
                                        OldParm->getInnerLocStart(),
2402
1.56M
                                        OldParm->getLocation(),
2403
1.56M
                                        OldParm->getIdentifier(),
2404
1.56M
                                        NewDI->getType(), NewDI,
2405
1.56M
                                        OldParm->getStorageClass());
2406
1.56M
  if (!NewParm)
2407
0
    return nullptr;
2408
2409
  // Mark the (new) default argument as uninstantiated (if any).
2410
1.56M
  if (OldParm->hasUninstantiatedDefaultArg()) {
2411
11.3k
    Expr *Arg = OldParm->getUninstantiatedDefaultArg();
2412
11.3k
    NewParm->setUninstantiatedDefaultArg(Arg);
2413
1.55M
  } else if (OldParm->hasUnparsedDefaultArg()) {
2414
13
    NewParm->setUnparsedDefaultArg();
2415
13
    UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
2416
1.55M
  } else if (Expr *Arg = OldParm->getDefaultArg()) {
2417
80.4k
    FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
2418
80.4k
    if (OwningFunc->isInLocalScopeForInstantiation()) {
2419
      // Instantiate default arguments for methods of local classes (DR1484)
2420
      // and non-defining declarations.
2421
48
      Sema::ContextRAII SavedContext(*this, OwningFunc);
2422
48
      LocalInstantiationScope Local(*this, true);
2423
48
      ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
2424
48
      if (NewArg.isUsable()) {
2425
        // It would be nice if we still had this.
2426
37
        SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
2427
37
        ExprResult Result =
2428
37
            ConvertParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
2429
37
        if (Result.isInvalid())
2430
7
          return nullptr;
2431
2432
30
        SetParamDefaultArgument(NewParm, Result.getAs<Expr>(), EqualLoc);
2433
30
      }
2434
80.3k
    } else {
2435
      // FIXME: if we non-lazily instantiated non-dependent default args for
2436
      // non-dependent parameter types we could remove a bunch of duplicate
2437
      // conversion warnings for such arguments.
2438
80.3k
      NewParm->setUninstantiatedDefaultArg(Arg);
2439
80.3k
    }
2440
80.4k
  }
2441
2442
1.56M
  NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
2443
2444
1.56M
  if (OldParm->isParameterPack() && 
!NewParm->isParameterPack()32.8k
) {
2445
    // Add the new parameter to the instantiated parameter pack.
2446
17.2k
    CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
2447
1.54M
  } else {
2448
    // Introduce an Old -> New mapping
2449
1.54M
    CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
2450
1.54M
  }
2451
2452
  // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
2453
  // can be anything, is this right ?
2454
1.56M
  NewParm->setDeclContext(CurContext);
2455
2456
1.56M
  NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
2457
1.56M
                        OldParm->getFunctionScopeIndex() + indexAdjustment);
2458
2459
1.56M
  InstantiateAttrs(TemplateArgs, OldParm, NewParm);
2460
2461
1.56M
  return NewParm;
2462
1.56M
}
2463
2464
/// Substitute the given template arguments into the given set of
2465
/// parameters, producing the set of parameter types that would be generated
2466
/// from such a substitution.
2467
bool Sema::SubstParmTypes(
2468
    SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
2469
    const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
2470
    const MultiLevelTemplateArgumentList &TemplateArgs,
2471
    SmallVectorImpl<QualType> &ParamTypes,
2472
    SmallVectorImpl<ParmVarDecl *> *OutParams,
2473
248k
    ExtParameterInfoBuilder &ParamInfos) {
2474
248k
  assert(!CodeSynthesisContexts.empty() &&
2475
248k
         "Cannot perform an instantiation without some context on the "
2476
248k
         "instantiation stack");
2477
2478
0
  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2479
248k
                                    DeclarationName());
2480
248k
  return Instantiator.TransformFunctionTypeParams(
2481
248k
      Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
2482
248k
}
2483
2484
/// Perform substitution on the base class specifiers of the
2485
/// given class template specialization.
2486
///
2487
/// Produces a diagnostic and returns true on error, returns false and
2488
/// attaches the instantiated base classes to the class template
2489
/// specialization if successful.
2490
bool
2491
Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
2492
                          CXXRecordDecl *Pattern,
2493
761k
                          const MultiLevelTemplateArgumentList &TemplateArgs) {
2494
761k
  bool Invalid = false;
2495
761k
  SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
2496
761k
  for (const auto &Base : Pattern->bases()) {
2497
302k
    if (!Base.getType()->isDependentType()) {
2498
60.3k
      if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
2499
60.3k
        if (RD->isInvalidDecl())
2500
4
          Instantiation->setInvalidDecl();
2501
60.3k
      }
2502
60.3k
      InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
2503
60.3k
      continue;
2504
60.3k
    }
2505
2506
242k
    SourceLocation EllipsisLoc;
2507
242k
    TypeSourceInfo *BaseTypeLoc;
2508
242k
    if (Base.isPackExpansion()) {
2509
      // This is a pack expansion. See whether we should expand it now, or
2510
      // wait until later.
2511
453
      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2512
453
      collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
2513
453
                                      Unexpanded);
2514
453
      bool ShouldExpand = false;
2515
453
      bool RetainExpansion = false;
2516
453
      Optional<unsigned> NumExpansions;
2517
453
      if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
2518
453
                                          Base.getSourceRange(),
2519
453
                                          Unexpanded,
2520
453
                                          TemplateArgs, ShouldExpand,
2521
453
                                          RetainExpansion,
2522
453
                                          NumExpansions)) {
2523
0
        Invalid = true;
2524
0
        continue;
2525
0
      }
2526
2527
      // If we should expand this pack expansion now, do so.
2528
453
      if (ShouldExpand) {
2529
1.27k
        for (unsigned I = 0; I != *NumExpansions; 
++I819
) {
2530
819
            Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2531
2532
819
          TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2533
819
                                                  TemplateArgs,
2534
819
                                              Base.getSourceRange().getBegin(),
2535
819
                                                  DeclarationName());
2536
819
          if (!BaseTypeLoc) {
2537
0
            Invalid = true;
2538
0
            continue;
2539
0
          }
2540
2541
819
          if (CXXBaseSpecifier *InstantiatedBase
2542
819
                = CheckBaseSpecifier(Instantiation,
2543
819
                                     Base.getSourceRange(),
2544
819
                                     Base.isVirtual(),
2545
819
                                     Base.getAccessSpecifierAsWritten(),
2546
819
                                     BaseTypeLoc,
2547
819
                                     SourceLocation()))
2548
819
            InstantiatedBases.push_back(InstantiatedBase);
2549
0
          else
2550
0
            Invalid = true;
2551
819
        }
2552
2553
453
        continue;
2554
453
      }
2555
2556
      // The resulting base specifier will (still) be a pack expansion.
2557
0
      EllipsisLoc = Base.getEllipsisLoc();
2558
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2559
0
      BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2560
0
                              TemplateArgs,
2561
0
                              Base.getSourceRange().getBegin(),
2562
0
                              DeclarationName());
2563
241k
    } else {
2564
241k
      BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2565
241k
                              TemplateArgs,
2566
241k
                              Base.getSourceRange().getBegin(),
2567
241k
                              DeclarationName());
2568
241k
    }
2569
2570
241k
    if (!BaseTypeLoc) {
2571
10
      Invalid = true;
2572
10
      continue;
2573
10
    }
2574
2575
241k
    if (CXXBaseSpecifier *InstantiatedBase
2576
241k
          = CheckBaseSpecifier(Instantiation,
2577
241k
                               Base.getSourceRange(),
2578
241k
                               Base.isVirtual(),
2579
241k
                               Base.getAccessSpecifierAsWritten(),
2580
241k
                               BaseTypeLoc,
2581
241k
                               EllipsisLoc))
2582
240k
      InstantiatedBases.push_back(InstantiatedBase);
2583
1.07k
    else
2584
1.07k
      Invalid = true;
2585
241k
  }
2586
2587
761k
  if (!Invalid && 
AttachBaseSpecifiers(Instantiation, InstantiatedBases)759k
)
2588
2
    Invalid = true;
2589
2590
761k
  return Invalid;
2591
761k
}
2592
2593
// Defined via #include from SemaTemplateInstantiateDecl.cpp
2594
namespace clang {
2595
  namespace sema {
2596
    Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
2597
                            const MultiLevelTemplateArgumentList &TemplateArgs);
2598
    Attr *instantiateTemplateAttributeForDecl(
2599
        const Attr *At, ASTContext &C, Sema &S,
2600
        const MultiLevelTemplateArgumentList &TemplateArgs);
2601
  }
2602
}
2603
2604
/// Instantiate the definition of a class from a given pattern.
2605
///
2606
/// \param PointOfInstantiation The point of instantiation within the
2607
/// source code.
2608
///
2609
/// \param Instantiation is the declaration whose definition is being
2610
/// instantiated. This will be either a class template specialization
2611
/// or a member class of a class template specialization.
2612
///
2613
/// \param Pattern is the pattern from which the instantiation
2614
/// occurs. This will be either the declaration of a class template or
2615
/// the declaration of a member class of a class template.
2616
///
2617
/// \param TemplateArgs The template arguments to be substituted into
2618
/// the pattern.
2619
///
2620
/// \param TSK the kind of implicit or explicit instantiation to perform.
2621
///
2622
/// \param Complain whether to complain if the class cannot be instantiated due
2623
/// to the lack of a definition.
2624
///
2625
/// \returns true if an error occurred, false otherwise.
2626
bool
2627
Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2628
                       CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
2629
                       const MultiLevelTemplateArgumentList &TemplateArgs,
2630
                       TemplateSpecializationKind TSK,
2631
796k
                       bool Complain) {
2632
796k
  CXXRecordDecl *PatternDef
2633
796k
    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
2634
796k
  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2635
796k
                                Instantiation->getInstantiatedFromMemberClass(),
2636
796k
                                     Pattern, PatternDef, TSK, Complain))
2637
35.9k
    return true;
2638
2639
761k
  llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
2640
1
    std::string Name;
2641
1
    llvm::raw_string_ostream OS(Name);
2642
1
    Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2643
1
                                        /*Qualified=*/true);
2644
1
    return Name;
2645
1
  });
2646
2647
761k
  Pattern = PatternDef;
2648
2649
  // Record the point of instantiation.
2650
761k
  if (MemberSpecializationInfo *MSInfo
2651
761k
        = Instantiation->getMemberSpecializationInfo()) {
2652
10.7k
    MSInfo->setTemplateSpecializationKind(TSK);
2653
10.7k
    MSInfo->setPointOfInstantiation(PointOfInstantiation);
2654
750k
  } else if (ClassTemplateSpecializationDecl *Spec
2655
750k
        = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2656
750k
    Spec->setTemplateSpecializationKind(TSK);
2657
750k
    Spec->setPointOfInstantiation(PointOfInstantiation);
2658
750k
  }
2659
2660
761k
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2661
761k
  if (Inst.isInvalid())
2662
1
    return true;
2663
761k
  assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
2664
0
  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2665
761k
                                      "instantiating class definition");
2666
2667
  // Enter the scope of this instantiation. We don't use
2668
  // PushDeclContext because we don't have a scope.
2669
761k
  ContextRAII SavedContext(*this, Instantiation);
2670
761k
  EnterExpressionEvaluationContext EvalContext(
2671
761k
      *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2672
2673
  // If this is an instantiation of a local class, merge this local
2674
  // instantiation scope with the enclosing scope. Otherwise, every
2675
  // instantiation of a class has its own local instantiation scope.
2676
761k
  bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2677
761k
  LocalInstantiationScope Scope(*this, MergeWithParentScope);
2678
2679
  // Some class state isn't processed immediately but delayed till class
2680
  // instantiation completes. We may not be ready to handle any delayed state
2681
  // already on the stack as it might correspond to a different class, so save
2682
  // it now and put it back later.
2683
761k
  SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
2684
2685
  // Pull attributes from the pattern onto the instantiation.
2686
761k
  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2687
2688
  // Start the definition of this instantiation.
2689
761k
  Instantiation->startDefinition();
2690
2691
  // The instantiation is visible here, even if it was first declared in an
2692
  // unimported module.
2693
761k
  Instantiation->setVisibleDespiteOwningModule();
2694
2695
  // FIXME: This loses the as-written tag kind for an explicit instantiation.
2696
761k
  Instantiation->setTagKind(Pattern->getTagKind());
2697
2698
  // Do substitution on the base class specifiers.
2699
761k
  if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2700
1.08k
    Instantiation->setInvalidDecl();
2701
2702
761k
  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2703
761k
  SmallVector<Decl*, 4> Fields;
2704
  // Delay instantiation of late parsed attributes.
2705
761k
  LateInstantiatedAttrVec LateAttrs;
2706
761k
  Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2707
2708
761k
  bool MightHaveConstexprVirtualFunctions = false;
2709
2.82M
  for (auto *Member : Pattern->decls()) {
2710
    // Don't instantiate members not belonging in this semantic context.
2711
    // e.g. for:
2712
    // @code
2713
    //    template <int i> class A {
2714
    //      class B *g;
2715
    //    };
2716
    // @endcode
2717
    // 'class B' has the template as lexical context but semantically it is
2718
    // introduced in namespace scope.
2719
2.82M
    if (Member->getDeclContext() != Pattern)
2720
218
      continue;
2721
2722
    // BlockDecls can appear in a default-member-initializer. They must be the
2723
    // child of a BlockExpr, so we only know how to instantiate them from there.
2724
    // Similarly, lambda closure types are recreated when instantiating the
2725
    // corresponding LambdaExpr.
2726
2.82M
    if (isa<BlockDecl>(Member) ||
2727
2.82M
        
(2.82M
isa<CXXRecordDecl>(Member)2.82M
&&
cast<CXXRecordDecl>(Member)->isLambda()780k
))
2728
206
      continue;
2729
2730
2.82M
    if (Member->isInvalidDecl()) {
2731
117
      Instantiation->setInvalidDecl();
2732
117
      continue;
2733
117
    }
2734
2735
2.82M
    Decl *NewMember = Instantiator.Visit(Member);
2736
2.82M
    if (NewMember) {
2737
2.82M
      if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2738
64.9k
        Fields.push_back(Field);
2739
2.76M
      } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2740
        // C++11 [temp.inst]p1: The implicit instantiation of a class template
2741
        // specialization causes the implicit instantiation of the definitions
2742
        // of unscoped member enumerations.
2743
        // Record a point of instantiation for this implicit instantiation.
2744
2.84k
        if (TSK == TSK_ImplicitInstantiation && 
!Enum->isScoped()2.81k
&&
2745
2.84k
            
Enum->isCompleteDefinition()2.71k
) {
2746
2.70k
          MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2747
2.70k
          assert(MSInfo && "no spec info for member enum specialization");
2748
0
          MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2749
2.70k
          MSInfo->setPointOfInstantiation(PointOfInstantiation);
2750
2.70k
        }
2751
2.75M
      } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2752
39.8k
        if (SA->isFailed()) {
2753
          // A static_assert failed. Bail out; instantiating this
2754
          // class is probably not meaningful.
2755
12
          Instantiation->setInvalidDecl();
2756
12
          break;
2757
12
        }
2758
2.71M
      } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2759
683k
        if (MD->isConstexpr() && 
!MD->getFriendObjectKind()133k
&&
2760
683k
            
(133k
MD->isVirtualAsWritten()133k
||
Instantiation->getNumBases()133k
))
2761
49.6k
          MightHaveConstexprVirtualFunctions = true;
2762
683k
      }
2763
2764
2.82M
      if (NewMember->isInvalidDecl())
2765
460
        Instantiation->setInvalidDecl();
2766
2.82M
    } else {
2767
      // FIXME: Eventually, a NULL return will mean that one of the
2768
      // instantiations was a semantic disaster, and we'll want to mark the
2769
      // declaration invalid.
2770
      // For now, we expect to skip some members that we can't yet handle.
2771
482
    }
2772
2.82M
  }
2773
2774
  // Finish checking fields.
2775
761k
  ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2776
761k
              SourceLocation(), SourceLocation(), ParsedAttributesView());
2777
761k
  CheckCompletedCXXClass(nullptr, Instantiation);
2778
2779
  // Default arguments are parsed, if not instantiated. We can go instantiate
2780
  // default arg exprs for default constructors if necessary now. Unless we're
2781
  // parsing a class, in which case wait until that's finished.
2782
761k
  if (ParsingClassDepth == 0)
2783
576k
    ActOnFinishCXXNonNestedClass();
2784
2785
  // Instantiate late parsed attributes, and attach them to their decls.
2786
  // See Sema::InstantiateAttrs
2787
761k
  for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2788
761k
       E = LateAttrs.end(); I != E; 
++I82
) {
2789
82
    assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2790
0
    CurrentInstantiationScope = I->Scope;
2791
2792
    // Allow 'this' within late-parsed attributes.
2793
82
    auto *ND = cast<NamedDecl>(I->NewDecl);
2794
82
    auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2795
82
    CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
2796
82
                               ND->isCXXInstanceMember());
2797
2798
82
    Attr *NewAttr =
2799
82
      instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2800
82
    if (NewAttr)
2801
82
      I->NewDecl->addAttr(NewAttr);
2802
82
    LocalInstantiationScope::deleteScopes(I->Scope,
2803
82
                                          Instantiator.getStartingScope());
2804
82
  }
2805
761k
  Instantiator.disableLateAttributeInstantiation();
2806
761k
  LateAttrs.clear();
2807
2808
761k
  ActOnFinishDelayedMemberInitializers(Instantiation);
2809
2810
  // FIXME: We should do something similar for explicit instantiations so they
2811
  // end up in the right module.
2812
761k
  if (TSK == TSK_ImplicitInstantiation) {
2813
754k
    Instantiation->setLocation(Pattern->getLocation());
2814
754k
    Instantiation->setLocStart(Pattern->getInnerLocStart());
2815
754k
    Instantiation->setBraceRange(Pattern->getBraceRange());
2816
754k
  }
2817
2818
761k
  if (!Instantiation->isInvalidDecl()) {
2819
    // Perform any dependent diagnostics from the pattern.
2820
759k
    if (Pattern->isDependentContext())
2821
759k
      PerformDependentDiagnostics(Pattern, TemplateArgs);
2822
2823
    // Instantiate any out-of-line class template partial
2824
    // specializations now.
2825
759k
    for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2826
759k
              P = Instantiator.delayed_partial_spec_begin(),
2827
759k
           PEnd = Instantiator.delayed_partial_spec_end();
2828
759k
         P != PEnd; 
++P9
) {
2829
9
      if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2830
9
              P->first, P->second)) {
2831
0
        Instantiation->setInvalidDecl();
2832
0
        break;
2833
0
      }
2834
9
    }
2835
2836
    // Instantiate any out-of-line variable template partial
2837
    // specializations now.
2838
759k
    for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2839
759k
              P = Instantiator.delayed_var_partial_spec_begin(),
2840
759k
           PEnd = Instantiator.delayed_var_partial_spec_end();
2841
759k
         P != PEnd; 
++P7
) {
2842
7
      if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2843
7
              P->first, P->second)) {
2844
0
        Instantiation->setInvalidDecl();
2845
0
        break;
2846
0
      }
2847
7
    }
2848
759k
  }
2849
2850
  // Exit the scope of this instantiation.
2851
761k
  SavedContext.pop();
2852
2853
761k
  if (!Instantiation->isInvalidDecl()) {
2854
    // Always emit the vtable for an explicit instantiation definition
2855
    // of a polymorphic class template specialization. Otherwise, eagerly
2856
    // instantiate only constexpr virtual functions in preparation for their use
2857
    // in constant evaluation.
2858
759k
    if (TSK == TSK_ExplicitInstantiationDefinition)
2859
1.54k
      MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2860
757k
    else if (MightHaveConstexprVirtualFunctions)
2861
11.2k
      MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2862
11.2k
                                   /*ConstexprOnly*/ true);
2863
759k
  }
2864
2865
761k
  Consumer.HandleTagDeclDefinition(Instantiation);
2866
2867
761k
  return Instantiation->isInvalidDecl();
2868
761k
}
2869
2870
/// Instantiate the definition of an enum from a given pattern.
2871
///
2872
/// \param PointOfInstantiation The point of instantiation within the
2873
///        source code.
2874
/// \param Instantiation is the declaration whose definition is being
2875
///        instantiated. This will be a member enumeration of a class
2876
///        temploid specialization, or a local enumeration within a
2877
///        function temploid specialization.
2878
/// \param Pattern The templated declaration from which the instantiation
2879
///        occurs.
2880
/// \param TemplateArgs The template arguments to be substituted into
2881
///        the pattern.
2882
/// \param TSK The kind of implicit or explicit instantiation to perform.
2883
///
2884
/// \return \c true if an error occurred, \c false otherwise.
2885
bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2886
                           EnumDecl *Instantiation, EnumDecl *Pattern,
2887
                           const MultiLevelTemplateArgumentList &TemplateArgs,
2888
48
                           TemplateSpecializationKind TSK) {
2889
48
  EnumDecl *PatternDef = Pattern->getDefinition();
2890
48
  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2891
48
                                 Instantiation->getInstantiatedFromMemberEnum(),
2892
48
                                     Pattern, PatternDef, TSK,/*Complain*/true))
2893
6
    return true;
2894
42
  Pattern = PatternDef;
2895
2896
  // Record the point of instantiation.
2897
42
  if (MemberSpecializationInfo *MSInfo
2898
42
        = Instantiation->getMemberSpecializationInfo()) {
2899
42
    MSInfo->setTemplateSpecializationKind(TSK);
2900
42
    MSInfo->setPointOfInstantiation(PointOfInstantiation);
2901
42
  }
2902
2903
42
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2904
42
  if (Inst.isInvalid())
2905
0
    return true;
2906
42
  if (Inst.isAlreadyInstantiating())
2907
0
    return false;
2908
42
  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2909
42
                                      "instantiating enum definition");
2910
2911
  // The instantiation is visible here, even if it was first declared in an
2912
  // unimported module.
2913
42
  Instantiation->setVisibleDespiteOwningModule();
2914
2915
  // Enter the scope of this instantiation. We don't use
2916
  // PushDeclContext because we don't have a scope.
2917
42
  ContextRAII SavedContext(*this, Instantiation);
2918
42
  EnterExpressionEvaluationContext EvalContext(
2919
42
      *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2920
2921
42
  LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2922
2923
  // Pull attributes from the pattern onto the instantiation.
2924
42
  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2925
2926
42
  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2927
42
  Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2928
2929
  // Exit the scope of this instantiation.
2930
42
  SavedContext.pop();
2931
2932
42
  return Instantiation->isInvalidDecl();
2933
42
}
2934
2935
2936
/// Instantiate the definition of a field from the given pattern.
2937
///
2938
/// \param PointOfInstantiation The point of instantiation within the
2939
///        source code.
2940
/// \param Instantiation is the declaration whose definition is being
2941
///        instantiated. This will be a class of a class temploid
2942
///        specialization, or a local enumeration within a function temploid
2943
///        specialization.
2944
/// \param Pattern The templated declaration from which the instantiation
2945
///        occurs.
2946
/// \param TemplateArgs The template arguments to be substituted into
2947
///        the pattern.
2948
///
2949
/// \return \c true if an error occurred, \c false otherwise.
2950
bool Sema::InstantiateInClassInitializer(
2951
    SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2952
278
    FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2953
  // If there is no initializer, we don't need to do anything.
2954
278
  if (!Pattern->hasInClassInitializer())
2955
0
    return false;
2956
2957
278
  assert(Instantiation->getInClassInitStyle() ==
2958
278
             Pattern->getInClassInitStyle() &&
2959
278
         "pattern and instantiation disagree about init style");
2960
2961
  // Error out if we haven't parsed the initializer of the pattern yet because
2962
  // we are waiting for the closing brace of the outer class.
2963
0
  Expr *OldInit = Pattern->getInClassInitializer();
2964
278
  if (!OldInit) {
2965
3
    RecordDecl *PatternRD = Pattern->getParent();
2966
3
    RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2967
3
    Diag(PointOfInstantiation,
2968
3
         diag::err_default_member_initializer_not_yet_parsed)
2969
3
        << OutermostClass << Pattern;
2970
3
    Diag(Pattern->getEndLoc(),
2971
3
         diag::note_default_member_initializer_not_yet_parsed);
2972
3
    Instantiation->setInvalidDecl();
2973
3
    return true;
2974
3
  }
2975
2976
275
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2977
275
  if (Inst.isInvalid())
2978
0
    return true;
2979
275
  if (Inst.isAlreadyInstantiating()) {
2980
    // Error out if we hit an instantiation cycle for this initializer.
2981
1
    Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
2982
1
      << Instantiation;
2983
1
    return true;
2984
1
  }
2985
274
  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2986
274
                                      "instantiating default member init");
2987
2988
  // Enter the scope of this instantiation. We don't use PushDeclContext because
2989
  // we don't have a scope.
2990
274
  ContextRAII SavedContext(*this, Instantiation->getParent());
2991
274
  EnterExpressionEvaluationContext EvalContext(
2992
274
      *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2993
2994
274
  LocalInstantiationScope Scope(*this, true);
2995
2996
  // Instantiate the initializer.
2997
274
  ActOnStartCXXInClassMemberInitializer();
2998
274
  CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
2999
3000
274
  ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3001
274
                                        /*CXXDirectInit=*/false);
3002
274
  Expr *Init = NewInit.get();
3003
274
  assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3004
0
  ActOnFinishCXXInClassMemberInitializer(
3005
274
      Instantiation, Init ? 
Init->getBeginLoc()268
:
SourceLocation()6
, Init);
3006
3007
274
  if (auto *L = getASTMutationListener())
3008
2
    L->DefaultMemberInitializerInstantiated(Instantiation);
3009
3010
  // Return true if the in-class initializer is still missing.
3011
274
  return !Instantiation->getInClassInitializer();
3012
275
}
3013
3014
namespace {
3015
  /// A partial specialization whose template arguments have matched
3016
  /// a given template-id.
3017
  struct PartialSpecMatchResult {
3018
    ClassTemplatePartialSpecializationDecl *Partial;
3019
    TemplateArgumentList *Args;
3020
  };
3021
}
3022
3023
bool Sema::usesPartialOrExplicitSpecialization(
3024
2
    SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3025
2
  if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3026
2
      TSK_ExplicitSpecialization)
3027
0
    return true;
3028
3029
2
  SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3030
2
  ClassTemplateSpec->getSpecializedTemplate()
3031
2
                   ->getPartialSpecializations(PartialSpecs);
3032
2
  for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I0
) {
3033
0
    TemplateDeductionInfo Info(Loc);
3034
0
    if (!DeduceTemplateArguments(PartialSpecs[I],
3035
0
                                 ClassTemplateSpec->getTemplateArgs(), Info))
3036
0
      return true;
3037
0
  }
3038
3039
2
  return false;
3040
2
}
3041
3042
/// Get the instantiation pattern to use to instantiate the definition of a
3043
/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3044
/// template or of a partial specialization).
3045
static ActionResult<CXXRecordDecl *>
3046
getPatternForClassTemplateSpecialization(
3047
    Sema &S, SourceLocation PointOfInstantiation,
3048
    ClassTemplateSpecializationDecl *ClassTemplateSpec,
3049
786k
    TemplateSpecializationKind TSK) {
3050
786k
  Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3051
786k
  if (Inst.isInvalid())
3052
364
    return {/*Invalid=*/true};
3053
786k
  if (Inst.isAlreadyInstantiating())
3054
0
    return {/*Invalid=*/false};
3055
3056
786k
  llvm::PointerUnion<ClassTemplateDecl *,
3057
786k
                     ClassTemplatePartialSpecializationDecl *>
3058
786k
      Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3059
786k
  if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3060
    // Find best matching specialization.
3061
786k
    ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3062
3063
    // C++ [temp.class.spec.match]p1:
3064
    //   When a class template is used in a context that requires an
3065
    //   instantiation of the class, it is necessary to determine
3066
    //   whether the instantiation is to be generated using the primary
3067
    //   template or one of the partial specializations. This is done by
3068
    //   matching the template arguments of the class template
3069
    //   specialization with the template argument lists of the partial
3070
    //   specializations.
3071
786k
    typedef PartialSpecMatchResult MatchResult;
3072
786k
    SmallVector<MatchResult, 4> Matched;
3073
786k
    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3074
786k
    Template->getPartialSpecializations(PartialSpecs);
3075
786k
    TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3076
1.31M
    for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I528k
) {
3077
528k
      ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3078
528k
      TemplateDeductionInfo Info(FailedCandidates.getLocation());
3079
528k
      if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
3080
528k
              Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
3081
        // Store the failed-deduction information for use in diagnostics, later.
3082
        // TODO: Actually use the failed-deduction info?
3083
345k
        FailedCandidates.addCandidate().set(
3084
345k
            DeclAccessPair::make(Template, AS_public), Partial,
3085
345k
            MakeDeductionFailureInfo(S.Context, Result, Info));
3086
345k
        (void)Result;
3087
345k
      } else {
3088
182k
        Matched.push_back(PartialSpecMatchResult());
3089
182k
        Matched.back().Partial = Partial;
3090
182k
        Matched.back().Args = Info.take();
3091
182k
      }
3092
528k
    }
3093
3094
    // If we're dealing with a member template where the template parameters
3095
    // have been instantiated, this provides the original template parameters
3096
    // from which the member template's parameters were instantiated.
3097
3098
786k
    if (Matched.size() >= 1) {
3099
175k
      SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3100
175k
      if (Matched.size() == 1) {
3101
        //   -- If exactly one matching specialization is found, the
3102
        //      instantiation is generated from that specialization.
3103
        // We don't need to do anything for this.
3104
168k
      } else {
3105
        //   -- If more than one matching specialization is found, the
3106
        //      partial order rules (14.5.4.2) are used to determine
3107
        //      whether one of the specializations is more specialized
3108
        //      than the others. If none of the specializations is more
3109
        //      specialized than all of the other matching
3110
        //      specializations, then the use of the class template is
3111
        //      ambiguous and the program is ill-formed.
3112
6.34k
        for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
3113
6.34k
                                                 PEnd = Matched.end();
3114
13.6k
             P != PEnd; 
++P7.27k
) {
3115
7.27k
          if (S.getMoreSpecializedPartialSpecialization(
3116
7.27k
                  P->Partial, Best->Partial, PointOfInstantiation) ==
3117
7.27k
              P->Partial)
3118
6.40k
            Best = P;
3119
7.27k
        }
3120
3121
        // Determine if the best partial specialization is more specialized than
3122
        // the others.
3123
6.34k
        bool Ambiguous = false;
3124
6.34k
        for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3125
6.34k
                                                 PEnd = Matched.end();
3126
19.9k
             P != PEnd; 
++P13.5k
) {
3127
13.6k
          if (P != Best && S.getMoreSpecializedPartialSpecialization(
3128
7.27k
                               P->Partial, Best->Partial,
3129
7.27k
                               PointOfInstantiation) != Best->Partial) {
3130
23
            Ambiguous = true;
3131
23
            break;
3132
23
          }
3133
13.6k
        }
3134
3135
6.34k
        if (Ambiguous) {
3136
          // Partial ordering did not produce a clear winner. Complain.
3137
23
          Inst.Clear();
3138
23
          ClassTemplateSpec->setInvalidDecl();
3139
23
          S.Diag(PointOfInstantiation,
3140
23
                 diag::err_partial_spec_ordering_ambiguous)
3141
23
              << ClassTemplateSpec;
3142
3143
          // Print the matching partial specializations.
3144
23
          for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3145
23
                                                   PEnd = Matched.end();
3146
73
               P != PEnd; 
++P50
)
3147
50
            S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3148
50
                << S.getTemplateArgumentBindingsText(
3149
50
                       P->Partial->getTemplateParameters(), *P->Args);
3150
3151
23
          return {/*Invalid=*/true};
3152
23
        }
3153
6.34k
      }
3154
3155
175k
      ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3156
611k
    } else {
3157
      //   -- If no matches are found, the instantiation is generated
3158
      //      from the primary template.
3159
611k
    }
3160
786k
  }
3161
3162
786k
  CXXRecordDecl *Pattern = nullptr;
3163
786k
  Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3164
786k
  if (auto *PartialSpec =
3165
786k
          Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3166
    // Instantiate using the best class template partial specialization.
3167
175k
    while (PartialSpec->getInstantiatedFromMember()) {
3168
      // If we've found an explicit specialization of this class template,
3169
      // stop here and use that as the pattern.
3170
547
      if (PartialSpec->isMemberSpecialization())
3171
1
        break;
3172
3173
546
      PartialSpec = PartialSpec->getInstantiatedFromMember();
3174
546
    }
3175
175k
    Pattern = PartialSpec;
3176
611k
  } else {
3177
611k
    ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3178
620k
    while (Template->getInstantiatedFromMemberTemplate()) {
3179
      // If we've found an explicit specialization of this class template,
3180
      // stop here and use that as the pattern.
3181
9.45k
      if (Template->isMemberSpecialization())
3182
41
        break;
3183
3184
9.41k
      Template = Template->getInstantiatedFromMemberTemplate();
3185
9.41k
    }
3186
611k
    Pattern = Template->getTemplatedDecl();
3187
611k
  }
3188
3189
786k
  return Pattern;
3190
786k
}
3191
3192
bool Sema::InstantiateClassTemplateSpecialization(
3193
    SourceLocation PointOfInstantiation,
3194
    ClassTemplateSpecializationDecl *ClassTemplateSpec,
3195
786k
    TemplateSpecializationKind TSK, bool Complain) {
3196
  // Perform the actual instantiation on the canonical declaration.
3197
786k
  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3198
786k
      ClassTemplateSpec->getCanonicalDecl());
3199
786k
  if (ClassTemplateSpec->isInvalidDecl())
3200
2
    return true;
3201
3202
786k
  ActionResult<CXXRecordDecl *> Pattern =
3203
786k
      getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
3204
786k
                                               ClassTemplateSpec, TSK);
3205
786k
  if (!Pattern.isUsable())
3206
387
    return Pattern.isInvalid();
3207
3208
786k
  return InstantiateClass(
3209
786k
      PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
3210
786k
      getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
3211
786k
}
3212
3213
/// Instantiates the definitions of all of the member
3214
/// of the given class, which is an instantiation of a class template
3215
/// or a member class of a template.
3216
void
3217
Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
3218
                              CXXRecordDecl *Instantiation,
3219
                        const MultiLevelTemplateArgumentList &TemplateArgs,
3220
9.00k
                              TemplateSpecializationKind TSK) {
3221
  // FIXME: We need to notify the ASTMutationListener that we did all of these
3222
  // things, in case we have an explicit instantiation definition in a PCM, a
3223
  // module, or preamble, and the declaration is in an imported AST.
3224
9.00k
  assert(
3225
9.00k
      (TSK == TSK_ExplicitInstantiationDefinition ||
3226
9.00k
       TSK == TSK_ExplicitInstantiationDeclaration ||
3227
9.00k
       (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
3228
9.00k
      "Unexpected template specialization kind!");
3229
112k
  for (auto *D : Instantiation->decls()) {
3230
112k
    bool SuppressNew = false;
3231
112k
    if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3232
71.2k
      if (FunctionDecl *Pattern =
3233
71.2k
              Function->getInstantiatedFromMemberFunction()) {
3234
3235
62.8k
        if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3236
30.5k
          continue;
3237
3238
32.3k
        MemberSpecializationInfo *MSInfo =
3239
32.3k
            Function->getMemberSpecializationInfo();
3240
32.3k
        assert(MSInfo && "No member specialization information?");
3241
32.3k
        if (MSInfo->getTemplateSpecializationKind()
3242
32.3k
                                                 == TSK_ExplicitSpecialization)
3243
385
          continue;
3244
3245
31.9k
        if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3246
31.9k
                                                   Function,
3247
31.9k
                                        MSInfo->getTemplateSpecializationKind(),
3248
31.9k
                                              MSInfo->getPointOfInstantiation(),
3249
31.9k
                                                   SuppressNew) ||
3250
31.9k
            SuppressNew)
3251
10
          continue;
3252
3253
        // C++11 [temp.explicit]p8:
3254
        //   An explicit instantiation definition that names a class template
3255
        //   specialization explicitly instantiates the class template
3256
        //   specialization and is only an explicit instantiation definition
3257
        //   of members whose definition is visible at the point of
3258
        //   instantiation.
3259
31.9k
        if (TSK == TSK_ExplicitInstantiationDefinition && 
!Pattern->isDefined()1.70k
)
3260
129
          continue;
3261
3262
31.7k
        Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3263
3264
31.7k
        if (Function->isDefined()) {
3265
          // Let the ASTConsumer know that this function has been explicitly
3266
          // instantiated now, and its linkage might have changed.
3267
1.42k
          Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
3268
30.3k
        } else if (TSK == TSK_ExplicitInstantiationDefinition) {
3269
1.49k
          InstantiateFunctionDefinition(PointOfInstantiation, Function);
3270
28.8k
        } else if (TSK == TSK_ImplicitInstantiation) {
3271
175
          PendingLocalImplicitInstantiations.push_back(
3272
175
              std::make_pair(Function, PointOfInstantiation));
3273
175
        }
3274
31.7k
      }
3275
71.2k
    } else 
if (auto *41.0k
Var41.0k
= dyn_cast<VarDecl>(D)) {
3276
2.26k
      if (isa<VarTemplateSpecializationDecl>(Var))
3277
1
        continue;
3278
3279
2.26k
      if (Var->isStaticDataMember()) {
3280
2.26k
        if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3281
4
          continue;
3282
3283
2.25k
        MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3284
2.25k
        assert(MSInfo && "No member specialization information?");
3285
2.25k
        if (MSInfo->getTemplateSpecializationKind()
3286
2.25k
                                                 == TSK_ExplicitSpecialization)
3287
7
          continue;
3288
3289
2.24k
        if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3290
2.24k
                                                   Var,
3291
2.24k
                                        MSInfo->getTemplateSpecializationKind(),
3292
2.24k
                                              MSInfo->getPointOfInstantiation(),
3293
2.24k
                                                   SuppressNew) ||
3294
2.24k
            SuppressNew)
3295
0
          continue;
3296
3297
2.24k
        if (TSK == TSK_ExplicitInstantiationDefinition) {
3298
          // C++0x [temp.explicit]p8:
3299
          //   An explicit instantiation definition that names a class template
3300
          //   specialization explicitly instantiates the class template
3301
          //   specialization and is only an explicit instantiation definition
3302
          //   of members whose definition is visible at the point of
3303
          //   instantiation.
3304
235
          if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
3305
141
            continue;
3306
3307
94
          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3308
94
          InstantiateVariableDefinition(PointOfInstantiation, Var);
3309
2.01k
        } else {
3310
2.01k
          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3311
2.01k
        }
3312
2.24k
      }
3313
38.7k
    } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
3314
7.98k
      if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3315
4
        continue;
3316
3317
      // Always skip the injected-class-name, along with any
3318
      // redeclarations of nested classes, since both would cause us
3319
      // to try to instantiate the members of a class twice.
3320
      // Skip closure types; they'll get instantiated when we instantiate
3321
      // the corresponding lambda-expression.
3322
7.97k
      if (Record->isInjectedClassName() || 
Record->getPreviousDecl()899
||
3323
7.97k
          
Record->isLambda()890
)
3324
7.09k
        continue;
3325
3326
884
      MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
3327
884
      assert(MSInfo && "No member specialization information?");
3328
3329
884
      if (MSInfo->getTemplateSpecializationKind()
3330
884
                                                == TSK_ExplicitSpecialization)
3331
1
        continue;
3332
3333
883
      if (Context.getTargetInfo().getTriple().isOSWindows() &&
3334
883
          
TSK == TSK_ExplicitInstantiationDeclaration19
) {
3335
        // On Windows, explicit instantiation decl of the outer class doesn't
3336
        // affect the inner class. Typically extern template declarations are
3337
        // used in combination with dll import/export annotations, but those
3338
        // are not propagated from the outer class templates to inner classes.
3339
        // Therefore, do not instantiate inner classes on this platform, so
3340
        // that users don't end up with undefined symbols during linking.
3341
11
        continue;
3342
11
      }
3343
3344
872
      if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3345
872
                                                 Record,
3346
872
                                        MSInfo->getTemplateSpecializationKind(),
3347
872
                                              MSInfo->getPointOfInstantiation(),
3348
872
                                                 SuppressNew) ||
3349
872
          SuppressNew)
3350
0
        continue;
3351
3352
872
      CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3353
872
      assert(Pattern && "Missing instantiated-from-template information");
3354
3355
872
      if (!Record->getDefinition()) {
3356
427
        if (!Pattern->getDefinition()) {
3357
          // C++0x [temp.explicit]p8:
3358
          //   An explicit instantiation definition that names a class template
3359
          //   specialization explicitly instantiates the class template
3360
          //   specialization and is only an explicit instantiation definition
3361
          //   of members whose definition is visible at the point of
3362
          //   instantiation.
3363
1
          if (TSK == TSK_ExplicitInstantiationDeclaration) {
3364
0
            MSInfo->setTemplateSpecializationKind(TSK);
3365
0
            MSInfo->setPointOfInstantiation(PointOfInstantiation);
3366
0
          }
3367
3368
1
          continue;
3369
1
        }
3370
3371
426
        InstantiateClass(PointOfInstantiation, Record, Pattern,
3372
426
                         TemplateArgs,
3373
426
                         TSK);
3374
445
      } else {
3375
445
        if (TSK == TSK_ExplicitInstantiationDefinition &&
3376
445
            Record->getTemplateSpecializationKind() ==
3377
10
                TSK_ExplicitInstantiationDeclaration) {
3378
4
          Record->setTemplateSpecializationKind(TSK);
3379
4
          MarkVTableUsed(PointOfInstantiation, Record, true);
3380
4
        }
3381
445
      }
3382
3383
871
      Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
3384
871
      if (Pattern)
3385
871
        InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
3386
871
                                TSK);
3387
30.7k
    } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
3388
38
      MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
3389
38
      assert(MSInfo && "No member specialization information?");
3390
3391
38
      if (MSInfo->getTemplateSpecializationKind()
3392
38
            == TSK_ExplicitSpecialization)
3393
0
        continue;
3394
3395
38
      if (CheckSpecializationInstantiationRedecl(
3396
38
            PointOfInstantiation, TSK, Enum,
3397
38
            MSInfo->getTemplateSpecializationKind(),
3398
38
            MSInfo->getPointOfInstantiation(), SuppressNew) ||
3399
38
          SuppressNew)
3400
0
        continue;
3401
3402
38
      if (Enum->getDefinition())
3403
26
        continue;
3404
3405
12
      EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
3406
12
      assert(Pattern && "Missing instantiated-from-template information");
3407
3408
12
      if (TSK == TSK_ExplicitInstantiationDefinition) {
3409
11
        if (!Pattern->getDefinition())
3410
1
          continue;
3411
3412
10
        InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
3413
10
      } else {
3414
1
        MSInfo->setTemplateSpecializationKind(TSK);
3415
1
        MSInfo->setPointOfInstantiation(PointOfInstantiation);
3416
1
      }
3417
30.7k
    } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3418
      // No need to instantiate in-class initializers during explicit
3419
      // instantiation.
3420
9.38k
      if (Field->hasInClassInitializer() && 
TSK == TSK_ImplicitInstantiation49
) {
3421
44
        CXXRecordDecl *ClassPattern =
3422
44
            Instantiation->getTemplateInstantiationPattern();
3423
44
        DeclContext::lookup_result Lookup =
3424
44
            ClassPattern->lookup(Field->getDeclName());
3425
44
        FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
3426
44
        assert(Pattern);
3427
0
        InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
3428
44
                                      TemplateArgs);
3429
44
      }
3430
9.38k
    }
3431
112k
  }
3432
9.00k
}
3433
3434
/// Instantiate the definitions of all of the members of the
3435
/// given class template specialization, which was named as part of an
3436
/// explicit instantiation.
3437
void
3438
Sema::InstantiateClassTemplateSpecializationMembers(
3439
                                           SourceLocation PointOfInstantiation,
3440
                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
3441
6.36k
                                               TemplateSpecializationKind TSK) {
3442
  // C++0x [temp.explicit]p7:
3443
  //   An explicit instantiation that names a class template
3444
  //   specialization is an explicit instantion of the same kind
3445
  //   (declaration or definition) of each of its members (not
3446
  //   including members inherited from base classes) that has not
3447
  //   been previously explicitly specialized in the translation unit
3448
  //   containing the explicit instantiation, except as described
3449
  //   below.
3450
6.36k
  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
3451
6.36k
                          getTemplateInstantiationArgs(ClassTemplateSpec),
3452
6.36k
                          TSK);
3453
6.36k
}
3454
3455
StmtResult
3456
185k
Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
3457
185k
  if (!S)
3458
0
    return S;
3459
3460
185k
  TemplateInstantiator Instantiator(*this, TemplateArgs,
3461
185k
                                    SourceLocation(),
3462
185k
                                    DeclarationName());
3463
185k
  return Instantiator.TransformStmt(S);
3464
185k
}
3465
3466
bool Sema::SubstTemplateArguments(
3467
    ArrayRef<TemplateArgumentLoc> Args,
3468
    const MultiLevelTemplateArgumentList &TemplateArgs,
3469
238k
    TemplateArgumentListInfo &Out) {
3470
238k
  TemplateInstantiator Instantiator(*this, TemplateArgs,
3471
238k
                                    SourceLocation(),
3472
238k
                                    DeclarationName());
3473
238k
  return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(),
3474
238k
                                                 Out);
3475
238k
}
3476
3477
ExprResult
3478
409k
Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
3479
409k
  if (!E)
3480
0
    return E;
3481
3482
409k
  TemplateInstantiator Instantiator(*this, TemplateArgs,
3483
409k
                                    SourceLocation(),
3484
409k
                                    DeclarationName());
3485
409k
  return Instantiator.TransformExpr(E);
3486
409k
}
3487
3488
ExprResult Sema::SubstInitializer(Expr *Init,
3489
                          const MultiLevelTemplateArgumentList &TemplateArgs,
3490
360k
                          bool CXXDirectInit) {
3491
360k
  TemplateInstantiator Instantiator(*this, TemplateArgs,
3492
360k
                                    SourceLocation(),
3493
360k
                                    DeclarationName());
3494
360k
  return Instantiator.TransformInitializer(Init, CXXDirectInit);
3495
360k
}
3496
3497
bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
3498
                      const MultiLevelTemplateArgumentList &TemplateArgs,
3499
0
                      SmallVectorImpl<Expr *> &Outputs) {
3500
0
  if (Exprs.empty())
3501
0
    return false;
3502
3503
0
  TemplateInstantiator Instantiator(*this, TemplateArgs,
3504
0
                                    SourceLocation(),
3505
0
                                    DeclarationName());
3506
0
  return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
3507
0
                                     IsCall, Outputs);
3508
0
}
3509
3510
NestedNameSpecifierLoc
3511
Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
3512
30.0k
                        const MultiLevelTemplateArgumentList &TemplateArgs) {
3513
30.0k
  if (!NNS)
3514
7.49k
    return NestedNameSpecifierLoc();
3515
3516
22.5k
  TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
3517
22.5k
                                    DeclarationName());
3518
22.5k
  return Instantiator.TransformNestedNameSpecifierLoc(NNS);
3519
30.0k
}
3520
3521
/// Do template substitution on declaration name info.
3522
DeclarationNameInfo
3523
Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3524
2.58M
                         const MultiLevelTemplateArgumentList &TemplateArgs) {
3525
2.58M
  TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
3526
2.58M
                                    NameInfo.getName());
3527
2.58M
  return Instantiator.TransformDeclarationNameInfo(NameInfo);
3528
2.58M
}
3529
3530
TemplateName
3531
Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
3532
                        TemplateName Name, SourceLocation Loc,
3533
9.84k
                        const MultiLevelTemplateArgumentList &TemplateArgs) {
3534
9.84k
  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3535
9.84k
                                    DeclarationName());
3536
9.84k
  CXXScopeSpec SS;
3537
9.84k
  SS.Adopt(QualifierLoc);
3538
9.84k
  return Instantiator.TransformTemplateName(SS, Name, Loc);
3539
9.84k
}
3540
3541
5.19M
static const Decl *getCanonicalParmVarDecl(const Decl *D) {
3542
  // When storing ParmVarDecls in the local instantiation scope, we always
3543
  // want to use the ParmVarDecl from the canonical function declaration,
3544
  // since the map is then valid for any redeclaration or definition of that
3545
  // function.
3546
5.19M
  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
3547
3.45M
    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
3548
3.45M
      unsigned i = PV->getFunctionScopeIndex();
3549
      // This parameter might be from a freestanding function type within the
3550
      // function and isn't necessarily referring to one of FD's parameters.
3551
3.45M
      if (i < FD->getNumParams() && 
FD->getParamDecl(i) == PV3.45M
)
3552
3.45M
        return FD->getCanonicalDecl()->getParamDecl(i);
3553
3.45M
    }
3554
3.45M
  }
3555
1.73M
  return D;
3556
5.19M
}
3557
3558
3559
llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
3560
1.23M
LocalInstantiationScope::findInstantiationOf(const Decl *D) {
3561
1.23M
  D = getCanonicalParmVarDecl(D);
3562
1.91M
  for (LocalInstantiationScope *Current = this; Current;
3563
1.91M
       
Current = Current->Outer677k
) {
3564
3565
    // Check if we found something within this scope.
3566
1.91M
    const Decl *CheckD = D;
3567
1.91M
    do {
3568
1.91M
      LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
3569
1.91M
      if (Found != Current->LocalDecls.end())
3570
1.23M
        return &Found->second;
3571
3572
      // If this is a tag declaration, it's possible that we need to look for
3573
      // a previous declaration.
3574
678k
      if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
3575
837
        CheckD = Tag->getPreviousDecl();
3576
677k
      else
3577
677k
        CheckD = nullptr;
3578
678k
    } while (CheckD);
3579
3580
    // If we aren't combined with our outer scope, we're done.
3581
678k
    if (!Current->CombineWithOuterScope)
3582
586
      break;
3583
678k
  }
3584
3585
  // If we're performing a partial substitution during template argument
3586
  // deduction, we may not have values for template parameters yet.
3587
586
  if (isa<NonTypeTemplateParmDecl>(D) || 
isa<TemplateTypeParmDecl>(D)567
||
3588
586
      
isa<TemplateTemplateParmDecl>(D)136
)
3589
450
    return nullptr;
3590
3591
  // Local types referenced prior to definition may require instantiation.
3592
136
  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
3593
38
    if (RD->isLocalClass())
3594
38
      return nullptr;
3595
3596
  // Enumeration types referenced prior to definition may appear as a result of
3597
  // error recovery.
3598
98
  if (isa<EnumDecl>(D))
3599
8
    return nullptr;
3600
3601
  // Materialized typedefs/type alias for implicit deduction guides may require
3602
  // instantiation.
3603
90
  if (isa<TypedefNameDecl>(D) &&
3604
90
      
isa<CXXDeductionGuideDecl>(D->getDeclContext())9
)
3605
9
    return nullptr;
3606
3607
  // If we didn't find the decl, then we either have a sema bug, or we have a
3608
  // forward reference to a label declaration.  Return null to indicate that
3609
  // we have an uninstantiated label.
3610
81
  assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
3611
0
  return nullptr;
3612
90
}
3613
3614
3.88M
void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
3615
3.88M
  D = getCanonicalParmVarDecl(D);
3616
3.88M
  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3617
3.88M
  if (Stored.isNull()) {
3618
3.75M
#ifndef NDEBUG
3619
    // It should not be present in any surrounding scope either.
3620
3.75M
    LocalInstantiationScope *Current = this;
3621
6.06M
    while (Current->CombineWithOuterScope && 
Current->Outer2.30M
) {
3622
2.30M
      Current = Current->Outer;
3623
2.30M
      assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3624
2.30M
             "Instantiated local in inner and outer scopes");
3625
2.30M
    }
3626
3.75M
#endif
3627
3.75M
    Stored = Inst;
3628
3.75M
  } else 
if (DeclArgumentPack *126k
Pack126k
= Stored.dyn_cast<DeclArgumentPack *>()) {
3629
353
    Pack->push_back(cast<VarDecl>(Inst));
3630
125k
  } else {
3631
125k
    assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
3632
125k
  }
3633
3.88M
}
3634
3635
void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
3636
41.0k
                                                       VarDecl *Inst) {
3637
41.0k
  D = getCanonicalParmVarDecl(D);
3638
41.0k
  DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3639
41.0k
  Pack->push_back(Inst);
3640
41.0k
}
3641
3642
27.5k
void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
3643
27.5k
#ifndef NDEBUG
3644
  // This should be the first time we've been told about this decl.
3645
27.5k
  for (LocalInstantiationScope *Current = this;
3646
42.9k
       Current && 
Current->CombineWithOuterScope42.8k
;
Current = Current->Outer15.4k
)
3647
15.4k
    assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3648
27.5k
           "Creating local pack after instantiation of local");
3649
27.5k
#endif
3650
3651
27.5k
  D = getCanonicalParmVarDecl(D);
3652
27.5k
  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3653
27.5k
  DeclArgumentPack *Pack = new DeclArgumentPack;
3654
27.5k
  Stored = Pack;
3655
27.5k
  ArgumentPacks.push_back(Pack);
3656
27.5k
}
3657
3658
55
bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) {
3659
55
  for (DeclArgumentPack *Pack : ArgumentPacks)
3660
61
    if (llvm::is_contained(*Pack, D))
3661
55
      return true;
3662
0
  return false;
3663
55
}
3664
3665
void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
3666
                                          const TemplateArgument *ExplicitArgs,
3667
24.2k
                                                    unsigned NumExplicitArgs) {
3668
24.2k
  assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
3669
24.2k
         "Already have a partially-substituted pack");
3670
0
  assert((!PartiallySubstitutedPack
3671
24.2k
          || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
3672
24.2k
         "Wrong number of arguments in partially-substituted pack");
3673
0
  PartiallySubstitutedPack = Pack;
3674
24.2k
  ArgsInPartiallySubstitutedPack = ExplicitArgs;
3675
24.2k
  NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3676
24.2k
}
3677
3678
NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
3679
                                         const TemplateArgument **ExplicitArgs,
3680
318k
                                              unsigned *NumExplicitArgs) const {
3681
318k
  if (ExplicitArgs)
3682
51.6k
    *ExplicitArgs = nullptr;
3683
318k
  if (NumExplicitArgs)
3684
51.6k
    *NumExplicitArgs = 0;
3685
3686
367k
  for (const LocalInstantiationScope *Current = this; Current;
3687
367k
       
Current = Current->Outer48.6k
) {
3688
367k
    if (Current->PartiallySubstitutedPack) {
3689
55.2k
      if (ExplicitArgs)
3690
17.9k
        *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3691
55.2k
      if (NumExplicitArgs)
3692
17.9k
        *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
3693
3694
55.2k
      return Current->PartiallySubstitutedPack;
3695
55.2k
    }
3696
3697
312k
    if (!Current->CombineWithOuterScope)
3698
263k
      break;
3699
312k
  }
3700
3701
263k
  return nullptr;
3702
318k
}