AESNI: Overhaul implementation selection
Have clearly separated code to:
* determine whether the assembly-based implementation is available;
* determine whether the intrinsics-based implementation is available;
* select one of the available implementations if any.
Now MBEDTLS_AESNI_HAVE_CODE can be the single interface for aes.c and
aesni.c to determine which AESNI is built.
Change the implementation selection: now, if both implementations are
available, always prefer assembly. Before, the intrinsics were used if
available. This preference is to minimize disruption, and will likely
be revised in a later minor release.
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
diff --git a/include/mbedtls/aesni.h b/include/mbedtls/aesni.h
index b3d49e4..20ad6e3 100644
--- a/include/mbedtls/aesni.h
+++ b/include/mbedtls/aesni.h
@@ -36,6 +36,9 @@
#define MBEDTLS_AESNI_AES 0x02000000u
#define MBEDTLS_AESNI_CLMUL 0x00000002u
+/* Can we do AESNI with inline assembly?
+ * (Only implemented with gas syntax, only for 64-bit.)
+ */
#if defined(MBEDTLS_HAVE_ASM) && defined(__GNUC__) && \
(defined(__amd64__) || defined(__x86_64__)) && \
!defined(MBEDTLS_HAVE_X86_64)
@@ -44,19 +47,33 @@
#if defined(MBEDTLS_AESNI_C)
-#if defined(MBEDTLS_HAVE_X86_64)
-#define MBEDTLS_AESNI_HAVE_CODE // via assembly
-#endif
-
+/* Can we do AESNI with intrinsics?
+ * (Only implemented with certain compilers, .)
+ */
+#undef MBEDTLS_AESNI_HAVE_INTRINSICS
#if defined(_MSC_VER)
-#define MBEDTLS_HAVE_AESNI_INTRINSICS
+/* Visual Studio supports AESNI intrinsics since VS 2008 SP1. We only support
+ * VS 2013 and up for other reasons anyway, so no need to check the version. */
+#define MBEDTLS_AESNI_HAVE_INTRINSICS
#endif
-#if defined(__GNUC__) && defined(__AES__)
-#define MBEDTLS_HAVE_AESNI_INTRINSICS
+/* GCC-like compilers: currently, we only support intrinsics if the requisite
+ * target flag is enabled when building the library (e.g. `gcc -mpclmul -msse2`
+ * or `clang -maes -mpclmul`). */
+#if defined(__GNUC__) && defined(__AES__) && defined(__PCLMUL__)
+#define MBEDTLS_AESNI_HAVE_INTRINSICS
#endif
-#if defined(MBEDTLS_HAVE_AESNI_INTRINSICS)
-#define MBEDTLS_AESNI_HAVE_CODE // via intrinsics
+/* Choose the implementation of AESNI, if one is available. */
+#undef MBEDTLS_AESNI_HAVE_CODE
+/* To minimize disruption when releasing the intrinsics-based implementation,
+ * favor the assembly-based implementation if it's available. We intend to
+ * revise this in a later release of Mbed TLS 3.x. In the long run, we will
+ * likely remove the assembly implementation. */
+#if defined(MBEDTLS_HAVE_X86_64)
+#define MBEDTLS_AESNI_HAVE_CODE 1 // via assembly
+#endif
+#if defined(MBEDTLS_AESNI_HAVE_INTRINSICS)
+#define MBEDTLS_AESNI_HAVE_CODE 2 // via intrinsics
#endif
#if defined(MBEDTLS_AESNI_HAVE_CODE)