diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp
index c75cf20eb38e29bffc646a1a887bd0418c559057..83f2c53a7c6b84fe0b16c410ad3748f2987ba191 100644
--- a/lib/AST/Decl.cpp
+++ b/lib/AST/Decl.cpp
@@ -976,7 +976,7 @@ getExplicitVisibilityAux(const NamedDecl *ND,
                            kind);
 
   // Use the most recent declaration.
-  if (!IsMostRecent) {
+  if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
     const NamedDecl *MostRecent = ND->getMostRecentDecl();
     if (MostRecent != ND)
       return getExplicitVisibilityAux(MostRecent, kind, true);
diff --git a/test/CodeGenCXX/visibility.cpp b/test/CodeGenCXX/visibility.cpp
index 6049bf8d2bcc79b3e6db379d074bcb5edc7c3575..1c4d5bb8e7a8e1c0462dc7c63295cb06f379eda7 100644
--- a/test/CodeGenCXX/visibility.cpp
+++ b/test/CodeGenCXX/visibility.cpp
@@ -1295,3 +1295,17 @@ namespace test68 {
   }
   // Check lines at top of file.
 }
+
+namespace test69 {
+  // PR18174
+  namespace foo {
+    void f();
+  }
+  namespace foo {
+    void f() {};
+  }
+  namespace foo __attribute__((visibility("hidden"))) {
+  }
+  // CHECK-LABEL: define void @_ZN6test693foo1fEv
+  // CHECK-HIDDEN-LABEL: define hidden void @_ZN6test693foo1fEv
+}