diff --git a/lib/Sema/Sema.cpp b/lib/Sema/Sema.cpp
index 4b82069..e444f3c 100644
--- a/lib/Sema/Sema.cpp
+++ b/lib/Sema/Sema.cpp
@@ -328,11 +328,7 @@ CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
 
 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
-  // Template instantiation can happen at the end of the translation unit
-  // and it sets the canonical (first) decl to used. Normal uses set the last
-  // decl at the time to used and subsequent decl inherit the flag. The net
-  // result is that we need to check both ends of the decl chain.
-  if (D->isUsed() || D->getMostRecentDecl()->isUsed())
+  if (D->getMostRecentDecl()->isUsed())
     return true;
 
   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
diff --git a/lib/Sema/SemaExpr.cpp b/lib/Sema/SemaExpr.cpp
index 191a26d..9d40faa 100644
--- a/lib/Sema/SemaExpr.cpp
+++ b/lib/Sema/SemaExpr.cpp
@@ -10496,7 +10496,18 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
     if (old.isInvalid()) old = Loc;
   }
 
-  Func->setUsed(true);
+  // Normally a decl is marked used while processing the file and any
+  // subsequent decls are marked used by decl merging. This fails with template
+  // instantiation since markin can happen at the end of the file and, because
+  // of the two phase lookup, this function is called with at decl in the middle
+  // of a decl chain. We loop to maintain the invariant that once a decl is
+  // used, all decls after it are also used.
+  for (FunctionDecl *F = Func->getMostRecentDecl();;) {
+    F->setUsed(true);
+    if (F == Func)
+      break;
+    F = F->getPreviousDecl();
+  }
 }
 
 static void
diff --git a/test/SemaCXX/warn-func-not-needed.cpp b/test/SemaCXX/warn-func-not-needed.cpp
index 0cc639f..d51c173 100644
--- a/test/SemaCXX/warn-func-not-needed.cpp
+++ b/test/SemaCXX/warn-func-not-needed.cpp
@@ -28,3 +28,17 @@ namespace test3 {
     g<int>();
   }
 }
+
+namespace test4 {
+  static void f();
+  static void f();
+  template<typename T>
+  static void g() {
+    f();
+  }
+  static void f() {
+  }
+  void h() {
+    g<int>();
+  }
+}
