Speculative execution predicts a branch and continues executing along that path before the decision is resolved. Correct predictions improve performance; wrong predictions flush pipelines and caches. When control flow depends on secrets, these effects can expose timing information through side-channel analysis, even without electronic probes. section 10.5
Threshold-dependent summation
A loop sums array elements only when array[i] exceeds 500. Predictable data lets the processor follow the branch efficiently, while unpredictable data makes the branch costly. A branchless version uses comparison and conditional-move instructions instead, illustrating a defensive alternative for sensitive control flow. section 10.5
Reduce exposure from secret-dependent control flow by:
- Avoid branching and iterating on sensitive data whenever practical. section 10.5
Listing 10.3 branch-predict.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRAY_SIZE 100000000
#define THRESHOLD 500
int compare(const void *a, const void *b) {
return ( *(int*)a - *(int*)b );
}
void fill_array(int *array, size_t size) {
for(size_t i = 0; i < size; ++i) {
array[i] = rand() % 1000;
}
}
long long sum_array(int *array, size_t size, int threshold) {
long long sum = 0;
for(size_t i = 0; i < size; ++i) {
if(array[i] > threshold) { #1
sum += array[i];
}
}
return sum;
}
Inspect the ordinary threshold branch that creates predictable or unpredictable processor control flow. section 10.5

