[c++] Adjust mark used member in instantiated class scope
authorNathan Sidwell <nathan@acm.org>
Tue, 4 Jan 2022 21:36:44 +0000 (13:36 -0800)
committerNathan Sidwell <nathan@acm.org>
Wed, 5 Jan 2022 12:13:56 +0000 (04:13 -0800)
The fix for PR97966 caused a regression with (non-template) member
functions of template classes.  We need to mark them used in the
instantiated class's scope, rather than the scope we were in before
instantiating, as the latter may itself be in template and change the
behaviour of marking a function as used.

gcc/cp/
* pt.c (instantiate_class_template_1): Process attribute((used)) set
in class's context.
gcc/testsuite/
* g++.dg/template/attr-used.C: New.

gcc/cp/pt.c
gcc/testsuite/g++.dg/template/attr-used.C [new file with mode: 0644]

index c587966..0fa4a16 100644 (file)
@@ -12277,6 +12277,14 @@ instantiate_class_template_1 (tree type)
 
   perform_instantiation_time_access_checks (pattern, args);
   perform_deferred_access_checks (tf_warning_or_error);
+
+  /* Now that we've gone through all the members, instantiate those
+     marked with attribute used.  We must do this in the context of
+     the class -- not the context we pushed from, as that might be
+     inside a template and change the behaviour of mark_used.  */
+  for (tree x : used)
+    mark_used (x);
+
   pop_nested_class ();
   maximum_field_alignment = saved_maximum_field_alignment;
   if (!fn_context)
@@ -12290,11 +12298,6 @@ instantiate_class_template_1 (tree type)
   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
     vec_safe_push (keyed_classes, type);
 
-  /* Now that we've gone through all the members, instantiate those
-     marked with attribute used.  */
-  for (tree x : used)
-    mark_used (x);
-
   return type;
 }
 
diff --git a/gcc/testsuite/g++.dg/template/attr-used.C b/gcc/testsuite/g++.dg/template/attr-used.C
new file mode 100644 (file)
index 0000000..e12bf4c
--- /dev/null
@@ -0,0 +1,16 @@
+// { dg-do compile }
+
+template<typename T> struct X {
+  void g () {}
+  void f () __attribute__((__used__)) {}
+};
+
+extern X<int> x; // X<int> incomplete here
+
+template <typename T>
+void Frob (T t) {
+  x.g(); // X<int> completed here, X<int>::f's body marked for instantiation
+}
+
+// Make sure X<int>::f is emitted
+// { dg-final { scan-assembler "_ZN1XIiE1fEv:" } }