Coverage Report

Created: 2021-01-19 06:58

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