clang API Documentation

Template.h
Go to the documentation of this file.
00001 //===------- SemaTemplate.h - C++ Templates ---------------------*- C++ -*-===/
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //===----------------------------------------------------------------------===/
00008 //
00009 //  This file provides types used in the semantic analysis of C++ templates.
00010 //
00011 //===----------------------------------------------------------------------===/
00012 #ifndef LLVM_CLANG_SEMA_TEMPLATE_H
00013 #define LLVM_CLANG_SEMA_TEMPLATE_H
00014 
00015 #include "clang/AST/DeclTemplate.h"
00016 #include "clang/AST/DeclVisitor.h"
00017 #include "clang/Sema/Sema.h"
00018 #include "llvm/ADT/SmallVector.h"
00019 #include <cassert>
00020 #include <utility>
00021 
00022 namespace clang {
00023   /// \brief Data structure that captures multiple levels of template argument
00024   /// lists for use in template instantiation.
00025   ///
00026   /// Multiple levels of template arguments occur when instantiating the 
00027   /// definitions of member templates. For example:
00028   ///
00029   /// \code
00030   /// template<typename T>
00031   /// struct X {
00032   ///   template<T Value>
00033   ///   struct Y {
00034   ///     void f();
00035   ///   };
00036   /// };
00037   /// \endcode
00038   ///
00039   /// When instantiating X<int>::Y<17>::f, the multi-level template argument
00040   /// list will contain a template argument list (int) at depth 0 and a
00041   /// template argument list (17) at depth 1.
00042   class MultiLevelTemplateArgumentList {
00043     /// \brief The template argument list at a certain template depth 
00044     typedef ArrayRef<TemplateArgument> ArgList;
00045 
00046     /// \brief The template argument lists, stored from the innermost template
00047     /// argument list (first) to the outermost template argument list (last).
00048     SmallVector<ArgList, 4> TemplateArgumentLists;
00049     
00050   public:
00051     /// \brief Construct an empty set of template argument lists.
00052     MultiLevelTemplateArgumentList() { }
00053     
00054     /// \brief Construct a single-level template argument list.
00055     explicit 
00056     MultiLevelTemplateArgumentList(const TemplateArgumentList &TemplateArgs) {
00057       addOuterTemplateArguments(&TemplateArgs);
00058     }
00059     
00060     /// \brief Determine the number of levels in this template argument
00061     /// list.
00062     unsigned getNumLevels() const { return TemplateArgumentLists.size(); }
00063     
00064     /// \brief Retrieve the template argument at a given depth and index.
00065     const TemplateArgument &operator()(unsigned Depth, unsigned Index) const {
00066       assert(Depth < TemplateArgumentLists.size());
00067       assert(Index < TemplateArgumentLists[getNumLevels() - Depth - 1].size());
00068       return TemplateArgumentLists[getNumLevels() - Depth - 1][Index];
00069     }
00070     
00071     /// \brief Determine whether there is a non-NULL template argument at the
00072     /// given depth and index.
00073     ///
00074     /// There must exist a template argument list at the given depth.
00075     bool hasTemplateArgument(unsigned Depth, unsigned Index) const {
00076       assert(Depth < TemplateArgumentLists.size());
00077       
00078       if (Index >= TemplateArgumentLists[getNumLevels() - Depth - 1].size())
00079         return false;
00080       
00081       return !(*this)(Depth, Index).isNull();
00082     }
00083     
00084     /// \brief Clear out a specific template argument.
00085     void setArgument(unsigned Depth, unsigned Index,
00086                      TemplateArgument Arg) {
00087       assert(Depth < TemplateArgumentLists.size());
00088       assert(Index < TemplateArgumentLists[getNumLevels() - Depth - 1].size());
00089       const_cast<TemplateArgument&>(
00090                 TemplateArgumentLists[getNumLevels() - Depth - 1][Index])
00091         = Arg;
00092     }
00093     
00094     /// \brief Add a new outermost level to the multi-level template argument 
00095     /// list.
00096     void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs) {
00097       addOuterTemplateArguments(ArgList(TemplateArgs->data(),
00098                                         TemplateArgs->size()));
00099     }
00100 
00101     /// \brief Add a new outmost level to the multi-level template argument
00102     /// list.
00103     void addOuterTemplateArguments(ArgList Args) {
00104       TemplateArgumentLists.push_back(Args);
00105     }
00106 
00107     /// \brief Retrieve the innermost template argument list.
00108     const ArgList &getInnermost() const { 
00109       return TemplateArgumentLists.front(); 
00110     }
00111   };
00112   
00113   /// \brief The context in which partial ordering of function templates occurs.
00114   enum TPOC {
00115     /// \brief Partial ordering of function templates for a function call.
00116     TPOC_Call,
00117     /// \brief Partial ordering of function templates for a call to a 
00118     /// conversion function.
00119     TPOC_Conversion,
00120     /// \brief Partial ordering of function templates in other contexts, e.g.,
00121     /// taking the address of a function template or matching a function 
00122     /// template specialization to a function template.
00123     TPOC_Other
00124   };
00125 
00126   // This is lame but unavoidable in a world without forward
00127   // declarations of enums.  The alternatives are to either pollute
00128   // Sema.h (by including this file) or sacrifice type safety (by
00129   // making Sema.h declare things as enums).
00130   class TemplatePartialOrderingContext {
00131     TPOC Value;
00132   public:
00133     TemplatePartialOrderingContext(TPOC Value) : Value(Value) {}
00134     operator TPOC() const { return Value; }
00135   };
00136 
00137   /// \brief Captures a template argument whose value has been deduced
00138   /// via c++ template argument deduction.
00139   class DeducedTemplateArgument : public TemplateArgument {
00140     /// \brief For a non-type template argument, whether the value was
00141     /// deduced from an array bound.
00142     bool DeducedFromArrayBound;
00143 
00144   public:
00145     DeducedTemplateArgument()
00146       : TemplateArgument(), DeducedFromArrayBound(false) { }
00147 
00148     DeducedTemplateArgument(const TemplateArgument &Arg,
00149                             bool DeducedFromArrayBound = false)
00150       : TemplateArgument(Arg), DeducedFromArrayBound(DeducedFromArrayBound) { }
00151 
00152     /// \brief Construct an integral non-type template argument that
00153     /// has been deduced, possibly from an array bound.
00154     DeducedTemplateArgument(ASTContext &Ctx,
00155                             const llvm::APSInt &Value,
00156                             QualType ValueType,
00157                             bool DeducedFromArrayBound)
00158       : TemplateArgument(Ctx, Value, ValueType),
00159         DeducedFromArrayBound(DeducedFromArrayBound) { }
00160 
00161     /// \brief For a non-type template argument, determine whether the
00162     /// template argument was deduced from an array bound.
00163     bool wasDeducedFromArrayBound() const { return DeducedFromArrayBound; }
00164 
00165     /// \brief Specify whether the given non-type template argument
00166     /// was deduced from an array bound.
00167     void setDeducedFromArrayBound(bool Deduced) {
00168       DeducedFromArrayBound = Deduced;
00169     }
00170   };
00171 
00172   /// \brief A stack-allocated class that identifies which local
00173   /// variable declaration instantiations are present in this scope.
00174   ///
00175   /// A new instance of this class type will be created whenever we
00176   /// instantiate a new function declaration, which will have its own
00177   /// set of parameter declarations.
00178   class LocalInstantiationScope {
00179   public:
00180     /// \brief A set of declarations.
00181     typedef SmallVector<Decl *, 4> DeclArgumentPack;
00182     
00183   private:
00184     /// \brief Reference to the semantic analysis that is performing
00185     /// this template instantiation.
00186     Sema &SemaRef;
00187 
00188     typedef llvm::SmallDenseMap<
00189         const Decl *, llvm::PointerUnion<Decl *, DeclArgumentPack *>, 4>
00190     LocalDeclsMap;
00191 
00192     /// \brief A mapping from local declarations that occur
00193     /// within a template to their instantiations.
00194     ///
00195     /// This mapping is used during instantiation to keep track of,
00196     /// e.g., function parameter and variable declarations. For example,
00197     /// given:
00198     ///
00199     /// \code
00200     ///   template<typename T> T add(T x, T y) { return x + y; }
00201     /// \endcode
00202     ///
00203     /// when we instantiate add<int>, we will introduce a mapping from
00204     /// the ParmVarDecl for 'x' that occurs in the template to the
00205     /// instantiated ParmVarDecl for 'x'.
00206     ///
00207     /// For a parameter pack, the local instantiation scope may contain a
00208     /// set of instantiated parameters. This is stored as a DeclArgumentPack
00209     /// pointer.
00210     LocalDeclsMap LocalDecls;
00211 
00212     /// \brief The set of argument packs we've allocated.
00213     SmallVector<DeclArgumentPack *, 1> ArgumentPacks;
00214     
00215     /// \brief The outer scope, which contains local variable
00216     /// definitions from some other instantiation (that may not be
00217     /// relevant to this particular scope).
00218     LocalInstantiationScope *Outer;
00219 
00220     /// \brief Whether we have already exited this scope.
00221     bool Exited;
00222 
00223     /// \brief Whether to combine this scope with the outer scope, such that
00224     /// lookup will search our outer scope.
00225     bool CombineWithOuterScope;
00226     
00227     /// \brief If non-NULL, the template parameter pack that has been
00228     /// partially substituted per C++0x [temp.arg.explicit]p9.
00229     NamedDecl *PartiallySubstitutedPack;
00230     
00231     /// \brief If \c PartiallySubstitutedPack is non-null, the set of
00232     /// explicitly-specified template arguments in that pack.
00233     const TemplateArgument *ArgsInPartiallySubstitutedPack;    
00234     
00235     /// \brief If \c PartiallySubstitutedPack, the number of 
00236     /// explicitly-specified template arguments in 
00237     /// ArgsInPartiallySubstitutedPack.
00238     unsigned NumArgsInPartiallySubstitutedPack;
00239 
00240     // This class is non-copyable
00241     LocalInstantiationScope(
00242       const LocalInstantiationScope &) LLVM_DELETED_FUNCTION;
00243     void operator=(const LocalInstantiationScope &) LLVM_DELETED_FUNCTION;
00244 
00245   public:
00246     LocalInstantiationScope(Sema &SemaRef, bool CombineWithOuterScope = false)
00247       : SemaRef(SemaRef), Outer(SemaRef.CurrentInstantiationScope),
00248         Exited(false), CombineWithOuterScope(CombineWithOuterScope),
00249         PartiallySubstitutedPack(nullptr)
00250     {
00251       SemaRef.CurrentInstantiationScope = this;
00252     }
00253 
00254     ~LocalInstantiationScope() {
00255       Exit();
00256     }
00257     
00258     const Sema &getSema() const { return SemaRef; }
00259 
00260     /// \brief Exit this local instantiation scope early.
00261     void Exit() {
00262       if (Exited)
00263         return;
00264       
00265       for (unsigned I = 0, N = ArgumentPacks.size(); I != N; ++I)
00266         delete ArgumentPacks[I];
00267         
00268       SemaRef.CurrentInstantiationScope = Outer;
00269       Exited = true;
00270     }
00271 
00272     /// \brief Clone this scope, and all outer scopes, down to the given
00273     /// outermost scope.
00274     LocalInstantiationScope *cloneScopes(LocalInstantiationScope *Outermost) {
00275       if (this == Outermost) return this;
00276       LocalInstantiationScope *newScope =
00277         new LocalInstantiationScope(SemaRef, CombineWithOuterScope);
00278 
00279       newScope->Outer = nullptr;
00280       if (Outer)
00281         newScope->Outer = Outer->cloneScopes(Outermost);
00282 
00283       newScope->PartiallySubstitutedPack = PartiallySubstitutedPack;
00284       newScope->ArgsInPartiallySubstitutedPack = ArgsInPartiallySubstitutedPack;
00285       newScope->NumArgsInPartiallySubstitutedPack =
00286         NumArgsInPartiallySubstitutedPack;
00287 
00288       for (LocalDeclsMap::iterator I = LocalDecls.begin(), E = LocalDecls.end();
00289            I != E; ++I) {
00290         const Decl *D = I->first;
00291         llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored =
00292           newScope->LocalDecls[D];
00293         if (I->second.is<Decl *>()) {
00294           Stored = I->second.get<Decl *>();
00295         } else {
00296           DeclArgumentPack *OldPack = I->second.get<DeclArgumentPack *>();
00297           DeclArgumentPack *NewPack = new DeclArgumentPack(*OldPack);
00298           Stored = NewPack;
00299           newScope->ArgumentPacks.push_back(NewPack);
00300         }
00301       }
00302       return newScope;
00303     }
00304 
00305     /// \brief deletes the given scope, and all otuer scopes, down to the
00306     /// given outermost scope.
00307     static void deleteScopes(LocalInstantiationScope *Scope,
00308                              LocalInstantiationScope *Outermost) {
00309       while (Scope && Scope != Outermost) {
00310         LocalInstantiationScope *Out = Scope->Outer;
00311         delete Scope;
00312         Scope = Out;
00313       }
00314     }
00315 
00316     /// \brief Find the instantiation of the declaration D within the current
00317     /// instantiation scope.
00318     ///
00319     /// \param D The declaration whose instantiation we are searching for.
00320     ///
00321     /// \returns A pointer to the declaration or argument pack of declarations
00322     /// to which the declaration \c D is instantiated, if found. Otherwise,
00323     /// returns NULL.
00324     llvm::PointerUnion<Decl *, DeclArgumentPack *> *
00325     findInstantiationOf(const Decl *D);
00326 
00327     void InstantiatedLocal(const Decl *D, Decl *Inst);
00328     void InstantiatedLocalPackArg(const Decl *D, Decl *Inst);
00329     void MakeInstantiatedLocalArgPack(const Decl *D);
00330     
00331     /// \brief Note that the given parameter pack has been partially substituted
00332     /// via explicit specification of template arguments 
00333     /// (C++0x [temp.arg.explicit]p9).
00334     ///
00335     /// \param Pack The parameter pack, which will always be a template
00336     /// parameter pack.
00337     ///
00338     /// \param ExplicitArgs The explicitly-specified template arguments provided
00339     /// for this parameter pack.
00340     ///
00341     /// \param NumExplicitArgs The number of explicitly-specified template
00342     /// arguments provided for this parameter pack.
00343     void SetPartiallySubstitutedPack(NamedDecl *Pack, 
00344                                      const TemplateArgument *ExplicitArgs,
00345                                      unsigned NumExplicitArgs);
00346 
00347     /// \brief Reset the partially-substituted pack when it is no longer of
00348     /// interest.
00349     void ResetPartiallySubstitutedPack() {
00350       assert(PartiallySubstitutedPack && "No partially-substituted pack");
00351       PartiallySubstitutedPack = nullptr;
00352       ArgsInPartiallySubstitutedPack = nullptr;
00353       NumArgsInPartiallySubstitutedPack = 0;
00354     }
00355 
00356     /// \brief Retrieve the partially-substitued template parameter pack.
00357     ///
00358     /// If there is no partially-substituted parameter pack, returns NULL.
00359     NamedDecl *
00360     getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs = nullptr,
00361                                 unsigned *NumExplicitArgs = nullptr) const;
00362   };
00363 
00364   class TemplateDeclInstantiator
00365     : public DeclVisitor<TemplateDeclInstantiator, Decl *> 
00366   {
00367     Sema &SemaRef;
00368     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex;
00369     DeclContext *Owner;
00370     const MultiLevelTemplateArgumentList &TemplateArgs;
00371     Sema::LateInstantiatedAttrVec* LateAttrs;
00372     LocalInstantiationScope *StartingScope;
00373 
00374     /// \brief A list of out-of-line class template partial
00375     /// specializations that will need to be instantiated after the
00376     /// enclosing class's instantiation is complete.
00377     SmallVector<std::pair<ClassTemplateDecl *,
00378                                 ClassTemplatePartialSpecializationDecl *>, 4>
00379       OutOfLinePartialSpecs;
00380 
00381     /// \brief A list of out-of-line variable template partial
00382     /// specializations that will need to be instantiated after the
00383     /// enclosing variable's instantiation is complete.
00384     /// FIXME: Verify that this is needed.
00385     SmallVector<
00386         std::pair<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>, 4>
00387     OutOfLineVarPartialSpecs;
00388 
00389   public:
00390     TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
00391                              const MultiLevelTemplateArgumentList &TemplateArgs)
00392       : SemaRef(SemaRef),
00393         SubstIndex(SemaRef, SemaRef.ArgumentPackSubstitutionIndex),
00394         Owner(Owner), TemplateArgs(TemplateArgs), LateAttrs(nullptr),
00395         StartingScope(nullptr) {}
00396 
00397 // Define all the decl visitors using DeclNodes.inc
00398 #define DECL(DERIVED, BASE) \
00399     Decl *Visit ## DERIVED ## Decl(DERIVED ## Decl *D);
00400 #define ABSTRACT_DECL(DECL)
00401 
00402 // Decls which never appear inside a class or function.
00403 #define OBJCCONTAINER(DERIVED, BASE)
00404 #define FILESCOPEASM(DERIVED, BASE)
00405 #define IMPORT(DERIVED, BASE)
00406 #define LINKAGESPEC(DERIVED, BASE)
00407 #define OBJCCOMPATIBLEALIAS(DERIVED, BASE)
00408 #define OBJCMETHOD(DERIVED, BASE)
00409 #define OBJCIVAR(DERIVED, BASE)
00410 #define OBJCPROPERTY(DERIVED, BASE)
00411 #define OBJCPROPERTYIMPL(DERIVED, BASE)
00412 #define EMPTY(DERIVED, BASE)
00413 
00414 // Decls which use special-case instantiation code.
00415 #define BLOCK(DERIVED, BASE)
00416 #define CAPTURED(DERIVED, BASE)
00417 #define IMPLICITPARAM(DERIVED, BASE)
00418 
00419 #include "clang/AST/DeclNodes.inc"
00420 
00421     // A few supplemental visitor functions.
00422     Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
00423                              TemplateParameterList *TemplateParams,
00424                              bool IsClassScopeSpecialization = false);
00425     Decl *VisitFunctionDecl(FunctionDecl *D,
00426                             TemplateParameterList *TemplateParams);
00427     Decl *VisitDecl(Decl *D);
00428     Decl *VisitVarDecl(VarDecl *D, bool InstantiatingVarTemplate);
00429 
00430     // Enable late instantiation of attributes.  Late instantiated attributes
00431     // will be stored in LA.
00432     void enableLateAttributeInstantiation(Sema::LateInstantiatedAttrVec *LA) {
00433       LateAttrs = LA;
00434       StartingScope = SemaRef.CurrentInstantiationScope;
00435     }
00436 
00437     // Disable late instantiation of attributes.
00438     void disableLateAttributeInstantiation() {
00439       LateAttrs = nullptr;
00440       StartingScope = nullptr;
00441     }
00442 
00443     LocalInstantiationScope *getStartingScope() const { return StartingScope; }
00444 
00445     typedef 
00446       SmallVectorImpl<std::pair<ClassTemplateDecl *,
00447                                      ClassTemplatePartialSpecializationDecl *> >
00448         ::iterator
00449       delayed_partial_spec_iterator;
00450 
00451     typedef SmallVectorImpl<std::pair<
00452         VarTemplateDecl *, VarTemplatePartialSpecializationDecl *> >::iterator
00453     delayed_var_partial_spec_iterator;
00454 
00455     /// \brief Return an iterator to the beginning of the set of
00456     /// "delayed" partial specializations, which must be passed to
00457     /// InstantiateClassTemplatePartialSpecialization once the class
00458     /// definition has been completed.
00459     delayed_partial_spec_iterator delayed_partial_spec_begin() {
00460       return OutOfLinePartialSpecs.begin();
00461     }
00462 
00463     delayed_var_partial_spec_iterator delayed_var_partial_spec_begin() {
00464       return OutOfLineVarPartialSpecs.begin();
00465     }
00466 
00467     /// \brief Return an iterator to the end of the set of
00468     /// "delayed" partial specializations, which must be passed to
00469     /// InstantiateClassTemplatePartialSpecialization once the class
00470     /// definition has been completed.
00471     delayed_partial_spec_iterator delayed_partial_spec_end() {
00472       return OutOfLinePartialSpecs.end();
00473     }
00474 
00475     delayed_var_partial_spec_iterator delayed_var_partial_spec_end() {
00476       return OutOfLineVarPartialSpecs.end();
00477     }
00478 
00479     // Helper functions for instantiating methods.
00480     TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
00481                              SmallVectorImpl<ParmVarDecl *> &Params);
00482     bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
00483     bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
00484 
00485     TemplateParameterList *
00486       SubstTemplateParams(TemplateParameterList *List);
00487 
00488     bool SubstQualifier(const DeclaratorDecl *OldDecl,
00489                         DeclaratorDecl *NewDecl);
00490     bool SubstQualifier(const TagDecl *OldDecl,
00491                         TagDecl *NewDecl);
00492 
00493     Decl *VisitVarTemplateSpecializationDecl(
00494         VarTemplateDecl *VarTemplate, VarDecl *FromVar, void *InsertPos,
00495         const TemplateArgumentListInfo &TemplateArgsInfo,
00496         ArrayRef<TemplateArgument> Converted);
00497 
00498     Decl *InstantiateTypedefNameDecl(TypedefNameDecl *D, bool IsTypeAlias);
00499     ClassTemplatePartialSpecializationDecl *
00500     InstantiateClassTemplatePartialSpecialization(
00501                                               ClassTemplateDecl *ClassTemplate,
00502                            ClassTemplatePartialSpecializationDecl *PartialSpec);
00503     VarTemplatePartialSpecializationDecl *
00504     InstantiateVarTemplatePartialSpecialization(
00505         VarTemplateDecl *VarTemplate,
00506         VarTemplatePartialSpecializationDecl *PartialSpec);
00507     void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern);
00508   };  
00509 }
00510 
00511 #endif // LLVM_CLANG_SEMA_TEMPLATE_H