--- name: branchless-programming description: Eliminate branches for CPU performance — conditional moves (cmov), bit manipulation tricks, SIMD-friendly patterns. Use when branch misprediction causes pipeline stalls, preventing auto-vectorization, or in hot loops. license: MIT --- ## What I Do Guide conversion of branchy code to branchless equivalents. Use when branches cause pipeline stalls, prevent vectorization, or have unpredictable behavior. --- ## Why Branches Are Slow ### Branch Misprediction Cost When the CPU mispredicts a branch: - Pipeline must be flushed - **10-20 cycles lost** on modern CPUs - In tight loops, even 1% misprediction is expensive ### Branch Prevention of Vectorization Vectorization requires SIMD instructions that operate on all lanes: - Branches make this impossible (need same operation on all elements) - Compiler must generate scalar code with branches ### When Branches Are Fine - **Predictable branches** - 99%+ accuracy = minimal cost - **Not in hot path** - Occasional misprediction doesn't matter - **Early exits** - Better to exit early than compute unnecessarily --- ## Conditional Moves (cmov) ### Basic Pattern ```c // Branchy int max(int a, int b) { if (a > b) return a; else return b; } // Branchless (cmov) int max(int a, int b) { int cmp = a > b; return cmp ? a : b; // Compiler generates cmov } ``` ### x86 Instruction ```asm ; Branchless max cmp eax, ebx cmovg eax, ebx ; Conditional move if greater ``` ### GCC/Clang Hint ```c __builtin_expect(!!(condition), 0) // Hint: unlikely ``` But prefer branchless when in tight loops. --- ## Bit Manipulation Selection ### Select Without Branch Use arithmetic to select based on condition: ```c // Condition as 0 or 1 int select(int condition, int a, int b) { // If condition: mask = 0xFFFFFFFF // If !condition: mask = 0x00000000 int mask = -condition; // -1 if true, 0 if false // mask selects a when true, b when false return (mask & a) | (~mask & b); } ``` ### Cleaner Version ```c // Using ternary (compiler often converts to cmov) int max = (a > b) ? a : b; // Using bit tricks int max = a - ((a - b) & ((a - b) >> 31)); // a-b positive if a>b, >>31 extracts sign bit as 0 or 1 ``` --- ## Clamping and Clipping ### Branchless Clamp ```c // Branchy int clamp(int x, int min, int max) { if (x < min) return min; if (x > max) return max; return x; } // Branchless int clamp(int x, int min, int max) { // Clamp to min int t = x < min ? min - x : 0; x -= t & (t >> 31); // if x max ? x - max : 0; x -= t & (t >> 31); return x; } ``` ### Alternative: Min/Max Composition ```c int clamp(int x, int min, int max) { return x < min ? min : (x > max ? max : x); // Compiler may or may not branch - test! } ``` --- ## Sign Extraction ### Absolute Value ```c // Branchless abs int abs(int x) { int mask = x >> 31; // -1 if negative, 0 if positive return (x + mask) ^ mask; // If negative: (x-1) ^ -1 = ~x+1 = -x } // Or using intrinsics int abs(int x) { return __builtin_abs(x); } ``` ### Sign Function ```c // Returns -1, 0, or 1 int sign(int x) { return (x > 0) - (x < 0); // Branchless } ``` --- ## Boolean to 0/1 Conversion ### Convert Any Non-Zero to 1 ```c // Branchless: any non-zero becomes 1 int boolify(int x) { return !!x; // Double negation // Or: return (x != 0); // Compare to 0 } ``` ### Convert -1/0/1 to 0/1/2 ```c // For sign extraction int sgn_to_idx(int x) { return (x > 0) - (x < 0) + 1; // Maps -1→0, 0→1, 1→2 } ``` --- ## SIMD Blending ### Vector Selection In SIMD, use blend instructions: ```c // AVX2: blendv_ps selects from a or b based on mask __m256 mask = _mm256_cmp_ps(a, b, _CMP_GT_OQ); __m256 result = _mm256_blendv_ps(b, a, mask); // Rust portable simd let mask = a.simd_gt(b); let result = mask.select(a, b); ``` ### Why Blend > Branch in SIMD - Branch = scalar loop or mask (half work wasted) - Blend = keep all work, select result --- ## Loop Conversion ### Counting with Condition ```c // Branchy: conditional in loop int count_positive(int* arr, int n) { int count = 0; for (int i = 0; i < n; i++) if (arr[i] > 0) count++; return count; } // Branchless int count_positive(int* arr, int n) { int count = 0; for (int i = 0; i < n; i++) count += (arr[i] > 0); // Adds 1 if true, 0 if false return count; } ``` ### Conditional Accumulation ```c // Branchy for (int i = 0; i < n; i++) { if (arr[i] > threshold) sum += arr[i]; } // Branchless: always add, multiply by boolean for (int i = 0; i < n; i++) sum += arr[i] * (arr[i] > threshold); ``` --- ## Array Indexing ### Safe Array Access ```c // Branchy: check bounds int get(int* arr, int n, int idx) { if (idx >= 0 && idx < n) return arr[idx]; return 0; } // Branchless: clamp index then access int get(int* arr, int n, int idx) { idx = idx < 0 ? 0 : (idx >= n ? n-1 : idx); return arr[idx]; } ``` ### Masked Store ```c // Store only if condition is true __m256i mask = _mm256_cmpgt_epi32(index, zero); __m256i data = _mm256_mask_load_epi32(output, mask, input); // Only stores where mask has bits set ``` --- ## When NOT to Use Branchless ### Branch Predictable ```c // Array sorted - branch always goes same way // Compiler + CPU predict well - branchless not needed for (int i = 0; i < n; i++) if (sorted[i] > 0) // Almost always true sum += sorted[i]; ``` ### Rarely Executed ```c // Error handling - usually doesn't run if (ptr == NULL) return error; // Keep branch, branchless adds overhead ``` ### Large Data-Dependent Work ```c // Work is huge - branch cost negligible if (large_condition) do_massive_computation_a(); else do_massive_computation_b(); // Branchless doubles work unnecessarily ``` --- ## Practical Guidelines ### Decision Tree ``` Is branch in hot path? ├─ NO → Keep branch └─ YES → Is branch predictable? ├─ YES (>95% same direction) → Keep branch └─ NO → Convert to branchless ``` ### Profile First 1. Run profiler 2. Check branch misprediction rate 3. Only convert if misprediction is significant ### Test Correctness Branchless code is harder to get right: - Edge cases (0, MIN, MAX) - Sign extension - Overflow --- ## Performance Comparison ### Typical Results | Pattern | Branchy | Branchless | Speedup | | --------------- | ------- | ---------- | ------------------------- | | Conditional sum | 1.0x | 1.5-3x | Depends on predictabilty | | min/max | 1.0x | 1.2-2x | | | SIMD loop | 1.0x | 2-4x | Much better vectorization | ### Benchmark! Always benchmark your specific case. Results vary by: - CPU model - Data patterns - Compiler version --- ## Example: Branchless Binary Search ```c // Branchless lower_bound int lower_bound(int* arr, int n, int target) { int lo = 0, hi = n; while (lo < hi) { int mid = lo + (hi - lo) / 2; // Branchless: if arr[mid] < target, lo = mid + 1 lo += ((arr[mid] < target) * (mid + 1 - mid)); // Branchless: if arr[mid] >= target, hi = mid hi -= ((arr[mid] >= target) * (mid - hi + mid)); // Simplified: // lo uses: lo + (arr[mid] < target) // hi uses: hi - (arr[mid] >= target) } return lo; } ``` --- ## Checklist - [ ] Profile to confirm branch is problem - [ ] Verify branch is unpredictable - [ ] Verify branch is in hot path - [ ] Test edge cases - [ ] Benchmark vs branchy version - [ ] Document why branchless (for future maintainers) --- ## Related Skills - `performance-optimization` - Apply optimizations - `profiling-analysis` - Identify branch issues - `cpu-architecture` - Understand hardware impact - `performance-simd` - SIMD blending