SemaTemplateInstantiate.cpp revision cca9e9674a5e50a283185d8e9d8a5c3414eb008e
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                                Loc, Entity);
425}
426
427QualType
428TemplateTypeInstantiator::
429InstantiateIncompleteArrayType(const IncompleteArrayType *T) const {
430  QualType ElementType = Instantiate(T->getElementType());
431  if (ElementType.isNull())
432    return ElementType;
433
434  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
435                                0, T->getIndexTypeQualifier(),
436                                Loc, Entity);
437}
438
439QualType
440TemplateTypeInstantiator::
441InstantiateVariableArrayType(const VariableArrayType *T) const {
442  // FIXME: Implement this
443  assert(false && "Cannot instantiate VariableArrayType yet");
444  return QualType();
445}
446
447QualType
448TemplateTypeInstantiator::
449InstantiateDependentSizedArrayType(const DependentSizedArrayType *T) const {
450  Expr *ArraySize = T->getSizeExpr();
451  assert(ArraySize->isValueDependent() &&
452         "dependent sized array types must have value dependent size expr");
453
454  // Instantiate the element type if needed
455  QualType ElementType = T->getElementType();
456  if (ElementType->isDependentType()) {
457    ElementType = Instantiate(ElementType);
458    if (ElementType.isNull())
459      return QualType();
460  }
461
462  // Instantiate the size expression
463  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
464  Sema::OwningExprResult InstantiatedArraySize =
465    SemaRef.InstantiateExpr(ArraySize, TemplateArgs);
466  if (InstantiatedArraySize.isInvalid())
467    return QualType();
468
469  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
470                                InstantiatedArraySize.takeAs<Expr>(),
471                                T->getIndexTypeQualifier(), Loc, Entity);
472}
473
474QualType
475TemplateTypeInstantiator::
476InstantiateDependentSizedExtVectorType(
477                                const DependentSizedExtVectorType *T) const {
478
479  // Instantiate the element type if needed.
480  QualType ElementType = T->getElementType();
481  if (ElementType->isDependentType()) {
482    ElementType = Instantiate(ElementType);
483    if (ElementType.isNull())
484      return QualType();
485  }
486
487  // The expression in a dependent-sized extended vector type is not
488  // potentially evaluated.
489  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
490
491  // Instantiate the size expression.
492  const Expr *SizeExpr = T->getSizeExpr();
493  Sema::OwningExprResult InstantiatedArraySize =
494    SemaRef.InstantiateExpr(const_cast<Expr *>(SizeExpr), TemplateArgs);
495  if (InstantiatedArraySize.isInvalid())
496    return QualType();
497
498  return SemaRef.BuildExtVectorType(ElementType,
499                                    SemaRef.Owned(
500                                      InstantiatedArraySize.takeAs<Expr>()),
501                                    T->getAttributeLoc());
502}
503
504QualType
505TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T) const {
506  // FIXME: Implement this
507  assert(false && "Cannot instantiate VectorType yet");
508  return QualType();
509}
510
511QualType
512TemplateTypeInstantiator::InstantiateExtVectorType(
513                                              const ExtVectorType *T) const {
514  // FIXME: Implement this
515  assert(false && "Cannot instantiate ExtVectorType yet");
516  return QualType();
517}
518
519QualType
520TemplateTypeInstantiator::
521InstantiateFunctionProtoType(const FunctionProtoType *T) const {
522  QualType ResultType = Instantiate(T->getResultType());
523  if (ResultType.isNull())
524    return ResultType;
525
526  llvm::SmallVector<QualType, 4> ParamTypes;
527  for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
528                                         ParamEnd = T->arg_type_end();
529       Param != ParamEnd; ++Param) {
530    QualType P = Instantiate(*Param);
531    if (P.isNull())
532      return P;
533
534    ParamTypes.push_back(P);
535  }
536
537  return SemaRef.BuildFunctionType(ResultType, ParamTypes.data(),
538                                   ParamTypes.size(),
539                                   T->isVariadic(), T->getTypeQuals(),
540                                   Loc, Entity);
541}
542
543QualType
544TemplateTypeInstantiator::
545InstantiateFunctionNoProtoType(const FunctionNoProtoType *T) const {
546  assert(false && "Functions without prototypes cannot be dependent.");
547  return QualType();
548}
549
550QualType
551TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T) const {
552  TypedefDecl *Typedef
553    = cast_or_null<TypedefDecl>(
554                           SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
555  if (!Typedef)
556    return QualType();
557
558  return SemaRef.Context.getTypeDeclType(Typedef);
559}
560
561QualType
562TemplateTypeInstantiator::InstantiateTypeOfExprType(
563                                              const TypeOfExprType *T) const {
564  // The expression in a typeof is not potentially evaluated.
565  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
566
567  Sema::OwningExprResult E
568    = SemaRef.InstantiateExpr(T->getUnderlyingExpr(), TemplateArgs);
569  if (E.isInvalid())
570    return QualType();
571
572  return SemaRef.BuildTypeofExprType(E.takeAs<Expr>());
573}
574
575QualType
576TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T) const {
577  QualType Underlying = Instantiate(T->getUnderlyingType());
578  if (Underlying.isNull())
579    return QualType();
580
581  return SemaRef.Context.getTypeOfType(Underlying);
582}
583
584QualType
585TemplateTypeInstantiator::InstantiateDecltypeType(const DecltypeType *T) const {
586  // C++0x [dcl.type.simple]p4:
587  //   The operand of the decltype specifier is an unevaluated operand.
588  EnterExpressionEvaluationContext Unevaluated(SemaRef,
589                                               Action::Unevaluated);
590
591  Sema::OwningExprResult E
592    = SemaRef.InstantiateExpr(T->getUnderlyingExpr(), TemplateArgs);
593
594  if (E.isInvalid())
595    return QualType();
596
597  return SemaRef.BuildDecltypeType(E.takeAs<Expr>());
598}
599
600QualType
601TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T) const {
602  RecordDecl *Record
603    = cast_or_null<RecordDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
604  if (!Record)
605    return QualType();
606
607  return SemaRef.Context.getTypeDeclType(Record);
608}
609
610QualType
611TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T) const {
612  EnumDecl *Enum
613    = cast_or_null<EnumDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
614  if (!Enum)
615    return QualType();
616
617  return SemaRef.Context.getTypeDeclType(Enum);
618}
619
620QualType
621TemplateTypeInstantiator::
622InstantiateTemplateTypeParmType(const TemplateTypeParmType *T) const {
623  if (T->getDepth() == 0) {
624    // Replace the template type parameter with its corresponding
625    // template argument.
626
627    // If the corresponding template argument is NULL or doesn't exist, it's
628    // because we are performing instantiation from explicitly-specified
629    // template arguments in a function template class, but there were some
630    // arguments left unspecified.
631    if (T->getIndex() >= TemplateArgs.size() ||
632        TemplateArgs[T->getIndex()].isNull())
633      return QualType(T, 0); // Would be nice to keep the original type here
634
635    assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
636           "Template argument kind mismatch");
637    return TemplateArgs[T->getIndex()].getAsType();
638  }
639
640  // The template type parameter comes from an inner template (e.g.,
641  // the template parameter list of a member template inside the
642  // template we are instantiating). Create a new template type
643  // parameter with the template "level" reduced by one.
644  return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
645                                                 T->getIndex(),
646                                                 T->isParameterPack(),
647                                                 T->getName());
648}
649
650QualType
651TemplateTypeInstantiator::
652InstantiateTemplateSpecializationType(
653                                  const TemplateSpecializationType *T) const {
654  llvm::SmallVector<TemplateArgument, 4> InstantiatedTemplateArgs;
655  InstantiatedTemplateArgs.reserve(T->getNumArgs());
656  for (TemplateSpecializationType::iterator Arg = T->begin(), ArgEnd = T->end();
657       Arg != ArgEnd; ++Arg) {
658    TemplateArgument InstArg = SemaRef.Instantiate(*Arg, TemplateArgs);
659    if (InstArg.isNull())
660      return QualType();
661
662    InstantiatedTemplateArgs.push_back(InstArg);
663  }
664
665  // FIXME: We're missing the locations of the template name, '<', and '>'.
666
667  TemplateName Name = SemaRef.InstantiateTemplateName(T->getTemplateName(),
668                                                      Loc,
669                                                      TemplateArgs);
670
671  return SemaRef.CheckTemplateIdType(Name, Loc, SourceLocation(),
672                                     InstantiatedTemplateArgs.data(),
673                                     InstantiatedTemplateArgs.size(),
674                                     SourceLocation());
675}
676
677QualType
678TemplateTypeInstantiator::
679InstantiateQualifiedNameType(const QualifiedNameType *T) const {
680  // When we instantiated a qualified name type, there's no point in
681  // keeping the qualification around in the instantiated result. So,
682  // just instantiate the named type.
683  return (*this)(T->getNamedType());
684}
685
686QualType
687TemplateTypeInstantiator::
688InstantiateTypenameType(const TypenameType *T) const {
689  if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
690    // When the typename type refers to a template-id, the template-id
691    // is dependent and has enough information to instantiate the
692    // result of the typename type. Since we don't care about keeping
693    // the spelling of the typename type in template instantiations,
694    // we just instantiate the template-id.
695    return InstantiateTemplateSpecializationType(TemplateId);
696  }
697
698  NestedNameSpecifier *NNS
699    = SemaRef.InstantiateNestedNameSpecifier(T->getQualifier(),
700                                             SourceRange(Loc),
701                                             TemplateArgs);
702  if (!NNS)
703    return QualType();
704
705  return SemaRef.CheckTypenameType(NNS, *T->getIdentifier(), SourceRange(Loc));
706}
707
708QualType
709TemplateTypeInstantiator::
710InstantiateObjCObjectPointerType(const ObjCObjectPointerType *T) const {
711  assert(false && "Objective-C types cannot be dependent");
712  return QualType();
713}
714
715QualType
716TemplateTypeInstantiator::
717InstantiateObjCInterfaceType(const ObjCInterfaceType *T) const {
718  assert(false && "Objective-C types cannot be dependent");
719  return QualType();
720}
721
722QualType
723TemplateTypeInstantiator::
724InstantiateObjCQualifiedInterfaceType(
725                                 const ObjCQualifiedInterfaceType *T) const {
726  assert(false && "Objective-C types cannot be dependent");
727  return QualType();
728}
729
730/// \brief The actual implementation of Sema::InstantiateType().
731QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
732  // If T is not a dependent type, there is nothing to do.
733  if (!T->isDependentType())
734    return T;
735
736  QualType Result;
737  switch (T->getTypeClass()) {
738#define TYPE(Class, Base)                                               \
739  case Type::Class:                                                     \
740    Result = Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()));  \
741    break;
742#define ABSTRACT_TYPE(Class, Base)
743#include "clang/AST/TypeNodes.def"
744  }
745
746  // C++ [dcl.ref]p1:
747  //   [...] Cv-qualified references are ill-formed except when
748  //   the cv-qualifiers are introduced through the use of a
749  //   typedef (7.1.3) or of a template type argument (14.3), in
750  //   which case the cv-qualifiers are ignored.
751  //
752  // The same rule applies to function types.
753  if (!Result.isNull() && T.getCVRQualifiers() &&
754      !Result->isFunctionType() && !Result->isReferenceType())
755    Result = Result.getWithAdditionalQualifiers(T.getCVRQualifiers());
756  return Result;
757}
758
759/// \brief Instantiate the type T with a given set of template arguments.
760///
761/// This routine substitutes the given template arguments into the
762/// type T and produces the instantiated type.
763///
764/// \param T the type into which the template arguments will be
765/// substituted. If this type is not dependent, it will be returned
766/// immediately.
767///
768/// \param TemplateArgs the template arguments that will be
769/// substituted for the top-level template parameters within T.
770///
771/// \param Loc the location in the source code where this substitution
772/// is being performed. It will typically be the location of the
773/// declarator (if we're instantiating the type of some declaration)
774/// or the location of the type in the source code (if, e.g., we're
775/// instantiating the type of a cast expression).
776///
777/// \param Entity the name of the entity associated with a declaration
778/// being instantiated (if any). May be empty to indicate that there
779/// is no such entity (if, e.g., this is a type that occurs as part of
780/// a cast expression) or that the entity has no name (e.g., an
781/// unnamed function parameter).
782///
783/// \returns If the instantiation succeeds, the instantiated
784/// type. Otherwise, produces diagnostics and returns a NULL type.
785QualType Sema::InstantiateType(QualType T,
786                               const TemplateArgumentList &TemplateArgs,
787                               SourceLocation Loc, DeclarationName Entity) {
788  assert(!ActiveTemplateInstantiations.empty() &&
789         "Cannot perform an instantiation without some context on the "
790         "instantiation stack");
791
792  // If T is not a dependent type, there is nothing to do.
793  if (!T->isDependentType())
794    return T;
795
796  TemplateTypeInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
797  return Instantiator(T);
798}
799
800/// \brief Instantiate the base class specifiers of the given class
801/// template specialization.
802///
803/// Produces a diagnostic and returns true on error, returns false and
804/// attaches the instantiated base classes to the class template
805/// specialization if successful.
806bool
807Sema::InstantiateBaseSpecifiers(CXXRecordDecl *Instantiation,
808                                CXXRecordDecl *Pattern,
809                                const TemplateArgumentList &TemplateArgs) {
810  bool Invalid = false;
811  llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
812  for (ClassTemplateSpecializationDecl::base_class_iterator
813         Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
814       Base != BaseEnd; ++Base) {
815    if (!Base->getType()->isDependentType()) {
816      // FIXME: Allocate via ASTContext
817      InstantiatedBases.push_back(new CXXBaseSpecifier(*Base));
818      continue;
819    }
820
821    QualType BaseType = InstantiateType(Base->getType(),
822                                        TemplateArgs,
823                                        Base->getSourceRange().getBegin(),
824                                        DeclarationName());
825    if (BaseType.isNull()) {
826      Invalid = true;
827      continue;
828    }
829
830    if (CXXBaseSpecifier *InstantiatedBase
831          = CheckBaseSpecifier(Instantiation,
832                               Base->getSourceRange(),
833                               Base->isVirtual(),
834                               Base->getAccessSpecifierAsWritten(),
835                               BaseType,
836                               /*FIXME: Not totally accurate */
837                               Base->getSourceRange().getBegin()))
838      InstantiatedBases.push_back(InstantiatedBase);
839    else
840      Invalid = true;
841  }
842
843  if (!Invalid &&
844      AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
845                           InstantiatedBases.size()))
846    Invalid = true;
847
848  return Invalid;
849}
850
851/// \brief Instantiate the definition of a class from a given pattern.
852///
853/// \param PointOfInstantiation The point of instantiation within the
854/// source code.
855///
856/// \param Instantiation is the declaration whose definition is being
857/// instantiated. This will be either a class template specialization
858/// or a member class of a class template specialization.
859///
860/// \param Pattern is the pattern from which the instantiation
861/// occurs. This will be either the declaration of a class template or
862/// the declaration of a member class of a class template.
863///
864/// \param TemplateArgs The template arguments to be substituted into
865/// the pattern.
866///
867/// \returns true if an error occurred, false otherwise.
868bool
869Sema::InstantiateClass(SourceLocation PointOfInstantiation,
870                       CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
871                       const TemplateArgumentList &TemplateArgs,
872                       bool ExplicitInstantiation) {
873  bool Invalid = false;
874
875  CXXRecordDecl *PatternDef
876    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
877  if (!PatternDef) {
878    if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
879      Diag(PointOfInstantiation,
880           diag::err_implicit_instantiate_member_undefined)
881        << Context.getTypeDeclType(Instantiation);
882      Diag(Pattern->getLocation(), diag::note_member_of_template_here);
883    } else {
884      Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
885        << ExplicitInstantiation
886        << Context.getTypeDeclType(Instantiation);
887      Diag(Pattern->getLocation(), diag::note_template_decl_here);
888    }
889    return true;
890  }
891  Pattern = PatternDef;
892
893  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
894  if (Inst)
895    return true;
896
897  // Enter the scope of this instantiation. We don't use
898  // PushDeclContext because we don't have a scope.
899  DeclContext *PreviousContext = CurContext;
900  CurContext = Instantiation;
901
902  // Start the definition of this instantiation.
903  Instantiation->startDefinition();
904
905  // Instantiate the base class specifiers.
906  if (InstantiateBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
907    Invalid = true;
908
909  llvm::SmallVector<DeclPtrTy, 4> Fields;
910  for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
911         MemberEnd = Pattern->decls_end();
912       Member != MemberEnd; ++Member) {
913    Decl *NewMember = InstantiateDecl(*Member, Instantiation, TemplateArgs);
914    if (NewMember) {
915      if (NewMember->isInvalidDecl())
916        Invalid = true;
917      else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
918        Fields.push_back(DeclPtrTy::make(Field));
919    } else {
920      // FIXME: Eventually, a NULL return will mean that one of the
921      // instantiations was a semantic disaster, and we'll want to set Invalid =
922      // true. For now, we expect to skip some members that we can't yet handle.
923    }
924  }
925
926  // Finish checking fields.
927  ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
928              Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
929              0);
930
931  // Add any implicitly-declared members that we might need.
932  AddImplicitlyDeclaredMembersToClass(Instantiation);
933
934  // Exit the scope of this instantiation.
935  CurContext = PreviousContext;
936
937  if (!Invalid)
938    Consumer.HandleTagDeclDefinition(Instantiation);
939
940  // If this is an explicit instantiation, instantiate our members, too.
941  if (!Invalid && ExplicitInstantiation) {
942    Inst.Clear();
943    InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs);
944  }
945
946  return Invalid;
947}
948
949bool
950Sema::InstantiateClassTemplateSpecialization(
951                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
952                           bool ExplicitInstantiation) {
953  // Perform the actual instantiation on the canonical declaration.
954  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
955                               Context.getCanonicalDecl(ClassTemplateSpec));
956
957  // We can only instantiate something that hasn't already been
958  // instantiated or specialized. Fail without any diagnostics: our
959  // caller will provide an error message.
960  if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
961    return true;
962
963  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
964  CXXRecordDecl *Pattern = Template->getTemplatedDecl();
965  const TemplateArgumentList *TemplateArgs
966    = &ClassTemplateSpec->getTemplateArgs();
967
968  // C++ [temp.class.spec.match]p1:
969  //   When a class template is used in a context that requires an
970  //   instantiation of the class, it is necessary to determine
971  //   whether the instantiation is to be generated using the primary
972  //   template or one of the partial specializations. This is done by
973  //   matching the template arguments of the class template
974  //   specialization with the template argument lists of the partial
975  //   specializations.
976  typedef std::pair<ClassTemplatePartialSpecializationDecl *,
977                    TemplateArgumentList *> MatchResult;
978  llvm::SmallVector<MatchResult, 4> Matched;
979  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
980         Partial = Template->getPartialSpecializations().begin(),
981         PartialEnd = Template->getPartialSpecializations().end();
982       Partial != PartialEnd;
983       ++Partial) {
984    TemplateDeductionInfo Info(Context);
985    if (TemplateDeductionResult Result
986          = DeduceTemplateArguments(&*Partial,
987                                    ClassTemplateSpec->getTemplateArgs(),
988                                    Info)) {
989      // FIXME: Store the failed-deduction information for use in
990      // diagnostics, later.
991      (void)Result;
992    } else {
993      Matched.push_back(std::make_pair(&*Partial, Info.take()));
994    }
995  }
996
997  if (Matched.size() == 1) {
998    //   -- If exactly one matching specialization is found, the
999    //      instantiation is generated from that specialization.
1000    Pattern = Matched[0].first;
1001    TemplateArgs = Matched[0].second;
1002  } else if (Matched.size() > 1) {
1003    //   -- If more than one matching specialization is found, the
1004    //      partial order rules (14.5.4.2) are used to determine
1005    //      whether one of the specializations is more specialized
1006    //      than the others. If none of the specializations is more
1007    //      specialized than all of the other matching
1008    //      specializations, then the use of the class template is
1009    //      ambiguous and the program is ill-formed.
1010    // FIXME: Implement partial ordering of class template partial
1011    // specializations.
1012    Diag(ClassTemplateSpec->getLocation(),
1013         diag::unsup_template_partial_spec_ordering);
1014  } else {
1015    //   -- If no matches are found, the instantiation is generated
1016    //      from the primary template.
1017
1018    // Since we initialized the pattern and template arguments from
1019    // the primary template, there is nothing more we need to do here.
1020  }
1021
1022  // Note that this is an instantiation.
1023  ClassTemplateSpec->setSpecializationKind(
1024                        ExplicitInstantiation? TSK_ExplicitInstantiation
1025                                             : TSK_ImplicitInstantiation);
1026
1027  bool Result = InstantiateClass(ClassTemplateSpec->getLocation(),
1028                                 ClassTemplateSpec, Pattern, *TemplateArgs,
1029                                 ExplicitInstantiation);
1030
1031  for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
1032    // FIXME: Implement TemplateArgumentList::Destroy!
1033    //    if (Matched[I].first != Pattern)
1034    //      Matched[I].second->Destroy(Context);
1035  }
1036
1037  return Result;
1038}
1039
1040/// \brief Instantiate the definitions of all of the member of the
1041/// given class, which is an instantiation of a class template or a
1042/// member class of a template.
1043void
1044Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
1045                              CXXRecordDecl *Instantiation,
1046                              const TemplateArgumentList &TemplateArgs) {
1047  for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
1048                               DEnd = Instantiation->decls_end();
1049       D != DEnd; ++D) {
1050    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
1051      if (!Function->getBody())
1052        InstantiateFunctionDefinition(PointOfInstantiation, Function);
1053    } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
1054      const VarDecl *Def = 0;
1055      if (!Var->getDefinition(Def))
1056        InstantiateVariableDefinition(Var);
1057    } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
1058      if (!Record->isInjectedClassName() && !Record->getDefinition(Context)) {
1059        assert(Record->getInstantiatedFromMemberClass() &&
1060               "Missing instantiated-from-template information");
1061        InstantiateClass(PointOfInstantiation, Record,
1062                         Record->getInstantiatedFromMemberClass(),
1063                         TemplateArgs, true);
1064      }
1065    }
1066  }
1067}
1068
1069/// \brief Instantiate the definitions of all of the members of the
1070/// given class template specialization, which was named as part of an
1071/// explicit instantiation.
1072void Sema::InstantiateClassTemplateSpecializationMembers(
1073                                           SourceLocation PointOfInstantiation,
1074                          ClassTemplateSpecializationDecl *ClassTemplateSpec) {
1075  // C++0x [temp.explicit]p7:
1076  //   An explicit instantiation that names a class template
1077  //   specialization is an explicit instantion of the same kind
1078  //   (declaration or definition) of each of its members (not
1079  //   including members inherited from base classes) that has not
1080  //   been previously explicitly specialized in the translation unit
1081  //   containing the explicit instantiation, except as described
1082  //   below.
1083  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
1084                          ClassTemplateSpec->getTemplateArgs());
1085}
1086
1087/// \brief Instantiate a nested-name-specifier.
1088NestedNameSpecifier *
1089Sema::InstantiateNestedNameSpecifier(NestedNameSpecifier *NNS,
1090                                     SourceRange Range,
1091                                     const TemplateArgumentList &TemplateArgs) {
1092  // Instantiate the prefix of this nested name specifier.
1093  NestedNameSpecifier *Prefix = NNS->getPrefix();
1094  if (Prefix) {
1095    Prefix = InstantiateNestedNameSpecifier(Prefix, Range, TemplateArgs);
1096    if (!Prefix)
1097      return 0;
1098  }
1099
1100  switch (NNS->getKind()) {
1101  case NestedNameSpecifier::Identifier: {
1102    assert(Prefix &&
1103           "Can't have an identifier nested-name-specifier with no prefix");
1104    CXXScopeSpec SS;
1105    // FIXME: The source location information is all wrong.
1106    SS.setRange(Range);
1107    SS.setScopeRep(Prefix);
1108    return static_cast<NestedNameSpecifier *>(
1109                                 ActOnCXXNestedNameSpecifier(0, SS,
1110                                                             Range.getEnd(),
1111                                                             Range.getEnd(),
1112                                                    *NNS->getAsIdentifier()));
1113    break;
1114  }
1115
1116  case NestedNameSpecifier::Namespace:
1117  case NestedNameSpecifier::Global:
1118    return NNS;
1119
1120  case NestedNameSpecifier::TypeSpecWithTemplate:
1121  case NestedNameSpecifier::TypeSpec: {
1122    QualType T = QualType(NNS->getAsType(), 0);
1123    if (!T->isDependentType())
1124      return NNS;
1125
1126    T = InstantiateType(T, TemplateArgs, Range.getBegin(), DeclarationName());
1127    if (T.isNull())
1128      return 0;
1129
1130    if (T->isDependentType() || T->isRecordType() ||
1131        (getLangOptions().CPlusPlus0x && T->isEnumeralType())) {
1132      assert(T.getCVRQualifiers() == 0 && "Can't get cv-qualifiers here");
1133      return NestedNameSpecifier::Create(Context, Prefix,
1134                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1135                                         T.getTypePtr());
1136    }
1137
1138    Diag(Range.getBegin(), diag::err_nested_name_spec_non_tag) << T;
1139    return 0;
1140  }
1141  }
1142
1143  // Required to silence a GCC warning
1144  return 0;
1145}
1146
1147TemplateName
1148Sema::InstantiateTemplateName(TemplateName Name, SourceLocation Loc,
1149                              const TemplateArgumentList &TemplateArgs) {
1150  if (TemplateTemplateParmDecl *TTP
1151        = dyn_cast_or_null<TemplateTemplateParmDecl>(
1152                                                 Name.getAsTemplateDecl())) {
1153    assert(TTP->getDepth() == 0 &&
1154           "Cannot reduce depth of a template template parameter");
1155    assert(TemplateArgs[TTP->getPosition()].getAsDecl() &&
1156           "Wrong kind of template template argument");
1157    ClassTemplateDecl *ClassTemplate
1158      = dyn_cast<ClassTemplateDecl>(
1159                               TemplateArgs[TTP->getPosition()].getAsDecl());
1160    assert(ClassTemplate && "Expected a class template");
1161    if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
1162      NestedNameSpecifier *NNS
1163        = InstantiateNestedNameSpecifier(QTN->getQualifier(),
1164                                         /*FIXME=*/SourceRange(Loc),
1165                                         TemplateArgs);
1166      if (NNS)
1167        return Context.getQualifiedTemplateName(NNS,
1168                                                QTN->hasTemplateKeyword(),
1169                                                ClassTemplate);
1170    }
1171
1172    return TemplateName(ClassTemplate);
1173  } else if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
1174    NestedNameSpecifier *NNS
1175      = InstantiateNestedNameSpecifier(DTN->getQualifier(),
1176                                       /*FIXME=*/SourceRange(Loc),
1177                                       TemplateArgs);
1178
1179    if (!NNS) // FIXME: Not the best recovery strategy.
1180      return Name;
1181
1182    if (NNS->isDependent())
1183      return Context.getDependentTemplateName(NNS, DTN->getName());
1184
1185    // Somewhat redundant with ActOnDependentTemplateName.
1186    CXXScopeSpec SS;
1187    SS.setRange(SourceRange(Loc));
1188    SS.setScopeRep(NNS);
1189    TemplateTy Template;
1190    TemplateNameKind TNK = isTemplateName(*DTN->getName(), 0, Template, &SS);
1191    if (TNK == TNK_Non_template) {
1192      Diag(Loc, diag::err_template_kw_refers_to_non_template)
1193        << DTN->getName();
1194      return Name;
1195    } else if (TNK == TNK_Function_template) {
1196      Diag(Loc, diag::err_template_kw_refers_to_non_template)
1197        << DTN->getName();
1198      return Name;
1199    }
1200
1201    return Template.getAsVal<TemplateName>();
1202  }
1203
1204
1205
1206  // FIXME: Even if we're referring to a Decl that isn't a template template
1207  // parameter, we may need to instantiate the outer contexts of that
1208  // Decl. However, this won't be needed until we implement member templates.
1209  return Name;
1210}
1211
1212TemplateArgument Sema::Instantiate(TemplateArgument Arg,
1213                                   const TemplateArgumentList &TemplateArgs) {
1214  switch (Arg.getKind()) {
1215  case TemplateArgument::Null:
1216    assert(false && "Should never have a NULL template argument");
1217    break;
1218
1219  case TemplateArgument::Type: {
1220    QualType T = InstantiateType(Arg.getAsType(), TemplateArgs,
1221                                 Arg.getLocation(), DeclarationName());
1222    if (T.isNull())
1223      return TemplateArgument();
1224
1225    return TemplateArgument(Arg.getLocation(), T);
1226  }
1227
1228  case TemplateArgument::Declaration:
1229    // FIXME: Template instantiation for template template parameters.
1230    return Arg;
1231
1232  case TemplateArgument::Integral:
1233    return Arg;
1234
1235  case TemplateArgument::Expression: {
1236    // Template argument expressions are not potentially evaluated.
1237    EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
1238
1239    Sema::OwningExprResult E = InstantiateExpr(Arg.getAsExpr(), TemplateArgs);
1240    if (E.isInvalid())
1241      return TemplateArgument();
1242    return TemplateArgument(E.takeAs<Expr>());
1243  }
1244
1245  case TemplateArgument::Pack:
1246    assert(0 && "FIXME: Implement!");
1247    break;
1248  }
1249
1250  assert(false && "Unhandled template argument kind");
1251  return TemplateArgument();
1252}
1253