SemaTemplateInstantiate.cpp revision 7e7eb3da052a6d80ddf2377cab0384c798f73f75
1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9//  This file implements C++ template instantiation.
10//
11//===----------------------------------------------------------------------===/
12
13#include "Sema.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
20#include "llvm/Support/Compiler.h"
21
22using namespace clang;
23
24//===----------------------------------------------------------------------===/
25// Template Instantiation Support
26//===----------------------------------------------------------------------===/
27
28/// \brief Retrieve the template argument list that should be used to
29/// instantiate the given declaration.
30const TemplateArgumentList &
31Sema::getTemplateInstantiationArgs(NamedDecl *D) {
32  // Template arguments for a class template specialization.
33  if (ClassTemplateSpecializationDecl *Spec
34        = dyn_cast<ClassTemplateSpecializationDecl>(D))
35    return Spec->getTemplateArgs();
36
37  // Template arguments for a function template specialization.
38  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
39    if (const TemplateArgumentList *TemplateArgs
40          = Function->getTemplateSpecializationArgs())
41      return *TemplateArgs;
42
43  // Template arguments for a member of a class template specialization.
44  DeclContext *EnclosingTemplateCtx = D->getDeclContext();
45  while (!isa<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx)) {
46    assert(!EnclosingTemplateCtx->isFileContext() &&
47           "Tried to get the instantiation arguments of a non-template");
48    EnclosingTemplateCtx = EnclosingTemplateCtx->getParent();
49  }
50
51  ClassTemplateSpecializationDecl *EnclosingTemplate
52    = cast<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx);
53  return EnclosingTemplate->getTemplateArgs();
54}
55
56Sema::InstantiatingTemplate::
57InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
58                      Decl *Entity,
59                      SourceRange InstantiationRange)
60  :  SemaRef(SemaRef) {
61
62  Invalid = CheckInstantiationDepth(PointOfInstantiation,
63                                    InstantiationRange);
64  if (!Invalid) {
65    ActiveTemplateInstantiation Inst;
66    Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
67    Inst.PointOfInstantiation = PointOfInstantiation;
68    Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
69    Inst.TemplateArgs = 0;
70    Inst.NumTemplateArgs = 0;
71    Inst.InstantiationRange = InstantiationRange;
72    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
73    Invalid = false;
74  }
75}
76
77Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
78                                         SourceLocation PointOfInstantiation,
79                                         TemplateDecl *Template,
80                                         const TemplateArgument *TemplateArgs,
81                                         unsigned NumTemplateArgs,
82                                         SourceRange InstantiationRange)
83  : SemaRef(SemaRef) {
84
85  Invalid = CheckInstantiationDepth(PointOfInstantiation,
86                                    InstantiationRange);
87  if (!Invalid) {
88    ActiveTemplateInstantiation Inst;
89    Inst.Kind
90      = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
91    Inst.PointOfInstantiation = PointOfInstantiation;
92    Inst.Entity = reinterpret_cast<uintptr_t>(Template);
93    Inst.TemplateArgs = TemplateArgs;
94    Inst.NumTemplateArgs = NumTemplateArgs;
95    Inst.InstantiationRange = InstantiationRange;
96    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
97    Invalid = false;
98  }
99}
100
101Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
102                                         SourceLocation PointOfInstantiation,
103                                      FunctionTemplateDecl *FunctionTemplate,
104                                        const TemplateArgument *TemplateArgs,
105                                                   unsigned NumTemplateArgs,
106                         ActiveTemplateInstantiation::InstantiationKind Kind,
107                                              SourceRange InstantiationRange)
108: SemaRef(SemaRef) {
109
110  Invalid = CheckInstantiationDepth(PointOfInstantiation,
111                                    InstantiationRange);
112  if (!Invalid) {
113    ActiveTemplateInstantiation Inst;
114    Inst.Kind = Kind;
115    Inst.PointOfInstantiation = PointOfInstantiation;
116    Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
117    Inst.TemplateArgs = TemplateArgs;
118    Inst.NumTemplateArgs = NumTemplateArgs;
119    Inst.InstantiationRange = InstantiationRange;
120    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
121    Invalid = false;
122  }
123}
124
125Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
126                                         SourceLocation PointOfInstantiation,
127                          ClassTemplatePartialSpecializationDecl *PartialSpec,
128                                         const TemplateArgument *TemplateArgs,
129                                         unsigned NumTemplateArgs,
130                                         SourceRange InstantiationRange)
131  : SemaRef(SemaRef) {
132
133  Invalid = CheckInstantiationDepth(PointOfInstantiation,
134                                    InstantiationRange);
135  if (!Invalid) {
136    ActiveTemplateInstantiation Inst;
137    Inst.Kind
138      = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
139    Inst.PointOfInstantiation = PointOfInstantiation;
140    Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
141    Inst.TemplateArgs = TemplateArgs;
142    Inst.NumTemplateArgs = NumTemplateArgs;
143    Inst.InstantiationRange = InstantiationRange;
144    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
145    Invalid = false;
146  }
147}
148
149void Sema::InstantiatingTemplate::Clear() {
150  if (!Invalid) {
151    SemaRef.ActiveTemplateInstantiations.pop_back();
152    Invalid = true;
153  }
154}
155
156bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
157                                        SourceLocation PointOfInstantiation,
158                                           SourceRange InstantiationRange) {
159  if (SemaRef.ActiveTemplateInstantiations.size()
160       <= SemaRef.getLangOptions().InstantiationDepth)
161    return false;
162
163  SemaRef.Diag(PointOfInstantiation,
164               diag::err_template_recursion_depth_exceeded)
165    << SemaRef.getLangOptions().InstantiationDepth
166    << InstantiationRange;
167  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
168    << SemaRef.getLangOptions().InstantiationDepth;
169  return true;
170}
171
172/// \brief Prints the current instantiation stack through a series of
173/// notes.
174void Sema::PrintInstantiationStack() {
175  // FIXME: In all of these cases, we need to show the template arguments
176  for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
177         Active = ActiveTemplateInstantiations.rbegin(),
178         ActiveEnd = ActiveTemplateInstantiations.rend();
179       Active != ActiveEnd;
180       ++Active) {
181    switch (Active->Kind) {
182    case ActiveTemplateInstantiation::TemplateInstantiation: {
183      Decl *D = reinterpret_cast<Decl *>(Active->Entity);
184      if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
185        unsigned DiagID = diag::note_template_member_class_here;
186        if (isa<ClassTemplateSpecializationDecl>(Record))
187          DiagID = diag::note_template_class_instantiation_here;
188        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
189                     DiagID)
190          << Context.getTypeDeclType(Record)
191          << Active->InstantiationRange;
192      } else {
193        FunctionDecl *Function = cast<FunctionDecl>(D);
194        unsigned DiagID;
195        if (Function->getPrimaryTemplate())
196          DiagID = diag::note_function_template_spec_here;
197        else
198          DiagID = diag::note_template_member_function_here;
199        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
200                     DiagID)
201          << Function
202          << Active->InstantiationRange;
203      }
204      break;
205    }
206
207    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
208      TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
209      std::string TemplateArgsStr
210        = TemplateSpecializationType::PrintTemplateArgumentList(
211                                                         Active->TemplateArgs,
212                                                      Active->NumTemplateArgs,
213                                                      Context.PrintingPolicy);
214      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
215                   diag::note_default_arg_instantiation_here)
216        << (Template->getNameAsString() + TemplateArgsStr)
217        << Active->InstantiationRange;
218      break;
219    }
220
221    case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
222      FunctionTemplateDecl *FnTmpl
223        = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
224      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
225                   diag::note_explicit_template_arg_substitution_here)
226        << FnTmpl << Active->InstantiationRange;
227      break;
228    }
229
230    case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
231      if (ClassTemplatePartialSpecializationDecl *PartialSpec
232            = dyn_cast<ClassTemplatePartialSpecializationDecl>(
233                                                    (Decl *)Active->Entity)) {
234        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
235                     diag::note_partial_spec_deduct_instantiation_here)
236          << Context.getTypeDeclType(PartialSpec)
237          << Active->InstantiationRange;
238      } else {
239        FunctionTemplateDecl *FnTmpl
240          = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
241        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
242                     diag::note_function_template_deduction_instantiation_here)
243          << FnTmpl << Active->InstantiationRange;
244      }
245      break;
246
247    }
248  }
249}
250
251bool Sema::isSFINAEContext() const {
252  using llvm::SmallVector;
253  for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
254         Active = ActiveTemplateInstantiations.rbegin(),
255         ActiveEnd = ActiveTemplateInstantiations.rend();
256       Active != ActiveEnd;
257       ++Active) {
258
259    switch(Active->Kind) {
260    case ActiveTemplateInstantiation::TemplateInstantiation:
261      // This is a template instantiation, so there is no SFINAE.
262      return false;
263
264    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
265      // A default template argument instantiation may or may not be a
266      // SFINAE context; look further up the stack.
267      break;
268
269    case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
270    case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
271      // We're either substitution explicitly-specified template arguments
272      // or deduced template arguments, so SFINAE applies.
273      return true;
274    }
275  }
276
277  return false;
278}
279
280//===----------------------------------------------------------------------===/
281// Template Instantiation for Types
282//===----------------------------------------------------------------------===/
283namespace {
284  class VISIBILITY_HIDDEN TemplateTypeInstantiator {
285    Sema &SemaRef;
286    const TemplateArgumentList &TemplateArgs;
287    SourceLocation Loc;
288    DeclarationName Entity;
289
290  public:
291    TemplateTypeInstantiator(Sema &SemaRef,
292                             const TemplateArgumentList &TemplateArgs,
293                             SourceLocation Loc,
294                             DeclarationName Entity)
295      : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
296        Loc(Loc), Entity(Entity) { }
297
298    QualType operator()(QualType T) const { return Instantiate(T); }
299
300    QualType Instantiate(QualType T) const;
301
302    // Declare instantiate functions for each type.
303#define TYPE(Class, Base)                                       \
304    QualType Instantiate##Class##Type(const Class##Type *T) const;
305#define ABSTRACT_TYPE(Class, Base)
306#include "clang/AST/TypeNodes.def"
307  };
308}
309
310QualType
311TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T) const {
312  // FIXME: Implement this
313  assert(false && "Cannot instantiate ExtQualType yet");
314  return QualType();
315}
316
317QualType
318TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T) const {
319  assert(false && "Builtin types are not dependent and cannot be instantiated");
320  return QualType(T, 0);
321}
322
323QualType
324TemplateTypeInstantiator::
325InstantiateFixedWidthIntType(const FixedWidthIntType *T) const {
326  // FIXME: Implement this
327  assert(false && "Cannot instantiate FixedWidthIntType yet");
328  return QualType();
329}
330
331QualType
332TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T) const {
333  // FIXME: Implement this
334  assert(false && "Cannot instantiate ComplexType yet");
335  return QualType();
336}
337
338QualType
339TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T) const {
340  QualType PointeeType = Instantiate(T->getPointeeType());
341  if (PointeeType.isNull())
342    return QualType();
343
344  return SemaRef.BuildPointerType(PointeeType, 0, Loc, Entity);
345}
346
347QualType
348TemplateTypeInstantiator::InstantiateBlockPointerType(
349                                            const BlockPointerType *T) const {
350  QualType PointeeType = Instantiate(T->getPointeeType());
351  if (PointeeType.isNull())
352    return QualType();
353
354  return SemaRef.BuildBlockPointerType(PointeeType, 0, Loc, Entity);
355}
356
357QualType
358TemplateTypeInstantiator::InstantiateLValueReferenceType(
359                                        const LValueReferenceType *T) const {
360  QualType ReferentType = Instantiate(T->getPointeeType());
361  if (ReferentType.isNull())
362    return QualType();
363
364  return SemaRef.BuildReferenceType(ReferentType, true, 0, Loc, Entity);
365}
366
367QualType
368TemplateTypeInstantiator::InstantiateRValueReferenceType(
369                                        const RValueReferenceType *T) const {
370  QualType ReferentType = Instantiate(T->getPointeeType());
371  if (ReferentType.isNull())
372    return QualType();
373
374  return SemaRef.BuildReferenceType(ReferentType, false, 0, Loc, Entity);
375}
376
377QualType
378TemplateTypeInstantiator::
379InstantiateMemberPointerType(const MemberPointerType *T) const {
380  QualType PointeeType = Instantiate(T->getPointeeType());
381  if (PointeeType.isNull())
382    return QualType();
383
384  QualType ClassType = Instantiate(QualType(T->getClass(), 0));
385  if (ClassType.isNull())
386    return QualType();
387
388  return SemaRef.BuildMemberPointerType(PointeeType, ClassType, 0, Loc,
389                                        Entity);
390}
391
392QualType
393TemplateTypeInstantiator::
394InstantiateConstantArrayType(const ConstantArrayType *T) const {
395  QualType ElementType = Instantiate(T->getElementType());
396  if (ElementType.isNull())
397    return ElementType;
398
399  // Build a temporary integer literal to specify the size for
400  // BuildArrayType. Since we have already checked the size as part of
401  // creating the dependent array type in the first place, we know
402  // there aren't any errors. However, we do need to determine what
403  // C++ type to give the size expression.
404  llvm::APInt Size = T->getSize();
405  QualType Types[] = {
406    SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
407    SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
408    SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
409  };
410  const unsigned NumTypes = sizeof(Types) / sizeof(QualType);
411  QualType SizeType;
412  for (unsigned I = 0; I != NumTypes; ++I)
413    if (Size.getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
414      SizeType = Types[I];
415      break;
416    }
417
418  if (SizeType.isNull())
419    SizeType = SemaRef.Context.getFixedWidthIntType(Size.getBitWidth(), false);
420
421  IntegerLiteral ArraySize(Size, SizeType, Loc);
422  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
423                                &ArraySize, T->getIndexTypeQualifier(),
424                                SourceRange(), // FIXME: provide proper range?
425                                Entity);
426}
427
428QualType
429TemplateTypeInstantiator::InstantiateConstantArrayWithExprType
430(const ConstantArrayWithExprType *T) const {
431  return InstantiateConstantArrayType(T);
432}
433
434QualType
435TemplateTypeInstantiator::InstantiateConstantArrayWithoutExprType
436(const ConstantArrayWithoutExprType *T) const {
437  return InstantiateConstantArrayType(T);
438}
439
440QualType
441TemplateTypeInstantiator::
442InstantiateIncompleteArrayType(const IncompleteArrayType *T) const {
443  QualType ElementType = Instantiate(T->getElementType());
444  if (ElementType.isNull())
445    return ElementType;
446
447  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
448                                0, T->getIndexTypeQualifier(),
449                                SourceRange(), // FIXME: provide proper range?
450                                Entity);
451}
452
453QualType
454TemplateTypeInstantiator::
455InstantiateVariableArrayType(const VariableArrayType *T) const {
456  // FIXME: Implement this
457  assert(false && "Cannot instantiate VariableArrayType yet");
458  return QualType();
459}
460
461QualType
462TemplateTypeInstantiator::
463InstantiateDependentSizedArrayType(const DependentSizedArrayType *T) const {
464  Expr *ArraySize = T->getSizeExpr();
465  assert(ArraySize->isValueDependent() &&
466         "dependent sized array types must have value dependent size expr");
467
468  // Instantiate the element type if needed
469  QualType ElementType = T->getElementType();
470  if (ElementType->isDependentType()) {
471    ElementType = Instantiate(ElementType);
472    if (ElementType.isNull())
473      return QualType();
474  }
475
476  // Instantiate the size expression
477  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
478  Sema::OwningExprResult InstantiatedArraySize =
479    SemaRef.InstantiateExpr(ArraySize, TemplateArgs);
480  if (InstantiatedArraySize.isInvalid())
481    return QualType();
482
483  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
484                                InstantiatedArraySize.takeAs<Expr>(),
485                                T->getIndexTypeQualifier(),
486                                SourceRange(), // FIXME: provide proper range?
487                                Entity);
488}
489
490QualType
491TemplateTypeInstantiator::
492InstantiateDependentSizedExtVectorType(
493                                const DependentSizedExtVectorType *T) const {
494
495  // Instantiate the element type if needed.
496  QualType ElementType = T->getElementType();
497  if (ElementType->isDependentType()) {
498    ElementType = Instantiate(ElementType);
499    if (ElementType.isNull())
500      return QualType();
501  }
502
503  // The expression in a dependent-sized extended vector type is not
504  // potentially evaluated.
505  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
506
507  // Instantiate the size expression.
508  const Expr *SizeExpr = T->getSizeExpr();
509  Sema::OwningExprResult InstantiatedArraySize =
510    SemaRef.InstantiateExpr(const_cast<Expr *>(SizeExpr), TemplateArgs);
511  if (InstantiatedArraySize.isInvalid())
512    return QualType();
513
514  return SemaRef.BuildExtVectorType(ElementType,
515                                    SemaRef.Owned(
516                                      InstantiatedArraySize.takeAs<Expr>()),
517                                    T->getAttributeLoc());
518}
519
520QualType
521TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T) const {
522  // FIXME: Implement this
523  assert(false && "Cannot instantiate VectorType yet");
524  return QualType();
525}
526
527QualType
528TemplateTypeInstantiator::InstantiateExtVectorType(
529                                              const ExtVectorType *T) const {
530  // FIXME: Implement this
531  assert(false && "Cannot instantiate ExtVectorType yet");
532  return QualType();
533}
534
535QualType
536TemplateTypeInstantiator::
537InstantiateFunctionProtoType(const FunctionProtoType *T) const {
538  QualType ResultType = Instantiate(T->getResultType());
539  if (ResultType.isNull())
540    return ResultType;
541
542  llvm::SmallVector<QualType, 4> ParamTypes;
543  for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
544                                         ParamEnd = T->arg_type_end();
545       Param != ParamEnd; ++Param) {
546    QualType P = Instantiate(*Param);
547    if (P.isNull())
548      return P;
549
550    ParamTypes.push_back(P);
551  }
552
553  return SemaRef.BuildFunctionType(ResultType, ParamTypes.data(),
554                                   ParamTypes.size(),
555                                   T->isVariadic(), T->getTypeQuals(),
556                                   Loc, Entity);
557}
558
559QualType
560TemplateTypeInstantiator::
561InstantiateFunctionNoProtoType(const FunctionNoProtoType *T) const {
562  assert(false && "Functions without prototypes cannot be dependent.");
563  return QualType();
564}
565
566QualType
567TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T) const {
568  TypedefDecl *Typedef
569    = cast_or_null<TypedefDecl>(
570                           SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
571  if (!Typedef)
572    return QualType();
573
574  return SemaRef.Context.getTypeDeclType(Typedef);
575}
576
577QualType
578TemplateTypeInstantiator::InstantiateTypeOfExprType(
579                                              const TypeOfExprType *T) const {
580  // The expression in a typeof is not potentially evaluated.
581  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
582
583  Sema::OwningExprResult E
584    = SemaRef.InstantiateExpr(T->getUnderlyingExpr(), TemplateArgs);
585  if (E.isInvalid())
586    return QualType();
587
588  return SemaRef.BuildTypeofExprType(E.takeAs<Expr>());
589}
590
591QualType
592TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T) const {
593  QualType Underlying = Instantiate(T->getUnderlyingType());
594  if (Underlying.isNull())
595    return QualType();
596
597  return SemaRef.Context.getTypeOfType(Underlying);
598}
599
600QualType
601TemplateTypeInstantiator::InstantiateDecltypeType(const DecltypeType *T) const {
602  // C++0x [dcl.type.simple]p4:
603  //   The operand of the decltype specifier is an unevaluated operand.
604  EnterExpressionEvaluationContext Unevaluated(SemaRef,
605                                               Action::Unevaluated);
606
607  Sema::OwningExprResult E
608    = SemaRef.InstantiateExpr(T->getUnderlyingExpr(), TemplateArgs);
609
610  if (E.isInvalid())
611    return QualType();
612
613  return SemaRef.BuildDecltypeType(E.takeAs<Expr>());
614}
615
616QualType
617TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T) const {
618  RecordDecl *Record
619    = cast_or_null<RecordDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
620  if (!Record)
621    return QualType();
622
623  return SemaRef.Context.getTypeDeclType(Record);
624}
625
626QualType
627TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T) const {
628  EnumDecl *Enum
629    = cast_or_null<EnumDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
630  if (!Enum)
631    return QualType();
632
633  return SemaRef.Context.getTypeDeclType(Enum);
634}
635
636QualType
637TemplateTypeInstantiator::
638InstantiateTemplateTypeParmType(const TemplateTypeParmType *T) const {
639  if (T->getDepth() == 0) {
640    // Replace the template type parameter with its corresponding
641    // template argument.
642
643    // If the corresponding template argument is NULL or doesn't exist, it's
644    // because we are performing instantiation from explicitly-specified
645    // template arguments in a function template class, but there were some
646    // arguments left unspecified.
647    if (T->getIndex() >= TemplateArgs.size() ||
648        TemplateArgs[T->getIndex()].isNull())
649      return QualType(T, 0); // Would be nice to keep the original type here
650
651    assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
652           "Template argument kind mismatch");
653    return TemplateArgs[T->getIndex()].getAsType();
654  }
655
656  // The template type parameter comes from an inner template (e.g.,
657  // the template parameter list of a member template inside the
658  // template we are instantiating). Create a new template type
659  // parameter with the template "level" reduced by one.
660  return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
661                                                 T->getIndex(),
662                                                 T->isParameterPack(),
663                                                 T->getName());
664}
665
666QualType
667TemplateTypeInstantiator::
668InstantiateTemplateSpecializationType(
669                                  const TemplateSpecializationType *T) const {
670  llvm::SmallVector<TemplateArgument, 4> InstantiatedTemplateArgs;
671  InstantiatedTemplateArgs.reserve(T->getNumArgs());
672  for (TemplateSpecializationType::iterator Arg = T->begin(), ArgEnd = T->end();
673       Arg != ArgEnd; ++Arg) {
674    TemplateArgument InstArg = SemaRef.Instantiate(*Arg, TemplateArgs);
675    if (InstArg.isNull())
676      return QualType();
677
678    InstantiatedTemplateArgs.push_back(InstArg);
679  }
680
681  // FIXME: We're missing the locations of the template name, '<', and '>'.
682
683  TemplateName Name = SemaRef.InstantiateTemplateName(T->getTemplateName(),
684                                                      Loc,
685                                                      TemplateArgs);
686
687  return SemaRef.CheckTemplateIdType(Name, Loc, SourceLocation(),
688                                     InstantiatedTemplateArgs.data(),
689                                     InstantiatedTemplateArgs.size(),
690                                     SourceLocation());
691}
692
693QualType
694TemplateTypeInstantiator::
695InstantiateQualifiedNameType(const QualifiedNameType *T) const {
696  // When we instantiated a qualified name type, there's no point in
697  // keeping the qualification around in the instantiated result. So,
698  // just instantiate the named type.
699  return (*this)(T->getNamedType());
700}
701
702QualType
703TemplateTypeInstantiator::
704InstantiateTypenameType(const TypenameType *T) const {
705  if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
706    // When the typename type refers to a template-id, the template-id
707    // is dependent and has enough information to instantiate the
708    // result of the typename type. Since we don't care about keeping
709    // the spelling of the typename type in template instantiations,
710    // we just instantiate the template-id.
711    return InstantiateTemplateSpecializationType(TemplateId);
712  }
713
714  NestedNameSpecifier *NNS
715    = SemaRef.InstantiateNestedNameSpecifier(T->getQualifier(),
716                                             SourceRange(Loc),
717                                             TemplateArgs);
718  if (!NNS)
719    return QualType();
720
721  return SemaRef.CheckTypenameType(NNS, *T->getIdentifier(), SourceRange(Loc));
722}
723
724QualType
725TemplateTypeInstantiator::
726InstantiateObjCObjectPointerType(const ObjCObjectPointerType *T) const {
727  assert(false && "Objective-C types cannot be dependent");
728  return QualType();
729}
730
731QualType
732TemplateTypeInstantiator::
733InstantiateObjCInterfaceType(const ObjCInterfaceType *T) const {
734  assert(false && "Objective-C types cannot be dependent");
735  return QualType();
736}
737
738QualType
739TemplateTypeInstantiator::
740InstantiateObjCQualifiedInterfaceType(
741                                 const ObjCQualifiedInterfaceType *T) const {
742  assert(false && "Objective-C types cannot be dependent");
743  return QualType();
744}
745
746/// \brief The actual implementation of Sema::InstantiateType().
747QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
748  // If T is not a dependent type, there is nothing to do.
749  if (!T->isDependentType())
750    return T;
751
752  QualType Result;
753  switch (T->getTypeClass()) {
754#define TYPE(Class, Base)                                               \
755  case Type::Class:                                                     \
756    Result = Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()));  \
757    break;
758#define ABSTRACT_TYPE(Class, Base)
759#include "clang/AST/TypeNodes.def"
760  }
761
762  // C++ [dcl.ref]p1:
763  //   [...] Cv-qualified references are ill-formed except when
764  //   the cv-qualifiers are introduced through the use of a
765  //   typedef (7.1.3) or of a template type argument (14.3), in
766  //   which case the cv-qualifiers are ignored.
767  //
768  // The same rule applies to function types.
769  if (!Result.isNull() && T.getCVRQualifiers() &&
770      !Result->isFunctionType() && !Result->isReferenceType())
771    Result = Result.getWithAdditionalQualifiers(T.getCVRQualifiers());
772  return Result;
773}
774
775/// \brief Instantiate the type T with a given set of template arguments.
776///
777/// This routine substitutes the given template arguments into the
778/// type T and produces the instantiated type.
779///
780/// \param T the type into which the template arguments will be
781/// substituted. If this type is not dependent, it will be returned
782/// immediately.
783///
784/// \param TemplateArgs the template arguments that will be
785/// substituted for the top-level template parameters within T.
786///
787/// \param Loc the location in the source code where this substitution
788/// is being performed. It will typically be the location of the
789/// declarator (if we're instantiating the type of some declaration)
790/// or the location of the type in the source code (if, e.g., we're
791/// instantiating the type of a cast expression).
792///
793/// \param Entity the name of the entity associated with a declaration
794/// being instantiated (if any). May be empty to indicate that there
795/// is no such entity (if, e.g., this is a type that occurs as part of
796/// a cast expression) or that the entity has no name (e.g., an
797/// unnamed function parameter).
798///
799/// \returns If the instantiation succeeds, the instantiated
800/// type. Otherwise, produces diagnostics and returns a NULL type.
801QualType Sema::InstantiateType(QualType T,
802                               const TemplateArgumentList &TemplateArgs,
803                               SourceLocation Loc, DeclarationName Entity) {
804  assert(!ActiveTemplateInstantiations.empty() &&
805         "Cannot perform an instantiation without some context on the "
806         "instantiation stack");
807
808  // If T is not a dependent type, there is nothing to do.
809  if (!T->isDependentType())
810    return T;
811
812  TemplateTypeInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
813  return Instantiator(T);
814}
815
816/// \brief Instantiate the base class specifiers of the given class
817/// template specialization.
818///
819/// Produces a diagnostic and returns true on error, returns false and
820/// attaches the instantiated base classes to the class template
821/// specialization if successful.
822bool
823Sema::InstantiateBaseSpecifiers(CXXRecordDecl *Instantiation,
824                                CXXRecordDecl *Pattern,
825                                const TemplateArgumentList &TemplateArgs) {
826  bool Invalid = false;
827  llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
828  for (ClassTemplateSpecializationDecl::base_class_iterator
829         Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
830       Base != BaseEnd; ++Base) {
831    if (!Base->getType()->isDependentType()) {
832      // FIXME: Allocate via ASTContext
833      InstantiatedBases.push_back(new CXXBaseSpecifier(*Base));
834      continue;
835    }
836
837    QualType BaseType = InstantiateType(Base->getType(),
838                                        TemplateArgs,
839                                        Base->getSourceRange().getBegin(),
840                                        DeclarationName());
841    if (BaseType.isNull()) {
842      Invalid = true;
843      continue;
844    }
845
846    if (CXXBaseSpecifier *InstantiatedBase
847          = CheckBaseSpecifier(Instantiation,
848                               Base->getSourceRange(),
849                               Base->isVirtual(),
850                               Base->getAccessSpecifierAsWritten(),
851                               BaseType,
852                               /*FIXME: Not totally accurate */
853                               Base->getSourceRange().getBegin()))
854      InstantiatedBases.push_back(InstantiatedBase);
855    else
856      Invalid = true;
857  }
858
859  if (!Invalid &&
860      AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
861                           InstantiatedBases.size()))
862    Invalid = true;
863
864  return Invalid;
865}
866
867/// \brief Instantiate the definition of a class from a given pattern.
868///
869/// \param PointOfInstantiation The point of instantiation within the
870/// source code.
871///
872/// \param Instantiation is the declaration whose definition is being
873/// instantiated. This will be either a class template specialization
874/// or a member class of a class template specialization.
875///
876/// \param Pattern is the pattern from which the instantiation
877/// occurs. This will be either the declaration of a class template or
878/// the declaration of a member class of a class template.
879///
880/// \param TemplateArgs The template arguments to be substituted into
881/// the pattern.
882///
883/// \returns true if an error occurred, false otherwise.
884bool
885Sema::InstantiateClass(SourceLocation PointOfInstantiation,
886                       CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
887                       const TemplateArgumentList &TemplateArgs,
888                       bool ExplicitInstantiation) {
889  bool Invalid = false;
890
891  CXXRecordDecl *PatternDef
892    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
893  if (!PatternDef) {
894    if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
895      Diag(PointOfInstantiation,
896           diag::err_implicit_instantiate_member_undefined)
897        << Context.getTypeDeclType(Instantiation);
898      Diag(Pattern->getLocation(), diag::note_member_of_template_here);
899    } else {
900      Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
901        << ExplicitInstantiation
902        << Context.getTypeDeclType(Instantiation);
903      Diag(Pattern->getLocation(), diag::note_template_decl_here);
904    }
905    return true;
906  }
907  Pattern = PatternDef;
908
909  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
910  if (Inst)
911    return true;
912
913  // Enter the scope of this instantiation. We don't use
914  // PushDeclContext because we don't have a scope.
915  DeclContext *PreviousContext = CurContext;
916  CurContext = Instantiation;
917
918  // Start the definition of this instantiation.
919  Instantiation->startDefinition();
920
921  // Instantiate the base class specifiers.
922  if (InstantiateBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
923    Invalid = true;
924
925  llvm::SmallVector<DeclPtrTy, 4> Fields;
926  for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
927         MemberEnd = Pattern->decls_end();
928       Member != MemberEnd; ++Member) {
929    Decl *NewMember = InstantiateDecl(*Member, Instantiation, TemplateArgs);
930    if (NewMember) {
931      if (NewMember->isInvalidDecl())
932        Invalid = true;
933      else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
934        Fields.push_back(DeclPtrTy::make(Field));
935    } else {
936      // FIXME: Eventually, a NULL return will mean that one of the
937      // instantiations was a semantic disaster, and we'll want to set Invalid =
938      // true. For now, we expect to skip some members that we can't yet handle.
939    }
940  }
941
942  // Finish checking fields.
943  ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
944              Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
945              0);
946
947  // Add any implicitly-declared members that we might need.
948  AddImplicitlyDeclaredMembersToClass(Instantiation);
949
950  // Exit the scope of this instantiation.
951  CurContext = PreviousContext;
952
953  if (!Invalid)
954    Consumer.HandleTagDeclDefinition(Instantiation);
955
956  // If this is an explicit instantiation, instantiate our members, too.
957  if (!Invalid && ExplicitInstantiation) {
958    Inst.Clear();
959    InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs);
960  }
961
962  return Invalid;
963}
964
965bool
966Sema::InstantiateClassTemplateSpecialization(
967                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
968                           bool ExplicitInstantiation) {
969  // Perform the actual instantiation on the canonical declaration.
970  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
971                               Context.getCanonicalDecl(ClassTemplateSpec));
972
973  // We can only instantiate something that hasn't already been
974  // instantiated or specialized. Fail without any diagnostics: our
975  // caller will provide an error message.
976  if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
977    return true;
978
979  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
980  CXXRecordDecl *Pattern = Template->getTemplatedDecl();
981  const TemplateArgumentList *TemplateArgs
982    = &ClassTemplateSpec->getTemplateArgs();
983
984  // C++ [temp.class.spec.match]p1:
985  //   When a class template is used in a context that requires an
986  //   instantiation of the class, it is necessary to determine
987  //   whether the instantiation is to be generated using the primary
988  //   template or one of the partial specializations. This is done by
989  //   matching the template arguments of the class template
990  //   specialization with the template argument lists of the partial
991  //   specializations.
992  typedef std::pair<ClassTemplatePartialSpecializationDecl *,
993                    TemplateArgumentList *> MatchResult;
994  llvm::SmallVector<MatchResult, 4> Matched;
995  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
996         Partial = Template->getPartialSpecializations().begin(),
997         PartialEnd = Template->getPartialSpecializations().end();
998       Partial != PartialEnd;
999       ++Partial) {
1000    TemplateDeductionInfo Info(Context);
1001    if (TemplateDeductionResult Result
1002          = DeduceTemplateArguments(&*Partial,
1003                                    ClassTemplateSpec->getTemplateArgs(),
1004                                    Info)) {
1005      // FIXME: Store the failed-deduction information for use in
1006      // diagnostics, later.
1007      (void)Result;
1008    } else {
1009      Matched.push_back(std::make_pair(&*Partial, Info.take()));
1010    }
1011  }
1012
1013  if (Matched.size() == 1) {
1014    //   -- If exactly one matching specialization is found, the
1015    //      instantiation is generated from that specialization.
1016    Pattern = Matched[0].first;
1017    TemplateArgs = Matched[0].second;
1018  } else if (Matched.size() > 1) {
1019    //   -- If more than one matching specialization is found, the
1020    //      partial order rules (14.5.4.2) are used to determine
1021    //      whether one of the specializations is more specialized
1022    //      than the others. If none of the specializations is more
1023    //      specialized than all of the other matching
1024    //      specializations, then the use of the class template is
1025    //      ambiguous and the program is ill-formed.
1026    // FIXME: Implement partial ordering of class template partial
1027    // specializations.
1028    Diag(ClassTemplateSpec->getLocation(),
1029         diag::unsup_template_partial_spec_ordering);
1030  } else {
1031    //   -- If no matches are found, the instantiation is generated
1032    //      from the primary template.
1033
1034    // Since we initialized the pattern and template arguments from
1035    // the primary template, there is nothing more we need to do here.
1036  }
1037
1038  // Note that this is an instantiation.
1039  ClassTemplateSpec->setSpecializationKind(
1040                        ExplicitInstantiation? TSK_ExplicitInstantiation
1041                                             : TSK_ImplicitInstantiation);
1042
1043  bool Result = InstantiateClass(ClassTemplateSpec->getLocation(),
1044                                 ClassTemplateSpec, Pattern, *TemplateArgs,
1045                                 ExplicitInstantiation);
1046
1047  for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
1048    // FIXME: Implement TemplateArgumentList::Destroy!
1049    //    if (Matched[I].first != Pattern)
1050    //      Matched[I].second->Destroy(Context);
1051  }
1052
1053  return Result;
1054}
1055
1056/// \brief Instantiate the definitions of all of the member of the
1057/// given class, which is an instantiation of a class template or a
1058/// member class of a template.
1059void
1060Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
1061                              CXXRecordDecl *Instantiation,
1062                              const TemplateArgumentList &TemplateArgs) {
1063  for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
1064                               DEnd = Instantiation->decls_end();
1065       D != DEnd; ++D) {
1066    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
1067      if (!Function->getBody())
1068        InstantiateFunctionDefinition(PointOfInstantiation, Function);
1069    } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
1070      const VarDecl *Def = 0;
1071      if (!Var->getDefinition(Def))
1072        InstantiateVariableDefinition(Var);
1073    } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
1074      if (!Record->isInjectedClassName() && !Record->getDefinition(Context)) {
1075        assert(Record->getInstantiatedFromMemberClass() &&
1076               "Missing instantiated-from-template information");
1077        InstantiateClass(PointOfInstantiation, Record,
1078                         Record->getInstantiatedFromMemberClass(),
1079                         TemplateArgs, true);
1080      }
1081    }
1082  }
1083}
1084
1085/// \brief Instantiate the definitions of all of the members of the
1086/// given class template specialization, which was named as part of an
1087/// explicit instantiation.
1088void Sema::InstantiateClassTemplateSpecializationMembers(
1089                                           SourceLocation PointOfInstantiation,
1090                          ClassTemplateSpecializationDecl *ClassTemplateSpec) {
1091  // C++0x [temp.explicit]p7:
1092  //   An explicit instantiation that names a class template
1093  //   specialization is an explicit instantion of the same kind
1094  //   (declaration or definition) of each of its members (not
1095  //   including members inherited from base classes) that has not
1096  //   been previously explicitly specialized in the translation unit
1097  //   containing the explicit instantiation, except as described
1098  //   below.
1099  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
1100                          ClassTemplateSpec->getTemplateArgs());
1101}
1102
1103/// \brief Instantiate a nested-name-specifier.
1104NestedNameSpecifier *
1105Sema::InstantiateNestedNameSpecifier(NestedNameSpecifier *NNS,
1106                                     SourceRange Range,
1107                                     const TemplateArgumentList &TemplateArgs) {
1108  // Instantiate the prefix of this nested name specifier.
1109  NestedNameSpecifier *Prefix = NNS->getPrefix();
1110  if (Prefix) {
1111    Prefix = InstantiateNestedNameSpecifier(Prefix, Range, TemplateArgs);
1112    if (!Prefix)
1113      return 0;
1114  }
1115
1116  switch (NNS->getKind()) {
1117  case NestedNameSpecifier::Identifier: {
1118    assert(Prefix &&
1119           "Can't have an identifier nested-name-specifier with no prefix");
1120    CXXScopeSpec SS;
1121    // FIXME: The source location information is all wrong.
1122    SS.setRange(Range);
1123    SS.setScopeRep(Prefix);
1124    return static_cast<NestedNameSpecifier *>(
1125                                 ActOnCXXNestedNameSpecifier(0, SS,
1126                                                             Range.getEnd(),
1127                                                             Range.getEnd(),
1128                                                    *NNS->getAsIdentifier()));
1129    break;
1130  }
1131
1132  case NestedNameSpecifier::Namespace:
1133  case NestedNameSpecifier::Global:
1134    return NNS;
1135
1136  case NestedNameSpecifier::TypeSpecWithTemplate:
1137  case NestedNameSpecifier::TypeSpec: {
1138    QualType T = QualType(NNS->getAsType(), 0);
1139    if (!T->isDependentType())
1140      return NNS;
1141
1142    T = InstantiateType(T, TemplateArgs, Range.getBegin(), DeclarationName());
1143    if (T.isNull())
1144      return 0;
1145
1146    if (T->isDependentType() || T->isRecordType() ||
1147        (getLangOptions().CPlusPlus0x && T->isEnumeralType())) {
1148      assert(T.getCVRQualifiers() == 0 && "Can't get cv-qualifiers here");
1149      return NestedNameSpecifier::Create(Context, Prefix,
1150                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1151                                         T.getTypePtr());
1152    }
1153
1154    Diag(Range.getBegin(), diag::err_nested_name_spec_non_tag) << T;
1155    return 0;
1156  }
1157  }
1158
1159  // Required to silence a GCC warning
1160  return 0;
1161}
1162
1163TemplateName
1164Sema::InstantiateTemplateName(TemplateName Name, SourceLocation Loc,
1165                              const TemplateArgumentList &TemplateArgs) {
1166  if (TemplateTemplateParmDecl *TTP
1167        = dyn_cast_or_null<TemplateTemplateParmDecl>(
1168                                                 Name.getAsTemplateDecl())) {
1169    assert(TTP->getDepth() == 0 &&
1170           "Cannot reduce depth of a template template parameter");
1171    assert(TemplateArgs[TTP->getPosition()].getAsDecl() &&
1172           "Wrong kind of template template argument");
1173    ClassTemplateDecl *ClassTemplate
1174      = dyn_cast<ClassTemplateDecl>(
1175                               TemplateArgs[TTP->getPosition()].getAsDecl());
1176    assert(ClassTemplate && "Expected a class template");
1177    if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
1178      NestedNameSpecifier *NNS
1179        = InstantiateNestedNameSpecifier(QTN->getQualifier(),
1180                                         /*FIXME=*/SourceRange(Loc),
1181                                         TemplateArgs);
1182      if (NNS)
1183        return Context.getQualifiedTemplateName(NNS,
1184                                                QTN->hasTemplateKeyword(),
1185                                                ClassTemplate);
1186    }
1187
1188    return TemplateName(ClassTemplate);
1189  } else if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
1190    NestedNameSpecifier *NNS
1191      = InstantiateNestedNameSpecifier(DTN->getQualifier(),
1192                                       /*FIXME=*/SourceRange(Loc),
1193                                       TemplateArgs);
1194
1195    if (!NNS) // FIXME: Not the best recovery strategy.
1196      return Name;
1197
1198    if (NNS->isDependent())
1199      return Context.getDependentTemplateName(NNS, DTN->getName());
1200
1201    // Somewhat redundant with ActOnDependentTemplateName.
1202    CXXScopeSpec SS;
1203    SS.setRange(SourceRange(Loc));
1204    SS.setScopeRep(NNS);
1205    TemplateTy Template;
1206    TemplateNameKind TNK = isTemplateName(*DTN->getName(), 0, Template, &SS);
1207    if (TNK == TNK_Non_template) {
1208      Diag(Loc, diag::err_template_kw_refers_to_non_template)
1209        << DTN->getName();
1210      return Name;
1211    } else if (TNK == TNK_Function_template) {
1212      Diag(Loc, diag::err_template_kw_refers_to_non_template)
1213        << DTN->getName();
1214      return Name;
1215    }
1216
1217    return Template.getAsVal<TemplateName>();
1218  }
1219
1220
1221
1222  // FIXME: Even if we're referring to a Decl that isn't a template template
1223  // parameter, we may need to instantiate the outer contexts of that
1224  // Decl. However, this won't be needed until we implement member templates.
1225  return Name;
1226}
1227
1228TemplateArgument Sema::Instantiate(TemplateArgument Arg,
1229                                   const TemplateArgumentList &TemplateArgs) {
1230  switch (Arg.getKind()) {
1231  case TemplateArgument::Null:
1232    assert(false && "Should never have a NULL template argument");
1233    break;
1234
1235  case TemplateArgument::Type: {
1236    QualType T = InstantiateType(Arg.getAsType(), TemplateArgs,
1237                                 Arg.getLocation(), DeclarationName());
1238    if (T.isNull())
1239      return TemplateArgument();
1240
1241    return TemplateArgument(Arg.getLocation(), T);
1242  }
1243
1244  case TemplateArgument::Declaration:
1245    // FIXME: Template instantiation for template template parameters.
1246    return Arg;
1247
1248  case TemplateArgument::Integral:
1249    return Arg;
1250
1251  case TemplateArgument::Expression: {
1252    // Template argument expressions are not potentially evaluated.
1253    EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
1254
1255    Sema::OwningExprResult E = InstantiateExpr(Arg.getAsExpr(), TemplateArgs);
1256    if (E.isInvalid())
1257      return TemplateArgument();
1258    return TemplateArgument(E.takeAs<Expr>());
1259  }
1260
1261  case TemplateArgument::Pack:
1262    assert(0 && "FIXME: Implement!");
1263    break;
1264  }
1265
1266  assert(false && "Unhandled template argument kind");
1267  return TemplateArgument();
1268}
1269