================
@@ -61,6 +59,48 @@ __attribute__((const, pure)) int func7(void); // 
expected-warning {{'const' attr
 // FIXME: this should also be diagnosed the same as func7.
 __attribute__((pure)) int func8(void);
 [[gnu::const]] int func8(void) {
-  return 12;
+return 12;
 }
 
+// Diagnosing invalid 'pure'/'const' attributes: writes through a pointer or
+// reference parameter, or to a global/static variable, violate the
+// attribute's no-visible-side-effects contract.
+
+int lookup(int key, int *value) __attribute__((__pure__));
+int lookup(int key, int *value) { // expected-note {{function declared 'pure' 
here}}
+  if (key == 42) {
+    *value = 47; // expected-warning {{function declared 'pure' stores through 
pointer parameter 'value'}}
+    return 0;
+  }
+  return -1;
+}
+
+static int global_cache;
+__attribute__((pure)) int writes_global(int x) { // expected-note {{function 
declared 'pure' here}}
+  global_cache = x; // expected-warning {{function declared 'pure' stores to 
global variable 'global_cache'}}
+  return global_cache;
+}
+
+__attribute__((pure)) int writes_static_local(int x) { // expected-note 
{{function declared 'pure' here}}
+  static int cache = 0;
+  cache += x; // expected-warning {{function declared 'pure' stores to static 
local variable 'cache'}}
+  return cache;
+}
+
+// No warning: local, non-static variable.
+__attribute__((pure)) int local_only(int x) {
+  int tmp = x * 2;
+  return tmp;
+}
+
+// No warning: read-only dereference of a const pointer.
+__attribute__((pure)) int reads_ptr_arg(const int *value) {
+  return *value;
+}
+
+#ifdef __cplusplus
+__attribute__((pure)) int writes_ref_arg(int &out) { // expected-note 
{{function declared 'pure' here}}
+  out = 1; // expected-warning {{function declared 'pure' stores through 
reference parameter 'out'}}
+  return 0;
+}
+#endif
----------------
ojhunt wrote:

new line according to GH review

https://github.com/llvm/llvm-project/pull/217817
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to