When the compiler can reduce the condition to a constant, it can elide the
conditional and one of the basic blocks.  However, arch_evaluate_nospec() will
still insert speculation protection, despite there being nothing to protect.

Allow the speculation protection to be skipped entirely when the compiler is
removing the condition entirely.

e.g. for x86, given:

  int foo(void)
  {
      if ( evaluate_nospec(1) )
          return 2;
      else
          return 42;
  }

then before, we get:

  <foo>:
      lfence
      mov    $0x2,%eax
      retq

and afterwards, we get:

  <foo>:
      mov    $0x2,%eax
      retq

which is correct.  With no conditional branch to protect, the lfence isn't
providing any relevant safety.

Signed-off-by: Andrew Cooper <andrew.coop...@citrix.com>
---
CC: Jan Beulich <jbeul...@suse.com>
CC: Roger Pau Monné <roger....@citrix.com>
CC: Wei Liu <w...@xen.org>
---
 xen/include/xen/nospec.h | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/xen/include/xen/nospec.h b/xen/include/xen/nospec.h
index a4155af08770..56cf67a44176 100644
--- a/xen/include/xen/nospec.h
+++ b/xen/include/xen/nospec.h
@@ -18,6 +18,15 @@ static always_inline bool evaluate_nospec(bool cond)
 #ifndef arch_evaluate_nospec
 #define arch_evaluate_nospec(cond) cond
 #endif
+
+    /*
+     * If the compiler can reduce the condition to a constant, then it won't
+     * be emitting a conditional branch, and there's nothing needing
+     * protecting.
+     */
+    if ( __builtin_constant_p(cond) )
+        return cond;
+
     return arch_evaluate_nospec(cond);
 }
 
-- 
2.30.2


Reply via email to