-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatterns.py
More file actions
1858 lines (1685 loc) · 58.9 KB
/
patterns.py
File metadata and controls
1858 lines (1685 loc) · 58.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from dataclasses import dataclass
@dataclass
class PatternEntry:
pattern_id: str # e.g., "SR-1"
category: str # e.g., "Semantic Redundancy"
name: str # e.g., "Loop-Invariant Semantic Computation"
slow_code: str # The inefficient C code
fast_code: str # Hand-optimized reference
test_harness: str # Code to call and verify the function
compiler_difficulty: str # "Low", "Medium", "High", "Very High"
description: str # What the inefficiency is
# All 27 patterns
PATTERNS = [
# ── CATEGORY 1: Semantic Redundancy ──
PatternEntry(
pattern_id="SR-1",
category="Semantic Redundancy",
name="Loop-Invariant Function Call (Log Series)",
compiler_difficulty="Very High",
description="A log-series calibration function with loop-invariant arguments "
"is called on every iteration. The compiler cannot hoist it because "
"the inner transcendental loop prevents const/pure analysis. "
"Hoist once before the loop.",
slow_code="""
#include <math.h>
/* 40-term log series — transcendental inner loop blocks compiler hoisting */
static double log_series(double base) {
double r = 0.0;
for (int k = 1; k <= 40; k++) r += log(base * k + 1.0) / k;
return r;
}
void sr1_slow(double *arr, int n, double base) {
for (int i = 0; i < n; i++)
arr[i] *= log_series(base); /* same result every iteration */
}""",
fast_code="""
#include <math.h>
static double log_series(double base) {
double r = 0.0;
for (int k = 1; k <= 40; k++) r += log(base * k + 1.0) / k;
return r;
}
void sr1_fast(double *arr, int n, double base) {
double scale = log_series(base); /* hoisted once */
for (int i = 0; i < n; i++) arr[i] *= scale;
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// LLM_CODE_HERE
int main() {
int n = 1000000;
double base = 1.5;
double *arr = malloc(n * sizeof(double));
double *expected = malloc(n * sizeof(double));
srand(42);
for (int i = 0; i < n; i++)
arr[i] = expected[i] = 0.5 + ((double)rand() / RAND_MAX);
/* compute scale inline — independent of LLM code */
double scale = 0.0;
for (int k = 1; k <= 40; k++) scale += log(base * k + 1.0) / k;
for (int i = 0; i < n; i++) expected[i] *= scale;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(arr, n, base);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0
+ (end.tv_nsec - start.tv_nsec) / 1e6;
int correct = 1;
for (int i = 0; i < n; i++) {
if (fabs(arr[i] - expected[i]) / fmax(fabs(expected[i]), 1e-12) > 1e-6) {
correct = 0; break;
}
}
printf("result=%.10f time_ms=%.4f correct=%d\\n", arr[0], ms, correct);
free(arr); free(expected);
return 0;
}"""
),
PatternEntry(
pattern_id="SR-2",
category="Semantic Redundancy",
name="Loop-Invariant Term in Mixed Expression",
compiler_difficulty="Very High",
description="Loop body contains `alpha*X[i]*X[i] + beta*Y[i] + penalty(alpha,beta)` "
"where penalty() has a transcendental inner loop with loop-invariant arguments. "
"Optimization: separate accumulators for data-dependent terms, "
"call penalty once and multiply by n.",
slow_code="""
#include <math.h>
/* regularization penalty — sin/exp inner loop blocks compiler hoisting */
static double penalty(double a, double b) {
double r = 0.0;
for (int k = 1; k <= 20; k++) r += sin(a * k) * exp(-b * k * 0.05);
return r;
}
__attribute__((noinline))
double sr2_slow(double *X, double *Y, int n, double alpha, double beta) {
double result = 0.0;
for (int i = 0; i < n; i++)
result += alpha * X[i] * X[i] + beta * Y[i] + penalty(alpha, beta);
return result;
}""",
fast_code="""
#include <math.h>
static double penalty(double a, double b) {
double r = 0.0;
for (int k = 1; k <= 20; k++) r += sin(a * k) * exp(-b * k * 0.05);
return r;
}
__attribute__((noinline))
double sr2_fast(double *X, double *Y, int n, double alpha, double beta) {
double sumXsq = 0.0, sumY = 0.0;
for (int i = 0; i < n; i++) {
sumXsq += X[i] * X[i];
sumY += Y[i];
}
return alpha * sumXsq + beta * sumY + (double)n * penalty(alpha, beta);
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// LLM_CODE_HERE
int main() {
int n = 1000000;
double *X = malloc(n * sizeof(double));
double *Y = malloc(n * sizeof(double));
srand(42);
for (int i = 0; i < n; i++) {
X[i] = -5.0 + 10.0 * ((double)rand() / RAND_MAX);
Y[i] = -5.0 + 10.0 * ((double)rand() / RAND_MAX);
}
double alpha = 2.5, beta = 1.5;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
double result = optimized(X, Y, n, alpha, beta);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
/* compute expected independently — penalty inlined in harness, no LLM dependency */
double p = 0.0;
for (int k = 1; k <= 20; k++) p += sin(alpha * k) * exp(-beta * k * 0.05);
double expected = 0.0;
for (int i = 0; i < n; i++)
expected += alpha * X[i] * X[i] + beta * Y[i] + p;
double err = fabs(result - expected) / fmax(fabs(expected), 1e-12);
printf("result=%.10f time_ms=%.4f correct=%d\\n", result, ms, err < 1e-4);
free(X); free(Y);
return 0;
}"""
),
PatternEntry(
pattern_id="SR-3",
category="Semantic Redundancy",
name="Redundant Aggregation Recomputation",
compiler_difficulty="Very High",
description="Recomputing a running average from scratch each iteration "
"(O(n^2)) instead of maintaining a running sum (O(n)).",
slow_code="""
void sr3_slow(double *data, double *running_avg, int n) {
for (int i = 0; i < n; i++) {
double sum = 0.0;
for (int j = 0; j <= i; j++) {
sum += data[j];
}
running_avg[i] = sum / (i + 1);
}
}""",
fast_code="""
void sr3_fast(double *data, double *running_avg, int n) {
double sum = 0.0;
for (int i = 0; i < n; i++) {
sum += data[i];
running_avg[i] = sum / (i + 1);
}
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// LLM_CODE_HERE
int main() {
int n = 20000;
double *data = malloc(n * sizeof(double));
double *result = malloc(n * sizeof(double));
srand(42);
for (int i = 0; i < n; i++) data[i] = (double)rand() / RAND_MAX;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(data, result, n);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
double sum = 0.0;
int correct = 1;
for (int i = 0; i < n; i++) {
sum += data[i];
double expected_i = sum / (i + 1);
if (fabs(result[i] - expected_i) / fmax(fabs(expected_i), 1e-12) > 1e-6) {
correct = 0; break;
}
}
printf("result=%.10f time_ms=%.4f correct=%d\\n", result[n-1], ms, correct);
free(data); free(result);
return 0;
}"""
),
PatternEntry(
pattern_id="SR-4",
category="Semantic Redundancy",
name="Invariant Function Call in Loop",
compiler_difficulty="High",
description="A pure function with loop-invariant arguments is called "
"every iteration. Compiler can't hoist across TU boundaries.",
slow_code="""
#include <math.h>
double expensive_lookup(int key) {
double r = 0.0;
for (int i = 0; i < 100; i++)
r += sin((double)(key+i)) * cos((double)(key-i));
return r;
}
void sr4_slow(double *arr, int n, int config_key) {
for (int i = 0; i < n; i++) {
double factor = expensive_lookup(config_key);
arr[i] *= factor;
}
}""",
fast_code="""
#include <math.h>
double expensive_lookup(int key) {
double r = 0.0;
for (int i = 0; i < 100; i++)
r += sin((double)(key+i)) * cos((double)(key-i));
return r;
}
void sr4_fast(double *arr, int n, int config_key) {
double factor = expensive_lookup(config_key);
for (int i = 0; i < n; i++) arr[i] *= factor;
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// LLM_CODE_HERE
int main() {
int n = 2000000;
double *arr = malloc(n * sizeof(double));
double *expected = malloc(n * sizeof(double));
for (int i = 0; i < n; i++) arr[i] = expected[i] = (double)(i % 100) * 0.01 + 0.1;
int config_key = 7;
double factor = 0.0;
for (int i = 0; i < 100; i++)
factor += sin((double)(config_key+i)) * cos((double)(config_key-i));
for (int i = 0; i < n; i++) expected[i] *= factor;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(arr, n, config_key);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
int correct = 1;
for (int i = 0; i < n; i++) {
if (fabs(arr[i] - expected[i]) / fmax(fabs(expected[i]), 1e-12) > 1e-6) {
correct = 0; break;
}
}
printf("result=%.10f time_ms=%.4f correct=%d\\n", arr[0], ms, correct);
free(arr); free(expected);
return 0;
}"""
),
PatternEntry(
pattern_id="SR-5",
category="Semantic Redundancy",
name="Repeated Division by Loop-Invariant Denominator",
compiler_difficulty="Very High",
description="Each element is divided by a value that is loop-invariant but "
"computed by a function whose result GCC cannot hoist due to aliasing: "
"without restrict qualifiers, out[] could alias w[], so the compiler "
"must re-evaluate compute_norm each iteration. "
"Optimize: call once, precompute reciprocal, multiply.",
slow_code="""
#include <math.h>
/* L2 norm — compiler cannot hoist: out[] may alias w[], making w loop-variant */
static double compute_norm(double *w, int m) {
double s = 0.0;
for (int j = 0; j < m; j++) s += w[j] * w[j];
return sqrt(s);
}
__attribute__((noinline))
void sr5_slow(double *out, double *data, int n, double *w, int m) {
for (int i = 0; i < n; i++)
out[i] = data[i] / compute_norm(w, m); /* recomputed every iteration */
}""",
fast_code="""
#include <math.h>
static double compute_norm(double *w, int m) {
double s = 0.0;
for (int j = 0; j < m; j++) s += w[j] * w[j];
return sqrt(s);
}
__attribute__((noinline))
void sr5_fast(double *out, double *data, int n, double *w, int m) {
double inv = 1.0 / compute_norm(w, m); /* hoist call + precompute reciprocal */
for (int i = 0; i < n; i++) out[i] = data[i] * inv;
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// LLM_CODE_HERE
int main() {
int n = 1000000, m = 256;
double *data = malloc(n * sizeof(double));
double *out = malloc(n * sizeof(double));
double *w = malloc(m * sizeof(double));
srand(42);
for (int i = 0; i < n; i++) data[i] = -5.0 + 10.0 * ((double)rand() / RAND_MAX);
for (int j = 0; j < m; j++) w[j] = ((double)rand() / RAND_MAX);
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(out, data, n, w, m);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
/* compute norm inline — independent of LLM */
double s = 0.0;
for (int j = 0; j < m; j++) s += w[j] * w[j];
double norm = sqrt(s);
int correct = 1;
for (int i = 0; i < n; i++) {
double expected = data[i] / norm;
if (fabs(out[i] - expected) / fmax(fabs(expected), 1e-12) > 1e-9) {
correct = 0; break;
}
}
printf("result=%.10f time_ms=%.4f correct=%d\\n", out[0], ms, correct);
free(data); free(out); free(w);
return 0;
}"""
),
# ── CATEGORY 2: Input-Sensitive ──
PatternEntry(
pattern_id="IS-1",
category="Input-Sensitive Inefficiency",
name="Sparse Data Redundancy",
compiler_difficulty="Very High",
description="Weight update `w[k][j] += delta[j]*layer[k]` processes all "
"elements even when 90% are zero. Add zero-skip guards.",
slow_code="""
void is1_slow(double *w, double *delta, double *layer, int nj, int nk) {
for (int k = 0; k < nk; k++) {
for (int j = 0; j < nj; j++) {
double new_dw = delta[j] * layer[k];
w[k * nj + j] += new_dw;
}
}
}""",
fast_code="""
void is1_fast(double *w, double *delta, double *layer, int nj, int nk) {
for (int k = 0; k < nk; k++) {
if (layer[k] == 0.0) continue;
for (int j = 0; j < nj; j++) {
if (delta[j] == 0.0) continue;
w[k * nj + j] += delta[j] * layer[k];
}
}
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// LLM_CODE_HERE
int main() {
int nj = 512, nk = 512;
double *w = calloc(nk * nj, sizeof(double));
double *expected = calloc(nk * nj, sizeof(double));
double *delta = calloc(nj, sizeof(double));
double *layer = calloc(nk, sizeof(double));
srand(42);
for (int j = 0; j < nj; j++)
delta[j] = (rand() % 10 == 0) ? ((double)rand() / RAND_MAX) : 0.0;
for (int k = 0; k < nk; k++)
layer[k] = (rand() % 10 == 0) ? ((double)rand() / RAND_MAX) : 0.0;
for (int k = 0; k < nk; k++)
for (int j = 0; j < nj; j++)
expected[k * nj + j] += delta[j] * layer[k];
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(w, delta, layer, nj, nk);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
int correct = 1;
for (int i = 0; i < nk * nj; i++) {
if (fabs(w[i] - expected[i]) / fmax(fabs(expected[i]), 1e-12) > 1e-6) {
correct = 0; break;
}
}
printf("result=%.10f time_ms=%.4f correct=%d\\n", w[0], ms, correct);
free(w); free(expected); free(delta); free(layer);
return 0;
}"""
),
PatternEntry(
pattern_id="IS-2",
category="Input-Sensitive Inefficiency",
name="Unconditional Expensive Call on Skewed Data",
compiler_difficulty="Very High",
description="soft_clip() (containing log()) is called unconditionally for every "
"element, even though 99% are within threshold and the result is "
"discarded via ternary. Because soft_clip is noinline, the compiler "
"cannot eliminate the dead call. Add a branch guard so the expensive "
"path only runs for the 1% outliers.",
slow_code="""
#include <math.h>
/* soft gradient clipping — noinline so compiler cannot eliminate dead calls */
static double __attribute__((noinline)) soft_clip(double val, double thresh) {
double sign = (val >= 0.0) ? 1.0 : -1.0;
return sign * (thresh + log(1.0 + fabs(val) - thresh));
}
void is2_slow(double *out, double *in, int n, double thresh) {
for (int i = 0; i < n; i++) {
double val = in[i];
double clipped = soft_clip(val, thresh); /* always called */
out[i] = (fabs(val) > thresh) ? clipped : val; /* but only used 1% of the time */
}
}""",
fast_code="""
#include <math.h>
static double __attribute__((noinline)) soft_clip(double val, double thresh) {
double sign = (val >= 0.0) ? 1.0 : -1.0;
return sign * (thresh + log(1.0 + fabs(val) - thresh));
}
void is2_fast(double *out, double *in, int n, double thresh) {
for (int i = 0; i < n; i++) {
double val = in[i];
if (fabs(val) > thresh) /* guard: only call for the 1% outliers */
out[i] = soft_clip(val, thresh);
else
out[i] = val;
}
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// LLM_CODE_HERE
int main() {
int n = 5000000;
double *in = malloc(n * sizeof(double));
double *out = malloc(n * sizeof(double));
double thresh = 1.0;
srand(42);
for (int i = 0; i < n; i++) {
if (rand() % 100 == 0)
in[i] = 1.5 + 3.5 * ((double)rand() / RAND_MAX); /* 1% outliers > thresh */
else
in[i] = -0.9 + 1.8 * ((double)rand() / RAND_MAX); /* 99% within thresh */
if (rand() % 2) in[i] = -in[i]; /* random sign */
}
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(out, in, n, thresh);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
int correct = 1;
for (int i = 0; i < n; i++) {
double val = in[i], sign = (val >= 0) ? 1.0 : -1.0;
double abs_val = fabs(val);
double expected_i = (abs_val > thresh)
? sign * (thresh + log(1.0 + abs_val - thresh))
: val;
if (fabs(out[i] - expected_i) / fmax(fabs(expected_i), 1e-12) > 1e-6) {
correct = 0; break;
}
}
printf("result=%.10f time_ms=%.4f correct=%d\\n", out[0], ms, correct);
free(in); free(out);
return 0;
}"""
),
PatternEntry(
pattern_id="IS-3",
category="Input-Sensitive Inefficiency",
name="Early Termination",
compiler_difficulty="High",
description="Counting all violations when only need to know if any exist. "
"Early return on first violation.",
slow_code="""
int is3_slow(double *arr, int n, double threshold) {
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > threshold) count++;
}
return count == 0;
}""",
fast_code="""
int is3_fast(double *arr, int n, double threshold) {
for (int i = 0; i < n; i++) {
if (arr[i] > threshold) return 0;
}
return 1;
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// LLM_CODE_HERE
int main() {
int n = 10000000;
double *arr = malloc(n * sizeof(double));
double thresh = 0.5;
srand(42);
for (int i = 0; i < n; i++)
arr[i] = (double)rand() / RAND_MAX;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
int result = optimized(arr, n, thresh);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
int violations = 0;
for (int i = 0; i < n; i++) if (arr[i] > thresh) violations++;
int expected = (violations == 0) ? 1 : 0;
printf("result=%d time_ms=%.4f correct=%d\\n", result, ms, result == expected);
free(arr);
return 0;
}"""
),
PatternEntry(
pattern_id="IS-4",
category="Input-Sensitive Inefficiency",
name="Sorted Input Exploitation",
compiler_difficulty="Very High",
description="Always running O(n log n) sort even when input is already sorted. "
"Check sorted first in O(n).",
slow_code="""
#include <stdlib.h>
static int cmp_int(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
void is4_slow(int *arr, int n) {
qsort(arr, n, sizeof(int), cmp_int);
}""",
fast_code="""
#include <stdlib.h>
static int cmp_int(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
void is4_fast(int *arr, int n) {
int sorted = 1;
for (int i = 1; i < n; i++) {
if (arr[i] < arr[i-1]) { sorted = 0; break; }
}
if (!sorted) qsort(arr, n, sizeof(int), cmp_int);
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static int _ref_cmp(const void *a, const void *b) { return (*(int*)a - *(int*)b); }
// LLM_CODE_HERE
int main() {
int n = 5000000;
int *arr = malloc(n * sizeof(int));
int *expected = malloc(n * sizeof(int));
srand(42);
for (int i = 0; i < n; i++) arr[i] = expected[i] = i + (rand() % 3 == 0 ? -1 : 0);
int tmp = arr[n/2]; arr[n/2] = arr[n/2 - 1]; arr[n/2 - 1] = tmp;
tmp = expected[n/2]; expected[n/2] = expected[n/2-1]; expected[n/2-1] = tmp;
qsort(expected, n, sizeof(int), _ref_cmp);
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(arr, n);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
int correct = 1;
for (int i = 0; i < n; i++) {
if (arr[i] != expected[i]) { correct = 0; break; }
}
printf("result=%d time_ms=%.4f correct=%d\\n", arr[0], ms, correct);
free(arr); free(expected);
return 0;
}"""
),
PatternEntry(
pattern_id="IS-5",
category="Input-Sensitive Inefficiency",
name="Runtime Alias Check for Restrict Fast-Path",
compiler_difficulty="Very High",
description="Compiler must emit conservative aliasing-safe code because it can't prove at "
"compile time that out, A, B don't overlap. Check pointer ranges once at runtime; "
"if non-overlapping (the common case), dispatch to a __restrict__-qualified kernel "
"the compiler can freely vectorize.",
slow_code="""
/* noinline forces compiler to compile conservatively: can't prove A, B, out don't overlap */
__attribute__((noinline))
void is5_slow(double *out, double *A, double *B, int n) {
for (int i = 0; i < n; i++) {
out[i] = A[i] * A[i] + B[i] * 2.0 - A[i] * 0.5 + B[i] * B[i];
}
}""",
fast_code="""
static void __attribute__((noinline))
is5_restrict_kernel(double * __restrict__ out,
const double * __restrict__ A,
const double * __restrict__ B, int n) {
for (int i = 0; i < n; i++) {
out[i] = A[i] * A[i] + B[i] * 2.0 - A[i] * 0.5 + B[i] * B[i];
}
}
void is5_fast(double *out, double *A, double *B, int n) {
int no_alias = (out + n <= A || A + n <= out) &&
(out + n <= B || B + n <= out);
if (no_alias) {
is5_restrict_kernel(out, A, B, n);
} else {
for (int i = 0; i < n; i++) {
out[i] = A[i] * A[i] + B[i] * 2.0 - A[i] * 0.5 + B[i] * B[i];
}
}
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// LLM_CODE_HERE
int main() {
int n = 5000000;
double *A = malloc(n * sizeof(double));
double *B = malloc(n * sizeof(double));
double *out = malloc(n * sizeof(double));
double *expected = malloc(n * sizeof(double));
srand(42);
for (int i = 0; i < n; i++) {
A[i] = 0.5 + 4.5 * ((double)rand() / RAND_MAX);
B[i] = 0.5 + 4.5 * ((double)rand() / RAND_MAX);
expected[i] = A[i] * A[i] + B[i] * 2.0 - A[i] * 0.5 + B[i] * B[i];
}
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(out, A, B, n);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
int correct = 1;
for (int i = 0; i < n; i++) {
if (fabs(out[i] - expected[i]) / fmax(fabs(expected[i]), 1e-12) > 1e-9) {
correct = 0; break;
}
}
printf("result=%.10f time_ms=%.4f correct=%d\\n", out[0], ms, correct);
free(A); free(B); free(out); free(expected);
return 0;
}"""
),
# ── CATEGORY 3: Control-Flow ──
PatternEntry(pattern_id="CF-3", category="Control-Flow", name="Vectorization-Hostile Conditional",
compiler_difficulty="High",
description="A noinline function wraps a computation with a runtime guard (always true "
"for this data). Verify the invariant once, then use an inline branch-free loop.",
slow_code="""
static double __attribute__((noinline)) cf3_guarded(double x) {
return x > 0.0 ? x * x + x * 0.5 : 0.0;
}
void cf3_slow(double *out, double *in, int n) {
for (int i = 0; i < n; i++) out[i] = cf3_guarded(in[i]);
}""",
fast_code="""
void cf3_fast(double *out, double *in, int n) {
for (int i = 0; i < n; i++) out[i] = in[i] * in[i] + in[i] * 0.5;
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
static double __attribute__((noinline)) cf3_guarded(double x) {
return x > 0.0 ? x * x + x * 0.5 : 0.0;
}
// LLM_CODE_HERE
int main() {
int n = 10000000;
double *in = malloc(n * sizeof(double));
double *out = malloc(n * sizeof(double));
for (int i = 0; i < n; i++) in[i] = (double)(i % 100 + 1) * 0.1;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(out, in, n);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
int correct = 1;
for (int i = 0; i < n; i++) {
double expected = in[i] * in[i] + in[i] * 0.5;
if (fabs(out[i] - expected) > 1e-9) { correct = 0; break; }
}
printf("result=%.10f time_ms=%.4f correct=%d\\n", out[0], ms, correct);
free(in); free(out);
return 0;
}"""
),
PatternEntry(pattern_id="CF-4", category="Control-Flow", name="Function Pointer Dispatch in Hot Loop",
compiler_difficulty="High",
description="Per-element indirect call through a function pointer (or noinline dispatch) "
"prevents vectorization. Identify the concrete function at runtime and "
"dispatch to an inline tight loop.",
slow_code="""
typedef double (*TransformFn)(double);
static double __attribute__((noinline)) fn_scale(double x) { return x * 1.5; }
static double __attribute__((noinline)) fn_square(double x) { return x * x; }
static double __attribute__((noinline)) fn_shift(double x) { return x + 1.0; }
void cf4_slow(double *out, double *in, int n, TransformFn fn) {
for (int i = 0; i < n; i++) out[i] = fn(in[i]);
}""",
fast_code="""
void cf4_fast(double *out, double *in, int n, TransformFn fn) {
if (fn == fn_scale) { for (int i=0;i<n;i++) out[i]=in[i]*1.5; }
else if (fn == fn_square) { for (int i=0;i<n;i++) out[i]=in[i]*in[i]; }
else if (fn == fn_shift) { for (int i=0;i<n;i++) out[i]=in[i]+1.0; }
else { for (int i=0;i<n;i++) out[i]=fn(in[i]); }
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
typedef double (*TransformFn)(double);
static double __attribute__((noinline)) fn_scale(double x) { return x * 1.5; }
static double __attribute__((noinline)) fn_square(double x) { return x * x; }
static double __attribute__((noinline)) fn_shift(double x) { return x + 1.0; }
// LLM_CODE_HERE
int main() {
int n = 10000000;
double *in = malloc(n * sizeof(double));
double *out = malloc(n * sizeof(double));
for (int i = 0; i < n; i++) in[i] = (double)(i % 200 + 1) * 0.05;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(out, in, n, fn_scale);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
int correct = 1;
for (int i = 0; i < n; i++) {
if (fabs(out[i] - in[i] * 1.5) > 1e-9) { correct = 0; break; }
}
printf("result=%.10f time_ms=%.4f correct=%d\\n", out[0], ms, correct);
free(in); free(out);
return 0;
}"""
),
# ── CATEGORY 4: Human-Style Antipatterns ──
PatternEntry(
pattern_id="HR-2",
category="Human-Style Antipatterns",
name="Copy-Paste Duplication",
compiler_difficulty="Medium",
description="Four separate passes over data (mean X, mean Y, var X, var Y) from "
"copy-pasted code blocks. Merge into two passes: one for both means, "
"one for both variances.",
slow_code="""
void hr2_slow(double *X, double *Y, int n,
double *mean_x, double *mean_y,
double *var_x, double *var_y) {
double sum_x = 0.0;
for (int i = 0; i < n; i++) sum_x += X[i];
*mean_x = sum_x / n;
double sum_y = 0.0;
for (int i = 0; i < n; i++) sum_y += Y[i];
*mean_y = sum_y / n;
double var_sum_x = 0.0;
for (int i = 0; i < n; i++) {
double diff = X[i] - *mean_x;
var_sum_x += diff * diff;
}
*var_x = var_sum_x / n;
double var_sum_y = 0.0;
for (int i = 0; i < n; i++) {
double diff = Y[i] - *mean_y;
var_sum_y += diff * diff;
}
*var_y = var_sum_y / n;
}""",
fast_code="""
void hr2_fast(double *X, double *Y, int n,
double *mean_x, double *mean_y,
double *var_x, double *var_y) {
double sx = 0.0, sy = 0.0;
for (int i = 0; i < n; i++) {
sx += X[i];
sy += Y[i];
}
*mean_x = sx / n;
*mean_y = sy / n;
double vx = 0.0, vy = 0.0;
double mx = *mean_x, my = *mean_y;
for (int i = 0; i < n; i++) {
double dx = X[i] - mx;
double dy = Y[i] - my;
vx += dx * dx;
vy += dy * dy;
}
*var_x = vx / n;
*var_y = vy / n;
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// LLM_CODE_HERE
int main() {
int n = 10000000;
double *X = malloc(n * sizeof(double));
double *Y = malloc(n * sizeof(double));
srand(42);
for (int i = 0; i < n; i++) {
X[i] = -10.0 + 20.0 * ((double)rand() / RAND_MAX);
Y[i] = -10.0 + 20.0 * ((double)rand() / RAND_MAX);
}
double mx, my, vx, vy;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(X, Y, n, &mx, &my, &vx, &vy);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
/* compute expected independently */
double sx = 0.0, sy = 0.0;
for (int i = 0; i < n; i++) { sx += X[i]; sy += Y[i]; }
double emx = sx / n, emy = sy / n;
double evx = 0.0, evy = 0.0;
for (int i = 0; i < n; i++) {
double dx = X[i] - emx, dy = Y[i] - emy;
evx += dx * dx; evy += dy * dy;
}
evx /= n; evy /= n;
int correct = fabs(mx - emx) < 1e-9 && fabs(my - emy) < 1e-9
&& fabs(vx - evx) / fmax(fabs(evx), 1e-12) < 1e-6
&& fabs(vy - evy) / fmax(fabs(evy), 1e-12) < 1e-6;
printf("result=%.10f time_ms=%.4f correct=%d\\n", mx, ms, correct);
free(X); free(Y);
return 0;
}"""
),
PatternEntry(
pattern_id="HR-3",
category="Human-Style Antipatterns",
name="Dead / Debug Code",
compiler_difficulty="High",
description="volatile debug_counter++, NaN checks, and overflow checks inside a hot loop — "
"volatile prevents the compiler from removing them. "
"Strip all debug instrumentation from the production path.",
slow_code="""
#include <stdio.h>
static volatile int debug_counter = 0;
void hr3_slow(double *out, double *in, int n) {
for (int i = 0; i < n; i++) {
debug_counter++;
if (in[i] != in[i]) {
fprintf(stderr, "Warning: NaN at index %d\\n", i);
}
out[i] = in[i] * 2.0 + 1.0;
if (out[i] < -1e15 || out[i] > 1e15) {
fprintf(stderr, "Warning: output overflow at %d\\n", i);
}
}
}""",
fast_code="""
void hr3_fast(double *out, double *in, int n) {
for (int i = 0; i < n; i++) {
out[i] = in[i] * 2.0 + 1.0;
}
}""",
test_harness="""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// LLM_CODE_HERE
int main() {
int n = 10000000;
double *in = malloc(n * sizeof(double));
double *out = malloc(n * sizeof(double));
srand(42);
for (int i = 0; i < n; i++)
in[i] = -10.0 + 20.0 * ((double)rand() / RAND_MAX);
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
optimized(out, in, n);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1e6;
int correct = 1;
for (int i = 0; i < n; i++) {
double expected = in[i] * 2.0 + 1.0;
if (fabs(out[i] - expected) > 1e-9) { correct = 0; break; }
}
printf("result=%.10f time_ms=%.4f correct=%d\\n", out[0], ms, correct);
free(in); free(out);
return 0;
}"""
),
PatternEntry(
pattern_id="HR-4",
category="Human-Style Antipatterns",
name="Overly Defensive Checks",
compiler_difficulty="Medium",