When we encounter a dependent type that was parsed before we know that
we were going to enter into the scope of a class template or class
template partial specialization, rebuild that type so that it can
refer to members of the current instantiation, as in code like

  template<typename T>
  struct X {
    typedef T* pointer;
    pointer data();
  };

  template<typename T>
  typename X<T>::pointer X<T>::data() { ... }

Without rebuilding the return type of this out-of-line definition, the
canonical return type of the out-of-line definition (a TypenameType)
will not match the canonical return type of the declaration (the
canonical type of T*).



git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@78316 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Sema/SemaDecl.cpp b/lib/Sema/SemaDecl.cpp
index 90ba65a..d6b32a7 100644
--- a/lib/Sema/SemaDecl.cpp
+++ b/lib/Sema/SemaDecl.cpp
@@ -1628,6 +1628,30 @@
          (S->getFlags() & Scope::TemplateParamScope) != 0)
     S = S->getParent();
   
+  // If this is an out-of-line definition of a member of a class template
+  // or class template partial specialization, we may need to rebuild the
+  // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
+  // for more information.
+  // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
+  // handle expressions properly.
+  DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
+  if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
+      isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
+      (DS.getTypeSpecType() == DeclSpec::TST_typename ||
+       DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
+       DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
+       DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
+    if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
+      QualType T = QualType::getFromOpaquePtr(DS.getTypeRep());
+      EnterDeclaratorContext(S, DC);
+      T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
+      ExitDeclaratorContext(S);
+      if (T.isNull())
+        return DeclPtrTy();
+      DS.UpdateTypeRep(T.getAsOpaquePtr());
+    }
+  }
+  
   DeclContext *DC;
   NamedDecl *PrevDecl;
   NamedDecl *New;