Make the main loop's logic clearer

The loop ends when there are no more bits to process, with one twist: when
that happens, we need to clear the window one last time. Since the window
does not start empty (E_limbs==0 is not supported), the loop always starts
with a non-empty window and some bits to process. So it's correct to move
the window clearing logic to the end of the loop. This lets us exit the loop
when the end of the exponent is reached.

It would be clearer not to do the final window clearing inside the loop, so
we wouldn't need to repeat the loop termination condition (end of exponent
reached) inside the loop. However, this requires duplicating the code to
clear the window. Empirically, this causes a significant code size increase,
even if the window clearing code is placed into a function.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
diff --git a/library/bignum_core.c b/library/bignum_core.c
index c05e603..737e08d 100644
--- a/library/bignum_core.c
+++ b/library/bignum_core.c
@@ -683,29 +683,8 @@
     mbedtls_mpi_uint window = 0;
     size_t window_bits = 0;
 
-    while( 1 )
+    do
     {
-        size_t window_bits_missing = wsize - window_bits;
-
-        const int no_more_bits =
-            ( E_bit_index == 0 ) && ( E_limb_index == 0 );
-        const int window_full =
-            ( window_bits_missing == 0 );
-
-        /* Clear window if it's full or if we don't have further bits. */
-        if( window_full || no_more_bits )
-        {
-            if( window_bits == 0 )
-                break;
-            /* Select table entry, square and multiply */
-            mbedtls_mpi_core_ct_uint_table_lookup( Wselect, Wtable,
-                                                   AN_limbs, welem, window );
-            mbedtls_mpi_core_montmul( X, X, Wselect, AN_limbs, N, AN_limbs, mm, temp );
-            window = 0;
-            window_bits = 0;
-            continue;
-        }
-
         /* Square */
         mbedtls_mpi_core_montmul( X, X, X, AN_limbs, N, AN_limbs, mm, temp );
 
@@ -722,7 +701,21 @@
         ++window_bits;
         window <<= 1;
         window |= ( E[E_limb_index] >> E_bit_index ) & 1;
+
+        /* Clear window if it's full. Also clear the window at the end,
+         * when we've finished processing the exponent. */
+        if( window_bits == wsize ||
+            ( E_bit_index == 0 && E_limb_index == 0 ) )
+        {
+            /* Select table entry, square and multiply */
+            mbedtls_mpi_core_ct_uint_table_lookup( Wselect, Wtable,
+                                                   AN_limbs, welem, window );
+            mbedtls_mpi_core_montmul( X, X, Wselect, AN_limbs, N, AN_limbs, mm, temp );
+            window = 0;
+            window_bits = 0;
+        }
     }
+    while( ! ( E_bit_index == 0 && E_limb_index == 0 ) );
 
     /* Convert X back to normal presentation */
     const mbedtls_mpi_uint one = 1;