diff --git a/gcc/attribs.cc b/gcc/attribs.cc
index 229d8b32c1ee0730ed4e0cdd920efe3a8c07e4a8..f9fd258598914ce2112ecaaeaad6c63cd69a44e2 100644
--- a/gcc/attribs.cc
+++ b/gcc/attribs.cc
@@ -579,9 +579,9 @@ attribute_ignored_p (tree attr)
     return false;
   if (tree ns = get_attribute_namespace (attr))
     {
-      if (attr_namespace_ignored_p (ns))
-	return true;
       const attribute_spec *as = lookup_attribute_spec (TREE_PURPOSE (attr));
+      if (as == NULL && attr_namespace_ignored_p (ns))
+	return true;
       if (as && as->max_length == -2)
 	return true;
     }
@@ -862,7 +862,10 @@ decl_attributes (tree *node, tree attributes, int flags,
 	    }
 	}
 
-      if (no_add_attrs)
+      if (no_add_attrs
+	  /* Don't add attributes registered just for -Wno-attributes=foo::bar
+	     purposes.  */
+	  || attribute_ignored_p (attr))
 	continue;
 
       if (spec->handler != NULL)
diff --git a/gcc/testsuite/c-c++-common/ubsan/Wno-attributes-1.c b/gcc/testsuite/c-c++-common/ubsan/Wno-attributes-1.c
new file mode 100644
index 0000000000000000000000000000000000000000..8e392c7fd6ea20611332c1fe63c8d390f645ed65
--- /dev/null
+++ b/gcc/testsuite/c-c++-common/ubsan/Wno-attributes-1.c
@@ -0,0 +1,9 @@
+/* PR c/112339 */
+/* { dg-do compile { target { c++11 || c } } } */
+/* { dg-options "-Wno-attributes=foo::no_sanitize -fsanitize=undefined" } */
+/* { dg-additional-options "-std=c2x" { target c } } */
+
+[[foo::no_sanitize("bounds")]] void
+foo (void)
+{
+}